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:password.pwm.http.servlet.resource.ResourceFileServlet.java

private void rawRequestProcessor(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException, PwmUnrecoverableException {

    final FileResource file = resolveRequestedFile(req.getServletContext(), figureRequestPathMinusContext(req),
            ResourceServletConfiguration.defaultConfiguration());

    if (file == null || !file.exists()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from   ww w  . jav a2s .  co m
    }

    handleUncachedResponse(resp, file, false);
}

From source file:pages.NewUser.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w . ja  v a  2 s  .  c om*/
 *
 * @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");

    HttpSession session = request.getSession();

    Random rn = new Random();

    String[] query = new String[5];
    String firstname = (String) request.getParameter("firstname");
    String lastname = (String) request.getParameter("lastname");
    String address = request.getParameter("address");
    String dob = request.getParameter("dob");

    Jdbc jdbc = new Jdbc();
    jdbc.connect((Connection) request.getServletContext().getAttribute("connection"));
    session.setAttribute("dbbean", jdbc);

    if (jdbc == null) {

        JOptionPane.showMessageDialog(null, "Names can't have numbers in, please try again.", "Warning",
                JOptionPane.WARNING_MESSAGE);
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    } else if (firstname.matches(".*\\d+.*") || lastname.matches(".*\\d+.*")
            || (lastname.isEmpty() || firstname.isEmpty())) {

        JOptionPane.showMessageDialog(null,
                "You have entered an invalid Firstname and Lastname, please try again.", "Warning",
                JOptionPane.WARNING_MESSAGE);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    } else if (address.isEmpty()) {
        JOptionPane.showMessageDialog(null, "You have entered an invalid Address, please try again.", "Warning",
                JOptionPane.WARNING_MESSAGE);
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    } else if (dob.isEmpty()) {
        JOptionPane.showMessageDialog(null, "You have entered an invalid date of birth, please try again.",
                "Warning", JOptionPane.WARNING_MESSAGE);
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    } else {

        query[0] = firstname.substring(0, 1).toLowerCase() + "-" + lastname.toLowerCase();
        query[1] = (String) request.getParameter("firstname") + " " + (String) request.getParameter("lastname");
        query[2] = (String) request.getParameter("address");
        query[3] = (String) request.getParameter("dob");
        //query[4] = RandomStringUtils.randomAlphabetic(10).toLowerCase();
        query[4] = dob.replaceAll("\\D+", "");

        jdbc.insertNewUser(query);
        request.setAttribute("username", query[0]);
        request.setAttribute("password", query[4]);
        session.setAttribute("userID", query[0]);
        session.setAttribute("Login", "yes");

        request.getRequestDispatcher("/WEB-INF/regSuccess.jsp").forward(request, response);
    }

}

From source file:Controllers.AddItem.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  w w. j a v a  2 s  .c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String name = null;
    String itemCode = null;
    String price = null;
    String quantity = null;
    String category = null;
    String image = null;
    HttpSession session = request.getSession(true);
    User user = (User) session.getAttribute("user");
    if (user == null) {
        response.sendRedirect("login");
        return;
    }
    //        request.getServletContext().getRealPath("/uploads");
    String path = request.getServletContext().getRealPath("/uploads");
    System.out.println(path);

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

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    //                        new File(path).mkdirs();
                    File directory = new File(path + File.separator + fileName);
                    image = fileName;
                    item.write(directory);
                } else {
                    if ("name".equals(item.getFieldName())) {
                        name = item.getString();
                    } else if ("itemCode".equals(item.getFieldName())) {
                        itemCode = item.getString();
                    } else if ("price".equals(item.getFieldName())) {
                        price = item.getString();
                    } else if ("quantity".equals(item.getFieldName())) {
                        quantity = item.getString();
                    } else if ("category".equals(item.getFieldName())) {
                        category = item.getString();
                    }
                }
            }

            //File uploaded successfully
            System.out.println("done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    boolean status = ItemRepository.saveItem(name, itemCode, price, quantity, category, image, user);
    String message;
    if (status) {
        message = "Item saved successfully";
        response.sendRedirect("dashboard");
    } else {
        message = "Item not saved !!";
        request.setAttribute("message", message);
        request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response);
    }
}

From source file:org.o3project.odenos.remoteobject.rest.servlet.RestServlet.java

protected void doRequestToComponent(HttpServletRequest req, HttpServletResponse resp, Request.Method method)
        throws ServletException, IOException {
    Matcher matcher = RestServlet.PATH_PATTERN.matcher(req.getRequestURI());
    if (!matcher.find()) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;//from w  w w. j a va2  s .c o  m
    }
    String objectId = matcher.group(1);
    String path = matcher.group(2);
    if (req.getQueryString() != null) {
        path = path + "?" + URLDecoder.decode(req.getQueryString(), "utf-8");
    }
    Object reqBody = JSONValue.parse(req.getReader());

    RESTTranslator translator = (RESTTranslator) req.getServletContext()
            .getAttribute(Attributes.REST_TRANSLATOR);
    Response odenosResp;
    try {
        odenosResp = translator.request(objectId, method, path, reqBody);
    } catch (Exception e) {
        this.logger.debug("Failed to request [{}, {}, {}, {}]", objectId, method, path, reqBody, e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    resp.setStatus(odenosResp.statusCode);
    if (!odenosResp.isBodyNull()) {
        Value value;
        try {
            byte[] packed = this.messagePack.write(odenosResp);
            value = this.messagePack.read(packed);
        } catch (IOException e) {
            this.logger.debug("Failed to serialize a response body. /req:[{}, {}, {}, {}]", objectId, method,
                    path, reqBody);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        resp.getWriter().write(value.asArrayValue().get(1).toString());
    }
}

From source file:org.seaborne.auth.DigestHttp.java

/** The RFC 2617 algorithm for determing whether a request is acceptable or not.
 * See also {@link #sendChallenge(HttpServletRequest, HttpServletResponse)}.
 * @return <code>true</code> if accepable, else <code>false</code>.
 *//*  www  . ja  v a  2  s . c  om*/
public AccessStatus accessYesOrNo(HttpServletRequest request, HttpServletResponse response) {
    String x = getAuthzHeader(request);
    if (x == null) {
        if (log.isDebugEnabled())
            log.debug("accessYesOrNo: null header");
        return AccessStatus.NO;
    }
    if (log.isDebugEnabled())
        log.debug("accessYesOrNo: " + x);

    ServletContext servletContext = request.getServletContext();

    AuthHeader authHeader = AuthHeader.parse(x, request.getMethod());
    if (authHeader == null) {
        if (log.isDebugEnabled())
            log.debug("accessYesOrNo: Bad auth header");
        return AccessStatus.BAD;
    }

    if (!authHeader.parsed.containsKey(AuthHeader.strDigest)) {
        // XXX Does
        badRequest(request, response, "No 'Digest' in Authorization header");
        return AccessStatus.BAD;
    }

    if (authHeader.opaque == null) {
        if (log.isDebugEnabled())
            log.debug("accessYesOrNo: Bad Authorization header");
        badRequest(request, response, "Bad Authorization header");
        return AccessStatus.BAD;
    }

    // XXX CONCURRENECY 

    String opaque = authHeader.opaque;

    DigestSession digestSession = null;

    if (activeSessions.containsKey(opaque)) {
        digestSession = activeSessions.get(opaque);
    } else if (pendingSessions.containsKey(opaque)) {
        // This might be null due to another request
        // but we check below for null.
        digestSession = pendingSessions.remove(opaque);
    }

    if (digestSession == null) {
        if (log.isDebugEnabled())
            log.debug("accessYesOrNo: No session for opaque found");
        return AccessStatus.NO;
    }

    String requestUri = request.getRequestURI();
    String requestMethod = request.getMethod();
    String username = authHeader.username;

    // Some checks.
    // XXX Check in RFC
    if (!digestSession.username.isEmpty() && !digestSession.username.equals(authHeader.username)) {
        if (log.isDebugEnabled())
            log.debug(
                    "Username change: header=" + authHeader.username + " : expected" + digestSession.username);
        badRequest(request, response, "Different username in 'Authorization' header");
        return AccessStatus.BAD;
    }
    if (!digestSession.realm.equals(authHeader.realm)) {
        if (log.isDebugEnabled())
            log.debug("Realm change: header=" + authHeader.realm + " : expected" + digestSession.realm);
        badRequest(request, response, "Different realm in 'Authorization' header");
        return AccessStatus.BAD;
    }
    if (!requestUri.equals(authHeader.uri)) {
        if (log.isDebugEnabled())
            log.debug("URI change: header=" + authHeader.uri + " : expected" + requestUri);
        badRequest(request, response, "Different URI in 'Authorization' header");
        return AccessStatus.BAD;
    }
    if (!requestMethod.equals(authHeader.method)) {
        if (log.isDebugEnabled())
            log.debug("Method change: header=" + authHeader.method + " : expected" + requestMethod);
        badRequest(request, response, "Different HTTP method in 'Authorization' header");
        return AccessStatus.BAD;
    }

    // Check nonce.
    //        log("Server nonce = "+perm.nonce);
    //        log("Header nonce = "+ah.nonce);

    if (username == null) {
        if (log.isDebugEnabled())
            log.debug("No password for user '" + username + "'");
        return AccessStatus.NO;
    }

    String password = getPassword(servletContext, username);
    if (password == null) {
        if (log.isDebugEnabled())
            log.debug("No password for user '" + username + "'");
        return AccessStatus.NO;
    }

    if (log.isDebugEnabled())
        //log.debug("Attempt: User = " + username + " : Password = " + password);
        log.debug("Attempt: User = " + username);

    String digestCalc = calcDigest(authHeader, password);
    String digestRequest = authHeader.response;

    if (!digestCalc.equals(digestRequest)) {
        // Remove all.
        pendingSessions.remove(opaque);
        activeSessions.remove(opaque);
        if (log.isDebugEnabled())
            log.debug("Digest does not match");
        return AccessStatus.NO;
    }

    boolean challengeResponse = StringUtils.isEmpty(digestSession.username);
    if (challengeResponse) {
        // First time - complete digestSession details.
        digestSession.username = username;
        activeSessions.put(opaque, digestSession);
    }

    if (log.isDebugEnabled()) {
        //log.debug("request: "+httpRequest.getRequestURI());
        log.debug("User " + digestSession.username + " authorized");
    }
    return AccessStatus.YES;
}

From source file:com.dlshouwen.wzgl.content.controller.ArticleController.java

/**
 * ?/*from w w w .ja v  a2  s.c o  m*/
 *
 * @param articleId ?
 * @param model ??
 * @param request 
 * @return base + 'editAnnouncement'
 * @throws Exception 
 */
@RequestMapping(value = "/{articleId}/check", method = RequestMethod.GET)
public ModelAndView checkArticle(@PathVariable String articleId, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ModelAndView view = new ModelAndView("/wzgl/content/articleDetail.btl");
    String sourcePath = AttributeUtils.getAttributeContent(request.getServletContext(),
            "source_webapp_file_postion");
    //   ??
    Article article = dao.getArticleById(articleId);
    String channel_id = article.getChannel_id();
    Channel channelNow = channelDao.getChannelById(channel_id);
    List<Map<String, Object>> secChannelList = null;
    if (channelNow.getChannel_parent().equals("top")) {
        secChannelList = channelDao.getSecChannelList(channelNow.getChannel_id());
        view.addObject("topChannelNow", channelNow);
        view.addObject("channelNow", null);
        view.addObject("secChannelList", secChannelList);
    } else {
        Channel channelTopNow = channelDao.getChannelById(channelNow.getChannel_parent());
        secChannelList = channelDao.getSecChannelList(channelTopNow.getChannel_id());
        view.addObject("topChannelNow", channelTopNow);
        view.addObject("channelNow", channelNow);
        view.addObject("secChannelList", secChannelList);
    }
    List<Map<String, Object>> allChannel = channelDao.getFirstChannel();
    List<Picture> pics = albumDao.findPicByAlbumId(articleId);
    if (null == pics || pics.size() == 0) {
        pics = null;
    }
    view.addObject("allChannel", allChannel);
    view.addObject("article", article);
    view.addObject("pictureList", pics);
    view.addObject("SOURCEPATH", sourcePath);

    //      ?
    LogUtils.updateOperationLog(request, OperationType.VISIT, "?");
    return view;
}

From source file:Controllers.EditItem.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w w w . ja  v  a  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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String id = null;
    String name = null;
    String itemCode = null;
    String price = null;
    String quantity = null;
    String category = null;
    String image = null;
    HttpSession session = request.getSession(true);
    User user = (User) session.getAttribute("user");
    if (user == null) {
        response.sendRedirect("login");
        return;
    }
    //        request.getServletContext().getRealPath("/uploads");
    String path = request.getServletContext().getRealPath("/uploads");
    System.out.println(path);

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

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    //                        new File(path).mkdirs();
                    File directory = new File(path + File.separator + fileName);
                    image = fileName;
                    item.write(directory);
                } else {
                    if ("name".equals(item.getFieldName())) {
                        name = item.getString();
                    } else if ("id".equals(item.getFieldName())) {
                        id = item.getString();
                    } else if ("itemCode".equals(item.getFieldName())) {
                        itemCode = item.getString();
                    } else if ("price".equals(item.getFieldName())) {
                        price = item.getString();
                    } else if ("quantity".equals(item.getFieldName())) {
                        quantity = item.getString();
                    } else if ("category".equals(item.getFieldName())) {
                        category = item.getString();
                    }
                }
            }

            //File uploaded successfully
            System.out.println("done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    boolean status = ItemRepository.editItem(name, itemCode, price, quantity, category, image, id);
    String message;
    System.out.println(status);
    if (status) {
        message = "Item saved successfully";
        response.sendRedirect("dashboard");
    } else {
        message = "Item not saved !!";
        request.setAttribute("message", message);
        request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response);
    }
}

From source file:com.matrimony.controller.ProfileController.java

@RequestMapping(value = "changeAvatar", method = RequestMethod.POST)
public String doChangeAvatar(HttpServletRequest request) {
    User ssUser = (User) request.getSession().getAttribute(SessionKey.USER);
    if (ssUser == null)
        return "joinUs";
    try {/*from   ww  w .  ja v a 2s.  co m*/
        Collection<Part> parts = request.getParts();
        for (Part p : parts) {
            String originName = p.getSubmittedFileName();
            if (originName != null) {
                System.out.println(originName);
                String[] extensionFile = originName.split("\\.");
                if (extensionFile.length > 1) {
                    String avatarFolderPath = request.getServletContext()
                            .getRealPath("/resources/profile/avatar");
                    System.out.println("avatar folder: " + avatarFolderPath);

                    // MAKE OBF NAME AVATAR IMAGE
                    String obfName = RandomStringUtils.randomAlphanumeric(26);
                    StringBuilder filePath = new StringBuilder(avatarFolderPath);
                    filePath.append("/");
                    filePath.append(obfName);
                    filePath.append(".");
                    filePath.append(extensionFile[1]);

                    UploadImageToServer upload = new UploadImageToServer();
                    upload.upload(filePath.toString(), p.getInputStream());
                    System.out.println("Uploaded " + filePath.toString());
                    // UPDATE AVATAR
                    UserDAO.Update(ssUser);
                    ssUser.setAvatarPhoto(obfName + "." + extensionFile[1]);
                    return "redirect:";
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "profile";
}

From source file:org.adeptnet.atlassian.common.Common.java

public String getSAMLUserName(final HttpServletRequest request) {
    if (!samlEnabled) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("!samlEnabled");
        }// w w w .j  a v a  2  s .c  o m
        return null;
    }
    final String samlTicket = request.getParameter(SAMLClient.SAML_RESPONSE);
    if (samlTicket == null) {
        return null;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Found SAML Ticket");
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace(samlTicket);
    }
    final AttributeSet aset;
    try {
        final SAMLClient client = getSAMLClient(request.getServletContext());
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            aset = client.validateResponseGET(request.getQueryString());
        } else {
            aset = client.validateResponsePOST(samlTicket);
        }
    } catch (SAMLException ex) {
        LOG.fatal(ex.getMessage(), ex);
        return null;
    }
    return aset.getNameId();
}