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.stormcloud.ide.api.filter.UserFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {/*from w  w  w.ja  v a  2 s .c  o  m*/

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

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

@RequestMapping(path = "", method = { RequestMethod.GET, RequestMethod.POST,
        RequestMethod.DELETE }, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity rootJson(@RequestBody @Valid QueryRequest _request, Authentication _authentication,
        HttpServletResponse _response) {

    User user = (User) _authentication.getPrincipal();

    List<Query> queries;

    try {//w w w . ja v a 2s .  c o m
        queries = parseQuery(vhosts.byId(user.getVhost()), _request);
    } catch (ParsingQueryException ex) {
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, ex.getMessage(), ex).response();
    }

    File f;
    FileOutputStream fos;
    try {
        f = File.createTempFile("lynx.", ".tmp");
        fos = new FileOutputStream(f);
    } catch (IOException ex) {
        return new ErrorResponse(mapper, HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex).response();
    }

    try {
        saveResponse(fos, queries);
    } catch (IOException ex) {
        return new ErrorResponse(mapper, HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex).response();
    }

    try {
        return ResponseEntity.ok(new InputStreamResource(new FileInputStream(f)));
    } catch (FileNotFoundException ex) {
        return new ErrorResponse(mapper, HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex).response();
    } finally {
        f.delete();
    }
}

From source file:com.haulmont.restapi.service.QueriesControllerManager.java

protected String _executeQuery(String entityName, String queryName, @Nullable Integer limit,
        @Nullable Integer offset, @Nullable String viewName, @Nullable Boolean returnNulls,
        @Nullable Boolean dynamicAttributes, @Nullable String version, Map<String, String> params) {
    LoadContext<Entity> ctx;
    entityName = restControllerUtils.transformEntityNameIfRequired(entityName, version,
            JsonTransformationDirection.FROM_VERSION);
    try {/*from w  w w  .  j a  v  a  2  s.  com*/
        ctx = createQueryLoadContext(entityName, queryName, limit, offset, params);
    } catch (ClassNotFoundException | ParseException e) {
        throw new RestAPIException("Error on executing the query", e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
    ctx.setLoadDynamicAttributes(BooleanUtils.isTrue(dynamicAttributes));

    //override default view defined in queries config
    if (!Strings.isNullOrEmpty(viewName)) {
        MetaClass metaClass = restControllerUtils.getMetaClass(entityName);
        restControllerUtils.getView(metaClass, viewName);
        ctx.setView(viewName);
    }
    List<Entity> entities = dataManager.loadList(ctx);
    entities.forEach(entity -> restControllerUtils.applyAttributesSecurity(entity));

    List<EntitySerializationOption> serializationOptions = new ArrayList<>();
    serializationOptions.add(EntitySerializationOption.SERIALIZE_INSTANCE_NAME);
    if (BooleanUtils.isTrue(returnNulls))
        serializationOptions.add(EntitySerializationOption.SERIALIZE_NULLS);

    String json = entitySerializationAPI.toJson(entities, ctx.getView(),
            serializationOptions.toArray(new EntitySerializationOption[0]));
    json = restControllerUtils.transformJsonIfRequired(entityName, version,
            JsonTransformationDirection.TO_VERSION, json);
    return json;
}

From source file:org.springsource.sinspctr.rest.SInspctrController.java

@RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
@ResponseBody/*  ww w  .  jav  a2  s  . co m*/
public ResponseEntity<String[]> getAllConfigs() {
    try {
        String[] results = ResourceLocator.findResourcesPaths("**/*.xml");
        // TODO convert to HATEOAS response
        return new ResponseEntity<String[]>(results, HttpStatus.OK);
    } catch (IOException e) {
        return new ResponseEntity<String[]>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

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

@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> locatorEndpoint(
        @RequestParam(value = "title", defaultValue = "") String articleTitle,
        @RequestParam(value = "id", defaultValue = "") String itemId,
        @RequestParam(value = "lang") String lang) {

    String language = wikiBrowserProperties.computeLang(lang);

    String thumbnailUrlStr = null;
    if (!articleTitle.equals("")) {
        // Check cache for thumbnail
        thumbnailUrlStr = ThumbnailCache.getThumbnailUrlByTitle(articleTitle, language);

        if (thumbnailUrlStr == null) {
            log.info(//from   www.jav a2s  .  c o m
                    "Thumbnail NOT previously requested for articleTitle: " + articleTitle + ", lang: " + lang);

            thumbnailUrlStr = title2Thumbnail(articleTitle, language);
            ThumbnailCache.setThumbnailUrlByTitle(articleTitle, language, thumbnailUrlStr);
        }
    } else if (!itemId.equals("")) {
        ItemInfoResponse itemInfoResponse = null;

        // Check cache for thumbnail
        thumbnailUrlStr = ThumbnailCache.getThumbnailUrlById(itemId, language);

        if (thumbnailUrlStr == null) {
            log.info("Thumbnail NOT previously requested for itemId: " + itemId + ", lang: " + lang);

            try {
                String url = this.wikiBrowserProperties.getLocatorServiceUrl(itemId, lang);
                itemInfoResponse = new RestTemplate().getForObject(url, ItemInfoResponse.class);

                //log.info(itemInfoResponse.toString());

                if (itemInfoResponse != null) {
                    thumbnailUrlStr = title2Thumbnail(itemInfoResponse.getArticleTitle(), language);
                } else {
                    thumbnailUrlStr = "";
                }

                ThumbnailCache.setThumbnailUrlById(itemId, language, thumbnailUrlStr);

            } catch (Exception e) {
                e.printStackTrace();
                log.info("Caught exception when calling /locator?id=" + itemId + " : " + e);
            }

        }
    }

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

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

/**
 * Lists all input brokers.// w  w w .  ja va2  s . c  o m
 * @param category category (optional)
 * @return array of broker infos
 */
@RequestMapping(value = "/rest/harvester/brokers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BrokerResponse[]> listBrokers(
        @RequestParam(value = "category", required = false) String category) {
    try {
        LOG.debug(
                formatForLog("GET /rest/harvester/brokers%s", category != null ? "&category=" + category : ""));
        Category ctg = null;
        try {
            ctg = Category.parse(category);
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        return new ResponseEntity<>(
                engine.getBrokersService().getBrokersDefinitions(ctg, LocaleContextHolder.getLocale()).stream()
                        .map(d -> BrokerResponse.createFrom(d)).collect(Collectors.toList())
                        .toArray(new BrokerResponse[0]),
                HttpStatus.OK);
    } catch (DataProcessorException ex) {
        LOG.error(String.format("Error listing all brokers"), ex);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:gateway.test.AlertTriggerTests.java

/**
 * Test GET /trigger/*ww w .j a va 2 s  . co  m*/
 */
@Test
public void testListTriggers() {
    // Mock Response
    when(restTemplate.getForObject(anyString(), eq(String.class))).thenReturn("Trigger");

    // Test
    ResponseEntity<?> response = alertTriggerController.getTriggers(0, 10, null, "test", 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.getTriggers(0, 10, null, "test", 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:jetbrains.buildServer.projectPush.PostProjectToSandboxController.java

@Nullable
@Override/*ww  w . j  av  a2  s . c o  m*/
protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response)
        throws Exception {
    if (!isPost(request)) {
        response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value());
        return null;
    }

    final StringBuilder stringBuffer = new StringBuilder();
    try {
        String line;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            stringBuffer.append(line);
    } catch (Exception e) {
        response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
        return null;
    }

    final String projectName = stringBuffer.toString();
    if (projectName.isEmpty()) {
        response.sendError(HttpStatus.BAD_REQUEST.value(), "Project name is empty.");
        return null;
    }

    if (mySettings.isDisabled()) {
        response.sendError(HttpStatus.FORBIDDEN.value(), "Sandbox disabled.");
        return null;
    }

    SUser user;
    user = SessionUser.getUser(request);
    if (user == null) {
        user = myAuthHelper.getAuthenticatedUser(request, response);
    }
    if (user == null)
        return null;

    final Role projectAdminRole = myRolesHelper.findProjectAdminRole();
    if (projectAdminRole == null) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "Failed to locate Project Admin role on the server.");
        return null;
    }

    final SProject project;
    try {
        final String sandboxProjectId = mySettings.getSandboxProjectId();
        final SProject sandboxProject = myProjectManager.findProjectByExternalId(sandboxProjectId);
        if (sandboxProject == null) {
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                    "Failed to locate sandbox project by ID " + sandboxProjectId);
            return null;
        }

        if (sandboxProject.findProjectByName(projectName) != null) {
            response.sendError(HttpStatus.CONFLICT.value(),
                    "Project with name " + projectName + " already exists.");
            return null;
        }

        project = sandboxProject.createProject(
                myProjectIdentifiersManager.generateNewExternalId(null, projectName, null), projectName);
        project.persist();
    } catch (Exception e) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        return null;
    }

    try {
        myRolesHelper.addRole(user, RoleScope.projectScope(project.getProjectId()), projectAdminRole);
    } catch (Throwable throwable) {
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), throwable.getMessage());
        return null;
    }

    response.setStatus(HttpStatus.CREATED.value());
    response.setHeader(HttpHeaders.LOCATION, RESTApiHelper.getProjectURI(project));

    return null;
}

From source file:com.ns.retailmgr.controller.ShopController.java

@ApiOperation(consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, httpMethod = "GET", value = "", response = ShopDetails.class, notes = "Find List of nearby shops for the provided latitude and longitude", responseContainer = "List")
@ApiImplicitParams({//from  ww w.j ava2 s .c  om
        @ApiImplicitParam(name = "customerLatitude", value = "Laitude of Customer's location", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "customerLongitude", value = "Longitude of Customer's location", required = true, dataType = "string", paramType = "query") })
@RequestMapping(method = RequestMethod.GET, consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getNearByShops(
        @RequestParam(required = true, name = "customerLatitude") String customerLatitude,
        @RequestParam(required = true, name = "customerLongitude") String customerLongitude) {
    LOGGER.debug("Started endpoint method {}, params - {}", "getNearByShops",
            new Object[] { customerLatitude, customerLongitude });
    List<ShopDetails> output = null;
    try {
        output = shopService.findShopNearByLatLng(customerLatitude, customerLongitude);
    } catch (Exception e) {
        LOGGER.error("Exception {}", e);
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity<>(output, HttpStatus.OK);
}

From source file:org.coursera.cmbrehm.kewlvideo.server.VideoController.java

@RequestMapping(value = "/video/{id}/data", method = RequestMethod.GET)
public void retrieveVideoData(@PathVariable("id") long id, HttpServletResponse response) {
    try {/* ww  w .  j av a2  s .  c  o m*/
        VideoFileManager vfmgr = VideoFileManager.get();
        Video video = videoList.get(id);
        if (video != null && vfmgr.hasVideoData(video)) {
            OutputStream outStream = response.getOutputStream();
            response.setContentType(video.getContentType());
            vfmgr.copyVideoData(video, outStream);
        } else {
            response.setStatus(HttpStatus.NOT_FOUND.value());
        }
    } catch (IOException iox) {
        try {
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), iox.getMessage());
        } catch (Throwable t) {
        }
    }

}