Example usage for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR

List of usage examples for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR.

Prototype

int SC_INTERNAL_SERVER_ERROR

To view the source code for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR.

Click Source Link

Document

Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request.

Usage

From source file:eu.trentorise.smartcampus.permissionprovider.controller.BasicProfileController.java

@RequestMapping(method = RequestMethod.GET, value = "/basicprofile/me")
public @ResponseBody BasicProfile findProfile(HttpServletResponse response) throws IOException {
    try {/*from w  w w .  j a va  2s  .c  o m*/
        Long user = getUserId();
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }
        return profileManager.getBasicProfileById(user.toString());
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}

From source file:com.devicehive.auth.rest.HttpAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    Optional<String> authHeader = Optional.ofNullable(httpRequest.getHeader(HttpHeaders.AUTHORIZATION));

    String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);
    logger.debug("Security intercepted request to {}", resourcePath);

    try {// ww w .j  a  v a2s .co  m
        if (authHeader.isPresent()) {
            String header = authHeader.get();
            if (header.startsWith(Constants.BASIC_AUTH_SCHEME)) {
                processBasicAuth(header);
            } else if (header.startsWith(Constants.TOKEN_SCHEME)) {
                processJwtAuth(authHeader.get().substring(6).trim());
            }
        } else {
            processAnonymousAuth();
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication instanceof AbstractAuthenticationToken) {
            MDC.put("usrinf", authentication.getName());
            HiveAuthentication.HiveAuthDetails details = createUserDetails(httpRequest);
            ((AbstractAuthenticationToken) authentication).setDetails(details);
        }

        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException e) {
        SecurityContextHolder.clearContext();
        logger.error("Internal authentication service exception", e);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (AuthenticationException e) {
        SecurityContextHolder.clearContext();
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
    } finally {
        MDC.remove("usrinf");
    }
}

From source file:net.sf.j2ep.ProxyFilter.java

/**
 * Implementation of a reverse-proxy. All request go through here. This is
 * the main class where are handling starts.
 * /*  w  ww.j  av a 2  s . c o  m*/
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    //httpRequest.setCharacterEncoding("UTF-8");
    //httpResponse.setCharacterEncoding("UTF-8");
    Server server = (Server) httpRequest.getAttribute("proxyServer");
    if (server == null) {
        server = serverChain.evaluate(httpRequest);
    }

    if (server == null) {
        filterChain.doFilter(request, response);
    } else {
        String uri = server.getRule().process(getURI(httpRequest));
        String url = request.getScheme() + "://" + server.getDomainName() + server.getPath() + uri;
        log.debug("Connecting to " + url);

        ResponseHandler responseHandler = null;

        try {
            httpRequest = server.preExecute(httpRequest);
            responseHandler = executeRequest(httpRequest, url);
            httpResponse = server.postExecute(httpResponse);

            responseHandler.process(httpResponse);
        } catch (HttpException e) {
            log.error("Problem while connecting to server", e);
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            server.setConnectionExceptionRecieved(e);
        } catch (UnknownHostException e) {
            log.error("Could not connection to the host specified", e);
            httpResponse.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            server.setConnectionExceptionRecieved(e);
        } catch (IOException e) {
            log.error("Problem probably with the input being send, either with a Header or the Stream", e);
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (MethodNotAllowedException e) {
            log.error("Incoming method could not be handled", e);
            httpResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            httpResponse.setHeader("Allow", e.getAllowedMethods());
        } finally {
            if (responseHandler != null) {
                responseHandler.close();
            }
        }
    }
}

From source file:com.imaginary.home.cloud.api.call.CommandCall.java

@Override
public void get(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {/*  w  ww  .  j a  va2  s. c om*/
        ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Boolean hasCommands = null;

        if (userId == null) {
            String apiKey = (String) headers.get(RestApi.API_KEY);
            ControllerRelay relay = ControllerRelay.getRelay(apiKey);

            if (relay == null) {
                throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        RestException.INTERNAL_ERROR, "Relay was lost");
            }
            for (PendingCommand cmd : PendingCommand.getCommandsToSend(relay, true)) {
                list.add(toJSON(cmd));
            }
            hasCommands = PendingCommand.hasCommands(relay);
        } else {
            User user = User.getUserByUserId(userId);

            if (user == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.NO_SUCH_USER,
                        "Invalid user access to location");
            }
            String locationId = req.getParameter("locationId");
            Collection<ControllerRelay> relays;

            if (locationId == null) {
                relays = new ArrayList<ControllerRelay>();
                for (Location location : user.getLocations()) {
                    relays.addAll(ControllerRelay.findRelaysInLocation(location));
                }
            } else {
                boolean mine = false;

                for (String lid : user.getLocationIds()) {
                    if (lid.equals(locationId)) {
                        mine = true;
                        break;
                    }
                }
                Location location = Location.getLocation(locationId);

                if (location == null || (!mine && !userId.equals(location.getOwnerId()))) {
                    throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PARAMETER,
                            "No such location: " + locationId);
                }
                relays = ControllerRelay.findRelaysInLocation(location);
            }
            for (ControllerRelay relay : relays) {
                for (PendingCommand cmd : PendingCommand.getCommands(relay)) {
                    list.add(toJSON(cmd));
                }
            }
        }
        if (hasCommands != null) {
            resp.setHeader("x-imaginary-has-commands", String.valueOf(hasCommands));
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().println((new JSONArray(list)).toString());
        resp.getWriter().flush();
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }
}

From source file:bbdn.lti2.LTI2Servlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//  ww w  .j  a  va  2s  .c  o m
        doRequest(request, response);
    } catch (Exception e) {
        String ipAddress = request.getRemoteAddr();
        String uri = request.getRequestURI();
        M_log.warn("General LTI2 Failure URI=" + uri + " IP=" + ipAddress);
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        doErrorJSON(request, response, null, "General failure", e);
    }
}

From source file:com.ephesoft.gxt.batchinstance.server.LogFileDownloadServlet.java

@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    LOGGER.info("Downloading the log files.");
    final String batchInstanceIdentifier = request.getParameter(BatchInfoConstants.BATCH_INSTANCE_IDENTIFIER);
    final String batchInstanceLogFilePath = request.getParameter(BatchInfoConstants.BI_LOG_FILE_PATH);
    LOGGER.debug("Batch Instance Identifier is : ", batchInstanceIdentifier);
    LOGGER.debug("Batch Instance log file path is : ", batchInstanceLogFilePath);

    if (EphesoftStringUtil.isNullOrEmpty(batchInstanceIdentifier)
            || EphesoftStringUtil.isNullOrEmpty(batchInstanceLogFilePath)) {
        LOGGER.error("Either the batch instance identifier or batch instance log file path is null.");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occured in downloading.");
    } else {/*w ww.ja  v  a2  s.c  o  m*/
        final String zipFileName = EphesoftStringUtil.concatenate(batchInstanceIdentifier,
                BatchInfoConstants.UNDER_SCORE, BatchInfoConstants.LOG_FOLDER);
        LOGGER.debug("Zip File Name is ", zipFileName);
        response.setContentType(BatchInfoConstants.APPLICATION_ZIP);
        final String downloadedFile = EphesoftStringUtil.concatenate(zipFileName, BatchInfoConstants.ZIP_EXT,
                "\"\r\n");
        response.setHeader(BatchInfoConstants.CONTENT_DISPOSITION, "attachment; filename=\"" + downloadedFile);
        LOGGER.debug("File path is ", batchInstanceLogFilePath);
        File file = new File(batchInstanceLogFilePath);
        if (file.exists()) {
            ServletOutputStream out = null;
            ZipOutputStream zout = null;
            try {
                out = response.getOutputStream();
                zout = new ZipOutputStream(out);
                FileUtils.zipMultipleFiles(batchInstanceLogFilePath, zout, downloadedFile);
                response.setStatus(HttpServletResponse.SC_OK);
            } catch (IOException ioException) {
                LOGGER.error(ioException, "Unable to download the files.");
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Error occured in downloading.");
            } finally {
                IOUtils.closeQuietly(zout);
                IOUtils.closeQuietly(out);
            }
        } else {
            throw new IOException("Error Occurred in download log file because no log file exists.");
        }
    }
}

From source file:net.myrrix.web.servlets.RecommendToAnonymousServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
        return;/*w  w w  .  ja  va2s  .  co m*/
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    Pair<long[], float[]> itemIDsAndValue;
    try {
        itemIDsAndValue = parseItemValuePairs(pathComponents);
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (NumberFormatException nfe) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nfe.toString());
        return;
    }

    if (itemIDsAndValue.getFirst().length == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No items");
        return;
    }

    long[] itemIDs = itemIDsAndValue.getFirst();
    float[] values = itemIDsAndValue.getSecond();

    MyrrixRecommender recommender = getRecommender();
    RescorerProvider rescorerProvider = getRescorerProvider();
    try {
        IDRescorer rescorer = rescorerProvider == null ? null
                : rescorerProvider.getRecommendToAnonymousRescorer(itemIDs, recommender,
                        getRescorerParams(request));
        Iterable<RecommendedItem> recommended = recommender.recommendToAnonymous(itemIDs, values,
                getHowMany(request), rescorer);
        output(request, response, recommended);
    } catch (NotReadyException nre) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (NoSuchItemException nsie) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
    }
}

From source file:com.iflytek.edu.cloud.frame.spring.DefaultHandlerExceptionResolver.java

@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    MainError mainError = null;/*from   w w  w . j av  a 2 s.c  o  m*/

    Locale locale = (Locale) request.getAttribute(Constants.SYS_PARAM_KEY_LOCALE);
    try {
        if (ex instanceof BindException) {
            mainError = handleBindException((BindException) ex, request, response, handler);
        } else if (ex instanceof MissingParamException) {
            MissingParamException _exception = (MissingParamException) ex;
            mainError = SubErrors.getMainError(SubErrorType.ISV_MISSING_PARAMETER, locale);

            SubError subError = SubErrors.getSubError(SubErrorType.ISV_MISSING_PARAMETER.value(), locale,
                    _exception.getParamName(), _exception.getMessage());
            mainError.addSubError(subError);

        } else if (ex instanceof InvalidParamException) {
            InvalidParamException _exception = (InvalidParamException) ex;
            mainError = SubErrors.getMainError(SubErrorType.ISV_INVALID_PARAMETER, locale);

            SubError subError = SubErrors.getSubError(SubErrorType.ISV_INVALID_PARAMETER.value(), locale,
                    _exception.getParamName(), _exception.getValue(), _exception.getMessage());
            mainError.addSubError(subError);

        } else if (ex instanceof CycoreErrorException) {
            CycoreErrorException _exception = (CycoreErrorException) ex;
            mainError = SubErrors.getMainError(SubErrorType.ISV_CYCORE_ERROR, locale);

            SubError subError = SubErrors.getSubError(SubErrorType.ISV_CYCORE_ERROR.value(), locale,
                    _exception.getErrorMessage(), _exception.getMessage());
            mainError.addSubError(subError);

        } else if (ex instanceof TypeMismatchException) {
            TypeMismatchException _exception = (TypeMismatchException) ex;

            mainError = SubErrors.getMainError(SubErrorType.ISV_PARAMETERS_MISMATCH, locale);
            SubErrorType tempSubErrorType = SubErrorType.ISV_PARAMETERS_MISMATCH;
            SubError subError = SubErrors.getSubError(tempSubErrorType.value(), locale, _exception.getValue(),
                    _exception.getRequiredType().getSimpleName());
            mainError.addSubError(subError);
        } else {
            SubError subError = SubErrors.getSubError(SubErrorType.ISP_SERVICE_UNAVAILABLE.value(),
                    (Locale) request.getAttribute(Constants.SYS_PARAM_KEY_LOCALE),
                    request.getParameter(Constants.SYS_PARAM_KEY_METHOD),
                    NestedExceptionUtils.buildMessage(ex.getMessage(), ex));

            mainError = MainErrors.getError(MainErrorType.SERVICE_CURRENTLY_UNAVAILABLE,
                    (Locale) request.getAttribute(Constants.SYS_PARAM_KEY_LOCALE));
            mainError.addSubError(subError);
        }

        request.setAttribute(Constants.MAIN_ERROR_CODE, mainError.getCode());
        messageConverter.convertData(request, response, mainError);

        logger.warn(ex.getMessage(), ex);
    } catch (Exception handlerException) {
        logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
    }

    return ERROR_MODEL_AND_VIEW;
}

From source file:com.ephesoft.gxt.admin.server.ExportBatchClassDownloadServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    BatchClassService batchClassService = this.getSingleBeanOfType(BatchClassService.class);
    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    BatchClass batchClass = batchClassService.getLoadedBatchClassByIdentifier(req.getParameter(IDENTIFIER));
    String exportLearning = req.getParameter(EXPORT_LEARNING);
    if (batchClass == null) {
        log.error("Incorrect batch class identifier specified.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Incorrect batch class identifier specified.");
    } else {//w  w w .  ja v a 2s .  c o  m
        // Marking exported batch class as 'Advance' as this batch has some advance feature like new FPR.rsp file.
        batchClass.setAdvancedBatchClass(Boolean.TRUE);
        Calendar cal = Calendar.getInstance();
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyy");
        String formattedDate = formatter.format(new Date());
        String zipFileName = batchClass.getIdentifier() + "_" + formattedDate + "_"
                + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.SECOND);

        String tempFolderLocation = exportSerailizationFolderPath + File.separator + zipFileName;
        File copiedFolder = new File(tempFolderLocation);

        if (copiedFolder.exists()) {
            copiedFolder.delete();
        }

        copiedFolder.mkdirs();

        BatchClassUtil.copyModules(batchClass);
        BatchClassUtil.copyDocumentTypes(batchClass);
        BatchClassUtil.copyConnections(batchClass);
        BatchClassUtil.copyScannerConfig(batchClass);
        BatchClassUtil.exportEmailConfiguration(batchClass);
        BatchClassUtil.exportUserGroups(batchClass);
        BatchClassUtil.exportBatchClassField(batchClass);
        BatchClassUtil.exportCMISConfiguration(batchClass);
        // BatchClassUtil.decryptAllPasswords(batchClass);

        File serializedExportFile = new File(
                tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT);
        try {
            SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile));

            File originalFolder = new File(
                    batchSchemaService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier());

            if (originalFolder.isDirectory()) {

                String[] folderList = originalFolder.list();
                Arrays.sort(folderList);

                for (int i = 0; i < folderList.length; i++) {
                    if (folderList[i].endsWith(SERIALIZATION_EXT)) {
                        // skip previous ser file since new is created.
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getTestKVExtractionFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getTestTableFolderName())
                            || FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                                    batchSchemaService.getFileboundPluginMappingFolderName())) {
                        // Skip this folder
                        continue;
                    } else if (FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (FilenameUtils.getName(folderList[i]).equalsIgnoreCase(
                            batchSchemaService.getSearchSampleName()) && Boolean.parseBoolean(exportLearning)) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    } else if (!(FilenameUtils.getName(folderList[i])
                            .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                            || FilenameUtils.getName(folderList[i])
                                    .equalsIgnoreCase(batchSchemaService.getSearchSampleName()))) {
                        FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]),
                                new File(copiedFolder, folderList[i]));
                    }
                }
            }

        } catch (FileNotFoundException e) {
            // Unable to read serializable file
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }
        resp.setContentType("application/x-zip\r\n");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
        ServletOutputStream out = null;
        ZipOutputStream zout = null;
        try {
            out = resp.getOutputStream();
            zout = new ZipOutputStream(out);
            FileUtils.zipDirectory(tempFolderLocation, zout, zipFileName);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            log.error("Error occurred while creating the zip file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        } finally {
            // clean up code
            if (zout != null) {
                zout.close();
            }
            if (out != null) {
                out.flush();
            }
            FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
        }
    }
}