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:ba.nwt.ministarstvo.server.fileUpload.FileUploadServlet.java

@SuppressWarnings("unchecked")
@Override/*from  w w  w. java  2  s. c o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        ServletRequestContext ctx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(ctx) == false) {
            sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "The servlet can only handle multipart requests." + " This is probably a software bug."));
            return;
        }

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> i = items.iterator();
        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, File> files = new HashMap<String, File>();

        while (i.hasNext() == true) {
            FileItem item = i.next();

            if (item.isFormField() == true) {
                String param = item.getFieldName();
                String value = item.getString();
                //                    System.out.println(getClass().getName() + ": param="
                //                            + param + ", value=" + value);
                params.put(param, value);
            } else {
                if (item.getSize() == 0) {
                    continue; // ignore zero-length files
                }

                File tempf = File.createTempFile(request.getRemoteAddr() + "-" + item.getFieldName() + "-", "");
                item.write(tempf);
                files.put(item.getFieldName(), tempf);
                //                    System.out.println("Creating temporary file "
                //                            + tempf.getAbsolutePath());
            }
        }

        // populate, invoke the listener, delete files if needed,
        // send response
        FileUploadAction action = (FileUploadAction) actionClass.newInstance();
        BeanUtils.populate(action, params); // populate the object
        action.setFileList(files);

        FormResponse resp = action.onSubmit(this, request);
        if (resp.isDeleteFiles()) {
            Iterator<Map.Entry<String, File>> j = files.entrySet().iterator();
            while (j.hasNext()) {
                Map.Entry<String, File> entry = j.next();
                File f = entry.getValue();
                f.delete();
            }
        }

        sendResponse(response, resp);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getClass().getName() + ": " + e.getMessage()));
    }
}

From source file:de.tu_dortmund.ub.hb_ng.middleware.MiddlewareHbNgEndpoint.java

protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    // CORS ORIGIN RESPONSE HEADER
    httpServletResponse.setHeader("Access-Control-Allow-Origin",
            config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_ORIGIN_IDENTIFIER));

    String authorization = "";
    String contenttype = "";

    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = headerNames.nextElement();
        this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = "
                + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }/*from w ww .ja  v a 2 s  .  co m*/
        if (headerNameKey.equals("Content-Type")) {
            contenttype = httpServletRequest.getHeader(headerNameKey);
        }
    }

    this.logger.info("contenttype = " + contenttype);

    try {

        // TODO validate Content-Type

        String data = httpServletRequest.getReader().lines()
                .collect(Collectors.joining(System.lineSeparator()));

        if (data == null || data.equals("")) {

            this.logger.error(HttpServletResponse.SC_NO_CONTENT + " - No Content");
            httpServletResponse.sendError(HttpServletResponse.SC_NO_CONTENT, "No Content");
        } else {

            String postableData = null;

            // TODO bind interface Preprocessing
            if (Lookup.lookupAll(PreprocessingInterface.class).size() > 0) {

                PreprocessingInterface preprocessingInterface = Lookup.lookup(PreprocessingInterface.class);
                // init Authorization Service
                preprocessingInterface.init(this.config);

                postableData = preprocessingInterface.process(data);
            } else {

                // TODO correct error handling
                this.logger.error("[" + this.config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                        + "Authorization Interface not implemented!");
            }

            if (postableData != null) {

                // TODO if successful then POST as application/sparql-update to LinkedDataPlatform
                String sparql_url = this.config.getProperty("ldp.sparql-endpoint");

                // HTTP Request
                int timeout = Integer.parseInt(this.config.getProperty("ldp.timeout"));

                RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                        .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

                CloseableHttpClient httpclient = HttpClients.custom()
                        .setDefaultRequestConfig(defaultRequestConfig).build();

                try {

                    HttpPost httpPost = new HttpPost(sparql_url);
                    httpPost.addHeader("Content-Type", "application/sparql-update");
                    httpPost.addHeader("Authorization", this.config.getProperty("ldp.authorization"));
                    httpPost.setEntity(new StringEntity(postableData));

                    CloseableHttpResponse httpResponse = null;

                    long start = System.nanoTime();
                    try {

                        httpResponse = httpclient.execute(httpPost);
                    } catch (ConnectTimeoutException | SocketTimeoutException e) {

                        this.logger.info("[" + this.getClass().getName() + "] " + e.getClass().getName() + ": "
                                + e.getMessage());
                        httpResponse = httpclient.execute(httpPost);
                    }
                    long elapsed = System.nanoTime() - start;
                    this.logger.info("[" + this.getClass().getName() + "] LDP request - "
                            + (elapsed / 1000.0 / 1000.0 / 1000.0) + " s");

                    try {

                        int statusCode = httpResponse.getStatusLine().getStatusCode();
                        HttpEntity httpEntity = httpResponse.getEntity();

                        // TODO
                        httpServletResponse.setStatus(statusCode);
                        httpServletResponse.getWriter().println(httpResponse.getStatusLine().getReasonPhrase());

                        EntityUtils.consume(httpEntity);

                    } finally {
                        httpResponse.close();
                    }
                } finally {

                    httpclient.close();
                }
            }
        }
    } catch (Exception e) {

        this.logger.error("something went wrong", e);
        httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "something went wrong");
    }
}

From source file:com.enonic.cms.web.webdav.DavResourceImpl.java

private void createCollection(final File localFile, final InputContext in) throws DavException {
    if (in.hasStream()) {
        throw new DavException(DavServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
    }/* w  ww .  j  a  v a 2  s . c o m*/

    if (!localFile.mkdirs()) {
        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create directory");
    }
}

From source file:com.google.ytd.embed.UploadResponseHandler.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String videoId = req.getParameter("id");
    String status = req.getParameter("status");

    UserSession userSession = userSessionManager.getUserSession(req);

    if (status.equals("200")) {
        String authSubToken = userSession.getMetaData("authSubToken");
        String articleUrl = userSession.getMetaData("articleUrl");
        String assignmentId = userSession.getMetaData("assignmentId");
        String videoTitle = userSession.getMetaData("videoTitle");
        String videoDescription = userSession.getMetaData("videoDescription");
        String youTubeName = userSession.getMetaData("youTubeName");
        String email = userSession.getMetaData("email");
        String phoneNumber = userSession.getMetaData("phoneNumber");
        String videoTags = userSession.getMetaData("videoTags");
        String videoLocation = userSession.getMetaData("videoLocation");
        String videoDate = userSession.getMetaData("videoDate");

        log.fine(String.format(/*from   w w w .  ja  v a2 s  .c om*/
                "Attempting to persist VideoSubmission with YouTube id '%s' " + "for assignment id '%s'...",
                videoId, assignmentId));

        VideoSubmission submission = submissionDao.newSubmission(Long.parseLong(assignmentId));

        submission.setArticleUrl(articleUrl);
        submission.setVideoId(videoId);
        submission.setVideoTitle(videoTitle);
        submission.setVideoDescription(videoDescription);
        submission.setVideoTags(videoTags);
        submission.setVideoLocation(videoLocation);
        submission.setVideoDate(videoDate);
        submission.setYouTubeName(youTubeName);
        submission.setVideoSource(VideoSubmission.VideoSource.NEW_UPLOAD);
        submission.setNotifyEmail(email);
        submission.setPhoneNumber(phoneNumber);

        userAuthTokenDao.setUserAuthToken(youTubeName, authSubToken);

        AdminConfig adminConfig = adminConfigDao.getAdminConfig();

        youTubeApiHelper.setAuthSubToken(adminConfig.getYouTubeAuthSubToken());

        if (adminConfig.getModerationMode() == AdminConfig.ModerationModeType.NO_MOD.ordinal()) {
            // NO_MOD is set, auto approve all submission
            // TODO: This isn't enough, as the normal approval flow (adding the branding, tags, emails,
            // etc.) isn't taking place.
            submission.setStatus(VideoSubmission.ModerationStatus.APPROVED);
            youTubeApiHelper.updateModeration(videoId, true);

            // Add video to YouTube playlist if it isn't in it already.
            // This code is kind of ugly and is mostly copy/pasted from UpdateVideoSubmissionStatus
            // TODO: It should be refactored into a common helper method somewhere...
            if (!submission.isInPlaylist()) {
                Assignment assignment = assignmentDao.getAssignmentById(assignmentId);

                if (assignment == null) {
                    log.warning(String.format("Couldn't find assignment id '%d' for video id '%s'.",
                            assignmentId, videoId));
                } else {
                    String playlistId = assignment.getPlaylistId();
                    if (util.isNullOrEmpty(playlistId)) {
                        log.warning(String.format("Assignment id '%d' does not have an associated playlist.",
                                assignmentId));
                    } else {
                        if (youTubeApiHelper.insertVideoIntoPlaylist(playlistId, videoId)) {
                            submission.setIsInPlaylist(true);
                        }
                    }
                }
            }
        } else {
            youTubeApiHelper.updateModeration(videoId, false);
        }

        submission = submissionDao.save(submission);

        log.fine("...VideoSubmission persisted.");

        emailUtil.sendNewSubmissionEmail(submission);

        try {
            JSONObject responseJsonObj = new JSONObject();
            responseJsonObj.put("videoId", videoId);
            responseJsonObj.put("status", status);
            resp.setContentType("text/html");
            resp.getWriter().println(responseJsonObj.toString());
        } catch (JSONException e) {
            log.warning(e.toString());
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    } else {
        String code = req.getParameter("code");
        log.warning(String.format(
                "Upload request for user with session id '%s' failed with " + "status '%s' and code '%s'.",
                userSession.getId(), status, code));
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, code);
    }
}

From source file:com.concursive.connect.web.modules.welcome.servlets.WelcomeServlet.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from  w  w  w .  ja v  a2 s.  c o  m
        request.setCharacterEncoding("UTF-8");
    } catch (Exception e) {
        LOG.warn("Unsupported encoding");
    }
    try {
        // Save the requestURI to be used downstream (it gets rewritten on forwards)
        String contextPath = request.getContextPath();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        String requestedURL = uri.substring(contextPath.length())
                + (queryString == null ? "" : "?" + queryString);
        if ("/index.shtml".equals(requestedURL)) {
            requestedURL = "";
        }
        request.setAttribute("requestedURL", requestedURL);
        // Configure the user's client
        ClientType clientType = (ClientType) request.getSession().getAttribute(Constants.SESSION_CLIENT_TYPE);
        if (clientType == null) {
            clientType = new ClientType();
            clientType.setParameters(request);
            request.getSession().setAttribute("clientType", clientType);
        }

        // Detect mobile
        if ("false".equals(request.getParameter("useMobile"))) {
            clientType.setMobile(false);
        }

        // Context startup initializes the prefs
        ApplicationPrefs applicationPrefs = (ApplicationPrefs) request.getSession().getServletContext()
                .getAttribute("applicationPrefs");
        if (!applicationPrefs.isConfigured()) {
            RequestDispatcher initialSetup = request.getRequestDispatcher("/Setup.do?command=Default");
            initialSetup.forward(request, response);
        } else if (ApplicationVersion.isOutOfDate(applicationPrefs)) {
            // If the site is setup, then check to see if this is an upgraded version of the app
            RequestDispatcher upgrade = getServletConfig().getServletContext()
                    .getRequestDispatcher("/Upgrade.do?command=Default&style=true");
            upgrade.forward(request, response);
        } else if ("true".equals(applicationPrefs.get("PORTAL"))) {
            // If the site supports a portal, go to the portal
            // @todo implement mobile pages then turn this back on
            //        if (clientType.getMobile()) {
            // If a mobile device is detected, offer a low-bandwidth option
            //          RequestDispatcher portal = request.getRequestDispatcher("/Login.do?command=DetectMobile");
            //          portal.forward(request, response);
            //        } else {
            String pathToUse = request.getRequestURI().substring(request.getContextPath().length());
            RequestDispatcher portal = request
                    .getRequestDispatcher(pathToUse + applicationPrefs.get("PORTAL.INDEX"));
            portal.forward(request, response);
            //        }
        } else {
            // Go to the user's home page if logged in
            User thisUser = (User) request.getSession().getAttribute(Constants.SESSION_USER);
            if (thisUser != null && thisUser.getId() > 0) {
                RequestDispatcher portal = request
                        .getRequestDispatcher("/ProjectManagement.do?command=Default");
                portal.forward(request, response);
            } else {
                RequestDispatcher portal = request.getRequestDispatcher("/Login.do?command=Default");
                portal.forward(request, response);
            }
        }
    } catch (Exception ex) {
        String msg = "Welcome failed";
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    }
}

From source file:com.linuxbox.enkive.web.search.SearchFolderServlet.java

@SuppressWarnings("unused")
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    res.setCharacterEncoding("UTF-8");
    try {//from w ww. jav a  2s .  c  o m

        String searchFolderId = WebScriptUtils.cleanGetParameter(req, "id");
        String action = WebScriptUtils.cleanGetParameter(req, "action");

        if (searchFolderId == null || searchFolderId.isEmpty())
            searchFolderId = "unimplemented";
        /*            searchFolderId = workspaceService.getActiveWorkspace(
          getPermissionService().getCurrentUsername())
          .getSearchFolderID();*/
        if (action == null || action.isEmpty())
            action = VIEW_SEARCH_FOLDER;

        WebPageInfo pageInfo = new WebPageInfo(WebScriptUtils.cleanGetParameter(req, PAGE_POSITION_PARAMETER),
                WebScriptUtils.cleanGetParameter(req, PAGE_SIZE_PARAMETER));

        JSONObject dataJSON = new JSONObject();
        JSONObject jsonResult = new JSONObject();
        dataJSON.put(SEARCH_ID_TAG, searchFolderId);

        if (LOGGER.isInfoEnabled())
            LOGGER.info("Loading " + searchFolderId);

        /*         SearchFolder searchFolder = workspaceService
                       .getSearchFolder(searchFolderId);*/
        SearchFolder searchFolder = null;

        JSONArray resultsJson = new JSONArray();

        if (searchFolder == null) {
            // No search folder
        } else if (action.equalsIgnoreCase(ADD_SEARCH_FOLDER_MESSAGE)) {
            String searchResultId = WebScriptUtils.cleanGetParameter(req, "searchResultId");
            String messageidlist = WebScriptUtils.cleanGetParameter(req, "messageids");
            Collection<String> messageIds = new HashSet<String>(Arrays.asList(messageidlist.split(",")));
            addSearchFolderMessages(searchFolder, searchResultId, messageIds);
        } else if (action.equalsIgnoreCase(EXPORT_SEARCH_FOLDER)) {
            res.setContentType("application/x-gzip; charset=ISO-8859-1");
            exportSearchFolder(searchFolder, res.getOutputStream());
        } else if (action.equalsIgnoreCase(REMOVE_SEARCH_FOLDER_MESSAGE)) {
            String messageidlist = WebScriptUtils.cleanGetParameter(req, "messageids");
            Collection<String> messageIds = new HashSet<String>(Arrays.asList(messageidlist.split(",")));
            removeSearchFolderMessages(searchFolder, messageIds);
        } else if (action.equalsIgnoreCase(VIEW_SEARCH_FOLDER)) {
            resultsJson = viewSearchFolder(searchFolder, pageInfo);
            dataJSON.put(ITEM_TOTAL_TAG, pageInfo.getItemTotal());

            dataJSON.put(RESULTS_TAG, resultsJson);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Returning search folder messages for folder id " + searchFolderId);

            jsonResult.put(DATA_TAG, dataJSON);
            jsonResult.put(PAGING_LABEL, pageInfo.getPageJSON());
            res.getWriter().write(jsonResult.toString());
        }

    } catch (WorkspaceException e) {
        respondError(HttpServletResponse.SC_UNAUTHORIZED, null, res);
        throw new EnkiveServletException("Could not login to repository to retrieve search", e);
    } catch (JSONException e) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to serialize JSON", e);
    } catch (CannotRetrieveException e) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to retrieve search folder messages", e);
    } finally {

    }
}

From source file:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPQuery.java

/**
 * Handles Get requests// w  w  w  .ja  v a 2 s.c  o  m
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int localPageSize = this.pageSize;

    ServletOutputStream out = response.getOutputStream();
    out = response.getOutputStream();

    Object[] resultSet = null;
    int pageNumber = 1;

    LexEVSHTTPUtils httpUtils = new LexEVSHTTPUtils(context);

    String queryType = httpUtils.getQueryType(request.getRequestURL().toString());

    String query = null;

    try {
        if (URLDecoder.decode(request.getQueryString(), "ISO-8859-1") != null) {
            query = URLDecoder.decode(request.getQueryString(), "ISO-8859-1");
        } else {
            throw new Exception("Query not defined" + getQuerySyntax());
        }
        if (query.indexOf("&username") > 0)
            query = query.substring(0, query.indexOf("&username"));

        validateQuery(query);
        httpUtils.setQueryArguments(query);

        httpUtils.setServletName(request.getRequestURL().toString());

        if (httpUtils.getPageSize() != null) {
            localPageSize = Integer.parseInt(httpUtils.getPageSize());
        } else {
            httpUtils.setPageSize(localPageSize);
        }

        resultSet = httpUtils.getResultSet();

        try {

            XMLOutputter xout = new XMLOutputter();
            org.jdom.Document domDoc = httpUtils.getXMLDocument(resultSet, pageNumber);

            if (queryType.endsWith("XML")) {
                response.setContentType("text/xml");
                xout.output(domDoc, out);
            } else if (queryType.endsWith("JSON")) {
                response.setContentType("application/x-javascript");
                if (httpUtils.getTargetPackageName() != null) {
                    printDocument(domDoc, jsonStyleSheet, out);

                }
            } else {
                response.setContentType("text/html");
                if (httpUtils.getTargetPackageName() != null) {
                    printDocument(domDoc, cacoreStyleSheet, out);
                }
            }

        } catch (Exception ex) {
            log.error("Print Results Exception: " + ex.getMessage());
            throw ex;
        }
    } catch (Exception ex) {

        log.error("Exception: ", ex);
        if (ex instanceof SelectionStrategyException
                || (ex.getCause() != null && ex.getCause() instanceof SelectionStrategyException)) {

            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "The requested Coding Scheme is not available. \n\n" + ex.getMessage());
        } else if (ex instanceof WebQueryException
                || (ex.getCause() != null && ex.getCause() instanceof WebQueryException)) {

            response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        }
    }
}

From source file:it.smartcommunitylab.weliveplayer.managers.WeLivePlayerManager.java

protected List<Comment> getComments(String artifactId) throws WeLivePlayerCustomException {

    List<Comment> commentsList = new ArrayList<Comment>();

    String url = env.getProperty("welive.mkp.singleApp.uri");
    url = url.replace("{artefact-id}", artifactId);

    try {//from w  ww .j a  v  a2 s  . c o m
        String response = weLivePlayerUtils.sendGET(url, "application/json", null, authHeader, -1);

        if (response != null && !response.isEmpty()) {
            JSONObject root = new JSONObject(response);
            if (root.has("name")) {
                JSONArray comments = root.getJSONArray("comments");
                for (int c = 0; c < comments.length(); c++) {
                    Artifact.Comment comment = new Artifact.Comment();
                    JSONObject commentResponse = comments.getJSONObject(c);
                    if (commentResponse.has("text")) {
                        comment.setComment(commentResponse.getString("text"));
                    }
                    if (commentResponse.has("creation_date")) {
                        comment.setPublishDate(commentResponse.getString("creation_date"));
                    }
                    if (commentResponse.has("author")) {
                        comment.setAuthorNode(commentResponse.getString("author"));

                    }

                    commentsList.add(comment);
                }
            }

        } else {
            logger.info("WLP: Calling[" + url + "] " + response);
        }
    } catch (Exception e) {
        logger.error("WLP: Calling[" + url + "] " + e.getMessage());
        throw new WeLivePlayerCustomException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }

    return commentsList;
}

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

@RequestMapping(method = RequestMethod.GET, value = "/geostops/{agencyId}")
public @ResponseBody List<Stop> getGeolocalizedStops(HttpServletRequest request, HttpServletResponse response,
        @PathVariable String agencyId, @RequestParam double lat, @RequestParam double lng,
        @RequestParam double radius, @RequestParam(required = false) Integer page,
        @RequestParam(required = false) Integer count) {
    try {/*from  w w w .  ja v a 2  s. co m*/

        //         String address =  otpURL + OTP + "getGeolocalizedStops";
        //         String res = HTTPConnector.doPost(address, content, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON);
        return smartPlannerHelper.stops(agencyId, lat, lng, radius, page, count);
        //         String res2 = new String(res.getBytes(), Charset.forName("UTF-8"));
        //         List result = mapper.readValue(res2, List.class);
        //         return result;

    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}