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:org.openmrs.module.openhmis.inventory.web.controller.JasperReportController.java

private String renderStockOperationsByStockroomReport(int reportId, WebRequest request,
        HttpServletResponse response) throws IOException {
    int itemId;//from w ww .  j a  v a  2  s  . c o m
    Date beginDate = null, endDate = null;
    int stockroomId;

    String temp = request.getParameter("stockroomId");
    if (!StringUtils.isEmpty(temp) && StringUtils.isNumeric(temp)) {
        stockroomId = Integer.parseInt(temp);
    } else {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The stockroom id ('" + temp + "') must be " + "defined and be numeric.");
        return null;
    }

    temp = request.getParameter("itemUuid");
    if (!StringUtils.isEmpty(temp)) {
        IItemDataService itemService = Context.getService(IItemDataService.class);
        Item item = itemService.getByUuid(temp);
        if (item != null) {
            itemId = item.getId();
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "No item with UUID '" + temp + "' could be found.");
            return null;
        }
    } else {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The item uuid must be defined.");
        return null;
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    temp = request.getParameter("beginDate");
    if (!StringUtils.isEmpty(temp)) {
        try {
            beginDate = dateFormat.parse(temp);
        } catch (Exception ex) {
            // Whatevs... dealing with stupid checked exceptions
        }
    }

    temp = request.getParameter("endDate");
    if (!StringUtils.isEmpty(temp)) {
        try {
            endDate = dateFormat.parse(temp);
        } catch (Exception ex) {
            // Whatevs... dealing with stupid checked exceptions
        }
    }

    if (beginDate == null || endDate == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The begin and end dates must be defined.");
        return null;
    }

    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("itemId", itemId);
    params.put("beginDate", beginDate);
    params.put("endDate", endDate);
    params.put("stockroomId", stockroomId);

    return renderReport(reportId, params, null, response);
}

From source file:gov.lanl.adore.djatoka.openurl.OpenURLJP2KMetadata.java

/**
 * Returns the OpenURLResponse of a JSON object defining the core image properties. Having obtained a result, this
 * method is then responsible for transforming it into an OpenURLResponse that acts as a proxy for
 * HttpServletResponse./*from   www  .  j av  a2 s  .c o  m*/
 */
@Override
public OpenURLResponse resolve(final ServiceType serviceType, final ContextObject contextObject,
        final OpenURLRequest openURLRequest, final OpenURLRequestProcessor processor) {

    String responseFormat = RESPONSE_TYPE;
    int status = HttpServletResponse.SC_OK;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode rootNode = mapper.createObjectNode();
        final IExtract jp2 = new KduExtractExe();

        ImageRecord r = ReferentManager.getImageRecord(contextObject.getReferent());
        r = jp2.getMetadata(r);

        rootNode.put("identifier", r.getIdentifier());
        rootNode.put("imagefile", r.getImageFile());
        rootNode.put("width", r.getWidth());
        rootNode.put("height", r.getHeight());
        rootNode.put("dwtLevels", r.getDWTLevels());
        rootNode.put("levels", r.getLevels());
        rootNode.put("compositingLayerCount", r.getCompositingLayerCount());

        mapper.writeValue(baos, rootNode);
    } catch (final DjatokaException e) {
        responseFormat = "text/plain";
        status = HttpServletResponse.SC_NOT_FOUND;
    } catch (final Exception e) {
        baos = new ByteArrayOutputStream();

        try {
            if (e.getMessage() != null) {
                baos.write(e.getMessage().getBytes("UTF-8"));
            } else {
                LOGGER.error(e.getMessage(), e);
                baos.write("Internal Server Error: ".getBytes());
            }
        } catch (final UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (final IOException e2) {
            e2.printStackTrace();
        }

        responseFormat = "text/plain";
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    final HashMap<String, String> header_map = new HashMap<String, String>();
    header_map.put("Content-Length", baos.size() + "");
    header_map.put("Date", HttpDate.getHttpDate());
    return new OpenURLResponse(status, responseFormat, baos.toByteArray(), header_map);
}

From source file:com.day.cq.wcm.foundation.forms.impl.FormsListServlet.java

/**
 * {@inheritDoc}/*from   ww  w .j av a2  s . c  o m*/
 */
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp, Predicate predicate)
        throws ServletException, IOException {
    try {
        JSONWriter w = new JSONWriter(resp.getWriter());
        if (req.getRequestURI().contains("/actions")) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");

            writeActions(w);
        } else if (req.getRequestURI().contains("/constraints")) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");

            writeConstraints(w);
        } else if (req.getRequestURI().contains("/actiondialog")) {
            final String dialogPath = this.formsManager.getDialogPathForAction(req.getParameter("id"));
            if (dialogPath != null) {
                req.getRequestDispatcher(dialogPath + ".infinity.json").forward(req, resp);
            } else {
                // if there is no dialog just return an empty dialog
                resp.setContentType("application/json");
                resp.setCharacterEncoding("utf-8");

                resp.getWriter().write("{jcr:primaryType:\"cq:WidgetCollection\"}");
            }
        } else if (req.getRequestURI().contains("/report")) {
            // we collect the information and then redirect to the bulk editor
            final String path = req.getParameter("path");
            if (path == null || path.trim().length() == 0) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Path parameter is missing.");
                return;
            }
            final Resource formStartResource = req.getResourceResolver().getResource(path);
            if (formStartResource == null) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found.");
                return;
            }
            final ValueMap vm = ResourceUtil.getValueMap(formStartResource);
            final StringBuilder sb = new StringBuilder();
            sb.append(req.getContextPath());
            sb.append("/etc/importers/bulkeditor.html?rootPath=");
            String actionPath = vm.get(FormsConstants.START_PROPERTY_ACTION_PATH, "");
            if (actionPath == null || actionPath.trim().length() == 0) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Missing '" + FormsConstants.START_PROPERTY_ACTION_PATH + "' property on node "
                                + formStartResource.getPath());
            }
            if (actionPath.endsWith("*")) {
                actionPath = actionPath.substring(0, actionPath.length() - 1);
            }
            if (actionPath.endsWith("/")) {
                actionPath = actionPath.substring(0, actionPath.length() - 1);
            }
            sb.append(FormsHelper.encodeValue(actionPath));
            sb.append("&initialSearch=true&contentMode=false&spc=true");
            final Iterator<Resource> elements = FormsHelper.getFormElements(formStartResource);
            while (elements.hasNext()) {
                final Resource element = elements.next();
                FieldHelper.initializeField(req, resp, element);
                final FieldDescription[] descs = FieldHelper.getFieldDescriptions(req, element);
                for (final FieldDescription desc : descs) {
                    if (!desc.isPrivate()) {
                        final String name = FormsHelper.encodeValue(desc.getName());
                        sb.append("&cs=");
                        sb.append(name);
                        sb.append("&cv=");
                        sb.append(name);
                    }
                }
            }
            resp.sendRedirect(sb.toString());
        }
    } catch (Exception e) {
        logger.error("Error while generating JSON list", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:contestTabulation.Setup.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    Entity contestInfo = Retrieve.contestInfo();

    GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
            .setTransport(httpTransport)
            .setClientSecrets((String) contestInfo.getProperty("OAuth2ClientId"),
                    (String) contestInfo.getProperty("OAuth2ClientSecret"))
            .build().setFromTokenResponse(new JacksonFactory().fromString(
                    ((Text) contestInfo.getProperty("OAuth2Token")).getValue(), GoogleTokenResponse.class));

    String docName = null, docLevel = null;
    for (Level level : Level.values()) {
        docName = req.getParameter("doc" + level.getName());
        if (docName != null) {
            docLevel = level.toString();
            break;
        }/*  ww w .jav  a 2  s . c o m*/
    }

    if (docLevel == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Spreadsheet creation request must have paramater document name parameter set");
        return;
    }

    Query query = new Query("registration")
            .setFilter(new FilterPredicate("schoolLevel", FilterOperator.EQUAL, docLevel))
            .addSort("schoolName", SortDirection.ASCENDING);
    List<Entity> registrations = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());

    Map<String, List<JSONObject>> studentData = new HashMap<String, List<JSONObject>>();
    for (Entity registration : registrations) {
        String regSchoolName = ((String) registration.getProperty("schoolName")).trim();
        String regStudentDataJSON = unescapeHtml4(((Text) registration.getProperty("studentData")).getValue());

        JSONArray regStudentData = null;
        try {
            regStudentData = new JSONArray(regStudentDataJSON);
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        for (int i = 0; i < regStudentData.length(); i++) {
            if (!studentData.containsKey(regSchoolName)) {
                studentData.put(regSchoolName, new ArrayList<JSONObject>());
            }
            try {
                studentData.get(regSchoolName).add(regStudentData.getJSONObject(i));
            } catch (JSONException e) {
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                e.printStackTrace();
                return;
            }
        }
    }

    for (List<JSONObject> students : studentData.values()) {
        Collections.sort(students, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject a, JSONObject b) {
                try {
                    return a.getString("name").compareTo(b.getString("name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }

    Workbook workbook = new XSSFWorkbook();

    XSSFCellStyle boldStyle = (XSSFCellStyle) workbook.createCellStyle();
    Font boldFont = workbook.createFont();
    boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    boldStyle.setFont(boldFont);

    Map<Subject, XSSFCellStyle> subjectCellStyles = new HashMap<Subject, XSSFCellStyle>();
    for (Subject subject : Subject.values()) {
        final double ALPHA = .144;
        String colorStr = (String) contestInfo.getProperty("color" + subject.getName());
        byte[] backgroundColor = new byte[] { Integer.valueOf(colorStr.substring(1, 3), 16).byteValue(),
                Integer.valueOf(colorStr.substring(3, 5), 16).byteValue(),
                Integer.valueOf(colorStr.substring(5, 7), 16).byteValue() };
        // http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
        byte[] borderColor = new byte[] { (byte) ((backgroundColor[0] & 0xff) * (1 - ALPHA)),
                (byte) ((backgroundColor[1] & 0xff) * (1 - ALPHA)),
                (byte) ((backgroundColor[2] & 0xff) * (1 - ALPHA)) };

        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
        style.setFillBackgroundColor(new XSSFColor(backgroundColor));
        style.setFillPattern(CellStyle.ALIGN_FILL);

        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(new XSSFColor(borderColor));
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(new XSSFColor(borderColor));
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(new XSSFColor(borderColor));
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(new XSSFColor(borderColor));
        subjectCellStyles.put(subject, style);
    }

    Entry<String, List<JSONObject>>[] studentDataEntries = studentData.entrySet().toArray(new Entry[] {});
    Arrays.sort(studentDataEntries, Collections.reverseOrder(new Comparator<Entry<String, List<JSONObject>>>() {
        @Override
        public int compare(Entry<String, List<JSONObject>> arg0, Entry<String, List<JSONObject>> arg1) {
            return Integer.compare(arg0.getValue().size(), arg1.getValue().size());
        }
    }));

    for (Entry<String, List<JSONObject>> studentDataEntry : studentDataEntries) {
        Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(studentDataEntry.getKey()));
        Row row = sheet.createRow((short) 0);

        String[] columnNames = { "Name", "Grade", "N", "C", "M", "S" };
        for (int i = 0; i < columnNames.length; i++) {
            String columnName = columnNames[i];
            Cell cell = row.createCell(i);
            cell.setCellValue(columnName);
            cell.setCellStyle(boldStyle);
            CellUtil.setAlignment(cell, workbook, CellStyle.ALIGN_CENTER);
        }

        int longestNameLength = 7;
        int rowNum = 1;
        for (JSONObject student : studentDataEntry.getValue()) {
            try {
                row = sheet.createRow((short) rowNum);
                row.createCell(0).setCellValue(student.getString("name"));
                row.createCell(1).setCellValue(student.getInt("grade"));

                for (Subject subject : Subject.values()) {
                    String value = student.getBoolean(subject.toString()) ? "" : "X";
                    Cell cell = row.createCell(Arrays.asList(columnNames).indexOf(subject.toString()));
                    cell.setCellValue(value);
                    cell.setCellStyle(subjectCellStyles.get(subject));
                }

                if (student.getString("name").length() > longestNameLength) {
                    longestNameLength = student.getString("name").length();
                }

                rowNum++;
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            }
        }

        sheet.createFreezePane(0, 1, 0, 1);
        // sheet.autoSizeColumn((short) 0); Not supported by App Engine
        sheet.setColumnWidth((short) 0, (int) (256 * longestNameLength * 1.1));
    }

    Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName("contestTabulation").build();

    File body = new File();
    body.setTitle(docName);
    body.setMimeType("application/vnd.google-apps.spreadsheet");

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    workbook.write(outStream);
    ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
    InputStreamContent content = new InputStreamContent(
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", inStream);

    drive.files().insert(body, content).execute();
    workbook.close();
}

From source file:axiom.servlet.AbstractServletClient.java

/**
 * Handle a request.//w w w  . jav a 2  s .  c o m
 *
 * @param request ...
 * @param response ...
 *
 * @throws ServletException ...
 * @throws IOException ...
 */
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final String httpMethod = request.getMethod();
    if (!"POST".equalsIgnoreCase(httpMethod) && !"GET".equalsIgnoreCase(httpMethod)) {
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "HTTP Method " + httpMethod + " not supported.");
        return;
    }

    RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request));

    try {
        // get the character encoding
        String encoding = request.getCharacterEncoding();

        if (encoding == null) {
            // no encoding from request, use the application's charset
            encoding = getApplication().getCharset();
        }

        // read and set http parameters
        parseParameters(request, reqtrans, encoding);

        List uploads = null;
        ServletRequestContext reqcx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(reqcx)) {
            // get session for upload progress monitoring
            UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans);
            try {
                uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding);
            } catch (Exception upx) {
                System.err.println("Error in file upload: " + upx);
                if (uploadSoftfail) {
                    String msg = upx.getMessage();
                    if (msg == null || msg.length() == 0) {
                        msg = upx.toString();
                    }
                    reqtrans.set("axiom_upload_error", msg);
                } else if (upx instanceof FileUploadBase.SizeLimitExceededException) {
                    sendError(response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                            "File upload size exceeds limit of " + uploadLimit + "kB");
                    return;
                } else {
                    sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Error in file upload: " + upx);
                    return;
                }
            }
        }

        parseCookies(request, reqtrans, encoding);

        // do standard HTTP variables
        String host = request.getHeader("Host");

        if (host != null) {
            host = host.toLowerCase();
            reqtrans.set("http_host", host);
        }

        String referer = request.getHeader("Referer");

        if (referer != null) {
            reqtrans.set("http_referer", referer);
        }

        try {
            long ifModifiedSince = request.getDateHeader("If-Modified-Since");

            if (ifModifiedSince > -1) {
                reqtrans.setIfModifiedSince(ifModifiedSince);
            }
        } catch (IllegalArgumentException ignore) {
        }

        String ifNoneMatch = request.getHeader("If-None-Match");

        if (ifNoneMatch != null) {
            reqtrans.setETags(ifNoneMatch);
        }

        String remotehost = request.getRemoteAddr();

        if (remotehost != null) {
            reqtrans.set("http_remotehost", remotehost);
        }

        // get the cookie domain to use for this response, if any.
        String resCookieDomain = cookieDomain;

        if (resCookieDomain != null) {
            // check if cookieDomain is valid for this response.
            // (note: cookieDomain is guaranteed to be lower case)
            // check for x-forwarded-for header, fix for bug 443
            String proxiedHost = request.getHeader("x-forwarded-host");
            if (proxiedHost != null) {
                if (proxiedHost.toLowerCase().indexOf(cookieDomain) == -1) {
                    resCookieDomain = null;
                }
            } else if ((host != null) && host.toLowerCase().indexOf(cookieDomain) == -1) {
                resCookieDomain = null;
            }
        }

        // check if session cookie is present and valid, creating it if not.
        checkSessionCookie(request, response, reqtrans, resCookieDomain);

        String browser = request.getHeader("User-Agent");

        if (browser != null) {
            reqtrans.set("http_browser", browser);
        }

        String language = request.getHeader("Accept-Language");

        if (language != null) {
            reqtrans.set("http_language", language);
        }

        String authorization = request.getHeader("authorization");

        if (authorization != null) {
            reqtrans.set("authorization", authorization);
        }

        ResponseTrans restrans = getApplication().execute(reqtrans);

        // if the response was already written and committed by the application
        // we can skip this part and return
        if (response.isCommitted()) {
            return;
        }

        // set cookies
        if (restrans.countCookies() > 0) {
            CookieTrans[] resCookies = restrans.getCookies();

            for (int i = 0; i < resCookies.length; i++)
                try {
                    Cookie c = resCookies[i].getCookie("/", resCookieDomain);

                    response.addCookie(c);
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
        }

        // write response
        writeResponse(request, response, reqtrans, restrans);

    } catch (Exception x) {
        try {
            if (debug) {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x);
                x.printStackTrace();
            } else {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "The server encountered an error while processing your request. "
                                + "Please check back later.");
            }

            log("Exception in execute: " + x);
        } catch (IOException io_e) {
            log("Exception in sendError: " + io_e);
        }
    }
}

From source file:eu.trentorise.smartcampus.unidataservice.controller.rest.StudentInfoController.java

@RequestMapping(method = RequestMethod.GET, value = "/getstudentexams")
public @ResponseBody StudentInfoExams getStudentExams(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) throws InvocationException {
    try {/*  w  w  w .  j a v a 2 s.co m*/
        User user = getCurrentUser();
        String userId = getUserId(user);
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        String token = getToken(request);
        String idAda = getIdAda(token);
        StudentInfoExams result = getStudentExams(idAda);
        if (result != null) {
            return result;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

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

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

/**
 * Update the material.//  w w  w .  jav a  2 s  . c om
 *
 * @param id the id
 * @param colId the col id
 * @param value the value
 * @param request the request
 * @param response the response
 * @return the string
 */
@RequestMapping(value = "/materials/update", method = RequestMethod.POST)
@PreAuthorize("hasAnyRole('ROLE_EDITOR','ROLE_ADMIN')")
public @ResponseBody String updateMaterial(@RequestParam(value = "id", required = true) final String id,
        @RequestParam(value = "columnPosition", required = true) final Integer colId,
        @RequestParam(value = "value", required = true) final String value, final HttpServletRequest request,
        final HttpServletResponse response) {

    String returnMessage = "";

    MaterialDetail material = MaterialDetail.findByName(id);

    if (material != null) {
        try {
            returnMessage = material.set(colId, value, this.getContext());
            material.merge();
            material.flush();
            List<Long> affectedProjects = material.postUpdate();

            if (affectedProjects.size() > 0) {
                Preferences preferences = this.getPreferences(request);

                if (preferences.addProjectsToRefresh(affectedProjects)) {
                    try {
                        preferences.merge();
                        preferences.flush();
                    } catch (Exception e) {
                        logger.error("Error updating affected projects: " + e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            returnMessage = this.getMessage("materials_library_update_error");
        }
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        returnMessage = this.getMessage("materials_library_update_notfounderror");
    }
    return returnMessage;
}

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

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String sortBy = null;/*from   ww  w .j  a v a  2 s. c  o m*/
    int sortDir = 1;
    res.setCharacterEncoding("UTF-8");
    try {
        String searchId = WebScriptUtils.cleanGetParameter(req, "id");
        sortBy = WebScriptUtils.cleanGetParameter(req, PAGE_SORT_BY_PARAMETER);
        String sortDirString = WebScriptUtils.cleanGetParameter(req, PAGE_SORT_DIR_PARAMETER);
        if (sortDirString != null)
            sortDir = Integer.parseInt(sortDirString);

        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, searchId);
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Loading " + searchId);

        SearchQuery query = workspaceService.getSearch(searchId);

        /* Query */
        try {
            dataJSON.put(QUERY_TAG, query.toJson());
        } catch (JSONException e) {
            LOGGER.error("could not return search criteria for search " + searchId, e);
        }

        /* Message Result List */

        try {
            SearchResult result = query.getResult();
            List<String> messageIds = result.getPage(sortBy, sortDir, pageInfo.getPagePos(),
                    pageInfo.getPageSize());

            List<MessageSummary> messageSummaries = archiveService.retrieveSummary(messageIds);
            pageInfo.setItemTotal(result.getCount());
            dataJSON.put(WebConstants.STATUS_ID_TAG, query.getStatus());

            JSONArray jsonMessageSummaryList = SearchResultsBuilder
                    .getMessageListJSON((Collection<MessageSummary>) messageSummaries);

            dataJSON.put(ITEM_TOTAL_TAG, pageInfo.getItemTotal());

            dataJSON.put(RESULTS_TAG, jsonMessageSummaryList);
        } catch (CannotRetrieveException e) {
            LOGGER.error("Could not access result message list", e);
            // throw new WebScriptException(
            // "Could not access query result message list", e);
        } catch (ResultPageException e) {
            LOGGER.error("Could not get page of results", e);
            this.addError(dataJSON, e.toString());
        }
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Returning saved search results for search id " + searchId);

        jsonResult.put(DATA_TAG, dataJSON);
        jsonResult.put(PAGING_LABEL, pageInfo.getPageJSON());
        jsonResult.write(res.getWriter());
    } 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);
    } finally {

    }
}