Example usage for javax.servlet.http HttpServletRequest getContextPath

List of usage examples for javax.servlet.http HttpServletRequest getContextPath

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getContextPath.

Prototype

public String getContextPath();

Source Link

Document

Returns the portion of the request URI that indicates the context of the request.

Usage

From source file:pivotal.au.se.gemfirexdweb.controller.MemberController.java

@RequestMapping(value = "/members", method = RequestMethod.GET)
public String showDiskstores(Model model, HttpServletResponse response, HttpServletRequest request,
        HttpSession session) throws Exception {
    javax.servlet.jsp.jstl.sql.Result allMemberInfoResult = null;

    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from w  w  w. j a v  a 2s.  c o  m
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to show members");

    MemberDAO mbrDAO = GemFireXDWebDAOFactory.getMemberDAO();

    String memberAction = request.getParameter("memberAction");
    String propertyAction = request.getParameter("propertyAction");

    if (memberAction != null) {
        logger.debug("memberAction = " + memberAction);
        logger.debug("propertyAction = " + propertyAction);

        if (memberAction.equals("ALLMEMBEREVENTINFO")) {
            allMemberInfoResult = mbrDAO.getMemberInfo((String) request.getParameter("memberId"),
                    (String) session.getAttribute("user_key"));
            model.addAttribute("allMemberInfoResult", allMemberInfoResult);
            model.addAttribute("memberid", (String) request.getParameter("memberId"));
        } else if (memberAction.equals("PROPERTIES")) {
            String props = mbrDAO.getMemberProperties((String) request.getParameter("memberId"), propertyAction,
                    (String) session.getAttribute("user_key"));

            model.addAttribute("props", props);
            model.addAttribute("propertyAction", propertyAction);
            model.addAttribute("memberid", (String) request.getParameter("memberId"));
        }
    }

    List<Member> members = mbrDAO.retrieveMembers((String) session.getAttribute("user_key"));

    model.addAttribute("members", members);
    model.addAttribute("records", members.size());
    model.addAttribute("estimatedrecords", members.size());

    // This will resolve to /WEB-INF/jsp/members.jsp
    return "members";
}

From source file:fr.norad.servlet.sample.html.template.IndexTemplateServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (template == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from w w w  .ja v a2s.  co  m
    }

    HashMap<String, String> hashMap = new HashMap<>(properties);
    String contextPath = req.getContextPath();
    if (contextPathSuffix != null && !contextPathSuffix.equals("")) {
        contextPath += contextPathSuffix;
    }
    hashMap.put("contextPath", contextPath);
    hashMap.put("fullWebPath", req.getRequestURL().toString().replace(req.getRequestURI(), contextPath));

    String response = StrSubstitutor.replace(template, hashMap);

    resp.setStatus(200);
    resp.setContentType("text/html; charset=utf-8");
    resp.getWriter().write(response);
}

From source file:net.sourceforge.ajaxtags.servlets.SourceLoader.java

/**
 * Write the content from the jarfile to the client stream. Use bufferedwriter to handle
 * newline. The filename is found in the requestURI, the contextpath is excluded and replaced
 * with the base package name./*from  w  w w.  jav  a 2s.c o  m*/
 *
 * @param req
 *            the request
 * @param resp
 *            the response
 * @throws ServletException
 *             any errors
 * @throws IOException
 *             any io errors
 */
public void service(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final String res = req.getRequestURI();
    final OutputStream stream = resp.getOutputStream();
    final byte[] buffer = new byte[BUFFER];

    String loadPath = res.substring(req.getContextPath().length());

    if (prefix != null && loadPath.startsWith(prefix)) {
        loadPath = loadPath.substring(prefix.length());
    }

    InputStream in = null;
    try {
        in = getClass().getResourceAsStream(SourceLoader.BASE + loadPath);
        if (in == null) {
            throw new IOException("resource not found");
        }
        int read = -1;
        while ((read = in.read(buffer)) != -1) {
            stream.write(buffer, 0, read);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        stream.flush();
        stream.close();
    }
}

From source file:de.itsvs.cwtrpc.security.AbstractRpcProcessingFilter.java

protected boolean matchesFilterProcessesUrl(HttpServletRequest request) throws IOException, ServletException {
    final String contextPath;
    final StringBuilder sb;
    final String uri;

    contextPath = request.getContextPath();
    sb = new StringBuilder(request.getRequestURI());
    if ((contextPath.length() > 0) && (sb.indexOf(contextPath) == 0)) {
        sb.delete(0, contextPath.length());
    }//from   w w  w .j  a  v a 2 s.c om
    if ((sb.length() == 0) || (sb.charAt(0) != '/')) {
        sb.insert(0, '/');
    }
    uri = sb.toString();

    if (log.isDebugEnabled()) {
        log.debug(
                "Checking received URI '" + uri + "' against configured URI '" + getFilterProcessesUrl() + "'");
    }
    return getFilterProcessesUrl().equals(uri);
}

From source file:pivotal.au.se.gemfirexdweb.controller.ReportsController.java

@RequestMapping(value = "/executequeryreport", method = RequestMethod.GET)
public String executeQuery(Model model, HttpServletResponse response, HttpServletRequest request,
        HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from   w  ww  .  j a  va2s  . co  m
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to execute a query");

    javax.servlet.jsp.jstl.sql.Result queryResult = null;
    QueryBeanReader reader = QueryBeanReader.getInstance();
    ConnectionManager cm = ConnectionManager.getInstance();

    String beanId = request.getParameter("beanId");

    if (beanId != null) {

        Query qb = reader.getQueryBean(beanId);

        if (qb instanceof GenericQuery) {
            logger.debug("Generic Query will be run");
            GenericQuery genericQuery = (GenericQuery) qb;

            queryResult = genericQuery.invoke(cm.getConnection((String) session.getAttribute("user_key")));
            model.addAttribute("queryResults", queryResult);
            model.addAttribute("queryDescription", genericQuery.getQueryDescription());
            model.addAttribute("querySQL", genericQuery.getQuery().trim());
            model.addAttribute("beanId", beanId);
        } else if (qb instanceof ParameterQuery) {
            ParameterQuery paramQuery = (ParameterQuery) qb;
            model.addAttribute("queryDescription", paramQuery.getQueryDescription());
            model.addAttribute("querySQL", paramQuery.getQuery().trim());
            model.addAttribute("beanId", beanId);
            model.addAttribute("paramMap", paramQuery.getParamMap());

            if (request.getParameter("pSubmit") != null) {
                // execute pressed, get param values
                Map paramValues = new HashMap();
                Set<String> keys = paramQuery.getParamMap().keySet();
                for (String param : keys) {
                    paramValues.put(param, (String) request.getParameter(param));
                }

                paramQuery.setParamValues(paramValues);
                queryResult = paramQuery.invoke(cm.getConnection((String) session.getAttribute("user_key")));
                request.setAttribute("queryResults", queryResult);
            }
        } else {
            // do nothing here
        }
    }

    // This will resolve to /WEB-INF/jsp/displayquery.jsp
    return "displayquery";
}

From source file:com.cpjit.swagger4j.support.internal.DefaultApiViewWriter.java

@Deprecated
@Override/*from w  ww . ja v  a  2  s .c  o m*/
public void writeIndex(HttpServletRequest request, HttpServletResponse response, String lang, Properties props)
        throws IOException {
    Map<String, Object> root = new HashMap<String, Object>();
    root.put("lang", lang);
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
    root.put("basePath", basePath);
    String host = request.getServerName() + ":" + request.getServerPort() + path;
    String suffix = props.getProperty("suffix");
    if (StringUtils.isBlank(suffix)) {
        suffix = "";
    }
    root.put("getApisUrl", "http://" + host + "/api" + suffix);
    root.put("apiDescription", props.getProperty("apiDescription"));
    root.put("apiTitle", props.getProperty("apiTitle"));
    root.put("apiVersion", props.getProperty("apiVersion"));
    root.put("suffix", suffix);
    Template template = FreemarkerUtils.getTemplate(getTemplateName());
    response.setContentType("text/html;charset=utf-8");
    Writer out = response.getWriter();
    try {
        template.process(root, out);
    } catch (TemplateException e) {
        throw new IOException(e);
    }
    out.flush();
    out.close();
}

From source file:com.ns.cm.ProvisionServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Redirecting...");
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    response.sendRedirect(request.getContextPath());
}

From source file:cn.vlabs.umt.ui.servlet.LoginServlet.java

private void saveParams(HttpServletRequest request) {
    int port = request.getServerPort();
    HttpSession session = request.getSession();
    String basePath = request.getScheme() + "://" + request.getServerName();
    if (port != 80) {
        basePath += ":" + request.getServerPort();
    }//from ww w .j a va2 s .  c  o  m
    session.setAttribute("rootPath", basePath);
    basePath += request.getContextPath();
    session.setAttribute("basePath", basePath);
    Map<String, String> siteInfo = new HashMap<String, String>();
    for (String param : Attributes.SSO_PARAMS) {
        if (request.getParameter(param) != null) {
            siteInfo.put(param, request.getParameter(param));
        }
    }
    session.setAttribute(Attributes.SITE_INFO, siteInfo);
}

From source file:org.openmrs.module.pmtct.web.controller.UpdatePatientInformationController.java

/**
 * @see org.springframework.web.servlet.mvc.ParameterizableViewController#handleRequestInternal(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *///w  ww . j ava2s .  c  o m
@SuppressWarnings({ "deprecation" })
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (Context.getAuthenticatedUser() == null)
        return new ModelAndView(new RedirectView(request.getContextPath() + "/login.htm"));

    Patient p = null;

    ModelAndView mav = new ModelAndView();
    mav.setView(new RedirectView(getViewName() + "?patientId=" + request.getParameter("patientId")));

    try {

        //         config = PMTCTConfiguration.getInstance(request.getRealPath(PMTCTConstants.CONFIGURATION_FILE_LOC));
        //         request.getSession().setAttribute("enableModification", "" + config.isModificationEnabled());
        //         constants = config.getConstants();

        request.getSession().setAttribute("pmtctModuleConfigured", "" + PMTCTConfigurationUtils.isConfigured());

        p = Context.getPatientService().getPatient(Integer.parseInt(request.getParameter("patientId")));
        //         PersonService ps = Context.getPersonService();
        //BIRTHDATE_ATTRIBUTE
        //p.setBirthdate(Context.getDateFormat().parse(request.getParameter("birthdate")));
        //p.setGender(request.getParameter("addGender"));

        if (request.getParameter("formAttribute") != null)
            p = updatePersonAttributes(request, p);
        //         if (request.getParameter("formAddress") != null)
        //            p = updatePersonAddress(request, p);

        //saving the changes
        Context.getPatientService().updatePatient(p);

        log.info("Information updated successifully for patient with id " + request.getParameter("patientId"));

        String msg = getMessageSourceAccessor().getMessage("pmtct.general.saveSuccess");
        request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, msg);

        //refreshing the patient object
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("patient", p);
        //         model.put("location", p.getPersonAddress());

        //         request.getSession().setAttribute("model", model);

        //         because the gender cant be updated from here, no need to check if the patient is male
        //         if(p.getGender().compareToIgnoreCase("M")==0)
        //            mav.setView(new RedirectView(request.getContextPath()+"/patientDashboard.form?patientId=" + request.getParameter("patientId")));

    } catch (Exception e) {
        log.error("An error occured when trying to update information for patient with id "
                + request.getParameter("patientId"));
        e.printStackTrace();

        String msg = getMessageSourceAccessor().getMessage("pmtct.general.notSaved");
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, msg);

    }

    return mav;
}

From source file:pivotal.au.se.gemfirexdweb.controller.AddWriterController.java

@RequestMapping(value = "/addwriter", method = RequestMethod.POST)
public String createWriterAction(@ModelAttribute("writerAttribute") AddWriter writerAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {// w  w w . j  a  va 2s  .  c om
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for Table Writer");

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer addWriter = new StringBuffer();

        addWriter.append("CALL SYS.ATTACH_WRITER ('" + writerAttribute.getSchemaName() + "', \n");
        addWriter.append("'" + writerAttribute.getTableName() + "', \n");
        addWriter.append("'" + writerAttribute.getFunctionString() + "', \n");

        if (!checkIfParameterEmpty(request, "initInfoString")) {
            addWriter.append("'" + writerAttribute.getInitInfoString() + "', \n");
        } else {
            addWriter.append("NULL, \n");
        }

        if (!checkIfParameterEmpty(request, "serverGroups")) {
            addWriter.append("'" + writerAttribute.getServerGroups() + "')");
        } else {
            addWriter.append("NULL), \n");
        }

        if (submit.equalsIgnoreCase("create")) {
            Result result = new Result();

            logger.debug("Creating Table Writer as -> " + addWriter.toString());

            result = GemFireXDWebDAOUtil.runStoredCommand(addWriter.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);

        } else if (submit.equalsIgnoreCase("Show SQL")) {
            logger.debug("Create Table Writer SQL as follows as -> " + addWriter.toString());
            model.addAttribute("sql", addWriter.toString());
        } else if (submit.equalsIgnoreCase("Save to File")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename="
                    + String.format(FILENAME, writerAttribute.getTableName() + "-Writer"));

            ServletOutputStream out = response.getOutputStream();
            out.println(addWriter.toString());
            out.close();
            return null;
        }

    }

    // This will resolve to /WEB-INF/jsp/addwriter.jsp
    return "addwriter";
}