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:catalogo.Main.java

private void deletePhotoFile(HttpServletRequest request, String photoFileName) {
    String appPath = request.getServletContext().getRealPath("");
    String filePath = appPath + File.separator + SAVE_DIR + File.separator + photoFileName;
    File photoFile = new File(filePath);
    photoFile.delete();/*from  w w w . j  a va  2 s  .  c o m*/
}

From source file:CNCServicesServlet.CNCServices.java

/**
 * Demo Call Buy Card Service//from  ww w . j  ava 2s.c  om
 */
private String BuyCard(HttpServletRequest request) {
    String txtData = "";
    String txtAgentCode = request.getServletContext().getInitParameter("agentCode");
    String txtAgentKey = request.getServletContext().getInitParameter("agentKey");
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 7);
    Date date = cal.getTime();
    SimpleDateFormat ft = new SimpleDateFormat("YYYYMMddhhmmssss");
    BuyCardRequest bcr = new BuyCardRequest(txtAgentCode, "VT", ft.format(date).toString(), 10000, 2);
    String bcrString = bcr.toString();
    ResponseRequest rr = new ResponseRequest();
    try {
        txtData = Util.Encrypt(txtAgentKey, bcrString);
        Softpin soft = new Softpin();
        String result = soft.getSoftpinSoap12().buyCard(txtAgentCode, txtData);
        JSONObject jsonObject = new JSONObject(result);
        String msg = jsonObject.isNull("msg") ? "" : jsonObject.getString("msg");
        rr.setMsg(msg);
        String tranid = jsonObject.isNull("tranid") ? "" : jsonObject.getString("tranid");
        rr.setTranid(tranid);
        String listCards = jsonObject.isNull("listCards") ? "" : jsonObject.getString("listCards");
        Integer code = jsonObject.getInt("code");
        rr.setCode(code);
        if (code == 1) {
            String listResult = Util.Decrypt(txtAgentKey, listCards);
            rr.setListCards(listResult);
            System.out.println("success");
        } else {
            rr.setListCards("");
            System.out.println("Error=" + msg);
        }
    } catch (Exception e) {
        rr.setListCards("");
        System.out.println("error=" + e.getMessage());
    }
    return rr.toString();
}

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

public void registerUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!verify(request, response))
        return;/*w  w w  .jav a2s  .c  o m*/

    UserManagerAPI userManager = (UserManagerAPI) request.getServletContext()
            .getAttribute(UserManagerAPI.class.getName());

    UserPreference userPreference = new UserPreference(-1, 0.1, false, 1900, Integer.MAX_VALUE, 5, false);

    ErrorCode code = userManager.insertUserPreference(userPreference);
    if (code.errorAccrued()) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    User user = new User(-1, request.getParameter("useremail"), request.getParameter("userpassword"),
            request.getParameter("userfirstName"), request.getParameter("userlastName"),
            request.getParameter("userphoneNumber"), getGender(request.getParameter("usergender")),
            filterSocialID(request.getParameter("userfacebookId")),
            filterSocialID(request.getParameter("usergoogleplusId")), 5.0, userPreference, false, false);

    registerSuper(userManager, user, request, response);
}

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

public void registerCompany(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!verify(request, response))
        return;//from w w w  . j  a  v a 2  s  .c  o  m

    CompanyManagerAPI companyManager = (CompanyManagerAPI) request.getServletContext()
            .getAttribute(CompanyManagerAPI.class.getName());

    Company company = new Company(-1, request.getParameter("companyCode"), request.getParameter("companyemail"),
            request.getParameter("companypassword"), request.getParameter("companyName"),
            request.getParameter("companyphoneNumber"),
            filterSocialID(request.getParameter("companyfacebookId")),
            filterSocialID(request.getParameter("companygoogleplusId")), false, false);

    registerSuper(companyManager, company, request, response);
}

From source file:com.esd.cs.statistics.ReportController.java

/**
 * // w w  w. j  a v a 2 s  . c o m
 * 
 * @param type
 * @param year
 * @param request
 * @return
 */
@RequestMapping(value = "/export/{type}/{year}", method = RequestMethod.POST)
@ResponseBody
public String export(@PathVariable(value = "type") String type, @PathVariable(value = "year") String year,
        HttpServletRequest request, HttpSession session) {

    List<ReportViewModel> list = null;
    // ??
    String url = request.getServletContext().getRealPath("/");
    // 
    CommonUtil.chineseFolder(url, uploadPath, companyPath);
    // ??
    String uuid = UUID.randomUUID().toString();
    // ?
    String exportPath = url + uploadPath + File.separator + companyPath + File.separator + uuid + ".xls";

    // ???
    ReportModel model = new ReportModel();
    model.setCreateCompany(createTabCompany);// ?
    model.setCreateData("" + CommonUtil.formatData());// 
    model.setCreatePeople("" + session.getAttribute(Constants.USER_REAL_NAME).toString());// 

    // 
    // ??
    if (StringUtils.equals("nature", type)) {
        list = reportViewService.getByCompanyType(year);
        model.setType("??");// 
        model.setTitle("??");// 
    }
    // 
    if (StringUtils.equals("area", type)) {
        list = reportViewService.getByArea(year);
        model.setType("");// 
        model.setTitle("");// 
    }
    // ?
    if (StringUtils.equals("economytype", type)) {
        list = reportViewService.getByArea(year);
        model.setType("?");// 
        model.setTitle("?");// 
    }

    // ?
    PoiCreateExcel.createRepeaExcel(exportPath, list, model);

    String destPath = request.getLocalAddr() + ":" + request.getLocalPort() + request.getContextPath();
    // ?
    String loaddown = "http://" + destPath + "/" + uploadPath + "/" + companyPath + "/" + uuid + ".xls";
    return loaddown;
}

From source file:com.github.diluka.dynamic.web.staticizer.filter.DynamicWebStaticizerFilter.java

private File getDir(IStaticizerConfig config, HttpServletRequest request) {
    String dir = config.getStaticPageDirectory();
    if (dir.contains(":")) {
        return new File(dir);
    } else {//w w w  .j ava  2s. co m
        return new File(request.getServletContext().getRealPath("/"), dir);
    }
}

From source file:br.edu.ifpb.sislivros.model.ProcessadorFotos.java

public String processarArquivoCapa(HttpServletRequest request, Part partCapa, String nameToSave)
        throws IOException {

    if (partCapa != null & nameToSave != null) {
        InputStream fileContent = partCapa.getInputStream();
        String contextPath = request.getServletContext().getRealPath("/");

        if (salvarImagemCapa(contextPath + File.separator + folder, fileContent, nameToSave)) {
            return folder + "/" + nameToSave;
        }//from www . j  a v  a2 s . c o m
    }

    return null;
}

From source file:equipeDFK.sistemaX.controller.ControllerAgenda.java

/**
 * Mtodo que recebe uma requisio para importar os feriados,
 * ento ler o arquivo CSV e depois persistir os dados no banco
 * @param arquivoCSV/*from www .j a  va2 s. c om*/
 * @param sobrescrever
 * @param req
 * @return String
 * @throws SQLException 
 */
@RequestMapping("openCSV")
public String OpenCSV(MultipartFile arquivoCSV, boolean sobrescrever, HttpServletRequest req)
        throws SQLException {
    GerenciadorDeFeriado gf = new GerenciadorDeFeriado();
    if (!arquivoCSV.isEmpty()) {
        try {
            byte[] b = arquivoCSV.getBytes();
            String caminho = req.getServletContext().getRealPath("/") + arquivoCSV.getOriginalFilename();
            System.out.println(caminho);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(caminho)));
            stream.write(b);
            stream.close();
            OpenCSV opencsv = new OpenCSV();
            if (sobrescrever) {

            } else {

            }
            gf.importaferiado(opencsv.lerCSV(new File(caminho)), sobrescrever);
            List eventos = gf.listar();
            eventos.stream().forEach((evento) -> {
                System.out.println(evento);
            });
            req.getSession().setAttribute("feriados", eventos);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return "managerHoliday";
}

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

public void registerDriver(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!verify(request, response))
        return;//from   ww w.  j av  a2 s .c o m

    DriverManagerAPI driverManager = (DriverManagerAPI) request.getServletContext()
            .getAttribute(DriverManagerAPI.class.getName());
    CompanyManagerAPI companyManager = (CompanyManagerAPI) request.getServletContext()
            .getAttribute(CompanyManagerAPI.class.getName());

    DriverPreference driverPreference = new DriverPreference(-1, 0.1, 0.0);

    ErrorCode code = driverManager.insertDriverPreference(driverPreference);
    if (code.errorAccrued()) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    Car car = new Car(RandomStringUtils.randomAlphanumeric(7), "Untitled", 1900, false, 0);

    code = driverManager.insertCar(car);
    if (code.errorAccrued()) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    Integer companyID = null;
    if (request.getParameter("drivercompanyCode") != "") {
        companyID = companyManager.getCompanyIDByCode(request.getParameter("drivercompanyCode"));
        if (companyID == null) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    Driver driver = new Driver(-1, request.getParameter("driverpersonalID"),
            request.getParameter("driveremail"), request.getParameter("driverpassword"), null,
            request.getParameter("driverfirstName"), request.getParameter("driverlastName"),
            getGender(request.getParameter("drivergender")), request.getParameter("driverphoneNumber"), car,
            filterSocialID(request.getParameter("driverfacebookId")),
            filterSocialID(request.getParameter("drivergoogleplusId")), 5.0, driverPreference, false, false,
            false);

    registerSuper(driverManager, driver, request, response);

    if (response.getStatus() == HttpServletResponse.SC_CREATED) {
        Company company = (Company) companyManager.getByID(companyID);
        driver = (Driver) driverManager.getByEmail(driver.getEmail());

        if (company != null && driver != null) {
            EmailSender.verifyCompany(driver, company);
        }
    }
}

From source file:web.UploadFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww  w . j a va  2s.  com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    filePath = request.getServletContext().getRealPath("/WEB-INF/uploads");

    try {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;

        try {
            items = upload.parseRequest(request);

        } catch (Exception e) {
            e.printStackTrace();
        }

        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            String itemName = item.getName();
            if ((itemName == null) || itemName.equals("")) {
                continue;
            }
            String filename = FilenameUtils.getName(itemName);
            File f = checkExist(filename);
            item.write(f);

            fileBean.create(filename, f.getPath());
        }

        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Documento Submetido</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<span>Documento Enviado!</span></br></br>");
        out.println("<a href='" + request.getHeader("referer") + "'>Return</a>");
        out.println("</body>");
        out.println("</html>");

    } catch (Exception e) {

    }
}