Example usage for javax.servlet.http HttpServletRequest getServletContext

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

Introduction

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

Prototype

public ServletContext getServletContext();

Source Link

Document

Gets the servlet context to which this ServletRequest was last dispatched.

Usage

From source file:com.sishuok.es.maintain.icon.web.controller.IconController.java

/**
 * ?  ? ??/*from  ww w. jav  a 2s.  c  om*/
 *
 * @param request
 * @return
 */
@RequestMapping(value = "/genCssFile")
@ResponseBody
public String genIconCssFile(HttpServletRequest request) {

    this.permissionList.assertHasEditPermission();

    String uploadFileTemplate = ".%1$s{background:url(%2$s/%3$s);width:%4$spx;height:%5$spx;display:inline-block;vertical-align: middle;%6$s}";
    String cssSpriteTemplate = ".%1$s{background:url(%2$s/%3$s) no-repeat -%4$spx -%5$spx;width:%6$spx;height:%7$spx;display:inline-block;vertical-align: middle;%8$s}";

    ServletContext sc = request.getServletContext();
    String ctx = sc.getContextPath();

    List<String> cssList = Lists.newArrayList();

    Searchable searchable = Searchable.newSearchable().addSearchParam("type_in",
            new IconType[] { IconType.upload_file, IconType.css_sprite });

    List<Icon> iconList = baseService.findAllWithNoPageNoSort(searchable);

    for (Icon icon : iconList) {

        if (icon.getType() == IconType.upload_file) {
            cssList.add(String.format(uploadFileTemplate, icon.getIdentity(), ctx, icon.getImgSrc(),
                    icon.getWidth(), icon.getHeight(), icon.getStyle()));
            continue;
        }

        if (icon.getType() == IconType.css_sprite) {
            cssList.add(String.format(cssSpriteTemplate, icon.getIdentity(), ctx, icon.getSpriteSrc(),
                    icon.getLeft(), icon.getTop(), icon.getWidth(), icon.getHeight(), icon.getStyle()));
            continue;
        }

    }

    try {
        ServletContextResource resource = new ServletContextResource(sc, iconClassFile);
        FileUtils.writeLines(resource.getFile(), cssList);
    } catch (Exception e) {
        LogUtils.logError("gen icon error", e);
        return "?" + e.getMessage();
    }

    return "??";
}

From source file:com.portal.controller.AdminController.java

@RequestMapping(value = "/employes/update", method = RequestMethod.POST)
public String submitUpdateEmployee(HttpServletRequest request, @RequestParam("id") int id,
        @ModelAttribute("employeedto") EmployeeDTO employeedto,
        @RequestParam(value = "avatarFile", required = false) MultipartFile avatar) throws Exception {

    //        Employee employee=new Employee();
    Employee employee = portalService.getEmployee(id);

    if (!avatar.isEmpty() && avatar.getContentType().equals("image/jpeg")) {
        portalService.saveFile(/*from  ww  w  . j  a  v a2  s. com*/
                request.getServletContext().getRealPath("/template/img/") + "/" + avatar.getOriginalFilename(),
                avatar);
        employee.setAvatar(avatar.getOriginalFilename());
    }

    //        employee.setId(id);
    employee.setName(employeedto.getName());
    employee.setDepartment(portalService.getDepartment(employeedto.getDepartment()));
    employee.setPosition(portalService.getPosition(employeedto.getPosition()));
    employee.setPhone(employeedto.getPhone());
    employee.setEmail(employeedto.getEmail());
    employee.setDescription(employeedto.getDescription());
    portalService.saveEmployee(employee);

    return "redirect:/admin/employes";
}

From source file:com.daphne.es.maintain.icon.web.controller.IconController.java

/**
 * ?  ? ??//from   w w w .ja va 2 s  . c  o m
 *
 * @param request
 * @return
 */
@RequestMapping(value = "/genCssFile")
@ResponseBody
public String genIconCssFile(HttpServletRequest request) {

    this.permissionList.assertHasEditPermission();

    String uploadFileTemplate = ".%1$s{background:url(%2$s/%3$s);width:%4$spx;height:%5$spx;display:inline-block;vertical-align: middle;%6$s}";
    String cssSpriteTemplate = ".%1$s{background:url(%2$s/%3$s) no-repeat -%4$spx -%5$spx;width:%6$spx;height:%7$spx;display:inline-block;vertical-align: middle;%8$s}";

    ServletContext sc = request.getServletContext();
    String ctx = sc.getContextPath();

    List<String> cssList = Lists.newArrayList();

    Searchable searchable = Searchable.newSearchable().addSearchParam("type_in",
            new IconType[] { IconType.upload_file, IconType.css_sprite });

    List<Icon> iconList = baseService.findAllWithNoPageNoSort(searchable);

    for (Icon icon : iconList) {

        if (icon.getType() == IconType.upload_file) {
            cssList.add(String.format(uploadFileTemplate, icon.getIdentity(), ctx, icon.getImgSrc(),
                    icon.getWidth(), icon.getHeight(), icon.getStyle()));
            continue;
        }

        if (icon.getType() == IconType.css_sprite) {
            cssList.add(String.format(cssSpriteTemplate, icon.getIdentity(), ctx, icon.getSpriteSrc(),
                    icon.getLeft(), icon.getTop(), icon.getWidth(), icon.getHeight(), icon.getStyle()));
            continue;
        }

    }

    try {

        ServletContextResource resource = new ServletContextResource(sc, iconClassFile);
        FileUtils.writeLines(resource.getFile(), cssList);
    } catch (Exception e) {
        LogUtils.logError("gen icon error", e);
        return "?" + e.getMessage();
    }

    return "??";
}

From source file:com.luna.maintain.icon.web.controller.IconController.java

/**
 * ?  ? ??/* w ww . j ava2  s. c o  m*/
 *
 * @param request
 * @return
 */
@RequestMapping(value = "/genCssFile")
@ResponseBody
public String genIconCssFile(HttpServletRequest request) {

    this.permissionList.assertHasEditPermission();

    String uploadFileTemplate = ".%1$s{background:url(%2$s/%3$s);width:%4$spx;height:%5$spx;display:inline-block;vertical-align: middle;%6$s}";
    String cssSpriteTemplate = ".%1$s{background:url(%2$s/%3$s) no-repeat -%4$spx -%5$spx;width:%6$spx;height:%7$spx;display:inline-block;vertical-align: middle;%8$s}";

    ServletContext sc = request.getServletContext();
    String ctx = sc.getContextPath();

    List<String> cssList = Lists.newArrayList();

    Searchable searchable = Searchable.newSearchable().addSearchParam("type_in",
            new IconType[] { IconType.upload_file, IconType.css_sprite });

    List<Icon> iconList = baseService.findAllWithNoPageNoSort(searchable);

    for (Icon icon : iconList) {

        if (icon.getType() == IconType.upload_file) {
            cssList.add(String.format(uploadFileTemplate, icon.getIdentity(), ctx, icon.getImgSrc(),
                    icon.getWidth(), icon.getHeight(), icon.getStyle()));
            continue;
        }

        if (icon.getType() == IconType.css_sprite) {
            cssList.add(String.format(cssSpriteTemplate, icon.getIdentity(), ctx, icon.getSpriteSrc(),
                    icon.getLeft(), icon.getTop(), icon.getWidth(), icon.getHeight(), icon.getStyle()));
            continue;
        }

    }

    try {
        ServletContextResource resource = new ServletContextResource(sc, iconClassFile);
        FileUtils.writeLines(resource.getFile(), cssList);
    } catch (Exception e) {
        log.error("gen icon error", e);
        return "?" + e.getMessage();
    }

    return "??";
}

From source file:uk.co.caprica.bootlace.security.web.filter.AngularJsCsrfHeaderFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    logger.debug("doFilterInternal()");
    CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
    if (csrf != null) {
        Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME);
        String token = csrf.getToken();
        if (cookie == null || token != null && !token.equals(cookie.getValue())) {
            logger.debug("Setting new CSRF cookie");
            cookie = new Cookie(CSRF_COOKIE_NAME, token);
            cookie.setPath(request.getServletContext().getContextPath() + "/");
            response.addCookie(cookie);/* www  .jav  a  2s  . c  om*/
        }
    }
    filterChain.doFilter(request, response);
}

From source file:net.swas.explorer.servlet.ms.GetMSStatus.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from   w w w.  jav  a  2  s .  co m*/
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String status = "", msg = "";

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    JSONObject messageJson = new JSONObject();
    JSONObject respJson = new JSONObject();

    messageJson.put("action", "status");
    this.prod.send(messageJson.toJSONString());

    String revMsg = this.cons.getReceivedMessage(request.getServletContext());

    if (FormFieldValidator.isLogin(request.getSession())) {
        log.info("Received Message :" + revMsg);
        if (revMsg != null) {

            JSONParser parser = new JSONParser();
            JSONObject revJson = null;
            try {

                revJson = (JSONObject) parser.parse(revMsg);
                respJson = revJson;

            } catch (ParseException e) {

                status = "1";
                msg = "Unable to reach modsercurity service. Please try later";
                e.printStackTrace();

            }

        } else {

            status = "1";
            msg = "Unable to reach modsercurity service. Please try later";
            log.info("Message is not received......");

        }

        if (!status.equals("")) {

            respJson.put("status", status);
            respJson.put("message", msg);

        }
    } else {
        status = "2";
        msg = "User Session Expired";
        respJson.put("status", status);
        respJson.put("message", msg);
    }

    try {
        log.info("Sending Json : " + respJson.toString());
        out.print(respJson.toString());
    } finally {
        out.close();
    }

}

From source file:org.nuxeo.ecm.platform.web.common.requestcontroller.filter.NuxeoRequestControllerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (log.isDebugEnabled()) {
        log.debug(doFormatLogMessage(httpRequest, "Entering NuxeoRequestController filter"));
    }/*from   w  w w .j  av a 2  s .c  om*/

    ServletContext servletContext = httpRequest.getServletContext();
    ServletHelper.setServletContext(servletContext);

    doInitIfNeeded();

    RequestFilterConfig config = rcm.getConfigForRequest(httpRequest);

    boolean useSync = config.needSynchronization();
    boolean useTx = config.needTransaction();

    // Add cache header if needed
    if (httpRequest.getMethod().equals("GET")) {
        boolean isCached = config.isCached();
        if (isCached) {
            addCacheHeader(httpResponse, config.isPrivate(), config.getCacheTime());
        }
    }

    if (!useSync && !useTx) {
        if (log.isDebugEnabled()) {
            log.debug(doFormatLogMessage(httpRequest,
                    "Existing NuxeoRequestController filter: nothing to be done"));
        }

        try {
            chain.doFilter(request, response);
        } catch (ServletException e) {
            if (DownloadHelper.isClientAbortError(e)) {
                DownloadHelper.logClientAbort(e);
            } else {
                throw e;
            }
        }
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug(
                doFormatLogMessage(httpRequest, "Handling request with tx=" + useTx + " and sync=" + useSync));
    }

    boolean sessionSynched = false;
    if (useSync) {
        sessionSynched = simpleSyncOnSession(httpRequest);
    }
    boolean txStarted = false;
    try {
        if (useTx) {
            txStarted = ServletHelper.startTransaction(httpRequest);
            if (txStarted) {
                if (config.needTransactionBuffered()) {
                    response = new BufferingHttpServletResponse(httpResponse);
                }
            }
        }
        chain.doFilter(request, response);
    } catch (RuntimeException | IOException | ServletException e) {
        if (txStarted) {
            if (log.isDebugEnabled()) {
                log.debug(doFormatLogMessage(httpRequest, "Marking transaction for RollBack"));
            }
            TransactionHelper.setTransactionRollbackOnly();
        }
        if (DownloadHelper.isClientAbortError(e)) {
            DownloadHelper.logClientAbort(e);
        } else {
            log.error(doFormatLogMessage(httpRequest, "Unhandled error was caught by the Filter"), e);
            throw new ServletException(e);
        }
    } finally {
        if (txStarted) {
            try {
                TransactionHelper.commitOrRollbackTransaction();
            } catch (TransactionRuntimeException e) {
                // commit failed, report this to the client before stopping buffering
                ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        e.getMessage());
                throw e;
            } finally {
                if (config.needTransactionBuffered()) {
                    ((BufferingHttpServletResponse) response).stopBuffering();
                }
            }
        }
        if (sessionSynched) {
            simpleReleaseSyncOnSession(httpRequest);
        }

        ServletHelper.removeServletContext();

        if (log.isDebugEnabled()) {
            log.debug(doFormatLogMessage(httpRequest, "Exiting NuxeoRequestController filter"));
        }
    }
}

From source file:com.ddubyat.develop.jhawtcode.web.InternalResourceController.java

private static void setTraceProps(HttpServletRequest request) throws UnsupportedEncodingException {
    log.trace("Generating system properties");
    if (systemUUID.equalsIgnoreCase("")) {
        try {// www  . ja va2  s . c o m
            //generate from hardware
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                systemUUID += Arrays.toString(ni.getHardwareAddress());
            }
        } catch (Exception e) {
            //generate a uuid randomly for failures
            systemUUID = UUID.randomUUID().toString();
        }
        //md5 the uuid
        try {
            byte[] bytesOfMessage = systemUUID.getBytes("UTF-8");
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(bytesOfMessage);
            systemUUID = new BigInteger(1, thedigest).toString(16);
            log.trace("UUID Generated {}", systemUUID);
        } catch (Exception e) {
            systemUUID = "1234567890";
            log.trace("UUID Defaulted {}", systemUUID);
        }
    }

    log.trace("Generating app name");
    if (appname.equalsIgnoreCase("")) {
        if (request.getSession() != null && request.getSession().getServletContext() != null
                && request.getSession().getServletContext().getServletContextName() != null) {
            appname = request.getServletContext().getServletContextName();
            log.trace("Application Name Set to {}", appname);
        } else {
            appname = "noappname";
        }
        log.trace("Appname {}", appname);
    }

    log.trace("Generating username");
    if (username.equalsIgnoreCase("")) {
        if (System.getProperty("user.name") != null && StringUtil.isNotEmpty(System.getProperty("user.name"))) {
            username = System.getProperty("user.name");
            log.trace("Username Set to {}", username);
        } else {
            username = "nouser";
        }
        log.trace("Username {}", username);
    }

    log.trace("Generating license info");
    if (license.equalsIgnoreCase("")) {
        if (System.getProperty("jhawtcode.license") != null
                && StringUtil.isNotEmpty(System.getProperty("jhawtcode.license"))) {
            license = System.getProperty("jhawtcode.license");
        } else {
            license = "demo";
        }
        license = URLEncoder.encode(license, "UTF-8");
        log.trace("License {}", license);
    }
}

From source file:com.tssa.cooperationBusiness.controller.CooperationController.java

public String saveFile(HttpServletRequest request) {
    String filePath = "";
    try {/*from w  w  w. j av a 2  s  .c  om*/
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multiFile = multipartRequest.getFile("businessLicensePic");
        String fileUrl = request.getServletContext().getRealPath("/") + "upload/";
        String viewUrl = request.getServletContext().getContextPath() + "/upload/";
        // 
        //         String fileUrl = "/Users/gmc/Works/eclipse/workspace/TSSA/WebContent/WEB-INF/upload/";

        File file = new File(fileUrl);
        if (!file.exists()) {
            file.mkdirs();
        }

        if (multiFile != null
                && (multiFile.getOriginalFilename() != null && !"".equals(multiFile.getOriginalFilename()))) {
            File uploadFile = new File(fileUrl + multiFile.getOriginalFilename());
            multiFile.transferTo(uploadFile);

            filePath = viewUrl + multiFile.getOriginalFilename();

            return filePath;

        } else {
            return null;
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    return filePath;
}

From source file:com.orangeandbronze.jblubble.sample.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        pathInfo = "/";
    }/*from  www . ja v  a 2 s .  c o  m*/
    LOGGER.debug("POST {}{}", PATH, pathInfo);
    Part part = request.getPart("file");
    if (part != null) {
        BlobKey blobKey = blobstoreService.createBlob(part.getInputStream(), getFileName(part),
                part.getContentType());
        LOGGER.debug("Created blob, generated key [{}]", blobKey);
        blobKeys.add(blobKey);
    }
    response.sendRedirect(request.getServletContext().getContextPath() + "/uploads");
}