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:net.myrrix.web.servlets.EstimateForAnonymousServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
        return;/* w ww  .  j av a 2 s  .c o m*/
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    long toItemID;
    Pair<long[], float[]> itemIDsAndValue;
    try {
        toItemID = Long.parseLong(pathComponents.next());
        itemIDsAndValue = RecommendToAnonymousServlet.parseItemValuePairs(pathComponents);
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (NumberFormatException nfe) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nfe.toString());
        return;
    }

    if (itemIDsAndValue.getFirst().length == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No items");
        return;
    }

    long[] itemIDs = itemIDsAndValue.getFirst();
    float[] values = itemIDsAndValue.getSecond();

    MyrrixRecommender recommender = getRecommender();
    try {
        float estimate = recommender.estimateForAnonymous(toItemID, itemIDs, values);
        Writer out = response.getWriter();
        out.write(Float.toString(estimate));
        out.write('\n');
    } catch (NotReadyException nre) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (NoSuchItemException nsie) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
    }
}

From source file:com.haulmont.cuba.core.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  w  w w  . j av a2 s  . c  o 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 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:org.apache.cxf.fediz.service.idp.FederationEntryPoint.java

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

    idpConfig = configService.getIDP(realm);
    Assert.notNull(this.idpConfig, "idpConfig cannot be null. Check realm and config service implementation");

    String redirectUrl = null;//from  w ww .j  av a  2  s . c  om
    String wauth = servletRequest.getParameter(FederationConstants.PARAM_AUTH_TYPE);
    if (wauth == null) {
        wauth = "default";
    }
    String loginUri = idpConfig.getAuthenticationURIs().get(wauth);
    if (loginUri == null) {
        LOG.warn("wauth value '" + wauth + "' not supported");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "wauth value '" + wauth + "' not supported");
    }
    redirectUrl = new StringBuilder(extractFullContextPath(servletRequest)).append(loginUri).append("?")
            .append(servletRequest.getQueryString()).toString();

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

From source file:com.pureinfo.tgirls.sns.servlet.SNSEntryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("tgirls sns entry.");

    String taobaoUserId = null;/* www  .j  a v a  2 s  .  com*/
    String taobaoUserName = null;

    String topSession = request.getParameter(APPConstants.REQ_PARAMETER_SESSION);
    String topParameters = request.getParameter(APPConstants.REQ_PARAMETER_PARAMETERS);
    String topSign = request.getParameter(APPConstants.REQ_PARAMETER_SIGN);

    TipBean tb = null;
    try {
        tb = TipUtil.beforeFetch(topSession, topParameters, topSign, APPConstants.SECRET);
        if (!tb.isOk()) {
            logger.error("top api failed." + tb.getErrMsg());

            throw new Exception("TOP API failed:" + tb.getErrMsg());
        }
        taobaoUserId = tb.getUserId() + "";
        taobaoUserName = tb.getUserNick();

        logger.debug("id:" + taobaoUserId);
        logger.debug("name:" + taobaoUserName);
        logger.debug("session:" + topSession);

        if ("0".equals(taobaoUserId) || StringUtils.isEmpty(taobaoUserId)
                || StringUtils.isEmpty(taobaoUserName)) {
            throw new Exception("parameter empty.");
        }
    } catch (Exception e) {
        logger.error("error when call top API.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "top system error." + e.getMessage());
        return;
    }

    HttpSession session = request.getSession(true);
    session.removeAttribute(ArkHelper.ATTR_LOGIN_USER);
    User loginUser = null;//(User) session.getAttribute(ArkHelper.ATTR_LOGIN_USER);
    //loginUser = CookieUtils.getLoginUser(request, response);

    if (loginUser != null && loginUser.getTaobaoID().equals(taobaoUserId)) {

        logger.debug("user " + taobaoUserId + " already logined.");

    } else {
        try {
            userMgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
            if (!userMgr.isUserExists(taobaoUserId)) {
                loginUser = createUser(taobaoUserId, topSession);
                //ScriptWriteUtils.reBuildUserInfoScript(loginUser);
                try {
                    //ScriptWriteUtils.reBuildUserBuyPhotosScript(loginUser);
                    //ScriptWriteUtils.reBuildUserUploadPhotosScript(loginUser);
                } catch (Exception e) {
                    logger.error("error when rebuild buy and upload scripts.", e);
                }
            } else {
                loginUser = userMgr.getUserByTaobaoId(taobaoUserId);
            }
        } catch (PureException e) {
            logger.error("tgirls system error.", e);
            response.sendError(HttpServletResponse.SC_BAD_GATEWAY, "tgirls system error." + e.getMessage());
            return;
        } catch (NumberFormatException e) {
            logger.error("number format error.", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        } catch (TaobaoApiException e) {
            logger.error("top system error.", e);
            response.sendError(HttpServletResponse.SC_BAD_GATEWAY, "top system error." + e.getMessage());
            return;
        }
    }

    if (loginUser == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "can not find current user.");
        return;
    }

    if (loginUser.getFunds() <= UserConstants.DISUSE_FUNDS
            || loginUser.getAssets() <= UserConstants.DISUSE_ASSETS) {
        response.sendRedirect(request.getContextPath() + "/disable.html");
        return;
    }

    updateUserHeadImg(loginUser, topSession);

    session.setAttribute(ArkHelper.ATTR_LOGIN_USER, loginUser);
    session.setAttribute(SessionConstants.TAOBAO_SESSION_ID, topSession);
    LocalContextHelper.setAttribute(SessionConstants.TAOBAO_SESSION_ID, topSession);

    addCookie(loginUser, request, response);

    //        System.out.println("========================");
    //        
    //        
    //       Cookie[] cs = request.getCookies();
    //        for (int i = 0; i < cs.length; i++) {
    //            Cookie c = cs[i];
    //            System.out.println("cookie[" + c.getName() + "]:" + c.getValue());
    //        }
    //        
    RequestDispatcher rd = request.getRequestDispatcher("/index.html");
    rd.forward(request, response);
    //response.sendRedirect(request.getContextPath());

    return;
}

From source file:com.pearson.developer.xapi.proxy.SSOServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//  w ww  .  ja v a  2 s . co  m
        // verify consumer key
        String ltiKey = this.getInitParameter("ltiConsumerKey");
        if (!ltiKey.equals(request.getParameter("oauth_consumer_key"))) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        // verify SSO with Basic LTI
        String ssoEndpoint = request.getRequestURL().toString(); // TODO - better to use parameter?
        String ltiSecret = this.getInitParameter("ltiSharedSecret");
        LtiVerificationResult ltiResult = BasicLTIUtil.validateMessage(request, ssoEndpoint, ltiSecret);
        if (!ltiResult.getSuccess()) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        // load the parameters 
        String activityProvider = request.getParameter("custom_xapi_ap_url");
        String email = request.getParameter("lis_person_contact_email_primary");
        String fullName = request.getParameter("lis_person_name_full");
        String userId = request.getParameter("user_id");

        // validate the incoming data has the expected data
        if (activityProvider == null || activityProvider.trim().length() == 0 || email == null
                || email.trim().length() == 0 || fullName == null || fullName.trim().length() == 0
                || userId == null || userId.trim().length() == 0) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Data");
            return;
        }

        // the parameter is passed double encoded, so decode it once more.
        activityProvider = URLDecoder.decode(activityProvider, "UTF-8");

        // validate the incoming data is valid
        try {
            // userId is expected to be numeric for LearningStudio (TODO - change accordingly)
            Long.parseLong(userId);

            // activity provider url must be valid
            UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" });
            if (!urlValidator.isValid(activityProvider))
                throw new RuntimeException();

            // learner email must be valid
            EmailValidator emailValidator = EmailValidator.getInstance();
            if (!emailValidator.isValid(email))
                throw new RuntimeException();

            // simple name validation (TODO - handle more complex names)
            if (!fullName.matches("[a-zA-Z .,-]+"))
                throw new RuntimeException();
        } catch (Exception e) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid Data");
            return;
        }

        // generate and save secret for session
        String sessionSecret = UUID.randomUUID().toString();
        SessionDatabase.save(userId, sessionSecret);

        // prepare auth for launch link
        String basicAuth = new String(Base64.encodeBase64((userId + ":" + sessionSecret).getBytes("UTF-8")),
                "UTF-8");
        basicAuth = URLEncoder.encode("Basic " + basicAuth, "UTF-8");

        // prepare endpoint for launch link
        String xapiEndpoint = ssoEndpoint.substring(0, ssoEndpoint.length() - request.getServletPath().length())
                + "/xapi";
        xapiEndpoint = URLEncoder.encode(xapiEndpoint, "UTF-8");

        // prepare actor for launch link
        String actor = "{\"mbox\":\"mailto:" + email + "\",\"name\":\"" + fullName
                + "\",\"objectType\":\"Agent\"}";
        actor = URLEncoder.encode(actor, "UTF-8");

        // append the appropriate first delimiter
        if (activityProvider.indexOf("?") == -1) {
            activityProvider += "?";
        } else {
            activityProvider += "&";
        }

        // add launch link parameters
        activityProvider += "auth=" + basicAuth;
        activityProvider += "&endpoint=" + xapiEndpoint;
        activityProvider += "&actor=" + actor;

        response.sendRedirect(activityProvider);
    } catch (Throwable t) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server Error");
    }
}

From source file:org.magnum.dataup.VideoUpController.java

@RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.POST)
public @ResponseBody VideoStatus setVideoData(@PathVariable(VideoSvcApi.ID_PARAMETER) long id,
        @RequestParam(VideoSvcApi.DATA_PARAMETER) MultipartFile videoData, HttpServletResponse resp) {
    if (videos.containsKey(id)) {
        Video v = videos.get(id);/*  w  w  w .  ja v  a2 s.c o  m*/
        try {
            saveVideo(v, videoData);
            return new VideoStatus(VideoState.READY);
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
    return null;
}

From source file:org.jbpm.formbuilder.server.ExportTemplateServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String profile = req.getParameter("profile");
    try {//from w  ww .  j a  v  a 2 s . c o m
        if (notEmpty(profile) && "jbpm".equals(profile)) {
            String uuid = req.getParameter("uuid");
            TaskDefinitionService taskService = createTaskService(req);
            FormDefinitionService formService = createFormService(req);
            String packageName = taskService.getContainingPackage(uuid);
            FormRepresentation form = formService.getFormByUUID(packageName, uuid);
            if (notEmpty(form.getProcessName()) || notEmpty(form.getTaskId())) {
                Translator translator = TranslatorFactory.getInstance().getTranslator("ftl");
                URL url = translator.translateForm(form);
                String content = IOUtils.toString(url.openStream());
                String templateName = "";
                if (!notEmpty(form.getTaskId())
                        || ProcessGetInputHandler.PROCESS_INPUT_NAME.equals(form.getTaskId())) {
                    templateName = form.getProcessName();
                } else {
                    templateName = form.getTaskId();
                }
                if (templateName != null && !"".equals(templateName)) {
                    templateName += "-taskform.ftl";
                    templateName = URLEncoder.encode(templateName, "UTF-8");
                    formService.saveTemplate(packageName, templateName, content);
                }
            }
        } else {
            throw new Exception("Profile not available for " + profile);
        }
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage());
    }
}

From source file:com.adobe.acs.commons.oak.impl.EnsureOakIndexServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    try {//from  ww  w.j a  va  2 s . com

        response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        response.getWriter().println("<pre>");
        response.getWriter().println();
        response.getWriter().println();
        response.getWriter().println("HTTP method GET is not supported by this URL");
        response.getWriter().println("Use HTTP POST to access this end-point");
        response.getWriter().println("--------------------------------------------");
        response.getWriter().println("HTTP POST /system/console/ensure-oak-index");
        response.getWriter().println(" Parameters");
        response.getWriter().println("   * force = true | false (optional; when blank defaults to false)");
        response.getWriter()
                .println("   * path = /abs/path/to/ensure/definition (optional; when blank indicates all)");
        response.getWriter().println();
        response.getWriter().println();
        response.getWriter().println(
                "Example: curl --user admin:admin --data \"force=true\" https://localhost:4502/system/console/ensure-oak-index");
        response.getWriter().println("</pre>");

    } catch (IOException e) {
        log.warn("Caught IOException while handling doGet() in the Ensure Oak Index Servlet.", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:net.longfalcon.web.WebExceptionHandlerResolver.java

private ModelAndView handleFlagrantSystemError(FlagrantSystemException ex, HttpServletRequest request,
        HttpServletResponse response, Object handler) throws IOException {
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    _log.error(ex, ex);//from  w  w  w .ja  v a 2  s .  co m
    return new ModelAndView();
}

From source file:com.pymegest.applicationserver.api.SessionController.java

@RequestMapping(value = { "/Session" }, method = RequestMethod.POST)
public void insert(HttpServletRequest httpServletRequest, HttpServletResponse response,
        @RequestBody String jsonSession) {

    try {/*  w  w  w.j av a2s  . c o  m*/

        ObjectMapper objectMapper = new ObjectMapper();

        Credentials credentials = (Credentials) objectMapper.readValue(jsonSession, Credentials.class);

        Usuario usuario = usuarioDAO.findByLogin(credentials.getLogin());

        if (usuario == null) {
            //No existe usuario con login introducido
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            String jsonOutput = objectMapper.writeValueAsString(null);
            response.getWriter().println(jsonOutput);
        } else {

            boolean existe = usuario.checkPassword(credentials.getPassword());

            if (existe) {

                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("application/json; chaset=UTF-8");

                String jsonOutput = objectMapper.writeValueAsString(usuario);
                response.getWriter().println(jsonOutput);

                httpServletRequest.getSession(true).setAttribute("idUsuario", usuario.getId_usuario());

            } else {

                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.setContentType("application/json; chaset=UTF-8");

                String jsonOutput = objectMapper.writeValueAsString(null);
                response.getWriter().println(jsonOutput);
            }

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}