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:at.gv.egiz.bku.online.webapp.WebRequestHandler.java

@Override
protected void doPost(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  w  w w.j ava2 s.  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");
    if (id == null) {
        String msg = "No request id! Configuration error: ServletFilter missing?";
        log.error(msg);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        return;
    }

    // if binding processor with same id is present: remove
    bindingProcessorManager.removeBindingProcessor(id);

    Locale locale = AcceptLanguage.getLocale(req.getHeader("Accept-Language"));
    if (log.isInfoEnabled()) {
        log.info("Received request (Accept-Language locale: {}).", locale);
    }

    // create new binding processor
    String protocol = MoccaParameterBean.getInitParameter("protocol", getServletConfig(), getServletContext());
    if (protocol == null || protocol.isEmpty()) {
        protocol = req.getScheme();
    }
    HTTPBindingProcessor bindingProcessor = (HTTPBindingProcessor) bindingProcessorManager
            .createBindingProcessor(protocol, locale);

    // set headers
    LinkedHashMap<String, String> headerMap = new LinkedHashMap<String, String>();
    if (req.getHeaderNames() != null) {
        for (Enumeration<?> headerName = req.getHeaderNames(); headerName.hasMoreElements();) {
            String name = (String) headerName.nextElement();
            // Account for multiple headers with the same field-name, but
            // they are very rare, so we are not using a StringBuffer.
            Enumeration<?> headers = req.getHeaders(name);
            String value = null;
            while (headers.hasMoreElements()) {
                value = (value == null) ? (String) headers.nextElement() : value + ", " + headers.nextElement();
            }
            headerMap.put(name, value);
        }
    }

    // set request stream 
    InputStream inputStream;
    if (req.getMethod().equals("POST")) {
        inputStream = req.getInputStream();
    } else {
        headerMap.put(HttpUtil.HTTP_HEADER_CONTENT_TYPE, InputDecoderFactory.URL_ENCODED);
        String queryString = req.getQueryString();
        if (queryString != null) {
            inputStream = new ByteArrayInputStream(queryString.getBytes("UTF-8"));
        } else {
            inputStream = new ByteArrayInputStream(new byte[] {});
        }
    }

    bindingProcessor.setHTTPHeaders(headerMap);
    bindingProcessor.consumeRequestStream(req.getRequestURL().toString(), inputStream);
    inputStream.close();

    // process
    bindingProcessorManager.process(id, bindingProcessor);

    log.debug("Sending redirect to user interface.");
    resp.sendRedirect(resp.encodeRedirectURL(uiRedirectUrl));

}

From source file:com.rsginer.spring.controllers.RestaurantesController.java

@RequestMapping(value = { "/restaurantes" }, method = RequestMethod.GET, produces = "application/json")
public void getRestaurantes(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse) {
    List<Restaurante> listaRestaurantes = new ArrayList<>();
    try {//  w w w  .ja va  2s .c o m
        listaRestaurantes = restaurantesDAO.findAll();
        String jsonSalida = jsonTransformer.toJson(listaRestaurantes);
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().println(jsonSalida);
    } catch (BussinessException ex) {
        List<BussinessMessage> bussinessMessages = ex.getBussinessMessages();
        String jsonSalida = jsonTransformer.toJson(bussinessMessages);
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
}

From source file:eu.city4ageproject.delivery.HTTPService.java

/**{@inheritDoc} */
@Override//from   w  w w. ja va2 s.  c  o m
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getContentType() != null && req.getContentType().toLowerCase().contains("application/json")
    //            && req.getCharacterEncoding() != null
    //            && req.getCharacterEncoding().toLowerCase().contains("utf")
    //            && req.getCharacterEncoding().toLowerCase().contains("8")
    ) {
        ServletInputStream is = req.getInputStream();
        String request = IOUtils.toString(is, "UTF-8");
        try {
            DeliveryRequest drequest = gsonBuilder.create().fromJson(request, DeliveryRequest.class);
            if (drequest.getPilotID() != null && !drequest.getPilotID().isEmpty()
                    && drequest.getUserID() != null && !drequest.getUserID().isEmpty()
                    && drequest.getIntervention() != null) {
                //connect to uAAL
                if (delivery.sendIntervention(drequest))
                    resp.setStatus(HttpServletResponse.SC_ACCEPTED);
                else
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }

            //TODO get parameters into the Actual delivery
        } catch (JsonSyntaxException e) {
            e.printStackTrace();

        }
        resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        PrintStream ps = new PrintStream(resp.getOutputStream());
        ps.print("Request not acceptable.\n cotnent is not compliant to schema.");
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintStream ps = new PrintStream(resp.getOutputStream());
        ps.print("Request not acceptable.<br> " + "Content-Type: application/json <br>"
        //               +" Content-Encoding: UTF-8"
        );
    }
}

From source file:com.adito.policyframework.actions.PrincipalInformationAction.java

public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    try {/*w w  w  .  j av  a  2s. c  om*/
        String principalType = request.getParameter("principalType");
        String principalName = request.getParameter("principalName");
        Principal principal;
        if ("account".equals(principalType)) {
            principal = UserDatabaseManager.getInstance()
                    .getUserDatabase(LogonControllerFactory.getInstance().getUser(request).getRealm())
                    .getAccount(principalName);
        } else if ("role".equals(principalType)) {
            principal = UserDatabaseManager.getInstance()
                    .getUserDatabase(LogonControllerFactory.getInstance().getUser(request).getRealm())
                    .getRole(principalName);
        } else {
            throw new Exception();
        }
        request.setAttribute(Constants.REQ_ATTR_INFO_RESOURCE, principal);
        return principalInformation(mapping, form, request, response);
    } catch (Exception e) {
        log.error("Failed to get principal information. ", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
    return null;
}

From source file:com.datatorrent.lib.io.HttpJsonChunksInputOperatorTest.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test//from   w  w  w . j  av a  2 s .c o m
public void testHttpInputModule() throws Exception {

    final List<String> receivedMessages = new ArrayList<String>();
    Handler handler = new AbstractHandler() {
        int responseCount = 0;

        @Override
        public void handle(String string, Request rq, HttpServletRequest request, HttpServletResponse response)
                throws IOException, ServletException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), bos);
            receivedMessages.add(new String(bos.toByteArray()));
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Transfer-Encoding", "chunked");
            try {
                JSONObject json = new JSONObject();
                json.put("responseId", "response" + ++responseCount);
                byte[] bytes = json.toString().getBytes();
                response.getOutputStream().println(bytes.length);
                response.getOutputStream().write(bytes);
                response.getOutputStream().println();
                response.getOutputStream().println(0);
                response.getOutputStream().flush();
            } catch (JSONException e) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Error generating response: " + e.toString());
            }

            ((Request) request).setHandled(true);
        }
    };

    Server server = new Server(0);
    server.setHandler(handler);
    server.start();

    String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext";
    final AbstractHttpInputOperator operator = new HttpJsonChunksInputOperator();

    CollectorTestSink sink = new CollectorTestSink();

    operator.outputPort.setSink(sink);
    operator.setUrl(new URI(url));

    operator.setup(null);
    operator.activate(null);

    int timeoutMillis = 3000;
    while (sink.collectedTuples.isEmpty() && timeoutMillis > 0) {
        operator.emitTuples();
        timeoutMillis -= 20;
        Thread.sleep(20);
    }

    Assert.assertTrue("tuple emitted", sink.collectedTuples.size() > 0);

    Map<String, String> tuple = (Map<String, String>) sink.collectedTuples.get(0);
    Assert.assertEquals("", tuple.get("responseId"), "response1");

    operator.deactivate();
    operator.teardown();
    server.stop();

}

From source file:eu.trentorise.smartcampus.mobility.controller.rest.CacheController.java

@RequestMapping(method = RequestMethod.POST, value = "/cachestatus")
public @ResponseBody Map<String, CacheUpdateResponse> cacheStatus(HttpServletRequest request,
        HttpServletResponse response, HttpSession session,
        @RequestBody(required = false) Map<String, String> versions) {
    try {/*w  w  w.j a  v a2 s. c om*/
        //         String address =  otpURL + OTP + "getCacheStatus";
        //         
        //         ObjectMapper mapper = new ObjectMapper();
        //         String content = mapper.writeValueAsString(versions);
        //         String res = HTTPConnector.doPost(address, content, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON);
        //         
        //         Map<String, CacheUpdateResponse> result = mapper.readValue(res, Map.class);
        //         
        //         return result;
        return new HashMap<String, CacheUpdateResponse>();
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}

From source file:jp.or.openid.eiwg.filter.InitFilter.java

/**
 * ????/*from   w  w w .j  ava2 s.  com*/
 *
 * @param request 
 * @param response ?
 * @param chain ?
 * @throws ServletException
 * @throws IOException
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {

        // ??
        String path = ((HttpServletRequest) request).getServletPath();
        if (path == null || StringUtils.isEmpty(path)) {
            // 
            this.errorResponse((HttpServletResponse) response, HttpServletResponse.SC_NOT_FOUND, null,
                    MessageConstants.ERROR_NOT_FOUND);
        } else {
            // ?????????
            if (!"/scim/ServiceProviderConfigs".equalsIgnoreCase(path)
                    && !"/scim/ResourceTypes".equalsIgnoreCase(path) && !"/scim/Schemas".equalsIgnoreCase(path)
                    && !"/scim/Users".equalsIgnoreCase(path)) {
                // 
                this.errorResponse((HttpServletResponse) response, HttpServletResponse.SC_NOT_FOUND, null,
                        MessageConstants.ERROR_NOT_FOUND);
            } else {
                // ??
                chain.doFilter(request, response);
            }
        }
    } catch (Throwable e) {
        // 
        e.printStackTrace();
        this.errorResponse((HttpServletResponse) response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null,
                MessageConstants.ERROR_UNKNOWN);
    }
}

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

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    String contextName = request.getContextPath();
    if (contextName == null || contextName.isEmpty()) {
        contextName = "/";
    }/*from  w ww.j  a v a 2 s.  c  o m*/
    FedizContext fedCtx = federationConfig.getFedizContext(contextName);
    try {
        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedCtx.getProtocol());
        RedirectionResponse redirectionResponse = wfProc.createSignOutRequest(request, null, fedCtx); //TODO
        String redirectURL = redirectionResponse.getRedirectionURL();
        if (redirectURL != null) {
            Map<String, String> headers = redirectionResponse.getHeaders();
            if (!headers.isEmpty()) {
                for (String headerName : headers.keySet()) {
                    response.addHeader(headerName, headers.get(headerName));
                }
            }

            response.sendRedirect(redirectURL);
        } else {
            LOG.warn("Failed to create SignOutRequest.");
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to create SignOutRequest.");
        }
    } catch (ProcessingException ex) {
        LOG.warn("Failed to create SignOutRequest: " + ex.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignOutRequest.");
    }
}

From source file:com.sonicle.webtop.core.app.AbstractServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   w  ww. j  a va  2s  .c  o m*/
        processRequest(request, response);
    } catch (Throwable t) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.getMessage());
    } finally {
        LoggerUtils.clearDC();
    }
}

From source file:com.streamsets.pipeline.stage.destination.http.TestHttpClientTarget.java

@Before
public void setUp() throws Exception {
    int port = getFreePort();
    server = new Server(port);
    server.setHandler(new AbstractHandler() {
        @Override/*  w ww . java  2s.  co m*/
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            serverRequested = true;
            if (returnErrorResponse) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }

            compressionType = request.getHeader(HttpConstants.CONTENT_ENCODING_HEADER);
            InputStream is = request.getInputStream();
            if (compressionType != null && compressionType.equals(HttpConstants.SNAPPY_COMPRESSION)) {
                is = new SnappyFramedInputStream(is, true);
            } else if (compressionType != null && compressionType.equals(HttpConstants.GZIP_COMPRESSION)) {
                is = new GZIPInputStream(is);
            }
            requestPayload = IOUtils.toString(is);
            requestContentType = request.getContentType();
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
        }
    });
    server.start();
}