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:com.amazon.dtasdk.v2.servlets.InstantAccessServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    try {/*from w ww.j  a v a  2 s  .  com*/
        Request req = new Request(request);

        if (!signer.verify(req, getCredentialStore())) {
            throw new SigningException("Request validation failed.");
        }

        String requestBody = req.getBody();

        // deserialize the content to a InstantAccessRequest object so we can check which operation is going
        // to be called
        InstantAccessRequest iaRequest = serializer.decode(requestBody, InstantAccessRequest.class);

        // process the request according to the operation
        InstantAccessResponse<?> iaResponse = processOperation(iaRequest.getOperation(), requestBody);

        response.setStatus(HttpServletResponse.SC_OK);
        response.getOutputStream().write(serializer.encode(iaResponse).getBytes(CHARSET));
    } catch (IOException e) {
        log.error("Unable to read the request.", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (SigningException e) {
        log.error("Unable to verify the request against the credential store.", e);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } catch (SerializationException e) {
        log.error("Serialization error.", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (Exception e) {
        log.error("Unable to process the request.", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:net.big_oh.common.web.servlets.mime.MimeServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.info(getServletConfig().getServletName() + " invoked.  Requested mime resource: "
            + req.getParameter(REQUESTED_RESOURCE_NAME));

    // Get the name of the requested resource
    String requestedResourceName = req.getParameter(REQUESTED_RESOURCE_NAME);

    if (requestedResourceName == null || requestedResourceName.equals("")) {
        logger.error("Called " + getServletConfig().getServletName() + " without providing a parameter for '"
                + REQUESTED_RESOURCE_NAME + "'");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;//from ww  w  . j a  v a  2s .c  o  m
    }

    // Ensure that the user is allowed to access the requested resource
    if (!isCanUserAccessRequestedResource(requestedResourceName, req.getSession(true))) {
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Get a byte array representation of the resource to be returned in the
    // response
    byte[] resourceBytes = getMimeResourceBytes(requestedResourceName);

    if (resourceBytes == null || resourceBytes.length == 0) {
        logger.error("No resource found under the name \"" + requestedResourceName + "\"");
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Set content length for the response
    resp.setContentLength(resourceBytes.length);

    // Get the MIME type for the resource
    String mimeType = getMimeType(requestedResourceName);

    if (mimeType == null || mimeType.equals("")) {
        logger.error("Failed to get MIME type for the requested resource.");
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Set the content type for the response
    resp.setContentType(mimeType);

    // Control the HTTP caching of the response
    // This setting controls how frequently the cached resource is
    // revalidated (which is not necessarily the same as reloaded)
    resp.setHeader("Cache-Control", "max-age=" + getMaxAgeInSeconds(requestedResourceName));

    // Use streams to return the requested resource
    ByteArrayInputStream in = new ByteArrayInputStream(resourceBytes);
    OutputStream out = resp.getOutputStream();

    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }

    in.close();
    out.close();

}

From source file:com.cognifide.cq.cqsm.core.servlets.ScriptRunServlet.java

@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {
    ResourceResolver resolver = request.getResourceResolver();
    final String searchPath = request.getParameter("file");
    final String modeName = request.getParameter("mode");

    if (StringUtils.isEmpty(searchPath)) {
        ServletUtils.writeMessage(response, "error", "Please set the script file name: -d \"file=[name]\"");
        return;/*from  w  w w. ja va 2s . c  o  m*/
    }

    if (StringUtils.isEmpty(modeName)) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ServletUtils.writeMessage(response, "error", "Running mode not specified.");
        return;
    }

    final Script script = scriptFinder.find(searchPath, resolver);
    if (script == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        ServletUtils.writeMessage(response, "error", String.format("Script not found: %s", searchPath));
        return;
    }

    try {
        final Mode mode = Mode.fromString(modeName, Mode.DRY_RUN);
        final Progress progressLogger = scriptManager.process(script, mode, resolver);

        if (progressLogger.isSuccess()) {
            ServletUtils.writeJson(response, ProgressHelper.toJson(progressLogger.getEntries()));
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            ServletUtils.writeJson(response, ProgressHelper.toJson(progressLogger.getLastError()));
        }

    } catch (RepositoryException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error", String
                .format("Script cannot be executed because of" + " repository error: %s", e.getMessage()));
    }
}

From source file:com.lyncode.oai.proxy.ProxyDataProvider.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ProxyIdentify identify = new ProxyIdentify(req);
    ProxySetRepository listsets = new ProxySetRepository();
    ProxyItemRepository itemRepository = new ProxyItemRepository();

    try {/*from  ww  w  .j  a va 2  s.  co  m*/
        XOAIManager.initialize("config" + File.separator + "xoai");
        log.debug("Creating XOAI Data Provider Instance");

        log.debug("Requested context: " + req.getPathInfo().replace("/", ""));

        OAIDataProvider dataprovider = new OAIDataProvider(req.getPathInfo().replace("/", ""), identify,
                listsets, itemRepository);
        log.debug("Reading parameters from request");

        OutputStream out = resp.getOutputStream();
        OAIRequestParameters parameters = new OAIRequestParameters();
        parameters.setFrom(req.getParameter("from"));
        parameters.setUntil(req.getParameter("until"));
        parameters.setSet(req.getParameter("set"));
        parameters.setVerb(req.getParameter("verb"));
        parameters.setMetadataPrefix(req.getParameter("metadataPrefix"));
        parameters.setIdentifier(req.getParameter("identifier"));
        parameters.setResumptionToken(req.getParameter("resumptionToken"));

        resp.setContentType("application/xml");

        dataprovider.handle(parameters, out);

        out.flush();
        out.close();
    } catch (InvalidContextException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND,
                "Requested OAI context \"" + req.getPathInfo().replace("/", "") + "\" does not exist");
    } catch (OAIException e) {
        log.error(e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occurred, please, contact the develop team development@lyncode.com");
    } catch (com.lyncode.xoai.dataprovider.exceptions.ConfigurationException e) {
        log.error(e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occurred, please, contact the develop team development@lyncode.com");
    }
}

From source file:ru.org.linux.exception.ExceptionResolver.java

/**
 *   ? ?./*ww w.j a  v  a  2 s  .  c o m*/
 *  ? ??  ? .
 *
 * @param request   ?  web-
 * @param response   web-
 * @param handler  ,    ?
 * @param ex       ?
 * @return  web-
 */
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
    // http://stackoverflow.com/questions/8271843/how-to-exclude-clientabortexception-from-simplemappingexceptionresolver
    if (ex != null && ex.getClass().getName().endsWith(".ClientAbortException") && response.isCommitted()) {
        return null;
    }

    ModelAndView modelAndView = super.doResolveException(request, response, handler, ex);
    if (modelAndView == null) {
        modelAndView = new ModelAndView("errors/common");
        prepareModelForCommonException(modelAndView, request, ex);
    }
    modelAndView.addObject("exception", ex);
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return modelAndView;
}

From source file:com.haulmont.cuba.core.controllers.FileDownloadController.java

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserSession userSession = getSession(request, response);
    if (userSession == null)
        return;//from ww  w.  ja va  2  s .c  o m

    AppContext.setSecurityContext(new SecurityContext(userSession));
    try {
        File file = null;
        FileDescriptor fd = null;
        if (request.getParameter("p") != null)
            file = getFile(request, response);
        else
            fd = getFileDescriptor(request, response);
        if (fd == null && file == null)
            return;

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setIntHeader("Expires", -1);
        response.setHeader("Content-Type", FileTypesHelper.DEFAULT_MIME_TYPE);

        InputStream is = null;
        ServletOutputStream os = null;
        try {
            is = fd != null ? fileStorage.openStream(fd) : FileUtils.openInputStream(file);
            os = response.getOutputStream();
            IOUtils.copy(is, os);
            os.flush();
        } catch (FileStorageException e) {
            log.error("Unable to download file", e);
            response.sendError(e.getType().getHttpStatus());
        } catch (Exception ex) {
            log.error("Unable to download file", ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    } finally {
        AppContext.setSecurityContext(null);
    }
}

From source file:com.linuxbox.enkive.web.search.AbstractSearchListServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String sortBy = null;//  w w  w.  j av  a  2s  . com
    int sortDir = -1;

    resp.setCharacterEncoding("UTF-8");
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Retrieving search list");
    try {
        WebPageInfo pageInfo = new WebPageInfo(
                WebScriptUtils.cleanGetParameter(req, WebPageInfo.PAGE_POSITION_PARAMETER),
                WebScriptUtils.cleanGetParameter(req, WebPageInfo.PAGE_SIZE_PARAMETER));
        sortBy = WebScriptUtils.cleanGetParameter(req, "sortBy");
        if (sortBy == null || sortBy.isEmpty())
            sortBy = WebConstants.SORTBYDATE;
        String sortDirString = WebScriptUtils.cleanGetParameter(req, "sortDir");
        if (sortDirString != null)
            sortDir = Integer.parseInt(sortDirString);

        JSONObject jObject = new JSONObject();
        jObject.put(WebConstants.DATA_TAG, getWorkspaceSearches(pageInfo, sortBy, sortDir));
        jObject.put(WebPageInfo.PAGING_LABEL, pageInfo.getPageJSON());
        String jsonString = jObject.toString();
        resp.getWriter().write(jsonString);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Returned search list");
    } catch (JSONException e) {
        LOGGER.error("Error retrieving search list", e);
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp);
        throw new EnkiveServletException("Unable to serialize JSON");
    }
}

From source file:at.gv.egiz.bku.online.webapp.ResultServlet.java

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, java.io.IOException {

    BindingProcessorManager bindingProcessorManager = (BindingProcessorManager) getServletContext()
            .getAttribute("bindingProcessorManager");
    if (bindingProcessorManager == null) {
        String msg = "Configuration error: BindingProcessorManager missing!";
        log.error(msg);/*from  ww  w .  j  a  v a 2s  .  com*/
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        return;
    }

    Configuration conf = ((BindingProcessorManagerImpl) bindingProcessorManager).getConfiguration();
    if (conf == null)
        log.error("No configuration");
    else
        MoccaParameterBean.setP3PHeader(conf, resp);

    Id id = (Id) req.getAttribute("id");
    BindingProcessor bindingProcessor = null;
    if (id == null || !((bindingProcessor = bindingProcessorManager
            .getBindingProcessor(id)) instanceof HTTPBindingProcessor)) {
        resp.sendRedirect(expiredPageUrl);
        return;
    }

    HTTPBindingProcessor bp = (HTTPBindingProcessor) bindingProcessor;

    OutputStream outputStream = null;
    try {
        String redirectUrl = bp.getRedirectURL();
        if (redirectUrl != null && !redirectUrl.trim().isEmpty()) {
            log.info("Sending (deferred) redirect to {}.", redirectUrl);
            resp.sendRedirect(redirectUrl);
            // TODO Couldn't we simply discard the output?
            outputStream = new NullOutputStream();
        } else {
            log.debug("Setting HTTP status code {}.", bp.getResponseCode());
            resp.setStatus(bp.getResponseCode());
            resp.setHeader("Cache-Control", "no-store"); // HTTP 1.1
            resp.setHeader("Pragma", "no-cache"); // HTTP 1.0
            resp.setDateHeader("Expires", 0);
            Map<String, String> responseHeaders = bp.getResponseHeaders();
            for (Entry<String, String> header : responseHeaders.entrySet()) {
                String key = header.getKey();
                String value = header.getValue();
                log.debug("Setting response header {}: {}.", key, value);
                resp.setHeader(key, value);
            }
            resp.setContentType(bp.getResultContentType());
            log.info("Sending result.");
            outputStream = resp.getOutputStream();
        }
        bp.writeResultTo(outputStream, responseEncoding);
    } finally {
        if (outputStream != null)
            outputStream.close();
        bindingProcessorManager.removeBindingProcessor(id);
    }
}

From source file:io.wcm.caravan.io.http.impl.CaravanHttpClientHystrixTest.java

@Before
public void setUp() {

    ArchaiusConfig.initialize();/*from   w  w  w.j a va  2 s.co m*/
    context.registerInjectActivateService(new CaravanHttpClientConfig(),
            Collections.singletonMap(CaravanHttpClientConfig.SERVLET_CLIENT_ENABLED, true));
    context.registerInjectActivateService(new SimpleLoadBalancerFactory());
    context.registerInjectActivateService(new LoadBalancerCommandFactory());
    context.registerInjectActivateService(new HttpClientFactoryImpl());
    context.registerInjectActivateService(new ServletHttpClient());
    context.registerInjectActivateService(new ApacheHttpClient());
    context.registerInjectActivateService(new RibbonHttpClient());
    underTest = context.registerInjectActivateService(new CaravanHttpClientImpl());

    host = "localhost:" + server.port();

    server.stubFor(get(urlEqualTo(HTTP_200_URI)).willReturn(aResponse()
            .withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8).withBody("success")));
    server.stubFor(
            get(urlEqualTo(HTTP_404_URI)).willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));
    server.stubFor(get(urlEqualTo(HTTP_500_URI))
            .willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));

    context.registerInjectActivateService(new CaravanHttpServiceConfig(),
            ImmutableMap.<String, Object>builder()
                    .put(CaravanHttpServiceConfig.SERVICE_ID_PROPERTY, SERVICE_NAME)
                    .put(CaravanHttpServiceConfig.RIBBON_HOSTS_PROPERTY, host)
                    .put(CaravanHttpServiceConfig.RIBBON_MAXAUTORETRIES_PROPERTY, 0)
                    .put(CaravanHttpServiceConfig.RIBBON_MAXAUTORETRIESNEXTSERVER_PROPERTY, 0)
                    .put(CaravanHttpServiceConfig.HYSTRIX_CIRCUITBREAKER_REQUESTVOLUMETHRESHOLD_PROPERTY, 20)
                    .put(CaravanHttpServiceConfig.HYSTRIX_CIRCUITBREAKER_ERRORTHRESHOLDPERCENTAGE_PROPERTY, 50)
                    .build());
}

From source file:org.cerberus.servlet.publi.ExecuteNextInQueue.java

/**
 * Process request for both GET and POST method.
 * /*from w w w .  ja  v a2 s  .  c  o m*/
 * <p>
 * Request processing is divided in two parts:
 * <ol>
 * <li>Getting the next test case to be executed;</li>
 * <li>Execute it.</li>
 * </ol>
 * </p>
 * 
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
private void processRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // Part 1: Getting the next test case to be executed.
    TestCaseExecutionInQueue lastInQueue = null;
    try {
        lastInQueue = inQueueService.getNextAndProceed();
    } catch (CerberusException ce) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ce.getMessage());
        return;
    }

    if (lastInQueue == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No execution in queue");
        }
        return;
    }

    // Part 2: Execute it
    executeNext(lastInQueue, req, resp);
}