List of usage examples for javax.servlet.http Cookie getValue
public String getValue()
From source file:com.example.web.Update_profile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String fileName = ""; int f = 0; String user = null;//ww w. ja v a 2 s. co m Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) { user = cookie.getValue(); } } } String email = request.getParameter("email"); String First_name = request.getParameter("First_name"); String Last_name = request.getParameter("Last_name"); String Phone_number_1 = request.getParameter("Phone_number_1"); String Address = request.getParameter("Address"); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/")); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); System.out.println("Uploaded Filename: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) { email = sb.toString(); } else if (f == 1) { First_name = sb.toString(); } else if (f == 2) { Last_name = sb.toString(); } else if (f == 3) { Phone_number_1 = sb.toString(); } else if (f == 4) { Address = sb.toString(); } f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (!email.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?"); pst.setString(1, email); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!First_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?"); pst.setString(1, First_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Last_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?"); pst.setString(1, Last_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Phone_number_1.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?"); pst.setString(1, Phone_number_1); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Address.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?"); pst.setString(1, Address); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!fileName.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?"); pst.setString(1, fileName); pst.setString(2, user); pst.executeUpdate(); pst.close(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { System.out.println("hi mom"); } request.setAttribute("s_page", "4"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }
From source file:fr.paris.lutece.plugins.mylutece.modules.openam.service.OpenamService.java
/** * Extract the value of the connection cookie * * @param request//from w w w. j av a2 s. c o m * The HTTP request * @return The cookie's value */ public String getConnectionCookie(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); String strOpenamCookie = null; if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(COOKIE_OPENAM_NAME)) { strOpenamCookie = cookie.getValue(); OpenamAPI._logger.debug("getHttpAuthenticatedUser : cookie '" + COOKIE_OPENAM_NAME + "' found - value=" + strOpenamCookie); } } } return strOpenamCookie; }
From source file:info.jtrac.wicket.JtracApplication.java
private boolean attemptRememberMeAutoLogin() { logger.debug("checking cookies for remember-me auto login"); Cookie[] cookies = ((WebRequest) RequestCycle.get().getRequest()).getCookies(); if (cookies == null) { logger.debug("no cookies found"); return false; }/*from w ww . j a va2 s .c o m*/ for (Cookie c : cookies) { if (logger.isDebugEnabled()) { logger.debug("examining cookie: " + WebUtils.getDebugStringForCookie(c)); } if (!c.getName().equals("jtrac")) { continue; } String value = c.getValue(); logger.debug("found jtrac cookie: " + value); if (value == null) { continue; } int index = value.indexOf(':'); if (index == -1) { continue; } String loginName = value.substring(0, index); String encodedPassword = value.substring(index + 1); logger.debug("valid cookie, attempting authentication"); User user = (User) getJtrac().loadUserByUsername(loginName); if (encodedPassword.equals(user.getPassword())) { ((JtracSession) Session.get()).setUser(user); logger.debug("remember me login success"); return true; } } // no valid cookies were found return false; }
From source file:io.stallion.plugins.flatBlog.comments.Comment.java
@JsonIgnore @JsonView(RestrictedViews.Member.class) public boolean isEditable() { if (Context.getUser().isInRole(Role.STAFF)) { return true; }//from w ww . j a va2 s .c o m if (Context.getRequest() != null) { Cookie cookie = Context.getRequest().getCookie(Constants.AUTHOR_SECRET_COOKIE); if (cookie != null && !empty(cookie.getValue())) { if (cookie.getValue().equals(getAuthorSecret())) { return true; } } } return false; }
From source file:azkaban.webapp.servlet.LoginAbstractAzkabanServlet.java
private Session getSessionFromRequest(HttpServletRequest req) throws ServletException { String remoteIp = req.getRemoteAddr(); Cookie cookie = getCookieByName(req, SESSION_ID_NAME); String sessionId = null;//from w w w . j a v a2s . co m if (cookie != null) { sessionId = cookie.getValue(); } if (sessionId == null && hasParam(req, "session.id")) { sessionId = getParam(req, "session.id"); } return getSessionFromSessionId(sessionId, remoteIp); }
From source file:com.sinosoft.one.mvc.web.var.FlashImpl.java
public void writeNewMessages() { if (logger.isDebugEnabled()) { logger.debug("writeNextMessages"); }/* w w w . j a v a 2 s . c o m*/ HttpServletResponse response = invocation.getResponse(); List<String> responseCookies = null; for (Map.Entry<String, String> entry : next.entrySet()) { if (responseCookies == null) { responseCookies = new ArrayList<String>(next.size()); } String cookieValue; if (entry.getValue() == null) { cookieValue = ""; } else { try { cookieValue = base64.encodeToString(entry.getValue().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Error(e); } } Cookie cookie = new Cookie(cookiePrefix + entry.getKey(), cookieValue); cookie.setPath("/"); // cookie.setMaxAge(1); response.addCookie(cookie); responseCookies.add(cookie.getName()); if (logger.isDebugEnabled()) { logger.debug("write flash cookie:" + cookie.getName() + "=" + cookie.getValue()); } } for (Map.Entry<String, String> entry : last.entrySet()) { if (responseCookies == null || !responseCookies.contains(entry.getKey())) { Cookie c = new Cookie(entry.getKey(), null); c.setMaxAge(0); c.setPath("/"); response.addCookie(c); if (logger.isDebugEnabled()) { logger.debug("delete flash cookie:" + c.getName() + "=" + c.getValue()); } } } }
From source file:com.laxser.blitz.web.var.FlashImpl.java
public void writeNewMessages() { if (logger.isDebugEnabled()) { logger.debug("writeNextMessages"); }/*from ww w. j a v a 2 s .co m*/ HttpServletResponse response = invocation.getResponse(); List<String> responseCookies = null; for (Map.Entry<String, String> entry : next.entrySet()) { if (responseCookies == null) { responseCookies = new ArrayList<String>(next.size()); } String cookieValue; if (entry.getValue() == null) { cookieValue = ""; } else { try { cookieValue = base64.encodeToString(entry.getValue().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Error(e); } } Cookie cookie = new Cookie(cookiePrefix + entry.getKey(), cookieValue); cookie.setPath("/"); cookie.setMaxAge(1); response.addCookie(cookie); responseCookies.add(cookie.getName()); if (logger.isDebugEnabled()) { logger.debug("write flash cookie:" + cookie.getName() + "=" + cookie.getValue()); } } for (Map.Entry<String, String> entry : last.entrySet()) { if (responseCookies == null || !responseCookies.contains(entry.getKey())) { Cookie c = new Cookie(entry.getKey(), null); c.setMaxAge(0); c.setPath("/"); response.addCookie(c); if (logger.isDebugEnabled()) { logger.debug("delete flash cookie:" + c.getName() + "=" + c.getValue()); } } } }
From source file:gr.abiss.calipso.userDetails.controller.UserDetailsController.java
@RequestMapping(method = RequestMethod.GET) @ResponseBody/*ww w .ja v a 2s.co m*/ public ICalipsoUserDetails remember() { if (LOGGER.isDebugEnabled()) { LOGGER.debug("remember"); } UserDetails resource = new UserDetails(); Cookie tokenCookie = null; Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (int i = 0; i < cookies.length; i++) { tokenCookie = cookies[i]; if (tokenCookie.getName().equals(this.userDetailsConfig.getCookiesBasicAuthTokenName())) { String token = tokenCookie.getValue(); if (StringUtils.isNotBlank(token)) { token = new String(Base64.decode(token.getBytes())); LOGGER.info("Request contained token: " + token); if (token.indexOf(':') > 0) { String[] parts = token.split(":"); if (StringUtils.isNotBlank(parts[0]) && StringUtils.isNotBlank(parts[1])) { resource.setUsername(parts[0]); resource.setPassword(parts[1]); } } else { LOGGER.warn("Invalid token received: " + token); } } break; } } } return this.create(resource); }
From source file:com.ssbusy.controller.catalog.CategoryController.java
@Override @SuppressWarnings("unchecked") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(); MyCustomer customer = (MyCustomer) CustomerState.getCustomer(); HttpSession session = request.getSession(); MyOfferCode myOfferCode = (MyOfferCode) session.getAttribute("bonusOfferCode"); Boolean w_flag = Boolean.FALSE; // cookies/*from w w w .ja v a 2 s. c o m*/ String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()); int count = 0;// ?? Cookie cookies[] = request.getCookies(); Boolean uiv2 = null; if (cookies != null) { for (Cookie c : cookies) { if (dateTime.equals(c.getName())) { count = Integer.valueOf(c.getValue()); break; // } else if ("uiv2".equals(c.getName())) { // uiv2 = Boolean.valueOf(c.getValue()); // 2 cookie } } } if (cookies != null) { for (Cookie c : cookies) { if ("SPRING_SECURITY_REMEMBER_ME_COOKIE".equals(c.getName())) { model.addObject("rember", c.getValue()); break; } } } // String uiParam = request.getParameter("uiv2"); // if (StringUtils.isNotEmpty(uiParam)) { // 1 param // uiv2 = Boolean.valueOf(uiParam); // Cookie c = new Cookie("uiv2", uiv2.toString()); // c.setPath("/"); // c.setMaxAge(60 * 60 * 24 * 360); // response.addCookie(c); // } else if (uiv2 == null) { uiv2 = Boolean.TRUE; // 3 default. // } session.setAttribute("uiv2", uiv2); // LOG.warn("uiv2=" + uiv2); if (myOfferCode != null) { if (customer.isRegistered()) giftService.updateOwnerCustomer(customer, myOfferCode); else myOfferCode = null; } else if (count < maxoffercodeCount) { myOfferCode = giftService.getgift(customer); if (myOfferCode != null) { if (customer.isAnonymous()) { session.setAttribute("bonusOfferCode", myOfferCode); model.addObject("bonusOfferCode", myOfferCode); myOfferCode = null; } } } if (myOfferCode != null) { session.removeAttribute("bonusOfferCode"); model.addObject("bonusOfferCode", myOfferCode); Cookie c = new Cookie(dateTime, String.valueOf(count + 1)); c.setPath("/"); c.setMaxAge(60 * 60 * 24); response.addCookie(c); LOG.info("offerCode sent, id=" + myOfferCode.getId() + ", ip=" + request.getRemoteAddr()); } if (request.getParameterMap().containsKey("facetField")) { // If we receive a facetField parameter, we need to convert the // field to the // product search criteria expected format. This is used in // multi-facet selection. We // will send a redirect to the appropriate URL to maintain canonical // URLs String fieldName = request.getParameter("facetField"); List<String> activeFieldFilters = new ArrayList<String>(); Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap()); for (Iterator<Entry<String, String[]>> iter = parameters.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, String[]> entry = iter.next(); String key = entry.getKey(); if (key.startsWith(fieldName + "-")) { activeFieldFilters.add(key.substring(key.indexOf('-') + 1)); iter.remove(); } } parameters.remove(ProductSearchCriteria.PAGE_NUMBER); parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()])); parameters.remove("facetField"); String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters); model.setViewName("redirect:" + newUrl); } else { // Else, if we received a GET to the category URL (either the user // clicked this link or we redirected // from the POST method, we can actually process the results Category category = (Category) request .getAttribute(CategoryHandlerMapping.CURRENT_CATEGORY_ATTRIBUTE_NAME); assert (category != null); List<SearchFacetDTO> availableFacets = searchService.getCategoryFacets(category); ProductSearchCriteria searchCriteria = facetService.buildSearchCriteria(request, availableFacets); String searchTerm = request.getParameter(ProductSearchCriteria.QUERY_STRING); ProductSearchResult result; List<FulfillmentLocation> locations = null; try { // if (customer != null && customer.getRegion() != null) { InventorySolrSearchServiceExtensionHandler.customerLocation .set(locations = customer.getRegion().getFulfillmentLocations()); } if (StringUtils.isNotBlank(searchTerm)) { result = searchService.findProductsByCategoryAndQuery(category, searchTerm, searchCriteria); } else { result = searchService.findProductsByCategory(category, searchCriteria); } } finally { InventorySolrSearchServiceExtensionHandler.customerLocation.remove(); } facetService.setActiveFacetResults(result.getFacets(), request); List<Product> products = result.getProducts(); if (products != null && products.size() > 0) { List<String> prodIds = new ArrayList<String>(products.size()); for (Product product : products) { prodIds.add(String.valueOf(product.getId())); } model.addObject("ratingSums", ratingService.readRatingSummaries(prodIds, RatingType.PRODUCT)); // ?productinventories if (locations != null) { Map<Product, List<Inventory>> invs = inventoryService.listAllInventories(products, locations); model.addObject("inventories", invs); } } model.addObject(PRODUCTS_ATTRIBUTE_NAME, products); model.addObject(CATEGORY_ATTRIBUTE_NAME, category); // facets List<SearchFacetDTO> facets = result.getFacets(); if (facets != null) { _nextFact: for (Iterator<SearchFacetDTO> itr = facets.iterator(); itr.hasNext();) { SearchFacetDTO dto = itr.next(); if (dto != null && dto.getFacetValues() != null) { for (SearchFacetResultDTO searchFacetDTO : dto.getFacetValues()) { if (searchFacetDTO != null) if (searchFacetDTO.getQuantity() != null && searchFacetDTO.getQuantity() > 0) continue _nextFact; } } itr.remove(); } model.addObject(FACETS_ATTRIBUTE_NAME, result.getFacets()); } model.addObject(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result); // TODO temp String view = category.getDisplayTemplate(); if (StringUtils.isEmpty(view)) view = getDefaultCategoryView(); if (request.getRequestURI().startsWith("/weixin/")) { view = "weixin/catalog/w_category_item"; w_flag = Boolean.TRUE; } if (uiv2) { if ("layout/home".equals(view)) view = "v2/home"; else { if (!view.startsWith("activity") && !view.startsWith("weixin/")) { view = "v2/" + view; } } } session.setAttribute("w_flag", w_flag); model.setViewName(view); } // if (isAjaxRequest(request)) { // model.setViewName(RETURN_PRODUCT_WATERFALL_ITEM); // model.addObject("ajax", Boolean.TRUE); // } return model; }