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:org.cloudfoundry.identity.uaa.codestore.CodeStoreEndpointsTests.java

@Test
public void testGenerateCodeWithDuplicateCode() throws Exception {
    RandomValueStringGenerator generator = mock(RandomValueStringGenerator.class);
    when(generator.generate()).thenReturn("duplicate");
    expiringCodeStore.setGenerator(generator);

    String data = "{}";
    Timestamp expiresAt = new Timestamp(System.currentTimeMillis() + 60000);
    ExpiringCode expiringCode = new ExpiringCode(null, expiresAt, data);

    try {//from   www .  ja v a2 s .  co m
        codeStoreEndpoints.generateCode(expiringCode);
        codeStoreEndpoints.generateCode(expiringCode);

        fail("duplicate code generated, should throw CodeStoreException.");
    } catch (CodeStoreException e) {
        assertEquals(e.getStatus(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.pubkit.web.controller.BaseController.java

@ExceptionHandler(RoquitoServerException.class)
void handleServerError(HttpServletResponse response) throws IOException {
    response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
}

From source file:access.test.PiazzaEnvironmentTests.java

@Test
public void testResourcesCauseServerError() {
    Mockito.when(this.restTemplate.exchange(Mockito.endsWith("/workspaces/piazza.json"),
            Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.eq(String.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

    Mockito.when(this.restTemplate.exchange(Mockito.endsWith("/datastores/piazza.json"),
            Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.eq(String.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

    piazzaEnvironment.initializeEnvironment();
    assertTrue(true); // no error occurred
}

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

@RequestMapping(value = "/claimsxml", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Object> renderClaimsXml(@RequestParam(value = "id", defaultValue = "Q7259") String itemId,
        @RequestParam(value = "lang") String lang) {

    String language = wikiBrowserProperties.computeLang(lang);
    ClaimsSparqlResponse claimsSparqlResponse = callClaimsSparqlQuery(itemId, language);
    ClaimsResponse claimsResponse = convertSparqlResponse(claimsSparqlResponse, language, itemId);

    return Optional.ofNullable(claimsResponse).map(cr -> new ResponseEntity<>((Object) cr, HttpStatus.OK))
            .orElse(new ResponseEntity<>("Wikidata query unsuccessful", HttpStatus.INTERNAL_SERVER_ERROR));

}

From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java

/**
 * This function gathers all dates where an event takes place within a specific month and year. The function is invoked by GETting the URI /api/admin/event/month and specifying the month and year via the request parameters.
 * @param month The selected month./*  w w w . j  av  a  2  s  . c  om*/
 * @param year The selected year.
 * @return An HTTP response with a status code. If the function succeeds, a list of dates, during the month, that contain an event, is returned, otherwise an error code is returned.
 */
@RequestMapping(value = "month", produces = "application/json", method = RequestMethod.GET)
public ResponseEntity<List<LocalDate>> getEventDatesOfMonth(@RequestParam String month,
        @RequestParam String year, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Gathering events of month " + month + " and year " + year);
    ArrayList<LocalDate> dates = new ArrayList<>();
    int monthInt, yearInt;
    try {
        monthInt = Integer.parseInt(month);
        yearInt = Integer.parseInt(year);
    } catch (NumberFormatException e) {
        logger.warn("[" + currentUser + "] Unable to parse month or year.");
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    LocalDateTime start = LocalDate.of(yearInt, monthInt, 1).atStartOfDay();
    LocalDateTime end = start.plusMonths(1);

    logger.debug("Getting all single day events...");
    dates.addAll(eventRepository.findAllByEndDateTimeBetweenAndMultiDate(start, end, false).parallelStream()
            .map(Event::getStartDate).collect(Collectors.toList()));
    logger.debug("All single day events retrieved, got " + dates.size() + " dates so far");

    logger.debug("Getting all multi day events...");
    //Collecting all multi date events, that either start or end within the selected month (which means that events that are spanning over several months are not collected)
    Stream.concat(eventRepository.findAllByStartDateTimeBetweenAndMultiDate(start, end, true).stream(), //All multi date events starting within the month
            eventRepository.findAllByEndDateTimeBetweenAndMultiDate(start, end, true).stream()) //All multi date events ending within the month
            .distinct() //Removing all duplicated events
            .parallel().forEach(event -> { //Creating a local date for each occupied date of the event
                for (LocalDate date = event.getStartDate(); //Starting with the start date
                        !date.equals(event.getEndDateTime().toLocalDate()); //Until reaching the end date
                        date = date.plusDays(1)) //Adding a day within each iterations
                {
                    dates.add(date);
                }
                dates.add(event.getEndDateTime().toLocalDate()); //Finally adding the last date
            });
    logger.debug("All multi day events gathered, got " + dates.size() + " dates so far");

    if (dates.isEmpty()) {
        logger.warn("[" + currentUser + "] Returning empty dates list of " + month + "/" + year);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
        logger.debug("[" + currentUser + "] Returning dates list " + month + "/" + year);
        return new ResponseEntity<>(dates.stream().distinct().collect(Collectors.toList()), HttpStatus.OK); //Returning an optimized set of events
    }
}

From source file:org.venice.piazza.servicecontroller.async.AsyncServiceWorkerTest.java

/**
 * Test error handling for service returning a 500 error
 * @throws InterruptedException /*ww w.j a v  a2s.  c  o m*/
 */
@Test
public void testExecutionErrorResponse() throws InterruptedException {
    // Mock an error coming from the execution service
    Mockito.doReturn(new ResponseEntity<String>("Error.", HttpStatus.INTERNAL_SERVER_ERROR))
            .when(executeServiceHandler).handle(any(ExecuteServiceJob.class));
    // Test
    worker.executeService(mockJob);
    // Verify that the error was processed by the worker
    Mockito.verify(accessor, Mockito.times(1)).deleteAsyncServiceInstance(Mockito.eq(mockJob.getJobId()));
    Mockito.verify(producer, Mockito.times(1)).send(Mockito.any());
}

From source file:gateway.test.AlertTriggerTests.java

/**
 * Test GET /trigger/{triggerId}/*from w  w  w .  ja v  a 2 s.  c o m*/
 */
@Test
public void testGetTrigger() {
    // Mock Response
    when(restTemplate.getForObject(anyString(), eq(String.class))).thenReturn("Trigger");

    // Test
    ResponseEntity<?> response = alertTriggerController.getTrigger("triggerId", user);

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

    // Test Exception
    when(restTemplate.getForObject(anyString(), eq(String.class)))
            .thenThrow(new RestClientException("Trigger Error"));
    response = alertTriggerController.getTrigger("triggerId", user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(response.getBody() instanceof ErrorResponse);
    assertTrue(((ErrorResponse) response.getBody()).message.contains("Trigger Error"));
}

From source file:org.dawnsci.marketplace.controllers.ExtendedRestApiController.java

/**
 * Uploads a p2-repository to the solution and updates the solution data
 * Returns a <b>403 Forbidden</b> if the logged in user is not the owner of
 * the solution.//from  www.  ja va  2  s. co  m
 *
 * The URL to the update site will be overwritten with a new value pointing
 * to this server.
 */
@PreAuthorize("hasRole('UPLOAD')")
@RequestMapping(value = "/upload-p2repo")
public ResponseEntity<String> uploadRepository(Principal principal, @RequestParam("id") Long id,
        @RequestParam("file") MultipartFile file) throws Exception {
    // verify that we have the correct owner
    Account account = accountRepository.findOne(principal.getName());
    Account a = accountRepository.findAccountBySolutionId(id);
    if (!account.getUsername().equals(a.getUsername())) {
        return new ResponseEntity<String>("Logged in user is not the owner of the solution",
                HttpStatus.FORBIDDEN);
    }
    fileService.uploadRepository(id, file);
    // get solution and update with new information
    Node node = marketplaceDAO.getSolution(id);
    node.setUpdateurl("/files/" + id + "/");
    Object result = marketplaceDAO.saveOrUpdateSolution(node, account);
    if (result instanceof Node) {
        return new ResponseEntity<String>(MarketplaceSerializer.serialize((Node) result), HttpStatus.OK);
    } else {
        return new ResponseEntity<String>((String) result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

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

/**
 * Query Neo4j for all relationships between given set of item IDs
 * @param items//from w w w . j  av a2 s.  c  o  m
 * @return
 */
@RequestMapping(value = "/visgraph", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> search(@RequestParam(value = "items", defaultValue = "") String items) {
    // Example endpoint usage is graph?items=Q24, Q30, Q23, Q16, Q20
    // Scrub the input, and output a string for the Cypher query similar to the following:
    // 'Q24','Q30','Q23','Q16','Q20'
    String argStr = WikiBrowserUtils.scrubItemIds(items, true);

    log.info("argStr=" + argStr);

    VisGraphResponseNear visGraphResponseNear = null;

    if (argStr.length() == 0) {
        // TODO: Consider handling an invalid items argument better than the way it is handled here
        //argStr = "'Q2'"; // If the items argumentisn't valid, pretend Q2 (Earth) was entered
    }

    if (argStr.length() > 0) {
        String neoCypherUrl = wikiBrowserProperties.getNeoCypherUrl();

        /*  Example Cypher query POST
        {
          "statements" : [ {
            "statement" : "MATCH (a)-[r]->(b) WHERE a.itemId IN ['Q24', 'Q30', 'Q23', 'Q16', 'Q20'] AND b.itemId IN ['Q24', 'Q30', 'Q23', 'Q16', 'Q20'] RETURN a, b, r",
            "resultDataContents" : ["graph" ]
          } ]
        }
        */

        /*
        MATCH (a:Item), (b:Item)
        WHERE a.itemId IN ['Q2', 'Q24', 'Q30'] AND b.itemId IN ['Q2', 'Q24', 'Q30']
        WITH a, b
        OPTIONAL MATCH (a)-[rel]-(b)
        RETURN a, b, collect(rel)
                
        was:
        MATCH (a:Item)
        WHERE a.itemId IN ['Q2', 'Q24', 'Q30']
        OPTIONAL MATCH (a:Item)-[rel]-(b:Item)
        WHERE b.itemId IN ['Q2', 'Q24', 'Q30']
        RETURN a, b, collect(rel)
        */

        String qa = "{\"statements\":[{\"statement\":\"MATCH (a:Item), (b:Item) WHERE a.itemId IN [";
        String qb = argStr; // Item IDs
        String qc = "] AND b.itemId IN [";
        String qd = argStr; // Item IDs
        String qe = "] WITH a, b OPTIONAL MATCH (a)-[rel]-(b) RETURN a, b, collect(rel)\",";
        String qf = "\"resultDataContents\":[\"graph\"]}]}";

        /*
        String qa = "{\"statements\":[{\"statement\":\"MATCH (a:Item) WHERE a.itemId IN [";
        String qb = argStr; // Item IDs
        String qc = "] OPTIONAL MATCH (a:Item)-[rel]-(b:Item) WHERE b.itemId IN [";
        String qd = argStr; // Item IDs
        String qe = "] RETURN a, b, collect(rel)\",";
        String qf = "\"resultDataContents\":[\"graph\"]}]}";
        */

        String postString = qa + qb + qc + qd + qe + qf;

        visGraphResponseNear = queryProcessSearchResponse(neoCypherUrl, postString);
    }

    return Optional.ofNullable(visGraphResponseNear).map(cr -> new ResponseEntity<>((Object) cr, HttpStatus.OK))
            .orElse(new ResponseEntity<>("visgraph query unsuccessful", HttpStatus.INTERNAL_SERVER_ERROR));
}

From source file:com.github.lynxdb.server.api.http.handlers.EpQuery.java

@RequestMapping(path = "", method = RequestMethod.POST)
public ResponseEntity rootForm(@RequestBody String _request, Authentication _authentication,
        HttpServletResponse _response) {

    QueryRequest request;/*from w  w w . j a  va2  s.com*/
    try {
        String decoded = URLDecoder.decode(_request, "UTF-8");
        decoded = decoded.substring(0, decoded.length() - 1);
        request = mapper.readValue(decoded, QueryRequest.class);
    } catch (IOException ex) {
        return new ErrorResponse(mapper, HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex).response();
    }

    return rootJson(request, _authentication, _response);

}