Example usage for javax.servlet.http HttpServletResponse setCharacterEncoding

List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setCharacterEncoding.

Prototype

public void setCharacterEncoding(String charset);

Source Link

Document

Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

Usage

From source file:cn.edu.hbcit.servlets.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*from   w  w  w .j  ava  2  s  .co  m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            FileOperate fo = new FileOperate();//liwei (+ )
            upload.setHeaderEncoding("UTF-8");//liwei 
            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String oldName = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);
                filename = fo.generateRandomFilename() + extension;//liwei (+ )
                //filename = UUID.randomUUID().toString()+"."+extension;//liwei (UUID)
                logger.warn("" + oldName + "" + filename + "");
                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.google.wave.api.AbstractRobot.java

/**
 * Serializes the given outgoing operations into a JSON string, and put it in
 * the given response object.//from   w  w w.j  a v  a2  s.c om
 *
 * @param operations the operations to be serialized.
 * @param resp the response object to flush the output string into.
 */
private static void serializeOperations(List<OperationRequest> operations, HttpServletResponse resp) {
    try {
        String json = SERIALIZER.toJson(operations, new TypeToken<List<OperationRequest>>() {
        }.getType());
        LOG.info("Outgoing operations: " + json);

        resp.setContentType(JSON_MIME_TYPE);
        resp.setCharacterEncoding(UTF_8);
        resp.getWriter().write(json);
        resp.setStatus(HttpURLConnection.HTTP_OK);
    } catch (IOException iox) {
        resp.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:com.wellmail.servlet.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*from  w  w w  .  ja va  2s  .  c o m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);

                //20k
                else if (uplFile.getSize() > 100 * 1024) {
                    ur = new UploadResponse(204);
                }

                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:net.sourceforge.subsonic.security.RESTRequestParameterProcessingFilter.java

private void sendErrorXml(HttpServletRequest request, HttpServletResponse response,
        RESTController.ErrorCode errorCode) throws IOException {
    String format = ServletRequestUtils.getStringParameter(request, "f", "xml");
    boolean json = "json".equals(format);
    boolean jsonp = "jsonp".equals(format);
    XMLBuilder builder;/*from www .j  av  a 2 s  .  com*/

    response.setCharacterEncoding(StringUtil.ENCODING_UTF8);

    if (json) {
        builder = XMLBuilder.createJSONBuilder();
        response.setContentType("application/json");
    } else if (jsonp) {
        builder = XMLBuilder.createJSONPBuilder(request.getParameter("callback"));
        response.setContentType("text/javascript");
    } else {
        builder = XMLBuilder.createXMLBuilder();
        response.setContentType("text/xml");
    }

    builder.preamble(StringUtil.ENCODING_UTF8);
    builder.add("subsonic-response", false, new XMLBuilder.Attribute("xmlns", "http://subsonic.org/restapi"),
            new XMLBuilder.Attribute("status", "failed"),
            new XMLBuilder.Attribute("version", StringUtil.getRESTProtocolVersion()));

    builder.add("error", true, new XMLBuilder.Attribute("code", errorCode.getCode()),
            new XMLBuilder.Attribute("message", errorCode.getMessage()));
    builder.end();
    response.getWriter().print(builder);
}

From source file:it.unimi.di.big.mg4j.query.InputStreamItem.java

protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    try {//from  ww  w . j av a2s .  c o  m
        if (request.getParameter("m") != null && request.getParameter("doc") != null) {
            DocumentCollection collection = (DocumentCollection) getServletContext().getAttribute("collection");
            if (collection == null)
                LOGGER.error("The servlet context does not contain a document collection.");
            response.setContentType(request.getParameter("m"));
            response.setCharacterEncoding("UTF-8");
            InputStream rawContent = collection.stream(Long.parseLong(request.getParameter("doc")));
            for (int i = skip; i-- != 0;)
                rawContent.reset();
            IOUtils.copy(rawContent, response.getOutputStream());
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
        LOGGER.error(e.toString());
        throw e;
    }
}

From source file:com.taobao.diamond.server.controller.BaseStoneController.java

@RequestMapping(params = "method=deleteConfig", method = RequestMethod.POST)
public String deleteConfig(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataId") String dataId, @RequestParam("group") String group,
        @RequestParam("content") String content) {
    response.setCharacterEncoding("GBK");

    boolean checkSuccess = true;
    String errorMessage = "";
    if (!StringUtils.hasLength(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
        checkSuccess = false;//from   w w  w . j av a  2  s.  c o  m
        errorMessage = "DataId";
    }
    if (!StringUtils.hasLength(group) || DiamondUtils.hasInvalidChar(group.trim())) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (!StringUtils.hasLength(content)) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (!checkSuccess) {
        try {
            response.sendError(INVALID_PARAM, errorMessage);
        } catch (IOException e) {
            log.error("response", e);
        }
        return "536";
    }

    this.removeConfigInfo(dataId, group, content);

    return "200";
}

From source file:com.lecheng.cms.servlet.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*  w w  w.j  a  va2  s .  co m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    // logger.debug("Parameter Command: {}", commandStr);
    // logger.debug("Parameter Type: {}", typeStr);
    // logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            // FileOperate fo = new FileOperate();//liwei
            // (+ )
            upload.setHeaderEncoding("UTF-8");// liwei 
            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String oldName = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);
                // filename = fo.generateRandomFilename() +
                // extension;//liwei
                // (+ )
                filename = UUID.randomUUID().toString() + "." + extension;// liwei
                // (UUID)
                // logger.warn(""+oldName+""+filename+"");
                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    // logger.debug("Exiting Connector#doPost");
}

From source file:it.unimi.di.big.mg4j.query.QueryServlet.java

public Template handleRequest(final HttpServletRequest request, final HttpServletResponse response,
        final Context context) {

    try {/*from   ww w.j  a  v  a 2 s  .c  o m*/
        response.setCharacterEncoding("UTF-8");

        // This string is URL-encoded, and with the wrong coding.
        //String query = request.getParameter( "q" ) != null ? new String( request.getParameter( "q" ).getBytes( "ISO-8859-1" ), "UTF-8" ) : null;
        String query = request.getParameter("q");
        context.put("action", request.getContextPath() + request.getServletPath());

        // Sanitise parameters.
        int start = 0, maxNumItems = STD_MAX_NUM_ITEMS;
        try {
            maxNumItems = Integer.parseInt(request.getParameter("m"));
        } catch (NumberFormatException dontCare) {
        }
        try {
            start = Integer.parseInt(request.getParameter("s"));
        } catch (NumberFormatException dontCare) {
        }

        if (maxNumItems < 0 || maxNumItems > 1000)
            maxNumItems = STD_MAX_NUM_ITEMS;
        if (start < 0)
            start = 0;

        if (query != null && query.length() != 0) {

            // This is used to display again the query in the input control.
            context.put("q", StringEscapeUtils.escapeHtml(query));
            // This is used to put the query in URLs.
            context.put("qUrl", URLEncoder.encode(query, "UTF-8"));
            context.put("firstItem", new Integer(start));

            // First of all, we check that the query is correct

            long time = -System.currentTimeMillis();
            ObjectArrayList<DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>>> results = new ObjectArrayList<DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>>>();

            int globNumItems;

            try {
                globNumItems = queryEngine.copy().process(query, start, maxNumItems, results);
            } catch (QueryBuilderVisitorException e) {
                context.put("errmsg", StringEscapeUtils.escapeHtml(e.getCause().toString()));
                return getTemplate(template);
            } catch (QueryParserException e) {
                context.put("errmsg", StringEscapeUtils.escapeHtml(e.getCause().toString()));
                return getTemplate(template);
            } catch (Exception e) {
                context.put("errmsg", StringEscapeUtils.escapeHtml(e.toString()));
                return getTemplate(template);
            }

            time += System.currentTimeMillis();

            ObjectArrayList<ResultItem> resultItems = new ObjectArrayList<ResultItem>();

            if (!results.isEmpty()) {
                SelectedInterval[] selectedInterval = null;

                final DocumentCollection collection = documentCollection != null ? documentCollection.copy()
                        : null;

                for (int i = 0; i < results.size(); i++) {
                    DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>> dsi = results.get(i);
                    LOGGER.debug("Intervals for item " + i);
                    final ResultItem resultItem = new ResultItem(dsi.document, dsi.score);
                    resultItems.add(resultItem);

                    if (collection != null) {
                        final Document document = collection.document(dsi.document);
                        // If both collection and title list are present, we override the collection title (cfr. Query)
                        resultItem.title = StringEscapeUtils
                                .escapeHtml(titleList != null ? titleList.get(resultItem.doc).toString()
                                        : document.title().toString());
                        if (useUri) {
                            if (document.uri() != null)
                                resultItem.uri = StringEscapeUtils.escapeHtml(document.uri().toString());
                        } else {
                            if (document.uri() != null) {
                                String stringUri = document.uri().toString();
                                // TODO: this is a quick patch to get the file server running with relative files
                                final String documentUri = URLEncoder.encode(derelativise
                                        ? new File(stringUri.startsWith("file:") ? stringUri.substring(5)
                                                : stringUri).getAbsoluteFile().toURI().toASCIIString()
                                        : document.uri().toString(), "UTF-8");
                                resultItem.uri = StringEscapeUtils.escapeHtml("./Item?doc=" + resultItem.doc
                                        + "&m=" + urlEncodedMimeType + "&uri=" + documentUri);
                            } else
                                resultItem.uri = StringEscapeUtils.escapeHtml(
                                        "./Item?doc=" + resultItem.doc + "&m=" + urlEncodedMimeType);
                        }

                        MarkingMutableString snippet = new MarkingMutableString(TextMarker.HTML_STRONG,
                                MarkingMutableString.HTML_ESCAPE);

                        for (int j = 0; j < sortedIndex.length; j++) {
                            if (!sortedIndex[j].hasPositions || dsi.info == null)
                                continue;
                            selectedInterval = dsi.info.get(sortedIndex[j]);
                            if (selectedInterval != null) {
                                final int field = documentCollection.factory().fieldIndex(sortedIndex[j].field);
                                // If the field is not present (e.g., because of parallel indexing) or it is not text we skip
                                if (field == -1 || documentCollection.factory()
                                        .fieldType(field) != DocumentFactory.FieldType.TEXT)
                                    continue;
                                LOGGER.debug(
                                        "Found intervals for " + sortedIndex[j].field + " (" + field + ")");
                                final Reader content = (Reader) document.content(field);
                                snippet.startField(selectedInterval)
                                        .appendAndMark(document.wordReader(field).setReader(content))
                                        .endField();
                            }
                            if (LOGGER.isDebugEnabled())
                                LOGGER.debug(sortedIndex[j].field + ": "
                                        + (selectedInterval == null ? null : Arrays.asList(selectedInterval)));
                            document.close();
                        }

                        resultItem.text = snippet;
                    } else {
                        if (titleList != null) {
                            // TODO: this is a bit radical
                            resultItem.title = resultItem.uri = titleList.get(resultItem.doc);
                        } else {
                            resultItem.title = "Document #" + resultItem.doc;
                            resultItem.uri = new MutableString("./Item?doc=").append(resultItem.doc)
                                    .append("&m=").append(urlEncodedMimeType);
                        }

                        MutableString text = new MutableString();
                        for (Iterator<Index> j = indexMap.values().iterator(); j.hasNext();) {
                            final Index index = j.next();
                            selectedInterval = dsi.info.get(index);
                            if (selectedInterval != null)
                                text.append("<p>").append(index.field).append(": ")
                                        .append(Arrays.asList(selectedInterval));
                            LOGGER.debug(index.field + ": "
                                    + (selectedInterval == null ? null : Arrays.asList(selectedInterval)));
                        }
                        resultItem.text = text;
                    }
                }

                if (collection != null)
                    collection.close();
            }

            // Note that if we pass an array to the template we lose the possibility of measuring its length.
            context.put("result", resultItems);
            /* Note that this number is just the number of relevant documents met while
               trying to obtain the current results. Due to the short-circuit semantics of the
               "and then" operator, it  might not reflect accurately the overall number of
               results of the query. */
            context.put("globNumItems", new Integer(globNumItems));
            context.put("start", new Integer(start));
            context.put("maxNumItems", new Integer(maxNumItems));
            context.put("time", new Integer((int) time));
            context.put("speed", new Long((int) (globNumItems * 1000L / (time + 1))));
        }

        return getTemplate(template);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        return null;
    }
}

From source file:com.jl.common.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //w w w.  jav  a 2  s .c o  m
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");//

            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID().toString() + "." + extension;//

                //
                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                }

                //
                else if (uplFile.getSize() > 50 * 1024) {
                    //
                    ur = new UploadResponse(204);
                }
                // 
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }
    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.rmn.qa.servlet.AutomationTestRunServlet.java

/**
 * Attempts to register a new run request with the server. Returns a 201 if the request can be fulfilled but AMIs
 * must be started Returns a 202 if the request can be fulfilled Returns a 400 if the required parameters are not
 * passed in. Returns a 409 if the server is at full node capacity
 *///w ww.  java 2s  .c o m
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    String browserRequested = request.getParameter("browser");
    String browserVersion = request.getParameter("browserVersion");
    String osRequested = request.getParameter("os");
    String threadCount = request.getParameter("threadCount");
    String uuid = request.getParameter(AutomationConstants.UUID);
    BrowserPlatformPair browserPlatformPairRequest;
    Platform requestedPlatform;

    // Return a 400 if any of the required parameters are not passed in
    // Check for uuid first as this is the most important variable
    if (uuid == null) {
        String msg = "Parameter 'uuid' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (browserRequested == null) {
        String msg = "Parameter 'browser' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (threadCount == null) {
        String msg = "Parameter 'threadCount' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (StringUtils.isEmpty(osRequested)) {
        requestedPlatform = Platform.ANY;
    } else {
        requestedPlatform = AutomationUtils.getPlatformFromObject(osRequested);
        if (requestedPlatform == null) {
            String msg = "Parameter 'os' does not have a valid Selenium Platform equivalent: " + osRequested;
            log.error(msg);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return;
        }
    }

    Integer threadCountRequested = Integer.valueOf(threadCount);

    AutomationRunRequest runRequest = new AutomationRunRequest(uuid, threadCountRequested, browserRequested,
            browserVersion, requestedPlatform);
    browserPlatformPairRequest = new BrowserPlatformPair(browserRequested, requestedPlatform);

    log.info(String.format("Server request [%s] received.", runRequest));
    boolean amisNeeded;
    int amiThreadsToStart = 0;
    int currentlyAvailableNodes;
    // Synchronize this block until we've added the run to our context for other potential threads to see
    synchronized (AutomationTestRunServlet.class) {
        int remainingNodesAvailable = AutomationContext.getContext().getTotalThreadsAvailable(getProxySet());
        // If the number of nodes this grid hub can actually run is less than the number requested, this hub can not
        // fulfill this run at this time
        if (remainingNodesAvailable < runRequest.getThreadCount()) {
            log.error(String.format(
                    "Requested node count of [%d] could not be fulfilled due to hub limit. [%d] nodes available - Request UUID [%s]",
                    threadCountRequested, remainingNodesAvailable, uuid));
            response.sendError(HttpServletResponse.SC_CONFLICT,
                    "Server cannot fulfill request due to configured node limit being reached.");
            return;
        }
        // Get the number of matching, free nodes to determine if we need to start up AMIs or not
        currentlyAvailableNodes = requestMatcher.getNumFreeThreadsForParameters(getProxySet(), runRequest);
        // If the number of available nodes is less than the total number requested, we will have to spin up AMIs in
        // order to fulfill the request
        amisNeeded = currentlyAvailableNodes < threadCountRequested;
        if (amisNeeded) {
            // Get the difference which will be the number of additional nodes we need to spin up to supplement
            // existing nodes
            amiThreadsToStart = threadCountRequested - currentlyAvailableNodes;
        }
        // If the browser requested is not supported by AMIs, we need to not unnecessarily spin up AMIs
        if (amisNeeded && !AutomationUtils.browserAndPlatformSupported(browserPlatformPairRequest)) {
            response.sendError(HttpServletResponse.SC_GONE,
                    "Request cannot be fulfilled and browser and platform is not supported by AMIs");
            return;
        }
        // Add the run to our context so we can track it
        AutomationRunRequest newRunRequest = new AutomationRunRequest(uuid, threadCountRequested,
                browserRequested, browserVersion, requestedPlatform);
        boolean addSuccessful = AutomationContext.getContext().addRun(newRunRequest);
        if (!addSuccessful) {
            log.warn(String.format("Test run already exists for the same UUID [%s]", uuid));
            //                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Test run already exists with the same UUID.");
            response.setStatus(HttpServletResponse.SC_CREATED);
            return;
        }
    }
    if (amisNeeded) {
        // Start up AMIs as that will be required
        log.warn(String.format(
                "Insufficient nodes to fulfill request. New AMIs will be queued up. Requested [%s] - Available [%s] - Request UUID [%s]",
                threadCountRequested, currentlyAvailableNodes, uuid));
        try {
            AutomationTestRunServlet.startNodes(ec2, uuid, amiThreadsToStart, browserRequested,
                    requestedPlatform);
        } catch (NodesCouldNotBeStartedException e) {
            // Make sure and de-register the run if the AMI startup was not successful
            AutomationContext.getContext().deleteRun(uuid);
            String throwableMessage = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
            String msg = "Nodes could not be started: " + throwableMessage;
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
            return;
        }
        // Return a 201 to let the caller know AMIs will be started
        response.setStatus(HttpServletResponse.SC_CREATED);
        return;
    } else {
        // Otherwise just return a 202 letting the caller know the requested resources are available
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }
}