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:fr.mycellar.interfaces.web.services.security.SecurityWebService.java

@POST
@Consumes(MediaType.APPLICATION_JSON)/*from   www . ja va  2  s. c o  m*/
@Path("sendPasswordResetMail")
public void sendPasswordResetMail(String email, @Context HttpServletRequest httpServletRequest) {
    userServiceFacade.resetPasswordRequest(email,
            httpServletRequest.getServletContext().getRealPath("reset-password"));
}

From source file:org.trimou.servlet.locator.ServletContextTemplateLocator.java

private ServletContext getServletContext() {

    if (servletContext != null) {
        return servletContext;
    }/*from ww  w . jav a  2  s  . c  o m*/

    HttpServletRequest httpServletRequest = RequestHolder.getCurrentRequest();

    if (httpServletRequest != null) {
        return httpServletRequest.getServletContext();
    }
    return null;
}

From source file:com.shoylpik.controller.AddProduct.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String SAVE_DIRECTORY = "menu_assets/ProductImage";
    String absolutePath = request.getServletContext().getRealPath("");
    String savePath = absolutePath + File.separator + SAVE_DIRECTORY;

    File imageSaveDirectory = new File(savePath);
    if (!imageSaveDirectory.exists()) {
        imageSaveDirectory.mkdir();/*  ww  w  .  j a v  a2 s . c o m*/
    }
    System.out.println("absolutePath: " + absolutePath);
    System.out.println("SavePath: " + savePath);
    //        System.out.println("imageSaveDirectory.getAbsolutePath(): " + imageSaveDirectory.getAbsolutePath());
    String fileName = null;

    try {

        Part filePart = request.getPart("IPimage");
        String filename = getFilename(filePart);
        //            System.out.println("filename: " + filename);
        InputStream imageInputStream = filePart.getInputStream();
        byte[] bytes = IOUtils.toByteArray(imageInputStream);

        Product product = new Product();
        product.setProductId(Integer.parseInt(request.getParameter("IPID")));
        product.setProductName(request.getParameter("IPname"));
        product.setProductImageName(filename);
        product.setProductCategory(request.getParameter("IPcat"));
        product.setProductPrice(Float.parseFloat(request.getParameter("IPprice")));
        product.setProductQuantity(Integer.parseInt(request.getParameter("IPQuant")));

        ProductBean pBean = new ProductBean();
        pBean.addProduct(product);

        //            String fullImagePath = "menu_assets/images/"+filename;

        String fullImagePath = savePath + File.separator + filename;
        File file = new File(fullImagePath);
        //            System.out.println("fullImagePath : " + fullImagePath);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bytes);

    } catch (SQLException ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | ServletException | NumberFormatException ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("AdministrationPage.jsp");
}

From source file:ge.taxistgela.servlet.RegistrationServlet.java

private void registerSuper(SuperUserManager man, SuperDaoUser obj, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    SmsQueue smsQueue = (SmsQueue) request.getServletContext().getAttribute(SmsQueue.class.getName());

    if (man == null || smsQueue == null) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } else {/*from w w w .j a  v a 2 s .  c om*/

        ErrorCode errorCode = new ErrorCode();

        errorCode.union(man.register(obj));

        if (errorCode.errorNotAccrued()) {
            response.setStatus(HttpServletResponse.SC_CREATED);

            EmailSender.verifyEmail(obj);

            smsQueue.addSms(obj);

            return;
        }

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().print(errorCode.toJson());
    }
}

From source file:Commands.UploadImageCommand.java

@Override
public String executeCommand(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String forwardToJsp = "uploadImage.jsp";
    HttpSession session = request.getSession(true);
    String UPLOAD_DIRECTORY = request.getServletContext().getRealPath("") + File.separator + "img"
            + File.separator;/*from  w w  w  . j a va  2  s  .  co m*/

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            ArrayList<FileItem> multiparts = (ArrayList<FileItem>) new ServletFileUpload(
                    new DiskFileItemFactory()).parseRequest(request);

            session.setAttribute("errorMsg", multiparts.size());
            if (multiparts.size() > 0) {
                for (FileItem item : multiparts) {
                    if (item != null) {

                        String name = new File(item.getName()).getName();

                        String filename = UPLOAD_DIRECTORY + name;
                        session.setAttribute("errorMsg", filename);
                        File f = new File(filename);
                        if (!item.isFormField()) {
                            item.write(f);
                        }
                    }
                }
            } else {
                session.setAttribute("errorMsg", "No File Choosen");
            }
        } catch (Exception ex) {

        }
    }
    return forwardToJsp;
}

From source file:id.go.customs.training.gudang.web.BarangUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Boolean adaFile = ServletFileUpload.isMultipartContent(req);
    if (adaFile) {
        try {//w w  w  . j  a v a2  s . c  o m
            String lokasiLengkap = req.getServletContext().getRealPath(lokasiPenyimpanan);
            System.out.println("Lokasi hasil upload : " + lokasiLengkap);

            // inisialisasi prosesor upload
            DiskFileItemFactory factory = new DiskFileItemFactory();
            File lokasiSementaraHasilUpload = (File) req.getServletContext()
                    .getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(lokasiSementaraHasilUpload);
            System.out.println("Lokasi upload sementara : " + lokasiSementaraHasilUpload.getAbsolutePath());
            ServletFileUpload prosesorUpload = new ServletFileUpload(factory);

            List<FileItem> hasilUpload = prosesorUpload.parseRequest(req);
            System.out.println("Jumlah file = " + hasilUpload.size());

            for (FileItem fileItem : hasilUpload) {
                System.out.println("----- Informasi File -----");
                System.out.println("Tipe File : " + fileItem.getContentType());
                System.out.println("Nama Field : " + fileItem.getFieldName());
                System.out.println("Nama File : " + fileItem.getName());
                System.out.println("Ukuran File : " + fileItem.getSize());

                String fileTujuan = lokasiLengkap + File.separator + fileItem.getName();
                File tujuan = new File(fileTujuan);
                fileItem.write(tujuan);
                System.out.println("Hasil upload ada di " + fileTujuan);

                HasilImportBarang hasil = BarangImporter.importCsv(tujuan);
                req.setAttribute("hasil", hasil);
            }
        } catch (Exception ex) {
            Logger.getLogger(BarangUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    // selesai upload, tampilkan hasil upload
    req.getRequestDispatcher("/WEB-INF/templates/jsp/barang/import.jsp").forward(req, resp);
}

From source file:com.toughland.helpmechoose.common.Helper.java

public String getBlendedImage(List<String> urls, Integer userId, HttpServletRequest request) {
    // TODO: add app logo
    urls.add("http://java-helpmechoose.rhcloud.com/images/help.png");

    String path = request.getServletContext().getRealPath("/") + "images\\temp\\";
    List<String> fileNames = new ArrayList<>();
    try {// w ww . ja va  2s.  co  m

        int count = 1;
        for (String item : urls) {
            URL url = new URL(item);
            InputStream in = new BufferedInputStream(url.openStream());
            OutputStream out = new BufferedOutputStream(
                    new FileOutputStream(path + userId.toString() + "_" + count + ".jpg"));
            for (int i; (i = in.read()) != -1;) {
                out.write(i);
            }
            in.close();
            out.close();

            fileNames.add(path + userId.toString() + "_" + count + ".jpg");

            count++;
        }
    } catch (Exception e) {
        Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, e);
    }

    return getUrl(request) + "images/temp/" + blendImages(fileNames, path, userId);
}

From source file:org.siphon.jssp.JsspRunner.java

public void run(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    String requestPath = getServletPath(request);
    String jsfile = request.getServletContext().getRealPath(requestPath);
    ScriptObjectMirror d2js = null;/*from   w w w .  j  av a 2 s. c o  m*/
    try {
        d2js = d2jsManager.getD2js(jsfile, requestPath);
        if (d2js == null) {
            response.setStatus(404);
            PrintWriter out = response.getWriter();
            out.print(request.getServletPath() + " not found");
            out.flush();
            return;
        }
    } catch (Exception e3) {
        logger.error("", e3);
        throw new ServletException(e3);
    }

    JsspRequest jsspRequest = new JsspRequest(request, engine);

    String params;
    try {
        params = getParams(jsspRequest);
    } catch (Exception e3) {
        response.setStatus(500);
        PrintWriter out = response.getWriter();
        out.print("params must be json");
        out.flush();
        return;
    }

    JsspWriter out = null;
    out = new JsspWriter(response, engine);
    JsspSession session = new JsspSession(request.getSession());

    try {
        ((Invocable) engine).invokeFunction("processJsspRequest", jsfile, params, jsspRequest, response,
                session, out);
    } catch (NoSuchMethodException | ScriptException e) {
        if (out.isDirty()) {
            response.setStatus(500);
            for (Throwable throwable = e; throwable != null; throwable = throwable.getCause()) {
                if (e != throwable) {
                    out.print("<br>Caused By: " + throwable.getMessage() + "<br>");
                } else {
                    out.print("<br>" + throwable.getMessage() + "<br>");
                }
                for (StackTraceElement frame : throwable.getStackTrace()) {
                    out.print("&nbsp;&nbsp;&nbsp;&nbsp;at " + frame.getClassName() + "." + frame.getMethodName()
                            + "(" + frame.getFileName() + ":" + frame.getLineNumber() + ")<br>");
                }
            }
        }
        throw new ServletException(e);
    }
}

From source file:org.apache.syncope.ext.saml2lsp.agent.Logout.java

private void doLogout(final SAML2ReceivedResponseTO receivedResponse, final HttpServletRequest request,
        final HttpServletResponse response) throws ServletException, IOException {

    SyncopeClientFactoryBean clientFactory = (SyncopeClientFactoryBean) request.getServletContext()
            .getAttribute(Constants.SYNCOPE_CLIENT_FACTORY);
    try {//from w  w w.  ja  v a 2  s .  com
        String accessToken = (String) request.getSession().getAttribute(Constants.SAML2SPJWT);
        if (StringUtils.isBlank(accessToken)) {
            throw new IllegalArgumentException("No access token found ");
        }

        SyncopeClient client = clientFactory.create(accessToken);
        client.getService(SAML2SPService.class).validateLogoutResponse(receivedResponse);

        String successURL = getServletContext().getInitParameter(Constants.CONTEXT_PARAM_LOGOUT_SUCCESS_URL);
        if (successURL == null) {
            request.getRequestDispatcher("logoutSuccess.jsp").forward(request, response);
        } else {
            response.sendRedirect(successURL);
        }
        request.getSession().removeAttribute(Constants.SAML2SPJWT);
    } catch (Exception e) {
        LOG.error("While processing authentication response from IdP", e);

        String errorURL = getServletContext().getInitParameter(Constants.CONTEXT_PARAM_LOGOUT_ERROR_URL);
        if (errorURL == null) {
            request.setAttribute("exception", e);
            request.getRequestDispatcher("logoutError.jsp").forward(request, response);

            e.printStackTrace(response.getWriter());
        } else {
            response.sendRedirect(errorURL + "?errorMessage="
                    + URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8.name()));
        }
    }
}