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.craftercms.profile.controllers.rest.ExceptionHandlers.java

@ExceptionHandler(ProfileException.class)
public ResponseEntity<Object> handleProfileException(ProfileException e, WebRequest request) {
    return handleExceptionInternal(e, HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.OTHER, request);
}

From source file:com.boyuanitsm.fort.web.rest.AccountResource.java

/**
 * GET  /account/sessions : get the current open sessions.
 *
 * @return the ResponseEntity with status 200 (OK) and the current open sessions in body,
 *  or status 500 (Internal Server Error) if the current open sessions couldn't be retrieved
 *//*from w ww .ja  v  a  2  s  .  co  m*/
@RequestMapping(value = "/account/sessions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<PersistentToken>> getCurrentSessions() {
    return userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin())
            .map(user -> new ResponseEntity<>(persistentTokenRepository.findByUser(user), HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
}

From source file:access.controller.AccessController.java

/**
 * Requests a file download that has been prepared by this Access component. This will return the raw bytes of the
 * resource.//from w  w w.  j  av a 2  s  .c  om
 * 
 * @param dataId
 *            The Id of the Data Item to get. Assumes this file is ready to be downloaded.
 */
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/file/{dataId}", method = RequestMethod.GET)
public ResponseEntity accessFile(@PathVariable(value = "dataId") String dataId,
        @RequestParam(value = "fileName", required = false) String name) {

    final String returnAction = "returningFileBytes";

    try {
        // Get the DataResource item
        DataResource data = accessor.getData(dataId);
        String fileName = StringUtils.isNullOrEmpty(name) ? dataId : name;
        pzLogger.log(String.format("Processing Data File for %s", dataId), Severity.INFORMATIONAL,
                new AuditElement(ACCESS, "beginProcessingFile", dataId));

        if (data == null) {
            pzLogger.log(String.format("Data not found for requested Id %s", dataId), Severity.WARNING);
            return new ResponseEntity<>(
                    new ErrorResponse(String.format("Data not found: %s", dataId), ACCESS_COMPONENT_NAME),
                    HttpStatus.NOT_FOUND);
        }

        if (data.getDataType() instanceof TextDataType) {
            // Stream the Bytes back
            TextDataType textData = (TextDataType) data.getDataType();
            pzLogger.log(String.format("Returning Bytes for %s", dataId), Severity.INFORMATIONAL,
                    new AuditElement(ACCESS, returnAction, dataId));
            return getResponse(MediaType.TEXT_PLAIN, String.format("%s%s", fileName, ".txt"),
                    textData.getContent().getBytes());
        } else if (data.getDataType() instanceof PostGISDataType) {
            // Obtain geoJSON from postGIS
            StringBuilder geoJSON = getPostGISGeoJSON(data);

            // Log the Request
            pzLogger.log(String.format("Returning Bytes for %s of length %s", dataId, geoJSON.length()),
                    Severity.INFORMATIONAL, new AuditElement(ACCESS, returnAction, dataId));

            // Stream the Bytes back
            return getResponse(MediaType.TEXT_PLAIN, String.format("%s%s", fileName, ".geojson"),
                    geoJSON.toString().getBytes());
        } else if (!(data.getDataType() instanceof FileRepresentation)) {
            String message = String.format("File download not available for Data Id %s; type is %s", dataId,
                    data.getDataType().getClass().getSimpleName());
            pzLogger.log(message, Severity.WARNING, new AuditElement(ACCESS, "accessBytesError", ""));
            throw new InvalidInputException(message);
        } else {
            byte[] bytes = accessUtilities.getBytesForDataResource(data);

            // Log the Request
            pzLogger.log(String.format("Returning Bytes for %s of length %s", dataId, bytes.length),
                    Severity.INFORMATIONAL, new AuditElement(ACCESS, returnAction, dataId));

            // Preserve the file extension from the original file.
            String originalFileName = ((FileRepresentation) data.getDataType()).getLocation().getFileName();
            String extension = FilenameUtils.getExtension(originalFileName);

            // Stream the Bytes back
            return getResponse(MediaType.APPLICATION_OCTET_STREAM, String.format("%s.%s", fileName, extension),
                    bytes);
        }
    } catch (Exception exception) {
        String error = String.format("Error fetching Data %s: %s", dataId, exception.getMessage());
        LOGGER.error(error, exception);
        pzLogger.log(error, Severity.ERROR, new AuditElement(ACCESS, "errorAccessingBytes", dataId));
        return new ResponseEntity<>(
                new ErrorResponse("Error fetching File: " + exception.getMessage(), ACCESS_COMPONENT_NAME),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:it.polimi.diceH2020.launcher.controller.rest.DownloadsController.java

@RequestMapping(value = "/solution/json/{id}", method = RequestMethod.GET)
public ResponseEntity<String> downloadSolutionJson(@PathVariable Long id) {
    ResponseEntity<String> output = new ResponseEntity<>(HttpStatus.NOT_FOUND);

    SimulationsManager manager = simulationsManagerRepository.findById(id);
    if (manager != null) {
        for (InteractiveExperiment experiment : manager.getExperimentsList()) {
            // TODO there is always only one InteractiveExperiment, all the monster should be treated accordingly
            if (experiment.isDone()) {
                try {
                    String solution = Compressor.decompress(experiment.getFinalSolution());
                    output = new ResponseEntity<>(solution, HttpStatus.OK);
                } catch (IOException e) {
                    String message = String.format("Could not decompress solutions JSON for experiment %d", id);
                    logger.error(message, e);
                    output = new ResponseEntity<>(message, HttpStatus.INTERNAL_SERVER_ERROR);
                }//from   ww w . j  ava  2  s .c om
            } else {
                output = new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }
        }
    }

    return output;
}

From source file:seava.j4e.web.controller.AbstractBaseController.java

/**
 * Generic exception handler/*from  w w w  .ja v  a  2 s.c  o  m*/
 * 
 * @param e
 * @param response
 * @return
 * @throws IOException
 */
@ExceptionHandler(value = Exception.class)
@ResponseBody
protected String handleException(Exception e, HttpServletResponse response) throws IOException {

    e.printStackTrace();

    StringBuffer sb = new StringBuffer(" NOT MANAGED EXCEPTION HANDLER ");
    if (e.getLocalizedMessage() != null) {
        sb.append(e.getLocalizedMessage());
    } else if (e.getCause() != null) {
        if (sb.length() > 0) {
            sb.append(" Reason: ");
        }
        sb.append(e.getCause().getLocalizedMessage());
    }
    if (sb.length() == 0) {
        if (e.getStackTrace() != null) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            e.printStackTrace(response.getWriter());
            return null;
        }
    }
    response.setStatus(HttpStatus.EXPECTATION_FAILED.value());
    response.getOutputStream().print(sb.toString());
    response.getOutputStream().flush();
    return null;

}

From source file:gateway.test.JobTests.java

/**
 * Test POST /v2/job/*from   w  w  w  . java  2 s  .  c  o  m*/
 */
@Test
public void testExecute() throws Exception {
    // Mock
    ExecuteServiceJob executeJob = new ExecuteServiceJob("123456");
    executeJob.data = new ExecuteServiceData();
    executeJob.data.setServiceId("654321");

    ServiceResponse serviceResponse = new ServiceResponse();
    Service service = new Service();
    service.setServiceId("654321");
    service.setResourceMetadata(new ResourceMetadata());
    service.getResourceMetadata().availability = "ONLINE";
    serviceResponse.data = service;

    Mockito.doNothing().when(logger).log(anyString(), anyString());
    when(serviceController.getService("654321", user))
            .thenReturn(new ResponseEntity<PiazzaResponse>(serviceResponse, HttpStatus.OK));

    // Test
    ResponseEntity<PiazzaResponse> entity = jobController.executeService(executeJob, user);

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

    // Test Exception
    Mockito.doThrow(new PiazzaJobException("REST Broke")).when(gatewayUtil)
            .sendJobRequest(any(PiazzaJobRequest.class), anyString());
    entity = jobController.executeService(executeJob, user);
    assertTrue(entity.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(entity.getBody() instanceof ErrorResponse);
    ErrorResponse error = (ErrorResponse) entity.getBody();
    assertTrue(error.message.contains("REST Broke"));
}

From source file:org.fineract.module.stellar.controller.BridgeController.java

@RequestMapping(value = "/balances/{assetCode}/{issuer}/", method = RequestMethod.GET, consumes = {
        "application/json" }, produces = { "application/json" })
public ResponseEntity<BigDecimal> getStellarAccountBalanceByIssuer(
        @RequestHeader(API_KEY_HEADER_LABEL) final String apiKey,
        @RequestHeader(TENANT_ID_HEADER_LABEL) final String mifosTenantId,
        @PathVariable("assetCode") final String assetCode,
        @PathVariable("issuer") final String urlEncodedIssuingStellarAddress) {
    this.securityService.verifyApiKey(apiKey, mifosTenantId);

    final String issuingStellarAddress;
    try {//from   www .ja v a  2 s.c om
        issuingStellarAddress = URLDecoder.decode(urlEncodedIssuingStellarAddress, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>(bridgeService.getBalanceByIssuer(mifosTenantId, assetCode,
            StellarAddress.parse(issuingStellarAddress)), HttpStatus.OK);
}

From source file:com.haulmont.idp.controllers.IdpController.java

@PostMapping(value = "/auth", produces = "application/json; charset=UTF-8")
@ResponseBody/*from  www  . ja va2  s. co  m*/
public AuthResponse authenticate(@RequestBody AuthRequest auth,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {
    String serviceProviderUrl = auth.getServiceProviderUrl();

    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    Locale sessionLocale = null;
    if (globalConfig.getLocaleSelectVisible() && auth.getLocale() != null) {
        Map<String, Locale> availableLocales = globalConfig.getAvailableLocales();
        Locale requestedLocale = Locale.forLanguageTag(auth.getLocale());

        if (availableLocales.containsValue(requestedLocale)) {
            sessionLocale = requestedLocale;
        }
    }
    if (sessionLocale == null) {
        sessionLocale = messageTools.getDefaultLocale();
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        boolean loggedOut = idpService.logout(idpSessionCookie);

        if (loggedOut) {
            log.info("Logged out IDP session {}", idpSessionCookie);

            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie);
        }
    }

    IdpService.IdpLoginResult loginResult;
    try {
        loginResult = idpService.login(auth.getUsername(), passwordEncryption.getPlainHash(auth.getPassword()),
                sessionLocale, ImmutableMap.of(ClientType.class.getName(), ClientType.WEB.name()));
    } catch (LoginException e) {
        // remove auth cookie
        Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        log.warn("Unable to login user {}", auth.getUsername());
        return AuthResponse.failed("invalid_credentials");
    }

    if (loginResult.getSessionId() != null) {
        Cookie idpCookie = new Cookie(CUBA_IDP_COOKIE_NAME, loginResult.getSessionId());
        idpCookie.setMaxAge(idpConfig.getIdpCookieMaxAge());
        idpCookie.setHttpOnly(idpConfig.getIdpCookieHttpOnly());
        response.addCookie(idpCookie);
    }

    String serviceProviderRedirectUrl;
    try {
        URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);

        if ("client-ticket".equals(auth.getResponseType())) {
            uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + loginResult.getServiceProviderTicket());
        } else {
            uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, loginResult.getServiceProviderTicket());
        }

        serviceProviderRedirectUrl = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        return AuthResponse.failed("invalid_params");
    }

    log.info("Logged in IDP session with ticket {}, user: {}", loginResult.getServiceProviderTicket(),
            auth.getUsername());

    return AuthResponse.authenticated(serviceProviderRedirectUrl);
}

From source file:com.ge.predix.test.utils.ZoneHelper.java

public HttpStatus deleteZone(final RestTemplate restTemplate, final String zoneName,
        final boolean registeredWithZac) {
    try {/*from  w  w  w. j  av  a2s .  c om*/
        restTemplate.delete(this.acsBaseUrl + ACS_ZONE_API_PATH + zoneName);
        if (registeredWithZac) {
            deleteServiceFromZac(zoneName);
        }
        return HttpStatus.NO_CONTENT;
    } catch (HttpClientErrorException httpException) {
        return httpException.getStatusCode();
    } catch (JsonProcessingException e) {
        return HttpStatus.INTERNAL_SERVER_ERROR;
    } catch (RestClientException e) {
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}

From source file:com.github.ukase.web.UkaseController.java

@ExceptionHandler(HandlebarsException.class)
@ResponseBody// w  w  w .j  av  a  2 s.co m
public ResponseEntity<String> handleHandlebarsException(HandlebarsException e) {
    log.error("Some grand error caused in template mechanism", e);
    return new ResponseEntity<>("Some error caused in template mechanism", HttpStatus.INTERNAL_SERVER_ERROR);
}