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.rsginer.spring.controllers.RestaurantesController.java

@RequestMapping(value = { "/upload-file" }, method = RequestMethod.POST, produces = "application/json")
public void uploadFile(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestParam("file") MultipartFile file) {
    try {/*from   w ww.j av a 2  s .c  o m*/
        String rutaRelativa = "/uploads";
        String rutaAbsoluta = httpServletRequest.getServletContext().getVirtualServerName();
        String jsonSalida = jsonTransformer
                .toJson("http://" + rutaAbsoluta + ":" + httpServletRequest.getLocalPort()
                        + httpServletRequest.getContextPath() + "/uploads/" + file.getOriginalFilename());
        if (!file.isEmpty()) {
            int res = fileSaveService.saveFile(file, httpServletRequest);
            if (res == 200) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                httpServletResponse.setContentType("application/json; charset=UTF-8");
                try {
                    httpServletResponse.getWriter().println(jsonSalida);
                } catch (IOException ex) {
                    Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    } catch (BussinessException ex) {
        List<BussinessMessage> bussinessMessages = ex.getBussinessMessages();
        String jsonSalida = jsonTransformer.toJson(bussinessMessages);
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }

    }

}

From source file:com.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request/* w w w  . j  a  v  a 2s. co m*/
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            ServletOutputStream op = response.getOutputStream();

            response.setContentType(getMimeType(file));
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, bytes);
            }

            in.close();
            op.flush();
            op.close();
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile"));
        if (file.exists()) {
            file.delete(); // TODO:check and report success
        }
    } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    BufferedImage thumb = Scalr.resize(im, 75);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:com.Uploader.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   w ww  .j  a va 2s.co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //  processRequest(request, response);
    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

From source file:mvc.parent.WebController.java

private boolean hasCommonRights(String url, HttpServletRequest request) {
    WebInvocationPrivilegeEvaluator wipe = (WebInvocationPrivilegeEvaluator) WebApplicationContextUtils
            .getWebApplicationContext(request.getServletContext())
            .getBean(WebInvocationPrivilegeEvaluator.class);
    return wipe.isAllowed(url, SecurityContextHolder.getContext().getAuthentication());
}

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

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */// w  ww. j a v a2s  . co m
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

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

    if (FormFieldValidator.isLogin(request.getSession())) {

    } else {

    }
    String revMsg = this.cons.getReceivedMessage(request.getServletContext());
    log.info("Received Message :" + revMsg);
    if (revMsg != null) {

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

            revJson = (JSONObject) parser.parse(revMsg);
            String reqStatus = (String) revJson.get("status");

            if (reqStatus.equals("0")) {

                String msStatus = (String) revJson.get("msStatus");
                if (msStatus.trim().equals("1")) {
                    request.setAttribute("msStatus", "1");
                } else if (msStatus.trim().equals("0")) {
                    request.setAttribute("msStatus", "0");
                }

            }

        } catch (ParseException e) {

            e.printStackTrace();

        }

    }

    RequestDispatcher rd = request.getRequestDispatcher("/msStateUpdate.jsp");
    rd.forward(request, response);

}

From source file:org.egov.services.zuulproxy.filter.ZuulProxyFilter.java

@Override
public Object run() {

    mapper = new ObjectMapper();
    final RequestContext ctx = RequestContext.getCurrentContext();
    final HttpServletRequest request = ctx.getRequest();

    final WebApplicationContext springContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(request.getServletContext());

    final HashMap<String, String> zuulProxyRoutingUrls;
    final ServicesApplicationProperties applicationProperties = (ServicesApplicationProperties) springContext
            .getBean(SERVICES_APPLICATION_PROPERTIES);
    try {/*  w  w  w .ja  v a2 s.  co m*/
        zuulProxyRoutingUrls = (HashMap<String, String>) applicationProperties.zuulProxyRoutingUrls();
        if (log.isInfoEnabled())
            log.info("Zuul Proxy Routing Mapping Urls... " + zuulProxyRoutingUrls);
    } catch (final Exception e) {
        throw new ApplicationRuntimeException("Could not get valid routing url mapping for mirco services", e);
    }
    try {
        final URL requestURL = new URL(request.getRequestURL().toString());

        String endPointURI;
        if (requestURL.getPath().startsWith(SERVICES_CONTEXTROOT))
            endPointURI = requestURL.getPath().split(SERVICES_CONTEXTROOT)[1];
        else
            endPointURI = requestURL.getPath();

        String mappingURL = "";
        for (final Entry<String, String> entry : zuulProxyRoutingUrls.entrySet()) {
            final String key = entry.getKey();
            if (endPointURI.contains(key)) {
                mappingURL = entry.getValue();
                break;
            }
        }
        if (log.isInfoEnabled())
            log.info(String.format("%s request to the url %s", request.getMethod(),
                    request.getRequestURL().toString()));

        final String tenantId = getTanentId(springContext);
        final StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(endPointURI).append('?')
                .append(updateQueryString(request.getQueryString(), TENANT_ID, tenantId));
        endPointURI = stringBuilder.toString();

        if (log.isInfoEnabled())
            log.info("endPointURI  " + endPointURI);

        final URL routedHost = new URL(mappingURL + endPointURI);
        ctx.setRouteHost(routedHost);
        ctx.set(REQUEST_URI, routedHost.getPath());

        Map<String, List<String>> map = HTTPRequestUtils.getInstance().getQueryParams();
        if (map == null) {
            RequestContext.getCurrentContext().setRequestQueryParams(new HashMap<String, List<String>>());
            map = HTTPRequestUtils.getInstance().getQueryParams();
        }
        map.put(TENANT_ID, Arrays.asList(tenantId));
        ctx.setRequestQueryParams(map);

        if (log.isInfoEnabled())
            log.info("TenantId from getRequestQueryParams() "
                    + ctx.getRequestQueryParams().get(TENANT_ID).toString());

        final String userInfo = getUserInfo(request, springContext, tenantId);

        //Adding userInfo to Response header - to show or hide some of the UI components based on user roles 
        ctx.addZuulResponseHeader(USER_INFO_FIELD_NAME, userInfo);

        if (log.isInfoEnabled())
            if (request.getSession() != null)
                log.info("SESSION ID " + request.getSession().getId());

        if (shouldPutUserInfoOnHeaders(ctx)) {
            ctx.addZuulRequestHeader(USER_INFO_FIELD_NAME, userInfo);
            if (request.getSession() != null)
                ctx.addZuulRequestHeader(SESSION_ID, request.getSession().getId());

        } else {
            if (request.getSession() != null)
                ctx.addZuulRequestHeader(SESSION_ID, request.getSession().getId());
            appendUserInfoToRequestBody(ctx, userInfo);
        }

    } catch (final MalformedURLException e) {
        throw new ApplicationRuntimeException("Could not form valid URL", e);
    } catch (final IOException ex) {
        ctx.setSendZuulResponse(false);
        throw new ApplicationRuntimeException("Problem while setting RequestInfo..", ex);
    }
    return null;
}

From source file:de.yaio.services.webshot.server.controller.WebshotProvider.java

public void downloadResultFile(HttpServletRequest request, HttpServletResponse response, File downloadFile)
        throws IOException {
    // construct the complete absolute path of the file
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // get MIME type of the file
    ServletContext context = request.getServletContext();
    String mimeType = context.getMimeType(downloadFile.getAbsolutePath());

    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }//from  w ww . jav a 2s  .c  o m
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("MIME type: " + mimeType);
    }

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close();
}

From source file:org.zht.framework.web.controller.DownloadController.java

@RequestMapping(value = "/download")
public String download(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "filename") String filename) throws Exception {

    filename = filename.replace("/", "\\");

    if (StringUtils.isEmpty(filename) || filename.contains("\\.\\.")) {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("??");
        return null;
    }/*www. ja va2  s.c o  m*/
    filename = URLDecoder.decode(filename, "UTF-8");

    String projectPath = request.getServletContext().getRealPath("/");

    String filePath = projectPath + File.separator + filename;

    DownloadUtils.download(request, response, filePath, filename);

    return null;
}

From source file:io.lavagna.web.security.HSTSFilter.java

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
        throws IOException, ServletException {

    Map<Key, String> configuration = config.findConfigurationFor(of(Key.USE_HTTPS, Key.BASE_APPLICATION_URL));

    final boolean requestOverHttps = isOverHttps(req);
    final boolean useHttps = "true".equals(configuration.get(Key.USE_HTTPS));

    boolean hasConfProblem = false;
    if (req.getServletContext().getSessionCookieConfig().isSecure() != useHttps) {
        LOG.warn("SessionCookieConfig is not aligned with settings. The application must be restarted.");
        hasConfProblem = true;/*from  w  w  w .ja  v a2 s. co m*/
    }
    if (useHttps && !configuration.get(Key.BASE_APPLICATION_URL).startsWith("https://")) {
        LOG.warn(
                "The base application url {} does not begin with https:// . It's a mandatory requirement if you want to enable full https mode.",
                configuration.get(Key.BASE_APPLICATION_URL));
        hasConfProblem = hasConfProblem || true;
    }

    // IF ANY CONF error, will skip the filter
    if (hasConfProblem) {
        chain.doFilter(req, resp);
        return;
    }

    String reqUriWithoutContextPath = reqUriWithoutContextPath(req);

    // TODO: we ignore the websocket because the openshift websocket proxy
    // does not add the X-Forwarded-Proto header. : -> no redirection and
    // STS for the calls under /api/socket/*
    if (useHttps && !requestOverHttps && !reqUriWithoutContextPath.startsWith("/api/socket/")) {
        LOG.debug("use https is true and request is not over https, should redirect request");
        sendRedirectAbsolute(configuration.get(Key.BASE_APPLICATION_URL), resp, reqUriWithoutContextPath,
                Collections.<String, List<String>>emptyMap());
        return;
    } else if (useHttps && requestOverHttps) {
        LOG.debug("use https is true and request is over https, adding STS header");
        resp.setHeader("Strict-Transport-Security", "max-age=31536000");
    }

    chain.doFilter(req, resp);
}