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:de.mpg.imeji.presentation.upload.UploadServlet.java

/**
 * {@inheritDoc}/*ww  w. j a v  a 2  s .  c o m*/
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final UploadItem upload = doUpload(req);
    final SessionBean session = getSession(req);
    final String uploadId = req.getParameter("uploadId");
    final License license = getLicense(upload);
    try {
        final User user = getUser(req, session);
        final CollectionImeji col = retrieveCollection(req, user);
        if (!StringHelper.isNullOrEmptyTrim(uploadId)) {
            itemService.uploadToStaging(uploadId, upload.getFile(), upload.getFilename(), col, user);
        } else {
            Item item = ImejiFactory.newItem(col);
            item.setLicenses(Arrays.asList(license));
            itemService.createWithFile(item, upload.getFile(), upload.getFilename(), col, user);
        }
        writeResponse(resp, "");
    } catch (final AuthenticationError e) {
        writeResponse(resp, e.getMessage());
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } catch (final ImejiException e) {
        LOGGER.error("Error uploading File", e);
        writeResponse(resp, e.getMessage());
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:nl.surfnet.mujina.saml.SSOSuccessAuthnResponder.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AuthnRequestInfo info = (AuthnRequestInfo) request.getSession()
            .getAttribute(AuthnRequestInfo.class.getName());

    if (info == null) {
        logger.warn("Could not find AuthnRequest on the request.  Responding with SC_FORBIDDEN.");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*from w  ww .  j  av a 2s .  co m*/
    }

    logger.debug("AuthnRequestInfo: {}", info);

    SimpleAuthentication authToken = (SimpleAuthentication) SecurityContextHolder.getContext()
            .getAuthentication();
    DateTime authnInstant = new DateTime(request.getSession().getCreationTime());

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(idpConfiguration.getEntityID()));
    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    Credential signingCredential = null;
    try {
        signingCredential = credentialResolver.resolveSingle(criteriaSet);
    } catch (org.opensaml.xml.security.SecurityException e) {
        logger.warn("Unable to resolve EntityID while signing", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    Validate.notNull(signingCredential);

    AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator(signingCredential,
            idpConfiguration.getEntityID(), timeService, idService, idpConfiguration);
    EndpointGenerator endpointGenerator = new EndpointGenerator();

    final String remoteIP = request.getRemoteAddr();
    String attributeJson = null;

    if (null != request.getCookies()) {
        for (Cookie current : request.getCookies()) {
            if (current.getName().equalsIgnoreCase("mujina-attr")) {
                logger.info("Found a attribute cookie, this is used for the assertion response");
                attributeJson = URLDecoder.decode(current.getValue(), "UTF-8");
            }
        }
    }
    String acsEndpointURL = info.getAssertionConsumerURL();
    if (idpConfiguration.getAcsEndpoint() != null) {
        acsEndpointURL = idpConfiguration.getAcsEndpoint().getUrl();
    }
    Response authResponse = authnResponseGenerator.generateAuthnResponse(remoteIP, authToken, acsEndpointURL,
            responseValidityTimeInSeconds, info.getAuthnRequestID(), authnInstant, attributeJson,
            info.getEntityId());
    Endpoint endpoint = endpointGenerator.generateEndpoint(
            org.opensaml.saml2.metadata.AssertionConsumerService.DEFAULT_ELEMENT_NAME, acsEndpointURL, null);

    request.getSession().removeAttribute(AuthnRequestInfo.class.getName());

    String relayState = request.getParameter("RelayState");

    //we could use a different adapter to send the response based on request issuer...
    try {
        adapter.sendSAMLMessage(authResponse, endpoint, response, relayState, signingCredential);
    } catch (MessageEncodingException mee) {
        logger.error("Exception encoding SAML message", mee);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
}

From source file:org.dspace.webmvc.controller.ResourceController.java

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path)) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    }/*from  ww  w . ja  v a  2 s  .co m*/

    final URL url;
    try {
        url = req.getSession().getServletContext().getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }

    final String mimeType = getMimeType(req, path);

    final String realpath = req.getSession().getServletContext().getRealPath(path);
    if (url != null && realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile()) {
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        } else {
            return new StaticFile(f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url);
        }
    } else {
        ClassPathResource cpr = new ClassPathResource(path);
        if (cpr.exists()) {
            URL cprURL = null;
            try {
                cprURL = cpr.getURL();

                // Try as a JAR Entry
                final ZipEntry ze = ((JarURLConnection) cprURL.openConnection()).getJarEntry();
                if (ze != null) {
                    if (ze.isDirectory()) {
                        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                    } else {
                        return new StaticFile(ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req),
                                cprURL);
                    }
                } else {
                    // Unexpected?
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                }
            } catch (ClassCastException e) {
                // Unknown resource type
                if (url != null) {
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                } else {
                    return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
                }
            } catch (IOException e) {
                return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
            }
        } else {
            return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");
        }
    }
}

From source file:eu.rethink.lhcb.broker.servlet.WellKnownServlet.java

private void handleRequest(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    // add header for cross domain stuff
    resp.addHeader("Access-Control-Allow-Origin", "*");
    String host = req.getHeader("X-Forwarded-Host");
    if (host == null)
        host = req.getHeader("Host");

    // setting external host here helps BrokerWebSocketListener to return info about HTTP interface
    // Broker might not know how it is accessible. This is a workaround for it
    LHCBBroker.externalHost = host;//w w w  .ja va 2  s .c om
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.start(() -> {
        ServletRequest aReq = asyncContext.getRequest();
        String payload = null;
        try {
            payload = IOUtils.toString(aReq.getReader());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String finalPayload = payload;

        Map<String, String[]> params = aReq.getParameterMap();
        LOG.debug("payload: {}\r\nparams: {}", payload, params);

        RequestCallback cb = new RequestCallback() {

            @Override
            public void response(Message msg) {
                resp.setStatus(HttpServletResponse.SC_OK);
                try {
                    asyncContext.getResponse().getWriter().write(msg.toString());
                    asyncContext.getResponse().getWriter().flush();
                    asyncContext.complete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Exception e) {
                String error = "Request failed.\r\npayload: " + finalPayload + "\r\nparams: " + params;
                LOG.error(error + "\r\nreason: " + e.getLocalizedMessage(),
                        e instanceof InvalidMessageException ? null : e);
                if (e instanceof InvalidMessageException) {
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                } else {
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

                }
                completeAsyncContext(asyncContext, error + "\r\nreason: " + e.getLocalizedMessage());
            }
        };

        try {
            Message msg = null;

            if (payload.length() > 0) {
                msg = Message.fromString(payload);
            } else {
                msg = Message.fromParams(params);
            }

            requestHandler.handleRequest(msg, cb);
        } catch (InvalidMessageException e) {
            cb.error(e);
        }
    });
}

From source file:com.webpagebytes.cms.utility.HttpServletToolbox.java

public void writeBodyResponseAsJson(HttpServletResponse response, org.json.JSONObject data,
        Map<String, String> errors) {

    try {//from   w  w w.  j a va 2  s . com
        org.json.JSONObject jsonResponse = new org.json.JSONObject();
        org.json.JSONObject jsonErrors = new org.json.JSONObject();
        if (errors == null || errors.keySet().size() == 0) {
            jsonResponse.put("status", "OK");
        } else {
            jsonResponse.put("status", "FAIL");
            for (String key : errors.keySet()) {
                jsonErrors.put(key, errors.get(key));
            }
        }
        jsonResponse.put("errors", jsonErrors);
        jsonResponse.put("payload", data);
        String jsonString = jsonResponse.toString();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream writer = response.getOutputStream();
        byte[] utf8bytes = jsonString.getBytes("UTF-8");
        writer.write(utf8bytes);
        response.setContentLength(utf8bytes.length);
        writer.flush();

    } catch (Exception e) {
        try {
            String errorResponse = "{\"status\":\"FAIL\",\"payload\":\"{}\",\"errors\":{\"reason\":\"WB_UNKNOWN_ERROR\"}}";
            ServletOutputStream writer = response.getOutputStream();
            response.setContentType("application/json");
            byte[] utf8bytes = errorResponse.getBytes("UTF-8");
            response.setContentLength(utf8bytes.length);
            writer.write(utf8bytes);
            writer.flush();
        } catch (IOException ioe) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}

From source file:io.wcm.caconfig.editor.impl.ConfigDataServlet.java

@Override
protected void doGet(@NotNull SlingHttpServletRequest request, @NotNull SlingHttpServletResponse response)
        throws ServletException, IOException {
    if (!editorConfig.isEnabled()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;// w w  w  . j  a v a2s. c  om
    }

    // get parameters
    String configName = request.getParameter(RP_CONFIGNAME);
    if (StringUtils.isBlank(configName)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    boolean collection = BooleanUtils.toBoolean(request.getParameter(RP_COLLECTION));

    // output configuration
    try {
        JSONObject result = getConfiguration(request.getResource(), configName, collection);
        if (result == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            response.setContentType("application/json;charset=" + CharEncoding.UTF_8);
            response.getWriter().write(result.toString());
        }
    }
    /*CHECKSTYLE:OFF*/ catch (Exception ex) { /*CHECKSTYLE:ON*/
        log.error("Error getting configuration for " + configName + (collection ? "[col]" : ""), ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:org.openmrs.module.openhmis.inventory.web.controller.JasperReportController.java

private String renderStockCardReport(int reportId, WebRequest request, HttpServletResponse response)
        throws IOException {
    int itemId;//from w w w.j  a  va2 s.c  o  m
    String itemName;
    Date beginDate = null, endDate = null;

    String temp = request.getParameter("itemUuid");
    if (!StringUtils.isEmpty(temp)) {
        IItemDataService itemService = Context.getService(IItemDataService.class);
        Item item = itemService.getByUuid(temp);
        if (item != null) {
            itemId = item.getId();
            itemName = item.getName();
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "No item with UUID '" + temp + "' could be found.");
            return null;
        }
    } else {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The item uuid must be defined.");
        return null;
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    temp = request.getParameter("beginDate");
    if (!StringUtils.isEmpty(temp)) {
        try {
            beginDate = dateFormat.parse(temp);
        } catch (Exception ex) {
            // Whatevs... dealing with stupid checked exceptions
        }
    }

    temp = request.getParameter("endDate");
    if (!StringUtils.isEmpty(temp)) {
        try {
            endDate = dateFormat.parse(temp);
        } catch (Exception ex) {
            // Whatevs... dealing with stupid checked exceptions
        }
    }

    if (beginDate == null || endDate == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The begin and end dates must be defined.");
        return null;
    }

    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("itemId", itemId);
    params.put("beginDate", beginDate);
    params.put("endDate", endDate);

    return renderReport(reportId, params, "Item Stock Card - " + itemName, response);
}

From source file:org.apache.cxf.fediz.spring.web.FederationAuthenticationEntryPoint.java

public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response,
        final AuthenticationException authenticationException) throws IOException, ServletException {

    FedizContext fedContext = federationConfig.getFedizContext();
    LOG.debug("Federation context: {}", fedContext);

    if (servletRequest.getRequestURL().indexOf(FederationConstants.METADATA_PATH_URI) != -1
            || servletRequest.getRequestURL().indexOf(getMetadataURI(fedContext)) != -1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Metadata document requested");
        }/*from  w w  w .j  av a 2s . c om*/
        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();

        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());
        try {
            Document metadata = wfProc.getMetaData(servletRequest, fedContext);
            out.write(DOM2Writer.nodeToString(metadata));
            return;
        } catch (Exception ex) {
            LOG.warn("Failed to get metadata document: " + ex.getMessage());
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    String redirectUrl = null;
    try {
        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());
        RedirectionResponse redirectionResponse = wfProc.createSignInRequest(servletRequest, fedContext);
        redirectUrl = redirectionResponse.getRedirectionURL();

        if (redirectUrl == null) {
            LOG.warn("Failed to create SignInRequest. Redirect URL null");
            throw new ServletException("Failed to create SignInRequest. Redirect URL null");
        }

        Map<String, String> headers = redirectionResponse.getHeaders();
        if (!headers.isEmpty()) {
            for (String headerName : headers.keySet()) {
                response.addHeader(headerName, headers.get(headerName));
            }
        }

    } catch (ProcessingException ex) {
        LOG.warn("Failed to create SignInRequest", ex);
        throw new ServletException("Failed to create SignInRequest: " + ex.getMessage());
    }

    preCommence(servletRequest, response);
    if (LOG.isInfoEnabled()) {
        LOG.info("Redirecting to IDP: " + redirectUrl);
    }
    response.sendRedirect(redirectUrl);
}

From source file:eu.freme.broker.security.AuthenticationFilter.java

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

    Optional<String> username = Optional.fromNullable(httpRequest.getHeader("X-Auth-Username"));
    Optional<String> password = Optional.fromNullable(httpRequest.getHeader("X-Auth-Password"));
    Optional<String> token = Optional.fromNullable(httpRequest.getHeader("X-Auth-Token"));

    if (httpRequest.getParameter("token") != null) {
        token = Optional.fromNullable(httpRequest.getParameter("token"));
    }/*w w  w.j av  a 2  s  .c o  m*/

    String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);

    try {
        if (postToAuthenticate(httpRequest, resourcePath)) {
            logger.debug("Trying to authenticate user {} by X-Auth-Username method", username);
            processUsernamePasswordAuthentication(httpResponse, username, password);
            return;
        }

        if (token.isPresent()) {
            logger.debug("Trying to authenticate user by X-Auth-Token method. Token: {}", token);
            processTokenAuthentication(token);
        }

        logger.debug("AuthenticationFilter is passing request down the filter chain");
        addSessionContextToLogging();
        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) {
        SecurityContextHolder.clearContext();
        logger.error("Internal authentication service exception", internalAuthenticationServiceException);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (AuthenticationException authenticationException) {
        SecurityContextHolder.clearContext();
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
    } finally {
        MDC.remove(TOKEN_SESSION_KEY);
        MDC.remove(USER_SESSION_KEY);
    }
}

From source file:com.google.api.server.spi.handlers.EndpointsMethodHandlerTest.java

@Test
public void fail_findService() throws Exception {
    EndpointMethod method = systemService.resolveService("TestEndpoint", "simple");
    ApiMethodConfig methodConfig = new ApiMethodConfig(method, typeLoader, apiConfig.getApiClassConfig());
    systemService = SystemService.builder().withDefaults(classLoader)
            .addService(ArrayEndpoint.class, new ArrayEndpoint()).build();
    TestMethodHandler handler = new TestMethodHandler(ServletInitializationParameters.builder().build(), method,
            apiConfig, methodConfig, systemService, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RESOURCE);
    handler.getRestHandler().handle(context);
}