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:org.tsm.concharto.web.filter.LoginFilter.java

/**
 * Returns the first part of the URL path: "/member/settings.htm?id=1234" returns "member"
 * @param httpRequest//from w  ww. j a va2  s .  c  o  m
 * @return first part of the URL path
 */
private String[] getUrlParts(HttpServletRequest httpRequest) {
    String uri = httpRequest.getRequestURI();
    //should like like '/admin/canDelete' or '/admin/findUsers'
    String path = StringUtils.substringBetween(uri, httpRequest.getContextPath(), ".htm");
    String[] parts = StringUtils.split(path, '/');
    return parts;
}

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

@RequestMapping(value = "/createtype", method = RequestMethod.POST)
public String createTypeAction(@ModelAttribute("typeAttribute") Type typeAttribute, 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 v  a2  s  .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 create UDT (Type)");

    String schema = typeAttribute.getSchemaName().trim();

    if (schema.length() == 0) {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("New Type schema name = " + schema);
    logger.debug("New Type name = " + typeAttribute.getTypeName());

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

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

        createType.append("CREATE TYPE " + schema + "." + typeAttribute.getTypeName() + " \n");
        createType.append("EXTERNAL NAME '" + typeAttribute.getJavaClassName() + "' \n");
        createType.append("LANGUAGE JAVA \n");

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

            logger.debug("Creating UDT Type as -> " + createType.toString());

            result = GemFireXDWebDAOUtil.runCommand(createType.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);

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

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

    }

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

From source file:io.mapzone.controller.vm.http.HttpResponseForwarder.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to
 * local path and renames cookie to avoid collisions.
 *//*  w  ww .  ja v  a2  s  .c  o  m*/
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        // set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = requestForwarder.cookieNamePrefix.get() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); // set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

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

@RequestMapping(value = "/addloader", method = RequestMethod.POST)
public String createLoaderAction(@ModelAttribute("loaderAttribute") AddLoader loaderAttribute, 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 av a2s .  com
        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 Loader");

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

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

        addLoader.append("CALL SYS.ATTACH_LOADER ('" + loaderAttribute.getSchemaName() + "', \n");
        addLoader.append("'" + loaderAttribute.getTableName() + "', \n");
        addLoader.append("'" + loaderAttribute.getFunctionName() + "', \n");

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

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

            logger.debug("Creating Table Loader as -> " + addLoader.toString());

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

            model.addAttribute("result", result);

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

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

    }

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

From source file:org.iti.agrimarket.view.LoginController.java

@RequestMapping(value = "/dummylogin.htm", method = RequestMethod.GET)
public String loginDummy(HttpServletRequest request, HttpServletResponse response, Model model) {
    User result = userService.getUserEager(1);
    if (result == null) {
        model.addAttribute("error", "Invalid Email or password!");
        return "sign_in";
    }//from w  w  w.  j a va  2 s . co  m
    request.getSession().setAttribute("user", result);
    try {
        response.sendRedirect(request.getContextPath() + "/index.htm");
    } catch (IOException ex) {
        Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "profile";

}

From source file:fr.aliasource.webmail.server.OBMSSOProvider.java

@Override
public Credentials obtainCredentials(Map<String, String> settings, HttpServletRequest req) {
    String ticket = req.getParameter("ticket");
    if (ticket == null) {
        logger.warn("no ticket in url");
        return null;
    }//from w ww .  ja  v a2 s.  c o  m

    try {
        String logoutUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath() + "/session;jsessionid=" + req.getSession().getId();
        URL url = new URL(settings.get(SSO_SERVER_URL) + "?action=validate&ticket=" + ticket + "&logout="
                + URLEncoder.encode(logoutUrl, "UTF-8"));
        InputStream in = url.openStream();
        String content = IOUtils.toString(in);
        in.close();
        if (logger.isDebugEnabled()) {
            logger.debug("SSO server returned:\n" + content);
        }
        Credentials creds = null;
        if (!content.equals("invalidOBMTicket")) {
            String[] ssoServerReturn = content.split("&password=");
            String login = ssoServerReturn[0].substring("login=".length());
            String pass = ssoServerReturn[1];
            creds = new Credentials(URLDecoder.decode(login, "UTF-8"), URLDecoder.decode(pass, "UTF-8"));
        }
        return creds;
    } catch (Exception e) {
        logger.error("Ticket validation error: " + e.getMessage(), e);
        return null;
    }

}

From source file:org.pegadi.webapp.webstart.WebstartController.java

protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {

    Map<String, Object> model = new HashMap<String, Object>();
    List<String> libs = new ArrayList<String>();

    configBean.setVersion(resourceBundle.getString("version"));
    String contextPath = httpServletRequest.getContextPath();
    int serverport = httpServletRequest.getServerPort();
    String server = httpServletRequest.getServerName();
    configBean.setWebBase("http://" + server + ":" + serverport + contextPath);
    configBean.getProperties().put("server.host", server);
    File clientFolder = resourceLoader.getResource(configBean.getCodeBase()).getFile();

    if (clientFolder.isDirectory()) {
        File[] files = clientFolder.listFiles();
        for (File tempFile : files) {
            if (!tempFile.getName().contains(".jar")) {
                continue;
            }/* www. j a  v  a  2 s .  c o  m*/
            if (tempFile.getName().contains(configBean.getMainLibBaseName())) {
                model.put("main", configBean.getCodeBase() + tempFile.getName());
            } else {
                libs.add(configBean.getCodeBase() + tempFile.getName());
            }
        }
    } else {
        log.error("ERROR: clientFolder " + clientFolder.getAbsolutePath() + " is not a directory");
        throw new ServletException("WebStartController: Could not read directory containing client jars.");
    }

    model.put("jars", libs);

    model.put("config", configBean);

    return new ModelAndView("webstart", model);
}

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

@RequestMapping(value = "/jmxmbeans", method = RequestMethod.POST)
public String performJMXAction(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 {//  ww  w  .  ja  v  a2 s. 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 search for Mbeans");
    UserPref userPref = (UserPref) session.getAttribute("prefs");
    String jolokiaURL = userPref.getJolokiaURL();

    logger.debug("jolokiaURL = " + jolokiaURL);
    String searchStr = request.getParameter("search");
    logger.debug("searchStr = " + searchStr);

    List<String> mbeanNames = searchMbeans("", jolokiaURL);

    List<String> returnMbeanList = new ArrayList<String>();

    for (String mbean : mbeanNames) {
        if (mbean.toUpperCase().contains(searchStr.toUpperCase())) {
            returnMbeanList.add(mbean);
        }
    }

    model.addAttribute("mbeanNames", returnMbeanList);
    model.addAttribute("records", returnMbeanList.size());
    model.addAttribute("search", searchStr);

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

}

From source file:org.cloudifysource.rest.controllers.AdminAPIController.java

/**
 * REST GET requests handler implementation
 *    Parses uri path//from w  w w.j a va 2  s.c  om
 *    activates appropriate getters
 *    serialize results into a document object and pass for JSON marshaling
 *
 *              uri type                          processing 
 *            ============                      ==============
 *          http:/../getArr/ind/...       =>  (intermed.) resolve to arr[ind] and continue processing
 *          http:/../getMap/key/...       =>  (intermed.) resolve to map.get(key) and continue processing
 *          http:/../getList/ind/...      =>  (intermed.) resolve to list(ind) and continue processing      
 *          http:/../getObj               =>  (final) return obj fields (by public getters)
 *          http:/../getArr               =>  (final) return arr.length
 *          http:/../getList              =>  (final) return list.size()
 *          http:/../getMap               =>  (final) return comma-separated list of map keys
 *
 *    
 */
private Map<String, Object> getImplementation(HttpServletRequest httpServletRequest) throws Exception {
    //admin acts as root
    CommandManager manager = new CommandManager(httpServletRequest, getAdmin());
    manager.runCommands();
    String hostAddress = getRemoteHostAddress(httpServletRequest);
    String hostContext = httpServletRequest.getContextPath();
    return OutputDispatcher.outputResultObjectToMap(manager, hostAddress, hostContext);
}

From source file:net.triptech.buildulator.service.OpenIdAuthenticationSuccessHandler.java

public final void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication authentication) throws IOException {

    Person person = Person.findByOpenIdIdentifier(authentication.getName());

    if (person != null) {
        // Transfer any previous projects to the authenticated user
        transferProjects(request, person);
    }/*from  ww w .j a  va  2 s .co m*/
    response.sendRedirect(request.getContextPath() + "/projects");
}