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

protected void downloadFromMiddlewareAndWriteResponse(FileDescriptor fd, HttpServletResponse response)
        throws IOException {
    ServletOutputStream os = response.getOutputStream();
    try (InputStream is = fileLoader.openStream(fd)) {
        IOUtils.copy(is, os);/*w  w w. ja v a  2  s .c om*/
        os.flush();
    } catch (FileStorageException e) {
        throw new RestAPIException("Unable to download file from FileStorage",
                "Unable to download file from FileStorage: " + fd.getId(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.openlmis.fulfillment.service.stockmanagement.StockEventStockManagementServiceTest.java

@Test(expected = DataRetrievalException.class)
public void shouldReturnDataRetrievalExceptionOnOtherErrorResponseCodes() throws IOException {
    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.POST), any(HttpEntity.class), eq(UUID.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

    service.submit(new StockEventDto());
}

From source file:com.bennavetta.appsite.processing.ProcessingController.java

public void handle(Request request, Response response, InputStream requestBody, OutputStream responseBody)
        throws Exception {
    for (RewriteRule rule : rewriteRules.get()) {
        if (rule.matches(request.getURI())) {
            URI rewritten = rule.rewrite(request.getURI());
            log.info("Rewriting {} to {}", request.getURI(), rewritten);
            handle(new RedirectedRequest(rewritten, request), response, requestBody, responseBody);
        }//from w  ww.j a v  a2s . c o  m
    }

    Resource resource = Resource.get(request.getURI());

    // index pages
    if (resource == null) {
        for (String indexPage : indexPages) {
            String indexUri = URI.create(request.getURI()).relativize(URI.create(indexPage)).toString();
            resource = Resource.get(indexUri);
            if (resource != null) {
                break;
            }
        }
    }

    if (resource == null) {
        resource = Resource.get(error.notFound()); //TODO: put requested page in attributes
        response.setStatus(HttpStatus.NOT_FOUND);
    }

    if (resource != null) {
        try {
            log.info("Serving resource {}", resource.getPath());
            sendResource(resource, request, response, requestBody, responseBody);
        } catch (Exception e) {
            log.error("Exception serving request", e);
            resource = Resource.get(error.exception()); //TODO: put exception in attributes
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            sendResource(resource, request, response, requestBody, responseBody);
        }
    } else {
        log.warn("No content found: {}", request.getURI());
        // send something to avoid a blank response
        response.setStatus(HttpStatus.NOT_FOUND);
        response.setContentType(MediaType.HTML_UTF_8);
        PrintStream ps = new PrintStream(responseBody);
        ps.println("<html>");
        ps.println("\t<head>");
        ps.println("\t\t<title>Page not found</title>");
        ps.println("\t</head>");
        ps.println("\t<body>");
        ps.println("\t\t<h1>Page not found</h1>");
        ps.println("\t\t<p>Page " + request.getURI() + " not found</p>");
        ps.println("\t</body>");
        ps.println("</html>");
    }
}

From source file:com.ge.predix.acs.zone.management.ZoneController.java

@RequestMapping(method = GET, value = V1
        + AcsApiUriTemplates.ZONE_URL, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "An ACS zone defines a data partition which encapsulates policy, resource and privelege data"
        + "for separation between ACS tenants.  Retrieves the zone by a zone name.", hidden = true)
public ResponseEntity<Zone> getZone(@PathVariable("zoneName") final String zoneName) {

    try {/*  w w  w. j  ava2 s. co m*/

        Zone zone = this.service.retrieveZone(zoneName);
        return ok(zone);

    } catch (ZoneManagementException e) {
        throw new RestApiException(HttpStatus.NOT_FOUND, e);
    } catch (Exception e) {
        String message = String.format("Unexpected Exception while retriving Zone with name %s", zoneName);
        throw new RestApiException(HttpStatus.INTERNAL_SERVER_ERROR, message, e);
    }
}

From source file:org.openwms.tms.api.TransportationController.java

@ExceptionHandler(BusinessRuntimeException.class)
public ResponseEntity<Response<Serializable>> handleNotFound(HttpServletResponse res,
        BusinessRuntimeException ex) throws Exception {
    if (ex instanceof BehaviorAwareException) {
        BehaviorAwareException bae = (BehaviorAwareException) ex;
        return new ResponseEntity<>(
                new Response<>(ex.getMessage(), bae.getMsgKey(), bae.getStatus().toString(), bae.getData()),
                bae.getStatus());//  www .j a va 2 s  .  co  m
    }
    return new ResponseEntity<>(new Response<>(ex.getMessage(), ex.getMsgKey(),
            HttpStatus.INTERNAL_SERVER_ERROR.toString(), new String[] { ex.getMsgKey() }),
            HttpStatus.INTERNAL_SERVER_ERROR);
}

From source file:com.esri.geoportal.harvester.rest.TriggerController.java

/**
 * Deactivates trigger./*from  w w  w .j  a  va  2 s  . c  o m*/
 * @param triggerId trigger id
 * @return trigger response
 */
@RequestMapping(value = "/rest/harvester/triggers/{triggerId}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TriggerResponse> deactivateTrigger(@PathVariable UUID triggerId) {
    try {
        LOG.debug(formatForLog("DELETE /rest/harvester/triggers/%s", triggerId));
        TriggerReference trigRef = engine.getTriggersService().deactivateTriggerInstance(triggerId);
        return new ResponseEntity<>(
                new TriggerResponse(trigRef.getUuid(), trigRef.getTaskId(), trigRef.getTriggerDefinition()),
                HttpStatus.OK);
    } catch (InvalidDefinitionException ex) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    } catch (DataProcessorException ex) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:edu.sjsu.cmpe275.project.controller.ReservationController.java

/** Create a reservation
 * Once the guest is assured of the room availability, he can make a
 reservation by providing his email, full name, driver license #, and billing
 address. Then a unique reservation ID is created for this reservation. An
 email with the reservation ID and details is sent to the guest, including a
 link for the guest to cancel the reservation.
 * @param email         email//from ww  w.  j a  v  a  2 s. co m
 * @param fname         first name
 * @param midname         middle name
 * @param lname         last name
 * @return         void
 */

@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<?> createReservation(@RequestParam(value = "email", required = true) String email,
        @RequestParam(value = "fname", required = true) String fname,
        @RequestParam(value = "midname", required = false) String midname,
        @RequestParam(value = "lname", required = true) String lname,
        @RequestParam(value = "dl_no", required = true) String dlNo,
        @RequestParam(value = "street", required = true) String street,
        @RequestParam(value = "city", required = true) String city,
        @RequestParam(value = "state", required = true) String state,
        @RequestParam(value = "zip", required = true) String zip,
        @RequestParam(value = "checkin_date", required = true) Date checkinDate,
        @RequestParam(value = "checkout_date", required = true) Date checkoutDate,
        @RequestParam(value = "discount", required = false) Integer discount,
        @RequestParam(value = "rooms", required = true) List<String> rooms) {

    Reservation reservation = new Reservation();
    reservation.setEmail(email);
    reservation.setDlNo(dlNo);
    reservation.setName(new Name(fname, midname, lname));
    reservation.setBillingAddress(new Address(street, city, state, zip));
    reservation.setCheckinDate(checkinDate);
    reservation.setCheckoutDate(checkoutDate);
    if (discount == null) {
        reservation.setDiscount(0);
    } else {
        reservation.setDiscount(discount);
    }

    List<Room> roomList = new LinkedList<>();
    for (String s : rooms) {
        roomList.add(new Room(s));
    }
    reservation.setRoomList(roomList);

    reservation = reservationService.confirm(reservation);
    if (reservation == null) {
        return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
        return new ResponseEntity<Object>(reservation, HttpStatus.OK);
    }
}

From source file:edu.sjsu.cmpe275.lab2.service.ManagePersonController.java

/** Create a person object
 * 1 Path: person?firstname=XX&lastname=YY& email=ZZ&description=UU&street=VV$...
 * Method: POST/*from w  ww  .  j  a  va 2s .  co m*/
 * This API creates a person object.
 * 1. For simplicity, all the person fields (firstname, lastname, email, street, city,
 *    organization, etc), except ID and friends, are passed in as query parameters. Only the
 *    firstname, lastname, and email are required. Anything else is optional.
 * 2. Friends is not allowed to be passed in as a parameter.
 * 3. The organization parameter, if present, must be the ID of an existing organization.
 * 4. The request returns the newly created person object in JSON in its HTTP payload,
 *    including all attributes. (Please note this differs from generally recommended practice
 *    of only returning the ID.)
 * 5. If the request is invalid, e.g., missing required parameters, the HTTP status code
 *    should be 400; otherwise 200.
 * @param a         Description of a
 * @param b         Description of b
 * @return         Description of c
 */

@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<?> createPerson(@RequestParam(value = "firstname", required = true) String firstname,
        @RequestParam(value = "lastname", required = true) String lastname,
        @RequestParam(value = "email", required = true) String email,
        @RequestParam(value = "description", required = false) String description,
        @RequestParam(value = "street", required = false) String street,
        @RequestParam(value = "city", required = false) String city,
        @RequestParam(value = "state", required = false) String state,
        @RequestParam(value = "zip", required = false) String zip,
        @RequestParam(value = "orgid", required = false) Long orgid) {

    Session session = null;
    Transaction transaction = null;
    Organization organization = null;

    Person person = new Person();
    person.setEmail(email);
    person.setFirstname(firstname);
    person.setLastname(lastname);

    person.setAddress(new Address(street, city, state, zip));
    person.setDescription(description);

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        if (orgid != null) {
            organization = (Organization) session.get(Organization.class, orgid);
            person.setOrg(organization);
        }

        session.save(person);
        transaction.commit();

    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
        return new ResponseEntity<Object>("Internal server error.", HttpStatus.INTERNAL_SERVER_ERROR);
    } finally {
        if (session != null) {
            session.close();
        }
    }

    return new ResponseEntity<Object>(person, HttpStatus.OK);
}

From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java

/**
 * Tests {@link ApiResponseErrorHandler#hasError} in the case where the response has an HTTP status code in the server
 * error (5xx) series, specifically HTTP 500 Internal Server Error.
 * // w  w  w .j  ava2  s.  c  om
 * @throws Exception If an unexpected error occurs.
 */
@Test
public void testHasErrorWhenHttpStatusInternalServerError() throws Exception {
    byte[] body = null;
    ClientHttpResponse response = new MockClientHttpResponse(body, HttpStatus.INTERNAL_SERVER_ERROR);
    assertThat(this.errorHandler.hasError(response), CoreMatchers.is(true));
}

From source file:de.hska.ld.recommendation.controller.RecommendationController.java

@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.GET, value = "/{documentId}")
@Transactional(readOnly = false, noRollbackFor = NoSuchElementException.class)
public ResponseEntity<LDRecommendationDto> getRecommendations(@PathVariable Long documentId)
        throws IOException {
    Document document = documentService.findById(documentId);
    if (document.getTagList().size() == 0) {
        return new ResponseEntity<LDRecommendationDto>(HttpStatus.INTERNAL_SERVER_ERROR);
    }// w w  w  .  ja  va  2  s . c  o  m
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    OIDCAuthenticationToken token = (OIDCAuthenticationToken) auth;
    SSSRecommResponseDto sssRecommResponseDto = sssClient.retrieveRecommendations(documentId,
            token.getAccessTokenValue());
    if (sssRecommResponseDto == null) {
        return new ResponseEntity<LDRecommendationDto>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    List<SSSUserRecommendationDto> sssUserRecommendationDtoList = sssRecommResponseDto.getUsers();
    List<LDRecommendationUserDto> userIdList = new ArrayList<>();
    List<LDRecommendationDocumentDto> documentIdList = new ArrayList<>();
    sssUserRecommendationDtoList.forEach(ur -> {
        String userUri = ur.getUser().getId();
        // 1. Determine if the result is a user or a document
        if (userUri != null && userUri.contains("/user/")) {
            // 1.1 it is a user instance
            String[] splittedUserId = userUri.split("/user/");
            String userId = splittedUserId[splittedUserId.length - 1];
            Double likelihood = ur.getLikelihood();
            try {
                LDRecommendationUserDto ldRecommendationUserDto = new LDRecommendationUserDto();
                ldRecommendationUserDto.setUserId(Long.parseLong(userId));
                ldRecommendationUserDto.setLikelihood(likelihood);
                userIdList.add(ldRecommendationUserDto);
            } catch (Exception e) {
                //
            }
        } else if (userUri != null && userUri.contains("/document/")) {
            // 1.2 it is a document instance
            String[] splittedDocumentId = userUri.split("/document/");
            String documentIdRecommended = splittedDocumentId[splittedDocumentId.length - 1];
            Double likelihood = ur.getLikelihood();
            try {
                LDRecommendationDocumentDto ldRecommendationDocumentDto = new LDRecommendationDocumentDto();
                ldRecommendationDocumentDto.setDocumentId(Long.parseLong(documentIdRecommended));
                ldRecommendationDocumentDto.setLikelihood(likelihood);
                documentIdList.add(ldRecommendationDocumentDto);
            } catch (Exception e) {
                //
            }
        }
    });

    // fetch the related data sets from the living documents db
    List<LDRecommendationUserDto> userList = documentRecommInfoService
            .fetchUserRecommendationDatasets(userIdList);
    List<LDRecommendationDocumentDto> documentList = documentRecommInfoService
            .fetchDocumentRecommendationDatasets(documentIdList);

    try {
        Collections.sort(userList);
        Collections.sort(documentList);
    } catch (Exception e) {
        e.printStackTrace();
    }

    Long currenUserId = Core.currentUser().getId();
    User initialLoadUser = userService.findByUsername("aur0rp3");

    // filter out current user
    LDRecommendationUserDto found1 = null;
    LDRecommendationUserDto foundInit = null;
    List<LDRecommendationUserDto> likelihood0Users = new ArrayList<LDRecommendationUserDto>();
    for (LDRecommendationUserDto userRecomm : userList) {
        /*if (0d == userRecomm.getLikelihood()) {
        likelihood0Users.add(userRecomm);
        }*/
        if (currenUserId.equals(userRecomm.getUserId())) {
            found1 = userRecomm;
        }
        if (initialLoadUser != null && initialLoadUser.getId().equals(userRecomm.getUserId())) {
            foundInit = userRecomm;
        }
    }
    if (found1 != null) {
        userList.remove(found1);
    }
    if (foundInit != null) {
        userIdList.remove(foundInit);
    }
    if (likelihood0Users.size() > 0) {
        userList.removeAll(likelihood0Users);
    }

    // filter out current document
    LDRecommendationDocumentDto found = null;
    List<LDRecommendationDocumentDto> likelihood0Documents = new ArrayList<LDRecommendationDocumentDto>();
    for (LDRecommendationDocumentDto documentRecomm : documentList) {
        if (0d == documentRecomm.getLikelihood()) {
            likelihood0Documents.add(documentRecomm);
        }
        if (documentId.equals(documentRecomm.getDocumentId())) {
            found = documentRecomm;
        }
    }
    if (found != null) {
        documentList.remove(found);
    }
    if (likelihood0Documents.size() > 0) {
        documentList.removeAll(likelihood0Documents);
    }

    // filter out documents the current user has no access to
    List<LDRecommendationDocumentDto> noPermissionDocuments = new ArrayList<LDRecommendationDocumentDto>();
    for (LDRecommendationDocumentDto documentRecomm : documentList) {
        Long documentIdPermissionCheck = documentRecomm.getDocumentId();
        Document document2 = documentService.findById(documentIdPermissionCheck);
        if (!documentService.checkPermissionSave(document2, Access.Permission.READ)) {
            noPermissionDocuments.add(documentRecomm);
        }
    }
    if (noPermissionDocuments.size() > 0) {
        documentList.removeAll(noPermissionDocuments);
    }

    LDRecommendationDto ldRecommendationDto = new LDRecommendationDto();
    ldRecommendationDto.setUserList(new ArrayList<>());
    ldRecommendationDto.setDocumentList(documentList);
    ldRecommendationDto.setDocumentId(documentId);

    return new ResponseEntity<LDRecommendationDto>(ldRecommendationDto, HttpStatus.OK);
}