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:mobi.jenkinsci.server.core.servlet.HttpRequestDispatcherServlet.java

private void setResponseHeaders(final HttpServletResponse resp, final AbstractNode responseTree) {
    if (!responseTree.isCacheable()) {
        resp.setHeader("Cache-Control", "no-cache");
    }/*from  www  .j  a  v  a 2 s. c o  m*/
    final String eTag = responseTree.getETag();
    if (eTag != null) {
        resp.setHeader("ETag", eTag);
    }
    if (responseTree.getHttpCharacterEncoding() != null) {
        resp.setCharacterEncoding(responseTree.getHttpCharacterEncoding());
    }
}

From source file:msec.org.FileUploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Map<String, String> fields = new HashMap<String, String>();
    List<String> fileNames = new ArrayList<String>();

    request.setCharacterEncoding("UTF-8");

    String result = FileUpload(fields, fileNames, request, response);

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();

    if (result == null || !result.equals("success")) {
        out.printf("{\"status\":100, \"message\":\"%s\"}", result == null ? "" : result);
        return;/*from   w  w w .  j  a  va  2 s.c o  m*/
    }
    String handleClass = fields.get("handleClass");
    if (handleClass != null && handleClass.equals("beans.service.LibraryFileUpload")) {
        //out.write(new LibraryFileUpload().run(fields, fileNames));
        return;
    }
    if (handleClass != null && handleClass.equals("beans.service.SharedobjectUpload")) {
        //  out.write(new SharedobjectUpload().run(fields, fileNames));
        return;

    }
    out.write("{\"status\":100, \"message\":\"unkown handle class\"}");
    return;

}

From source file:com.sshdemo.common.report.manage.web.ParameterSetAction.java

private void buildText() {
    PrintWriter pw = null;/*from   w  ww  . j  ava 2 s.c om*/
    InputStream in = null;
    try {
        TextReport report = reportFac.findTextReportById(reportId);
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpServletRequest request = ServletActionContext.getRequest();

        pw = response.getWriter();
        response.reset();// 
        response.setContentLength(0);
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
        byte[] bytes = textFactory.export(paraMap, report, fileFormat, response, request);
        in = new ByteArrayInputStream(bytes);
        int len = 0;
        while ((len = in.read()) > -1) {
            pw.write(len);
        }
        pw.flush();
    } catch (Exception e) {
        // log.error(e.toString());
    } finally {
        if (pw != null) {
            try {
                pw.close();
                pw = null;
            } catch (Exception e) {
            }
        }
        if (in != null) {
            try {
                in.close();
                in = null;
            } catch (Exception e) {
            }
        }
    }
}

From source file:br.unicamp.cotuca.dpd.pd12.acinet.vagalmail.servlet.Configuracoes.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    if (request.getRequestURI().contains("/pasta")) {
        String acao = request.getParameter("acao"), url = request.getParameter("url"),
                novo = request.getParameter("novo");

        JSONObject obj = new JSONObject();
        if (acao == null || url == null) {
            obj.put("erro", "Solicitao invlida");
            obj.writeJSONString(response.getWriter());
            return;
        }/*from  w  w w  .j av  a  2  s.co  m*/

        if ((acao.equals("renomear") || acao.equals("nova")) && novo == null) {
            obj.put("erro", "Solicitao invlida");
            obj.writeJSONString(response.getWriter());
            return;
        }

        try {
            Conta conta = (Conta) request.getSession().getAttribute("conta");
            Store store = Logar.getImapStore(conta);

            Folder pasta = null;

            if (!acao.equals("nova")) {
                URLName urln = new URLName(url);
                pasta = store.getFolder(urln);

                if (pasta.isOpen())
                    pasta.close(false);
            }

            switch (acao) {
            case "renomear":
                if (pasta.renameTo(store.getFolder(novo))) {
                    obj.put("sucesso", "Renomeado com sucesso");
                } else {
                    obj.put("erro", "Erro ao renomear a pasta");
                }
                break;
            case "esvaziar":
                pasta.open(Folder.READ_WRITE);
                pasta.setFlags(1, pasta.getMessageCount(), new Flags(Flags.Flag.DELETED), true);
                pasta.expunge();
                obj.put("sucesso", "Esvaziado com sucesso");
                break;
            case "excluir":
                if (pasta.delete(true)) {
                    obj.put("sucesso", "Excludo com sucesso");
                } else {
                    obj.put("erro", "Erro ao excluir a pasta");
                }
                break;
            case "nova":
                pasta = store.getFolder(novo);
                if (!pasta.exists()) {
                    if (pasta.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)) {
                        obj.put("sucesso", "Criado com sucesso");
                    } else {
                        obj.put("erro", "Erro ao criar a pasta");
                    }
                } else {
                    obj.put("erro", "Erro ao criar a pasta");
                }
                break;
            }
        } catch (MessagingException ex) {
            obj.put("erro", "Erro ao processar solicitao");
        }

        obj.writeJSONString(response.getWriter());

        return;
    }

    String metodo = request.getParameter("acao");
    if (metodo == null) {
        return;
    } else if (metodo.equals("nova")) {
        EntityManager em = BD.getEntityManager();

        try {
            em.getTransaction().begin();

            Login usuario = Logar.getLogin(request.getSession());

            Conta conta = new Conta();
            conta.setEmail(request.getParameter("email"));
            conta.setImapHost(request.getParameter("imapHost"));
            conta.setImapPort(Integer.parseInt(request.getParameter("imapPort")));
            conta.setImapPassword(request.getParameter("imapPassword"));
            conta.setImapUser(request.getParameter("imapLogin"));
            conta.setSmtpHost(request.getParameter("smtpHost"));
            conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort")));
            conta.setSmtpPassword(request.getParameter("smtpPassword"));
            conta.setSmtpUser(request.getParameter("smtpLogin"));
            conta.setIdLogin(usuario);

            em.persist(conta);
            em.merge(usuario);

            em.getTransaction().commit();
            em.refresh(conta);
            em.refresh(usuario);

            request.setAttribute("mensagem", "sucesso");
        } catch (Logar.NaoAutenticadoException | PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=nova").forward(request, response);
    } else if (metodo.equals("conta")) {
        EntityManager em = BD.getEntityManager();

        try {
            em.getTransaction().begin();

            Conta conta = (Conta) request.getSession().getAttribute("conta");

            em.refresh(conta);
            conta.setEmail(request.getParameter("email"));
            conta.setImapHost(request.getParameter("imapHost"));
            conta.setImapPort(Integer.parseInt(request.getParameter("imapPort")));
            conta.setImapPassword(request.getParameter("imapPassword"));
            conta.setImapUser(request.getParameter("imapLogin"));
            conta.setSmtpHost(request.getParameter("smtpHost"));
            conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort")));
            conta.setSmtpPassword(request.getParameter("smtpPassword"));
            conta.setSmtpUser(request.getParameter("smtpLogin"));

            em.getTransaction().commit();

            request.setAttribute("mensagem", "sucesso");
        } catch (PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=conta").forward(request, response);

    } else if (metodo.equals("senha")) {
        EntityManager em = BD.getEntityManager();

        try {

            Login usuario = Logar.getLogin(request.getSession());

            em.refresh(usuario);

            String senatu = request.getParameter("senAtu"), novasen = request.getParameter("senNova"),
                    novasen2 = request.getParameter("senNova2");

            if (novasen.equals(novasen2) && senatu.equals(usuario.getSenha())) {

                em.getTransaction().begin();

                usuario.setSenha(novasen);

                em.getTransaction().commit();

                request.setAttribute("mensagem", "sucesso");
            } else {
                if (!novasen.equals(novasen2))
                    request.setAttribute("mensagem", "senneq");
                else
                    request.setAttribute("mensagem", "antsen");
            }
        } catch (Logar.NaoAutenticadoException | PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=senha").forward(request, response);

    }
}

From source file:com.cynertia.track.iCalendar.ICalendarSynchronizeAction.java

public String sendIcs() {
    if (!ApplicationStarter.getInstance().isServerReady()) {
        return "";
    }/*  w  w  w .ja va  2s .  co m*/
    HttpServletRequest request = org.apache.struts2.ServletActionContext.getRequest();
    TPersonBean user = this.authenticate(request);
    if (user == null) {
        LOGGER.error("User not found or invalid password");
        return null;
    }
    String project = "";
    try {
        project = request.getParameter("project").trim();
    } catch (Exception ex) {
        LOGGER.error("Missing project parameter in iCalendarURL of user " + user.getFullName());
    }

    Calendar calendar = null;

    try {
        calendar = generateCalendar(user, project);
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }

    if (calendar == null) {
        LOGGER.error("Error generating the calendar");
        return null;
    }

    HttpServletResponse response = org.apache.struts2.ServletActionContext.getResponse();
    response.setContentType("text/calendar");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Disposition", "inline; filename=\"TrackPlusCalendar.ics\"");

    final CalendarOutputter calendarOutputter = new CalendarOutputter(false);

    try {
        calendarOutputter.output(calendar, response.getOutputStream());
        LOGGER.debug("ICalendar Plugin: Sent Calendar for Projects '" + project + "' to " + user.getFullName());
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    return null;
}

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

private void serializeOperations(OperationMessageBundle operations, HttpServletResponse resp) {
    try {/*from   w w  w  . jav a2s  .c  o  m*/
        String json = serializer.toJSON(operations);
        log.info("Outgoing operations: " + json);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(json);
        resp.setStatus(200);
    } catch (IOException iox) {
        iox.printStackTrace();
        resp.setStatus(500);
    } catch (MarshallException mx) {
        mx.printStackTrace();
        resp.setStatus(500);
    }
}

From source file:mecha.http.servlets.ProcServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from w  w w . j a  va 2s  . c  om*/
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        final JSONObject params = new JSONObject();
        Map<String, String[]> requestParamMap = request.getParameterMap();
        for (String k : requestParamMap.keySet()) {
            String[] values = requestParamMap.get(k);
            if (values.length == 1) {
                params.put(k, values[0]);
            } else {
                params.put(k, values);
            }
        }

        String[] parts = request.getPathInfo().substring(1).split("/");

        String subsystem = parts[0];

        JSONObject result;

        long t_start = System.currentTimeMillis();

        /*
         * /proc/metrics
        */
        if (subsystem.equals("metrics")) {
            result = doMetricsRequest(parts, params);

            /*
             * /proc/top
            */
        } else if (subsystem.equals("top")) {
            result = doTopRequest(parts, params);

            /*
             * /proc/node
            */
        } else if (subsystem.equals("node")) {
            result = doNodeRequest(parts, params);

            /* 
             * /proc/config
            */
        } else if (subsystem.equals("config")) {
            result = doConfigRequest(parts, params);

            /*
             * /proc/cluster
            */
        } else if (subsystem.equals("cluster")) {
            result = doClusterRequest(parts, params);

            /*
             * /proc/riak
            */
        } else if (subsystem.equals("riak")) {
            result = doRiakRequest(parts, params);

            /*
             * unknown request
            */
        } else {
            response.getWriter().println("bad request\n");
            return;
        }
        long t_elapsed = System.currentTimeMillis() - t_start;

        JSONObject resultObj = new JSONObject();
        resultObj.put("elapsed", t_elapsed);
        resultObj.put("result", result);
        response.getWriter().println(resultObj.toString(2));
    } catch (Exception ex) {
        Mecha.getMonitoring().error("mecha.http.servlets.macro-servlet", ex);
        ex.printStackTrace();
    }
}

From source file:com.mirth.connect.server.servlets.MessageObjectServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {/*from  ww w.  j  av  a  2  s . com*/
        try {
            MessageObjectController messageObjectController = ControllerFactory.getFactory()
                    .createMessageObjectController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            String uid = null;
            boolean useNewTempTable = false;
            Map<String, Object> parameterMap = new HashMap<String, Object>();

            if (request.getParameter("uid") != null && !request.getParameter("uid").equals("")) {
                uid = request.getParameter("uid");
                useNewTempTable = true;
            } else {
                uid = request.getSession().getId();
            }

            if (operation.equals(Operations.MESSAGE_CREATE_TEMP_TABLE)) {
                MessageObjectFilter filter = (MessageObjectFilter) serializer
                        .fromXML(request.getParameter("filter"));
                redactMessageObjectFilter(request, filter);
                parameterMap.put("messageFilter", filter);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);
                    out.println(messageObjectController.createMessagesTempTable(filter, uid, useNewTempTable));
                }
            } else if (operation.equals(Operations.MESSAGE_FILTER_TABLES_REMOVE)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.removeFilterTable(uid);
                }
            } else if (operation.equals(Operations.MESSAGE_GET_BY_PAGE)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    int page = Integer.parseInt(request.getParameter("page"));
                    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
                    int max = Integer.parseInt(request.getParameter("maxMessages"));
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(messageObjectController.getMessagesByPage(page, pageSize, max, uid, true),
                            out);
                }

            } else if (operation.equals(Operations.MESSAGE_GET_BY_PAGE_LIMIT)) {
                MessageObjectFilter filter = (MessageObjectFilter) serializer
                        .fromXML(request.getParameter("filter"));
                redactMessageObjectFilter(request, filter);
                parameterMap.put("filter", filter);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    int page = Integer.parseInt(request.getParameter("page"));
                    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
                    int max = Integer.parseInt(request.getParameter("maxMessages"));
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(
                            messageObjectController.getMessagesByPageLimit(page, pageSize, max, uid, filter),
                            out);
                }
            } else if (operation.equals(Operations.MESSAGE_REMOVE)) {
                MessageObjectFilter filter = (MessageObjectFilter) serializer
                        .fromXML(request.getParameter("filter"));
                redactMessageObjectFilter(request, filter);
                parameterMap.put("filter", filter);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.removeMessages(filter);
                }
            } else if (operation.equals(Operations.MESSAGE_CLEAR)) {
                String channelId = request.getParameter("data");
                parameterMap.put("channelId", channelId);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.clearMessages(channelId);
                }
            } else if (operation.equals(Operations.MESSAGE_REPROCESS)) {
                MessageObjectFilter filter = (MessageObjectFilter) serializer
                        .fromXML(request.getParameter("filter"));
                redactMessageObjectFilter(request, filter);
                boolean replace = Boolean.valueOf(request.getParameter("replace"));
                List<String> destinations = (List<String>) serializer
                        .fromXML(request.getParameter("destinations"));
                parameterMap.put("filter", filter);
                parameterMap.put("replace", replace);
                parameterMap.put("destinations", destinations);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.reprocessMessages(filter, replace, destinations);
                }
            } else if (operation.equals(Operations.MESSAGE_PROCESS)) {
                MessageObject message = (MessageObject) serializer.fromXML(request.getParameter("message"));
                parameterMap.put("message", message);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.processMessage(message);
                }
            } else if (operation.equals(Operations.MESSAGE_IMPORT)) {
                MessageObject message = (MessageObject) serializer.fromXML(request.getParameter("message"));
                parameterMap.put("message", message);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.importMessage(message);
                }
            } else if (operation.equals(Operations.MESSAGE_ATTACHMENT_GET)) {
                String attachmentId = request.getParameter("attachmentId");
                parameterMap.put("attachmentId", attachmentId);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    Attachment attachment = messageObjectController.getAttachment(attachmentId);
                    serializer.toXML(attachment, out);
                }
            } else if (operation.equals(Operations.MESSAGE_ATTACHMENT_GET_BY_MESSAGE_ID)) {
                String messageId = request.getParameter("messageId");
                parameterMap.put("messageId", messageId);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    List<Attachment> list = messageObjectController.getAttachmentsByMessageId(messageId);
                    serializer.toXML(list, out);
                    out.println("");
                }
            } else if (operation.equals(Operations.MESSAGE_ATTACHMENT_GET_ID_BY_MESSAGE_ID)) {
                String messageId = request.getParameter("messageId");
                parameterMap.put("messageId", messageId);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    List<Attachment> list = messageObjectController.getAttachmentIdsByMessageId(messageId);
                    serializer.toXML(list, out);
                    out.println("");
                }
            } else if (operation.equals(Operations.MESSAGE_DICOM_MESSAGE_GET)) {
                MessageObject message = (MessageObject) serializer.fromXML(request.getParameter("message"));
                parameterMap.put("message", message);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    String dicomMessage = DICOMUtil.getDICOMRawData(message);
                    out.println(dicomMessage);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:edu.lafayette.metadb.web.metadata.UpdateAdminDescMetadata.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from w ww  .j  a  va2  s .c o m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    response.setCharacterEncoding("utf-8");
    request.setCharacterEncoding("utf-8");
    JSONObject output = new JSONObject();

    String type = request.getParameter("type");
    String message = type + " metadata cannot be updated\n";

    try {
        HttpSession session = request.getSession(false);
        if (session == null)
            return;
        String projname = (String) session.getAttribute(Global.SESSION_PROJECT);
        String userName = (String) session.getAttribute("username");
        int itemNumber = Integer.parseInt(request.getParameter("current"));

        String locker = ItemsDAO.getLocker(projname, itemNumber);
        if (!(userName.equals(locker) || locker.trim().equals("") || locker == null))
            return;

        output.put("projname", projname);
        String[] ids_array = request.getParameter("edited-ids").split(" ");
        Set<String> ids = new HashSet<String>();
        for (String id : ids_array) {
            ids.add(id);
        }

        JSONArray failed_items = new JSONArray();
        message = "Metadata exist and will be updated\n";
        for (String id_string : ids) {
            int id = Integer.parseInt(id_string);
            JSONObject whitelisted = whitelist(id_string, projname, type, itemNumber, request);

            if (whitelisted.getBoolean("success")) {
                MetaDbHelper.note("Whitelist succeeded, proj " + projname + ", item " + itemNumber + ", id "
                        + id + ", data " + whitelisted.getString("data"));
                AdminDescDataDAO.updateAdminDescData(projname, itemNumber, id,
                        whitelisted.getString("data").trim());

            } else {
                MetaDbHelper.note("Didn't pass whitelist");
                failed_items.put(whitelisted);
            }

        }
        output.put("failure", failed_items);
        output.put("message", message);
        output.put("type", type);
    } catch (NumberFormatException e) {
        //No problem, when splitting string last element is "", thus cannot be
        //converted to numbers
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    out.print(output);
    out.flush();
}