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:net.duckling.ddl.web.controller.pan.PanShareDownloadController.java

private void sendPreviewDoc(String filename, long size, String panShareId, HttpServletRequest request,
        HttpServletResponse response) {
    OutputStream os = null;/*from   w w w  .j a  v  a 2  s. c  om*/
    long p0 = System.currentTimeMillis();
    long tmpSize = size;
    try {
        response.setCharacterEncoding("utf-8");
        String headerValue = ResponseHeaderUtils.buildResponseHeader(request, filename, true);
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", headerValue);
        response.setContentLength((int) size);
        response.setHeader("Content-Length", tmpSize + "");
        os = response.getOutputStream();
        panService.getShareContent(panShareId, null, os);
    } catch (UnsupportedEncodingException e) {
        LOG.error("", e);
    } catch (MeePoException e) {
        LOG.error("", e);
    } catch (IOException e) {
        LOG.error("", e);
    } catch (Exception e) {
        LOG.error("", e);
    } finally {
        IOUtils.closeQuietly(os);
        long p1 = System.currentTimeMillis();
        LOG.info("Download document[name:" + filename + ",size:" + tmpSize + "] use time " + (p1 - p0));
    }

}

From source file:com.honnix.yaacs.adapter.http.ACRequestHandler.java

private void setHttpHeader(HttpServletResponse response) {
    response.setContentType(ACHttpConstant.HTTP_CONTENT_TYPE);
    response.setStatus(HttpServletResponse.SC_OK);
    response.setCharacterEncoding(ACHttpPropertiesConstant.HTTP_CHARSET);
}

From source file:net.fckeditor.connector.ConnectorServlet.java

/**
 * Manage the <code>GET</code> requests (<code>GetFolders</code>,
 * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/>
 * //from ww w .  j  av a  2  s . co  m
 * The servlet accepts commands sent in the following format:<br/>
 * <code>connector?Command=&lt;CommandName&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * <p>
 * It executes the commands and then returns the result to the client in XML
 * format.
 * </p>
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering ConnectorServlet#doGet");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/xml; 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);

    XmlResponse xr;

    if (!RequestCycleHandler.isEnabledForFileBrowsing(request))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);
    else if (!CommandHandler.isValidForGet(commandStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);
    else {
        CommandHandler command = CommandHandler.getCommand(commandStr);
        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())
            xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);
        else {

            xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse.constructResponseUrl(
                    request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()));

            if (command.equals(CommandHandler.GET_FOLDERS))
                xr.setFolders(currentDir);
            else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))
                xr.setFoldersAndFiles(currentDir);
            else if (command.equals(CommandHandler.CREATE_FOLDER)) {

                // TODO ############? ############
                String tempStr = request.getParameter("NewFolderName");
                tempStr = new String(tempStr.getBytes("iso8859-1"), "UTF-8");

                String newFolderStr = UtilsFile.sanitizeFolderName(tempStr);
                logger.debug("Parameter NewFolderName: {}", newFolderStr);

                File newFolder = new File(currentDir, newFolderStr);
                int errorNumber = XmlResponse.EN_UKNOWN;

                if (newFolder.exists())
                    errorNumber = XmlResponse.EN_ALREADY_EXISTS;
                else {
                    try {
                        errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK
                                : XmlResponse.EN_INVALID_FOLDER_NAME;
                    } catch (SecurityException e) {
                        errorNumber = XmlResponse.EN_SECURITY_ERROR;
                    }
                }
                xr.setError(errorNumber);
            }
        }
    }
    out.print(xr);
    out.flush();
    out.close();
    logger.debug("Exiting ConnectorServlet#doGet");
}

From source file:net.solarnetwork.web.support.SimpleCsvView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (model.isEmpty()) {
        return;//from  w  w  w  .  jav  a2 s  . c  om
    }

    final String charset = getResponseCharacterEncoding();
    response.setCharacterEncoding(charset);
    response.setContentType(getContentType());

    final Object data = (dataModelKey != null && model.containsKey(dataModelKey) ? model.get(dataModelKey)
            : model);

    if (data == null) {
        return;
    }

    @SuppressWarnings("unchecked")
    final Collection<String> fieldOrder = (fieldOrderKey != null
            && model.get(fieldOrderKey) instanceof Collection ? (Collection<String>) model.get(fieldOrderKey)
                    : null);

    Iterable<?> rows = null;
    if (data instanceof Iterable) {
        rows = (Iterable<?>) data;
    } else {
        List<Object> tmpList = new ArrayList<Object>(1);
        tmpList.add(data);
        rows = tmpList;
    }

    Object row = null;
    Iterator<?> rowIterator = rows.iterator();
    if (!rowIterator.hasNext()) {
        return;
    }

    // get first row, to use for fields
    row = rowIterator.next();
    if (row == null) {
        return;
    }

    final List<String> fieldList = getCSVFields(row, fieldOrder);
    final String[] fields = fieldList.toArray(new String[fieldList.size()]);

    final ICsvMapWriter writer = new CsvMapWriter(response.getWriter(), CsvPreference.EXCEL_PREFERENCE);

    try {
        // output header
        if (true) { // TODO make configurable property
            Map<String, String> headerMap = new HashMap<String, String>(fields.length);
            for (String field : fields) {
                headerMap.put(field, field);
            }
            writeCSV(writer, fields, headerMap);
        }

        // output first row
        writeCSV(writer, fields, row);

        // output remainder rows
        while (rowIterator.hasNext()) {
            row = rowIterator.next();
            writeCSV(writer, fields, row);
        }
    } finally {
        writer.flush();
        writer.close();
    }
}

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

/**
 * Manage the <code>GET</code> requests (<code>GetFolders</code>,
 * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/>
 * /*from   w  ww.  j  a  va 2s  .c om*/
 * The servlet accepts commands sent in the following format:<br/>
 * <code>connector?Command=&lt;CommandName&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * <p>
 * It executes the commands and then returns the result to the client in XML
 * format.
 * </p>
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering ConnectorServlet#doGet");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/xml; 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);

    XmlResponse xr;

    if (!RequestCycleHandler.isEnabledForFileBrowsing(request))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);
    else if (!CommandHandler.isValidForGet(commandStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);
    else {
        CommandHandler command = CommandHandler.getCommand(commandStr);
        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())
            xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);
        else {

            xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse.constructResponseUrl(
                    request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()));

            if (command.equals(CommandHandler.GET_FOLDERS))
                xr.setFolders(currentDir);
            else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))
                xr.setFoldersAndFiles(currentDir);
            else if (command.equals(CommandHandler.CREATE_FOLDER)) {

                String temp = request.getParameter("NewFolderName");
                temp = new String(temp.getBytes("ISO8859-1"), "UTF-8");

                String newFolderStr = UtilsFile.sanitizeFolderName(temp);
                logger.debug("Parameter NewFolderName: {}", newFolderStr);

                File newFolder = new File(currentDir, newFolderStr);
                int errorNumber = XmlResponse.EN_UKNOWN;

                if (newFolder.exists())
                    errorNumber = XmlResponse.EN_ALREADY_EXISTS;
                else {
                    try {
                        errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK
                                : XmlResponse.EN_INVALID_FOLDER_NAME;
                    } catch (SecurityException e) {
                        errorNumber = XmlResponse.EN_SECURITY_ERROR;
                    }
                }
                xr.setError(errorNumber);
            }
        }
    }

    out.print(xr);
    out.flush();
    out.close();
    logger.debug("Exiting ConnectorServlet#doGet");
}

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

/**
 * Manage the <code>GET</code> requests (<code>GetFolders</code>,
 * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/>
 * //w ww  . j av a 2s .c  o m
 * The servlet accepts commands sent in the following format:<br/>
 * <code>connector?Command=&lt;CommandName&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * <p>
 * It executes the commands and then returns the result to the client in XML
 * format.
 * </p>
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering ConnectorServlet#doGet");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/xml; 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);

    XmlResponse xr;

    if (!RequestCycleHandler.isEnabledForFileBrowsing(request))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);
    else if (!CommandHandler.isValidForGet(commandStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);
    else {
        CommandHandler command = CommandHandler.getCommand(commandStr);
        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())
            xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);
        else {

            xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse.constructResponseUrl(
                    request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()));

            if (command.equals(CommandHandler.GET_FOLDERS))
                xr.setFolders(currentDir);
            else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))
                xr.setFoldersAndFiles(currentDir);
            else if (command.equals(CommandHandler.CREATE_FOLDER)) {
                //String newFolderStr = UtilsFile.sanitizeFolderName(request.getParameter("NewFolderName"));
                /*
                 * liwei 
                 */
                String tempStr = request.getParameter("NewFolderName");
                tempStr = new String(tempStr.getBytes("iso8859-1"), "utf-8");
                String newFolderStr = UtilsFile.sanitizeFolderName(tempStr);

                logger.debug("Parameter NewFolderName: {}", newFolderStr);

                File newFolder = new File(currentDir, newFolderStr);
                int errorNumber = XmlResponse.EN_UKNOWN;

                if (newFolder.exists())
                    errorNumber = XmlResponse.EN_ALREADY_EXISTS;
                else {
                    try {
                        errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK
                                : XmlResponse.EN_INVALID_FOLDER_NAME;
                    } catch (SecurityException e) {
                        errorNumber = XmlResponse.EN_SECURITY_ERROR;
                    }
                }
                xr.setError(errorNumber);
            }
        }
    }

    out.print(xr);
    out.flush();
    out.close();
    logger.debug("Exiting ConnectorServlet#doGet");
}

From source file:com.addthis.hydra.job.SpawnHttp.java

@Override
public void handle(String target, Request request, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    //To change body of implemented methods use File | Settings | File Templates.
    httpServletResponse.setCharacterEncoding(CharEncoding.UTF_8);
    if (target.equals("/")) {
        httpServletResponse.sendRedirect("/spawn/index.html");
    } else if (target.startsWith("/metrics")) {
        if (!metricsHandler.isStarted()) {
            log.warn("Metrics servlet failed to start");
        }//w w  w.j ava2 s .  co m
        metricsHandler.handle(target, request, httpServletRequest, httpServletResponse);
    } else {
        HTTPService handler = serviceMap.get(target);
        if (handler != null) {
            try {
                HTTPLink link = new HTTPLink(target, request, httpServletResponse);
                if (failAuth(link))
                    return;
                handler.httpService(link);
            } catch (Exception ex) {
                log.warn("handler error " + ex, ex);
                httpServletResponse.sendError(500, ex.getMessage());
            }
        } else {
            File file = new File(webDir, target);
            if (file.exists() && file.isFile()) {
                OutputStream out = httpServletResponse.getOutputStream();
                InputStream in = new FileInputStream(file);
                byte buf[] = new byte[1024];
                int read = 0;
                while ((read = in.read(buf)) >= 0) {
                    out.write(buf, 0, read);
                }
            } else {
                log.warn("[http.unhandled] " + target);
                httpServletResponse.sendError(404);
            }
        }
    }
    ((Request) request).setHandled(true);
}

From source file:com.addthis.hydra.job.web.old.SpawnHttp.java

@Override
public void handle(String target, Request request, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    //To change body of implemented methods use File | Settings | File Templates.
    httpServletResponse.setCharacterEncoding(CharEncoding.UTF_8);
    if (target.equals("/")) {
        httpServletResponse.sendRedirect("/spawn/index.html");
    } else if (target.startsWith("/metrics")) {
        if (!metricsHandler.isStarted()) {
            log.warn("Metrics servlet failed to start");
        }/*from   w  w  w .  j  a va  2s.  c o  m*/
        metricsHandler.handle(target, request, httpServletRequest, httpServletResponse);
    } else {
        HTTPService handler = serviceMap.get(target);
        if (handler != null) {
            try {
                HTTPLink link = new HTTPLink(target, request, httpServletResponse);
                if (failAuth(link))
                    return;
                handler.httpService(link);
            } catch (Exception ex) {
                log.warn("handler error " + ex, ex);
                httpServletResponse.sendError(500, ex.getMessage());
            }
        } else {
            File file = new File(webDir, target);
            if (file.exists() && file.isFile()) {
                OutputStream out = httpServletResponse.getOutputStream();
                InputStream in = new FileInputStream(file);
                byte[] buf = new byte[1024];
                int read = 0;
                while ((read = in.read(buf)) >= 0) {
                    out.write(buf, 0, read);
                }
            } else {
                log.warn("[http.unhandled] " + target);
                httpServletResponse.sendError(404);
            }
        }
    }
    ((Request) request).setHandled(true);
}

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

/**
 * Manage the <code>GET</code> requests (<code>GetFolders</code>,
 * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/>
 * // ww  w  . j  a  v a 2 s  .co  m
 * The servlet accepts commands sent in the following format:<br/>
 * <code>connector?Command=&lt;CommandName&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * <p>
 * It executes the commands and then returns the result to the client in XML
 * format.
 * </p>
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering ConnectorServlet#doGet");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/xml; 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);

    XmlResponse xr;

    if (!RequestCycleHandler.isEnabledForFileBrowsing(request))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);
    else if (!CommandHandler.isValidForGet(commandStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);
    else {
        CommandHandler command = CommandHandler.getCommand(commandStr);
        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())
            xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);
        else {

            xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse.constructResponseUrl(
                    request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()));

            if (command.equals(CommandHandler.GET_FOLDERS))
                xr.setFolders(currentDir);
            else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))
                xr.setFoldersAndFiles(currentDir);
            else if (command.equals(CommandHandler.CREATE_FOLDER)) {

                String newStr = request.getParameter("NewFolderName");
                newStr = new String(newStr.getBytes("iso8859-1"), "UTF-8");//

                String newFolderStr = UtilsFile.sanitizeFolderName(newStr);
                logger.debug("Parameter NewFolderName: {}", newFolderStr);

                File newFolder = new File(currentDir, newFolderStr);
                int errorNumber = XmlResponse.EN_UKNOWN;

                if (newFolder.exists())
                    errorNumber = XmlResponse.EN_ALREADY_EXISTS;
                else {
                    try {
                        errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK
                                : XmlResponse.EN_INVALID_FOLDER_NAME;
                    } catch (SecurityException e) {
                        errorNumber = XmlResponse.EN_SECURITY_ERROR;
                    }
                }
                xr.setError(errorNumber);
            }
        }
    }
    out.print(xr);
    out.flush();
    out.close();
    logger.debug("Exiting ConnectorServlet#doGet");
}

From source file:org.motechproject.server.decisiontree.web.VxmlController.java

/**
 * Handles Decision Tree Node HTTP requests and generates a VXML document based on a Velocity template.
 * The HTTP request should contain the Tree ID, Node ID, Patient ID and Selected Transition Key (optional) parameters
 *
 *//* w w w  .  ja  v a2 s .  c  o m*/
public ModelAndView node(HttpServletRequest request, HttpServletResponse response) {
    logger.info("Generating decision tree node VXML");

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    Node node = null;
    String transitionPath = null;
    Map<String, Object> params = convertParams(request.getParameterMap());

    String patientId = request.getParameter(PATIENT_ID_PARAM);
    String language = request.getParameter(LANGUAGE_PARAM);
    String treeNameString = request.getParameter(TREE_NAME_PARAM);
    String encodedParentTransitionPath = request.getParameter(TRANSITION_PATH_PARAM);
    String transitionKey = request.getParameter(TRANSITION_KEY_PARAM);

    logger.info(" Node HTTP  request parameters: " + PATIENT_ID_PARAM + ": " + patientId + ", " + LANGUAGE_PARAM
            + ": " + language + ", " + TREE_NAME_PARAM + ": " + treeNameString + ", " + TRANSITION_PATH_PARAM
            + ": " + encodedParentTransitionPath + ", " + TRANSITION_KEY_PARAM + ": " + transitionKey);

    if (StringUtils.isBlank(patientId) || StringUtils.isBlank(language)
            || StringUtils.isBlank(treeNameString)) {

        logger.error("Invalid HTTP request - the following parameters: " + PATIENT_ID_PARAM + ", "
                + LANGUAGE_PARAM + " and " + TREE_NAME_PARAM + " are mandatory");
        return getErrorModelAndView(Errors.NULL_PATIENTID_LANGUAGE_OR_TREENAME_PARAM);
    }

    String[] treeNames = treeNameString.split(TREE_NAME_SEPARATOR);
    String currentTree = treeNames[0];
    // put only one tree name in params
    params.put(TREE_NAME_PARAM, currentTree);

    if (transitionKey == null) { // get root node
        try {
            String rootTransitionPath = TreeNodeLocator.PATH_DELIMITER;
            node = decisionTreeService.getNode(currentTree, rootTransitionPath);
            transitionPath = rootTransitionPath;
        } catch (Exception e) {
            logger.error("Can not get node by Tree Name: " + currentTree + " transition path: " + patientId, e);
        }
    } else { // get not root node
        String parentTransitionPath = null;
        try {
            if (encodedParentTransitionPath == null) {

                logger.error(
                        "Invalid HTTP request - the  " + TRANSITION_PATH_PARAM + " parameter is mandatory");
                return getErrorModelAndView(Errors.NULL_TRANSITION_PATH_PARAM);
            }

            parentTransitionPath = new String(Base64.decodeBase64(encodedParentTransitionPath));
            Node parentNode = decisionTreeService.getNode(currentTree, parentTransitionPath);

            Transition transition = parentNode.getTransitions().get(transitionKey);

            if (transition == null) {
                logger.error("Invalid Transition Key. There is no transition with key: " + transitionKey
                        + " in the Node: " + parentNode);
                return getErrorModelAndView(Errors.INVALID_TRANSITION_KEY);
            }

            treeEventProcessor.sendActionsAfter(parentNode, parentTransitionPath, params);

            treeEventProcessor.sendTransitionActions(transition, params);

            node = transition.getDestinationNode();

            if (node == null || (node.getPrompts().isEmpty() && node.getActionsAfter().isEmpty()
                    && node.getActionsBefore().isEmpty() && node.getTransitions().isEmpty())) {
                if (treeNames.length > 1) {
                    //reduce the current tree and redirect to the next tree
                    treeNames = (String[]) ArrayUtils.remove(treeNames, 0);
                    String view = String.format(
                            "redirect:/tree/vxml/node?" + PATIENT_ID_PARAM + "=%s&" + TREE_NAME_PARAM + "=%s&"
                                    + LANGUAGE_PARAM + "=%s",
                            patientId, StringUtils.join(treeNames, TREE_NAME_SEPARATOR), language);
                    ModelAndView mav = new ModelAndView(view);
                    return mav;
                } else {
                    //TODO: Add support for return url
                    ModelAndView mav = new ModelAndView(EXIT_TEMPLATE_NAME);
                    return mav;
                }

            } else {
                transitionPath = parentTransitionPath
                        + (TreeNodeLocator.PATH_DELIMITER.equals(parentTransitionPath) ? ""
                                : TreeNodeLocator.PATH_DELIMITER)
                        + transitionKey;
            }

        } catch (Exception e) {
            logger.error("Can not get node by Tree ID : " + currentTree + " and Transition Path: "
                    + parentTransitionPath, e);
        }
    }

    if (node != null) {

        //validate node
        for (Map.Entry<String, Transition> transitionEntry : node.getTransitions().entrySet()) {

            try {
                Integer.parseInt(transitionEntry.getKey());
            } catch (NumberFormatException e) {
                logger.error("Invalid node: " + node
                        + "\n In order  to be used in VXML transition keys should be an Integer");
                return getErrorModelAndView(Errors.INVALID_TRANSITION_KEY_TYPE);
            }

            Transition transition = transitionEntry.getValue();
            if (transition.getDestinationNode() == null) {
                logger.error(
                        "Invalid node: " + node + "\n Null Destination Node in the Transition: " + transition);
                return getErrorModelAndView(Errors.NULL_DESTINATION_NODE);
            }
        }

        treeEventProcessor.sendActionsBefore(node, transitionPath, params);

        ModelAndView mav = new ModelAndView();
        if (node.getTransitions().size() > 0) {
            mav.setViewName(NODE_TEMPLATE_NAME);
            mav.addObject("treeName", treeNameString);
        } else { // leaf
            //reduce the current tree and redirect to the next tree
            treeNames = (String[]) ArrayUtils.remove(treeNames, 0);
            mav.setViewName(LEAF_TEMPLATE_NAME);
            mav.addObject("treeName", StringUtils.join(treeNames, TREE_NAME_SEPARATOR));
        }
        mav.addObject("contentPath", request.getContextPath());
        mav.addObject("node", node);
        mav.addObject("patientId", patientId);
        mav.addObject("language", language);
        mav.addObject("transitionPath", Base64.encodeBase64URLSafeString(transitionPath.getBytes()));
        mav.addObject("escape", new StringEscapeUtils());

        return mav;
    } else {
        return getErrorModelAndView(Errors.GET_NODE_ERROR);
    }

}