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.adobe.acs.commons.replication.impl.ReplicateVersionServlet.java

@Override
public final void doPost(SlingHttpServletRequest req, SlingHttpServletResponse res)
        throws ServletException, IOException {

    log.debug("Entering ReplicatePageVersionServlet.doPost(..)");

    String[] rootPaths = req.getParameterValues("rootPaths");
    Date date = getDate(req.getParameter("datetimecal"));
    String[] agents = req.getParameterValues("cmbAgent");

    JsonObject obj = validate(rootPaths, agents, date);

    if (!obj.has(KEY_ERROR)) {
        log.debug("Initiating version replication");

        List<ReplicationResult> response = replicateVersion.replicate(req.getResourceResolver(), rootPaths,
                agents, date);// w ww.j a  v  a  2  s.c om

        if (log.isDebugEnabled()) {
            for (final ReplicationResult replicationResult : response) {
                log.debug("Replication result: {} -- {}", replicationResult.getPath(),
                        replicationResult.getStatus());
            }
        }

        JsonArray arr = convertResponseToJson(response);
        obj = new JsonObject();
        obj.add(KEY_RESULT, arr);

    } else {
        log.debug("Did not attempt to replicate version due to issue with input params");

        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        obj.addProperty(KEY_STATUS, KEY_ERROR);
    }

    res.setContentType("application/json");
    res.getWriter().print(obj.toString());
}

From source file:org.keycloak.secretstore.boundary.QRCodeServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String tokenIdAsString = req.getParameter("tokenId");
    String sizeAsString = req.getParameter("size");
    Principal principal = req.getUserPrincipal();

    int size = 250;

    if (null != sizeAsString && !sizeAsString.isEmpty()) {
        try {//w  w w .j av  a2 s.  c om
            size = Integer.parseInt(req.getParameter("size"));
        } catch (Throwable t) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Size is invalid.");
            return;
        }
    }

    if (null == tokenIdAsString || tokenIdAsString.isEmpty()) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Token key is missing.");
        return;
    }

    UUID tokenId;
    try {
        tokenId = UUID.fromString(tokenIdAsString);
    } catch (Throwable t) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Token key is invalid.");
        return;
    }

    Token token = tokenService.getByIdForDistribution(tokenId);
    if (null == token) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Token could not be found.");
        return;
    }

    if (!principal.getName().equals(token.getPrincipal())) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Token could not be found for principal.");
        return;
    }

    String response = token.getId().toString() + "," + token.getSecret();

    if (null != token.getExpiresAt()) {
        response += "," + token.getExpiresAt().toString();
    }

    BitMatrix bitMatrix;
    try {
        QRCodeWriter writer = new QRCodeWriter();
        bitMatrix = writer.encode(response, BarcodeFormat.QR_CODE, size, size);
    } catch (WriterException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while generating the QR Code.");
        return;
    }

    ByteArrayOutputStream pngOut = new ByteArrayOutputStream();
    MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOut);
    byte[] pngData = pngOut.toByteArray();

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType("image/png");
    resp.getOutputStream().write(pngData);
}

From source file:de.afbb.bibo.servlet.server.servlet.MainServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) {
    try {/* www  .j  a v  a 2 s .c o m*/
        processRequest(request, response);
    } catch (final NumberFormatException | IOException e) {
        log.debug(e.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.linuxbox.enkive.web.AttachmentRetrieveServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    final MessageRetrieverService retriever = getMessageRetrieverService();
    final String attachmentUUID = req.getParameter(PARAM_ATTACHMENT_ID);

    try {//w  ww. j  a  va 2s  . c o m
        EncodedContentReadData attachment = retriever.retrieveAttachment(attachmentUUID);

        String filename = req.getParameter(PARAM_FILE_NAME);
        if (filename == null || filename.isEmpty()) {
            filename = attachment.getFilename();
        }
        if (filename == null || filename.isEmpty()) {
            filename = DEFAULT_FILE_NAME;
        }

        String mimeType = req.getParameter(PARAM_MIME_TYPE);
        if (mimeType == null || mimeType.isEmpty()) {
            mimeType = attachment.getMimeType();
        }

        // is there a purpose to the nested trys?
        try {
            if (mimeType != null) {
                resp.setContentType(mimeType);
            }
            resp.setCharacterEncoding("utf-8");
            resp.setHeader("Content-disposition",
                    "attachment;  filename=" + MimeUtility.quote(filename, HeaderTokenizer.MIME));

            final InputStream in = attachment.getBinaryContent();
            final OutputStream out = resp.getOutputStream();

            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        } catch (ContentException e) {
            LOGGER.error("error transferring attachment  " + attachmentUUID, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "error transferring attachment " + attachmentUUID + "; see server logs");
        }
    } catch (CannotRetrieveException e) {
        LOGGER.error("error retrieving attachment " + attachmentUUID, e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "error retrieving attachment " + attachmentUUID + "; see server logs");
    }
}

From source file:com.haulmont.cuba.web.controllers.LogDownloadController.java

@RequestMapping(value = "/log/{file:[a-zA-Z0-9\\.\\-_]+}", method = RequestMethod.GET)
public void getLogFile(HttpServletResponse response, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "full", required = false) Boolean downloadFull,
        @PathVariable(value = "file") String logFileName) throws IOException {
    UserSession userSession = getSession(sessionId, response);
    if (userSession == null)
        return;/*  w  ww.j  a  v  a  2  s .  c  om*/

    if (!userSession.isSpecificPermitted("cuba.gui.administration.downloadlogs")) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // security check, handle only valid file name
    String filename = FilenameUtils.getName(logFileName);

    try {
        File logFile = logControl.getLogFile(filename);

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", "application/zip");
        response.setHeader("Pragma", "no-cache");

        response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".zip");

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            if (BooleanUtils.isTrue(downloadFull)) {
                LogArchiver.writeArchivedLogToStream(logFile, outputStream);
            } else {
                LogArchiver.writeArchivedLogTailToStream(logFile, outputStream);
            }
        } catch (RuntimeException | IOException ex) {
            log.error("Unable to download file", ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }

    } catch (LogFileNotFoundException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:io.druid.server.AsyncQueryForwardingServlet.java

private static void handleException(HttpServletResponse response, ObjectMapper objectMapper,
        Exception exception) throws IOException {
    if (!response.isCommitted()) {
        final String errorMessage = exception.getMessage() == null ? "null exception" : exception.getMessage();

        response.resetBuffer();/*  w  ww  .  j  a va  2  s  . co  m*/
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));
    }
    response.flushBuffer();
}

From source file:com.haulmont.cuba.portal.controllers.LogDownloadController.java

@RequestMapping(value = "/log/{file:[a-zA-Z0-9\\.\\-_]+}", method = RequestMethod.GET)
public void getLogFile(HttpServletResponse response, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "full", required = false) Boolean downloadFull,
        @PathVariable(value = "file") String logFileName) throws IOException {
    UserSession userSession = getSession(sessionId, response);
    if (userSession == null)
        return;/*from ww  w  . j  av a  2s  .co m*/

    if (!userSession.isSpecificPermitted("cuba.gui.administration.downloadlogs")) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // security check, handle only valid file name
    String filename = FilenameUtils.getName(logFileName);

    try {
        File logFile = logControl.getLogFile(filename);

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", "application/zip");
        response.setHeader("Pragma", "no-cache");

        response.setHeader("Content-Disposition", "attachment; filename=" + filename);

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            if (BooleanUtils.isTrue(downloadFull)) {
                LogArchiver.writeArchivedLogToStream(logFile, outputStream);
            } else {
                LogArchiver.writeArchivedLogTailToStream(logFile, outputStream);
            }
        } catch (RuntimeException | IOException ex) {
            log.error("Unable to assemble zipped log file", ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }

    } catch (LogFileNotFoundException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.mypackage.spring.controllers.ContactsSpringController.java

@RequestMapping(value = "/contacts/{id}", method = RequestMethod.GET)
public ModelAndView getAContact(@PathVariable String id) {
    ModelAndView modelAndView = new ModelAndView();
    try {/*from   w  w w .  ja v a2  s.  c o  m*/
        Contact contact = contactsController.getContact(id);

        modelAndView.addObject("contact", contact);
        List<Email> emailsList = contactsController.retrieveAllEmails(id);
        modelAndView.addObject("emailList", emailsList);
        modelAndView.addObject("contactId", id);
        modelAndView.setViewName("/viewContact.jsp");

    } catch (DalException ex) {
        logger.error("A database error occured.", ex);
        modelAndView.addObject("errorCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        modelAndView.addObject("errorMessage", "There was a an internal database error.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (MalformedIdentifierException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_BAD_REQUEST);
        modelAndView.addObject("errorMessage", "An error occured because of a malformed id (caused by id = "
                + id + "). Please use only numeric values.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (ResourceNotFoundException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_NOT_FOUND);
        modelAndView.addObject("errorMessage", "Requested contact (with id = " + id + ") does not exist.");
        modelAndView.setViewName("/errorPage.jsp");
    }
    return modelAndView;
}

From source file:no.smint.anthropos.authentication.TokenAuthenticationProvider.java

private Person getLoggedInUser(String username) {
    System.out.println(username);
    Person person = new Person();
    try {// www .j  a v a  2  s  .  c o  m
        person = search(username).get(0);
    } catch (NamingException e) {
        e.printStackTrace();
    }
    if (person == null) {
        throw new RestException("User was logged in, but not found in our database!",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return person;
}

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

@Before
public void setUp() {

    ArchaiusConfig.initialize();/*from  w  w  w.  j  av  a 2  s.c  o m*/

    wireMockHost = "localhost:" + wireMock.port();

    serviceConfig = context.registerInjectActivateService(new ResilientHttpServiceConfig(),
            getServiceConfigProperties(wireMockHost));

    httpClientFactory = context.registerInjectActivateService(new HttpClientFactoryImpl());
    underTest = context.registerInjectActivateService(new ResilientHttpImpl());

    // setup wiremock
    wireMock.stubFor(get(urlEqualTo(HTTP_200_URI)).willReturn(aResponse()
            .withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8).withBody(DUMMY_CONTENT)));
    wireMock.stubFor(
            get(urlEqualTo(HTTP_404_URI)).willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));
    wireMock.stubFor(get(urlEqualTo(HTTP_500_URI))
            .willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
    wireMock.stubFor(get(urlEqualTo(CONNECT_TIMEOUT_URI)).willReturn(aResponse()
            .withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8).withBody(DUMMY_CONTENT)));
    wireMock.stubFor(get(urlEqualTo(RESPONSE_TIMEOUT_URI))
            .willReturn(aResponse().withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8)
                    .withBody(DUMMY_CONTENT).withFixedDelay(1000)));
}