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:nl.surfnet.coin.api.saml.SAMLAuthenticationEntryPoint.java

private void sendAuthnRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    AuthnRequestGenerator authnRequestGenerator = new AuthnRequestGenerator(openSAMLContext.entityId(),
            timeService, idService);/*w  w w  .  j  av a  2 s.c o  m*/
    EndpointGenerator endpointGenerator = new EndpointGenerator();

    final String target = openSAMLContext.idpUrl();

    Endpoint endpoint = endpointGenerator.generateEndpoint(SingleSignOnService.DEFAULT_ELEMENT_NAME, target,
            openSAMLContext.assertionConsumerUri());

    AuthnRequest authnRequest = authnRequestGenerator.generateAuthnRequest(target,
            openSAMLContext.assertionConsumerUri());

    Scoping scoping = scopingBuilder.buildObject();

    scoping.getRequesterIDs().add(createRequesterID(getSPEntityIdByRequest(request)));
    authnRequest.setScoping(scoping);
    try {
        CriteriaSet criteriaSet = new CriteriaSet();
        criteriaSet.add(new EntityIDCriteria(openSAMLContext.entityId()));
        criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

        Credential signingCredential = openSAMLContext.keyStoreCredentialResolver().resolveSingle(criteriaSet);

        Validate.notNull(signingCredential);

        String originalUrl = String.format("%s?%s", request.getRequestURI(), request.getQueryString());
        LOG.debug("About to send authnRequest to endpoint {}", endpoint.getLocation());
        openSAMLContext.samlMessageHandler().sendSAMLMessage(authnRequest, endpoint, response, originalUrl,
                signingCredential);
    } catch (MessageEncodingException mee) {
        LOG.error("Could not send authnRequest to Identity Provider.", mee);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (org.opensaml.xml.security.SecurityException e) {
        LOG.error("Could not send authnRequest to Identity Provider.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.fpmislata.banco.presentation.controladores.UsuarioController.java

@RequestMapping(value = {
        "/usuario" }, method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void insert(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestBody String jsonEntrada) {
    try {/*from w  w  w . j av a2  s  .  c  o m*/
        Usuario usuario = (Usuario) jsonTransformer.fromJsonToObject(jsonEntrada, Usuario.class);
        if (usuario == null) {
            throw new BusinessException("Campo", "Debe rellenar los datos");
        }

        if (!passwordManager.checkComplexity(usuario.getPassword()) || usuario.getPassword().isEmpty()) {
            throw new BusinessException("Password",
                    "La contrasea debe contener Minusculas, Maysculas, Dgitos y de 6-20 caractres");
        }

        usuario.setPassword(passwordManager.encrypt(usuario.getPassword()));

        usuarioService.insert(usuario);

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().println(jsonTransformer.ObjectToJson(usuario));

    } catch (BusinessException ex) {
        List<BusinessMessage> bussinessMessage = ex.getBusinessMessages();
        String jsonSalida = jsonTransformer.ObjectToJson(bussinessMessage);
        //System.out.println(jsonSalida);

        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(EntidadBancariaController.class.getName()).log(Level.SEVERE,
                    "Error devolviendo Lista de Mensajes", ex1);
        }
    } catch (Exception ex1) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex1.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex2) {
            Logger.getLogger(EntidadBancariaController.class.getName()).log(Level.SEVERE,
                    "Error devolviendo la traza", ex2);
        }
    }
}

From source file:com.imaginary.home.cloud.api.call.LocationCall.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 {//from ww  w  .ja  va 2 s .  c om
        String locationId = (path.length > 1 ? path[1] : null);

        if (locationId != null) {
            Location location = Location.getLocation(locationId);

            if (location == null) {
                throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                        "The location " + locationId + " does not exist.");
            }
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().println((new JSONObject(toJSON(location))).toString());
            resp.getWriter().flush();
        } else {
            Collection<Location> locations;

            if (userId == null) {
                String apiKey = (String) headers.get(RestApi.API_KEY);
                Location location = null;

                if (apiKey != null) {
                    ControllerRelay relay = ControllerRelay.getRelay(apiKey);

                    if (relay != null) {
                        location = relay.getLocation();
                    }
                }
                if (location == null) {
                    locations = Collections.emptyList();
                } else {
                    locations = Collections.singletonList(location);
                }
            } else {
                User user = User.getUserByUserId(userId);

                if (user == null) {
                    locations = Collections.emptyList();
                } else {
                    locations = user.getLocations();
                }
            }
            ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

            for (Location l : locations) {
                list.add(toJSON(l));
            }
            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:au.edu.uq.cmm.benny.Benny.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String user = req.getParameter("user");
    String password = req.getParameter("password");
    if (user == null && password == null) {
        String[] credentials = getBasicAuthCredentials(req);
        if (credentials == null) {
            resp.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
            respond(resp, HttpServletResponse.SC_UNAUTHORIZED, "No credentials provided");
            return;
        }// w ww .j a  va 2 s  . c  o m
        user = credentials[0];
        password = credentials[1];
    }
    try {
        LOG.debug("checking user='" + user + "', password='XXXXXX'");
        boolean ok = authenticator.authenticate(user, password, null) != null;
        if (ok) {
            respond(resp, HttpServletResponse.SC_OK, "Credentials accepted");
        } else {
            respond(resp, HttpServletResponse.SC_FORBIDDEN, "Credentials rejected");
        }
    } catch (IOException ex) {
        throw ex;
    } catch (Exception ex) {
        LOG.error("Unexpected exception", ex);
        respond(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Service error");
    }
}

From source file:uk.urchinly.wabi.expose.DownloadController.java

@RequestMapping(value = "/download/{assetId}", method = RequestMethod.GET)
public void download(HttpServletResponse response, @PathVariable("assetId") String assetId) throws IOException {

    Asset asset = this.assetMongoRepository.findOne(assetId);

    if (asset == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//  w w w. j a  v  a 2  s .  com
    }

    File file = new File(appSharePath, asset.getFileName());

    if (file.canRead()) {
        this.rabbitTemplate.convertAndSend(MessagingConstants.USAGE_ROUTE,
                new UsageEvent("download asset", asset.toString()));

        response.setContentType(asset.getContentType());
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
        response.setContentLength((int) file.length());

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } else {
        logger.warn("File '{}' not found.", file.getAbsolutePath());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.epam.wilma.webapp.config.servlet.stub.upload.MultiPartFormUploadServletTest.java

@Test
public void testDoGetShouldSendErrorResponseWhenFileParsingFailed()
        throws ServletException, IOException, FileUploadException {
    //GIVEN//  w  w w  . j a v a  2  s.c o m
    List<FileItem> uploadedFiles = new ArrayList<>();
    given(request.getMethod()).willReturn("POST");
    given(fileUpload.parseRequest(request)).willReturn(uploadedFiles);
    given(filesParser.parseMultiPartFiles(uploadedFiles))
            .willThrow(new CannotUploadExternalResourceException("", null));
    //WHEN
    underTest.doGet(request, response);
    //THEN
    verify(response).setContentType("text/html");
    verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    verify(writer).write(Matchers.anyString());
}

From source file:org.imsglobal.lti2.LTI2Servlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//  ww w.  j  av  a 2 s .  c  o  m
        doRequest(request, response);
    } catch (Exception e) {
        String ipAddress = request.getRemoteAddr();
        String uri = request.getRequestURI();
        M_log.log(Level.WARNING, "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.qut.middleware.spep.filter.SPEPFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest)) {
        throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$
    }//from w ww.j a v a  2s  .  c  o  m
    if (!(servletResponse instanceof HttpServletResponse)) {
        throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String resource, decodedResource, requested, redirectURL;
    URL serviceHost;

    ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName);

    // Get servlet context.
    if (spepContext == null) {
        throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Establish SPEPProxy object.
    SPEPProxy spep;
    try {
        spep = Initializer.init(spepContext);
    } catch (Exception e) {
        this.logger.error(
                "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n"
                        + e.getLocalizedMessage());
        throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$
    }

    // Ensure SPEP startup.
    if (!spep.isStarted()) {
        // Don't allow anything to occur if SPEP hasn't started correctly.
        this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty ");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$
    }

    // Get SPEP cookie.
    Cookie spepCookie = null;
    Cookie globalESOECookie = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(spep.getTokenName())) {
                spepCookie = cookie;
                this.logger.debug("Located spep cookie with value of " + spepCookie.getValue());
            }
            if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) {
                globalESOECookie = cookie;
                this.logger
                        .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue());
            }
        }
    }

    // value for re-determining session status after Authz request
    boolean validSession = false;

    // Check SPEP session is valid.
    if (spepCookie != null) {
        String sessionID = spepCookie.getValue();

        this.logger.info("Attempting to retrieve data for session with ID of " + sessionID);
        PrincipalSession PrincipalSession = spep.verifySession(sessionID);

        if (PrincipalSession != null) {
            this.logger.info("Located session with ID of " + sessionID);

            if (request.getSession().getAttribute(ATTRIBUTES) == null) {
                // over write with new data if it exists
                WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>();
                attributeMap.putAll(PrincipalSession.getAttributes());
                attributeMap.close();

                request.getSession().setAttribute(ATTRIBUTES, attributeMap);
                request.getSession().setAttribute(SPEP_SESSIONID, sessionID);
            }

            /*
             * This section of code is critical, we must pass the PEP an exact representation of what the user is
             * attempting to access additionally the PEP expects that the string is not in encoded form as it will
             * do exact matching, so we decode before passing our request to it.
             */
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource);

            // the authz processor may destroy the session if the PDP determines that the client
            // session is no longer valid, so we have to check it again
            if ((PrincipalSession = spep.verifySession(sessionID)) != null)
                validSession = true;

            if (validSession) {
                if (authzDecision == SPEPProxy.decision.permit) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was permissable");
                    chain.doFilter(request, response);
                    return;
                } else if (authzDecision == SPEPProxy.decision.deny) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was denied, forcing response of"
                            + HttpServletResponse.SC_FORBIDDEN);
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN);
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else if (authzDecision == SPEPProxy.decision.error) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was in error, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$
                } else {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was undetermined, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$
                }
            }
        }

        /* Clear the local session object the supplied request is invalid */
        this.logger.debug("Invalidating session for ID of " + sessionID);
        request.getSession().invalidate();
    }

    /*
     * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the
     * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have
     * come back to the SPEP since logging out.
     */
    List<Cookie> clearCookies = new Vector<Cookie>();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (spep.getLogoutClearCookies() != null) {
                for (Cookie clearCookie : spep.getLogoutClearCookies()) {
                    if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) {
                        Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone();
                        clearCookieCloneInsecure.setMaxAge(0);
                        clearCookieCloneInsecure.setSecure(false);

                        clearCookies.add(clearCookieCloneInsecure);

                        // Don't need to process the inner loop again for this cookie.
                        break;
                    }
                }
            }
        }
    }

    /* Add the cookies to be cleared into the response object. */
    for (Cookie c : clearCookies)
        response.addCookie(c);

    /*
     * Remove any principal object details which may be in the session, this state can occur if the user has removed
     * their spepSession cookie but retained their jsessionid cookie
     */
    request.getSession().removeAttribute(ATTRIBUTES);

    /*
     * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered
     * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the
     * logical reasons below they will be forced to authenticate.
     */
    if (spep.isLazyInit()) {
        this.logger.info(
                "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP");

        /*
         * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the
         * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out
         * if user is accessing something that has been configured to force a session to be established before it is
         * accessible
         */
        if (globalESOECookie == null) {
            this.logger.debug("globalESOECookie was not set for this request");

            boolean matchedLazyInitResource = false;
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            for (String lazyInitResource : spep.getLazyInitResources()) {
                if (decodedResource.matches(lazyInitResource)) {
                    matchedLazyInitResource = true;
                    this.logger.info("Lazy session init attempt matched initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
                } else
                    this.logger.debug("Lazy session init attempt failed to match initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
            }

            // If we still have no reason to engage spep functionality for this request let the request pass
            if (matchedLazyInitResource) {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            } else {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
    }

    /*
     * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment
     * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically
     */
    this.logger.debug("Failed all avenues to provide access to content");
    if (request.getQueryString() != null)
        requested = request.getRequestURI() + "?" + request.getQueryString();
    else
        requested = request.getRequestURI();

    /*
     * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to
     * the local node.
     */
    serviceHost = new URL(spep.getServiceHost());

    String ssoRedirect = spep.getSsoRedirect();
    String timestampParameter;
    if (ssoRedirect.indexOf('?') > -1) {
        timestampParameter = "&ts=" + System.currentTimeMillis();
    } else {
        timestampParameter = "?ts=" + System.currentTimeMillis();
    }

    if (request.getServerName().equals(serviceHost.getHost())) {
        /* Ensures that SSL offloading in Layer 7 environments is correctly handled */
        requested = spep.getServiceHost() + requested;
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    } else {
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    }

    this.logger.debug("Redirecting to " + redirectURL + " to establish secure session");
    response.sendRedirect(redirectURL);
}

From source file:com.devicehive.websockets.AbstractWebSocketHandler.java

@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    logger.error("Error in session " + session.getId(), exception);
    JsonMessageBuilder builder;//from w  w  w .java  2 s  . c  o  m

    session = sessionMonitor.getSession(session.getId());

    if (exception instanceof JsonParseException) {
        builder = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST,
                "Incorrect JSON syntax");
    } else {
        builder = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Internal server error");
    }
    session.sendMessage(new TextMessage(GsonFactory.createGson().toJson(builder.build())));
}

From source file:net.triptech.buildulator.web.AdminController.java

/**
 * Delete the user./*  w  w w .j  a  v  a 2 s .  c o  m*/
 *
 * @param id the id
 * @param request the request
 * @param response the response
 * @return the string
 */
@RequestMapping(value = "/users/delete", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public @ResponseBody String deleteUser(@RequestParam(value = "id", required = true) final String id,
        final HttpServletRequest request, final HttpServletResponse response) {

    String returnMessage = "";

    Person person = Person.findByEmailAddress(id);

    if (person != null) {
        try {
            person.remove();
            returnMessage = "ok";
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            returnMessage = this.getMessage("users_delete_error");
        }
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        returnMessage = this.getMessage("users_delete_notfounderror");
    }
    return returnMessage;
}