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:edu.ucsf.orng.shindig.service.JsonLDHandler.java

/**
 * Returns a list of people that correspond to the passed in person ids.
 * /*from   ww  w  .j  a v a 2s.  c o  m*/
 * @param userIds
 *            A set of users
 * @param groupId
 *            The group
 * @param collectionOptions
 *            How to filter, sort and paginate the collection being fetched
 * @param fields
 *            The profile details to fetch. Empty set implies all
 * @param token
 *            The gadget token @return a list of people.
 * @return Future that returns a RestfulCollection of Person
 */
private Future<JSONObject> getJSONItems(Set<String> urls, boolean nocache, String output, Set<String> fields,
        String containerSessionId, GroupId groupId, CollectionOptions collectionOptions, SecurityToken token)
        throws ProtocolException {
    try {
        Model model = null;
        Set<String> uris = Sets.newLinkedHashSet();
        for (String url : urls) {
            RdfItem item = rdfService.getRDF(url, nocache, "full".equalsIgnoreCase(output), fields,
                    containerSessionId, token);
            model = model == null ? item.getModel() : model.add(item.getModel());
            uris.add(item.getRequestedUri());
        }
        JSONObject jsonld = jsonldService.getJSONObject(model);
        // add the URI's
        JSONObject retval = new JSONObject().put("base", jsonldService.getBase()).put("uris", uris)
                .put("jsonld", jsonld);
        return Futures.immediateFuture(retval);
    } catch (Exception e) {
        throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
    }
}

From source file:com.streamsets.datacollector.http.JMXJsonServlet.java

/**
 * Process a GET request for the specified resource.
 *
 * @param request//from ww  w.j  ava 2  s .c  om
 *          The servlet request we are processing
 * @param response
 *          The servlet response we are creating
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {
        JsonGenerator jg = null;
        String jsonpcb = null;
        PrintWriter writer = null;
        try {
            writer = response.getWriter();

            // "callback" parameter implies JSONP outpout
            jsonpcb = request.getParameter(CALLBACK_PARAM);
            if (jsonpcb != null) {
                response.setContentType("application/javascript; charset=utf8");
                writer.write(jsonpcb + "(");
            } else {
                response.setContentType("application/json; charset=utf8");
            }

            jg = jsonFactory.createGenerator(writer);
            jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
            jg.useDefaultPrettyPrinter();
            jg.writeStartObject();

            // query per mbean attribute
            String getmethod = request.getParameter("get");
            if (getmethod != null) {
                String[] splitStrings = getmethod.split("\\:\\:");
                if (splitStrings.length != 2) {
                    jg.writeStringField("result", "ERROR");
                    jg.writeStringField("message", "query format is not as expected.");
                    jg.flush();
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                listBeans(jg, new ObjectName(splitStrings[0]), splitStrings[1], response);
                return;
            }

            // query per mbean
            String qry = request.getParameter("qry");
            if (qry == null) {
                qry = "*:*";
            }
            listBeans(jg, new ObjectName(qry), null, response);
        } finally {
            if (jg != null) {
                jg.close();
            }
            if (jsonpcb != null) {
                writer.write(");");
            }
            if (writer != null) {
                writer.close();
            }
        }
    } catch (IOException e) {

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.CASController.java

/**
 * Retrieve the with the user data: currently on the username is added.
 * @return//from w w w .  ja v a  2s . co m
 */
@RequestMapping("/cas/serviceValidate")
public @ResponseBody String validateService(HttpServletRequest req, HttpServletResponse res,
        @RequestParam String service, @RequestParam String ticket) {
    try {
        res.setContentType("application/xml");
        checkService(req, res, service);
        Ticket obj = ticketManager.checkTicket(service, ticket);
        User user = userRepository.findOne(Long.parseLong(obj.getId()));
        return generateSuccess(user, obj.isFromNewLogin());//new ModelAndView("redirect:"+service);
    } catch (CASException e) {
        logger.error("CAS login error: " + e.getMessage());
        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            return generateFailure(e.getCode().toString(), e.getMessage());
        } catch (Exception e1) {
            logger.error("CAS login error: " + e.getMessage());
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("CAS login error: " + e.getMessage());
        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

}

From source file:org.apache.servicemix.http.security.HttpSecurityTest.java

public void testWSSecBadCred() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    FileUtil.copyInputStream(getClass().getResourceAsStream("request-bc.xml"), out);
    String request = out.toString();
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://localhost:8192/WSSec/");
    try {/*from   w w  w . j av a2s . c  o m*/
        method.setDoAuthentication(true);
        method.setRequestEntity(new StringRequestEntity(request));
        int state = client.executeMethod(method);
        String str = method.getResponseBodyAsString();
        log.info(str);
        assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, state);
        Element e = new SourceTransformer().toDOMElement(new StringSource(str));
        assertEquals("Envelope", e.getLocalName());
        e = (Element) e.getFirstChild();
        assertEquals("Body", e.getLocalName());
        e = (Element) e.getFirstChild();
        assertEquals("Fault", e.getLocalName());
    } finally {
        method.releaseConnection();
    }
}

From source file:com.ebay.pulsar.metric.servlet.MetricRestServlet.java

private void getMetrics(final HttpServletRequest request, final String pathInfo,
        final HttpServletResponse response) throws Exception {
    String queryString = request.getQueryString();
    QueryParam queryParam = getCassandraQueryParam(queryString);
    ListenableFuture<List<RawNumericMetric>> future = metricService.findData(queryParam);

    try {/*from w ww  . ja  v a 2  s . c o m*/
        List<RawNumericMetric> metrics = future.get(5000, TimeUnit.MILLISECONDS);
        String result = metricResultWriter.writeValueAsString(metrics);
        response.getWriter().print(result);
        response.setContentLength(result.length());
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (TimeoutException e) {
        response.getWriter().print(QUERY_CASSANDRA_TIMEOUT);
        response.setContentLength(QUERY_CASSANDRA_TIMEOUT.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ExecutionException e) {
        response.getWriter().print(QUERY_CASSANDRA_ERROR);
        response.setContentLength(QUERY_CASSANDRA_ERROR.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.egreen.tesla.server.api.config.resolver.RequestResolver.java

private void sendErrorMessage(HttpServletResponse resp, String message) throws IOException {
    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    resp.getWriter().print("<html><head><title>Oops an error happened!</title></head>");
    resp.getWriter().print("<body>" + message + "!</body>");
    resp.getWriter().println("</html>");
}

From source file:info.raack.appliancelabeler.web.BaseController.java

@ExceptionHandler
public ModelAndView handleUncaughtException(Exception ex, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    if (ex instanceof AccessDeniedException) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else if (ex instanceof OAuthUnauthorizedException) {
        /*if(request.getSession() != null) {
           request.getSession().invalidate();
        }//from   ww w .j  ava2 s.co  m
        SecurityContextHolder.getContext().setAuthentication(null);*/
        try {
            response.sendRedirect("/t/logout.do");
            logger.warn("Could not authorize oauth request", ex);
        } catch (IOException e1) {
            logger.error("Could not send redirect", e1);
        }
        return null;
    } else if (ex instanceof ClientAPIException) {
        if (ex.getCause() != null && ex.getCause() instanceof OAuthUnauthorizedException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
        response.getOutputStream().write(ex.getMessage().getBytes());
        return null;
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        errorService.reportError("Error while processing user web page request", URGENCY.URGENT, ex);
        logger.error("An exception was caught while processing", ex);
    }
    return templateProvider.showPageInTemplate(1, "error/basic", new ModelMap());
}

From source file:iddb.web.security.service.UserServiceFilter.java

private boolean checkRoles(Subject s, HttpServletRequest req, HttpServletResponse resp, String p)
        throws IOException {
    if (s.isAuthenticated()) {
        Set<String> r = urls.get(p);
        for (String role : r) {
            if ("*".equals(role) || s.hasRole(role)) {
                log.debug("Allowed");
                return true;
            }/*  w w  w  .jav  a2s  .c  o  m*/
            log.debug("Forbidden");
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } else {
        log.debug("Redirect to Login");
        UrlReverse reverse = new UrlReverse(this.context);
        try {
            resp.sendRedirect(req.getContextPath() + reverse.resolve("login") + "?next="
                    + URLEncoder.encode(req.getRequestURI(), "UTF-8"));
        } catch (RuleNotFoundException e) {
            log.error(e.getMessage());
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (ReverseException e) {
            log.error(e.getMessage());
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    return false;
}

From source file:de.perdoctus.synology.jdadapter.controller.JdAdapter.java

public void handleClassicRequest(final String jk, final String crypted, final HttpServletResponse resp)
        throws IOException {
    LOG.debug("Configuration: " + drClient.toString());

    try {//from w  w w . j a  v  a  2s  . c  om
        final String key = extractKey(jk);
        final List<URI> targets = Decrypter.decryptDownloadUri(crypted, key);
        final List<URI> fixedTargets = fixURIs(targets);

        LOG.debug("Sending download URLs to Synology NAS. Number of URIs: " + targets.size());
        for (URI target : fixedTargets) {
            drClient.addDownloadUrl(target);
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        analyticsTracker.trackEvent(ANALYTICS_EVENT_CATEGORY, "Classic Request", "added targets",
                targets.size());

    } catch (ScriptException ex) {
        LOG.error(ex.getMessage(), ex);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Failed to evaluate script:\n" + ex.getMessage());

    } catch (SynoException ex) {
        LOG.error(ex.getMessage(), ex);
        if (ex instanceof LoginException) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
        } else {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        }

    } catch (URISyntaxException ex) {
        LOG.error("Decrypted URL seems to be corrupt.", ex);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

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

@Override
@SuppressWarnings("null")
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    if (!editorConfig.isEnabled()) {
        sendForbiddenWithMessage(response, "Configuration editor is disabled.");
        return;//from   w ww.  j a  v  a  2  s. c o m
    }

    // 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));

    ConfigurationMetadata configMetadata = configManager.getConfigurationMetadata(configName);
    if (configMetadata != null && configMetadata.isCollection() != collection) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Collection parameter mismatch.");
        return;
    }

    // parse JSON parameter data
    ConfigurationPersistData persistData = null;
    ConfigurationCollectionPersistData collectionPersistData = null;
    try {
        String jsonDataString = IOUtils.toString(request.getInputStream(), CharEncoding.UTF_8);
        JSONObject jsonData = new JSONObject(jsonDataString);
        if (collection) {
            collectionPersistData = parseCollectionConfigData(jsonData, configMetadata);
        } else {
            persistData = parseConfigData(jsonData, configMetadata);
        }
    } catch (JSONException ex) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid JSON data: " + ex.getMessage());
        return;
    }

    // persist data
    try {
        if (collection) {
            configManager.persistConfigurationCollection(request.getResource(), configName,
                    collectionPersistData);
        } else {
            configManager.persistConfiguration(request.getResource(), configName, persistData);
        }
    } catch (ConfigurationPersistenceAccessDeniedException ex) {
        sendForbiddenWithMessage(response, ex.getMessage());
    } catch (ConfigurationPersistenceException ex) {
        log.warn("Unable to persist data for " + configName + (collection ? "[col]" : ""), ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Unable to persist data: " + ex.getMessage());
    }
    /*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());
    }
}