List of usage examples for javax.servlet.http HttpServletResponse addCookie
public void addCookie(Cookie cookie);
From source file:org.apache.accumulo.monitor.servlets.OperationServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Verify that this is the active Monitor instance if (!isActiveMonitor()) { resp.sendError(HttpURLConnection.HTTP_UNAVAILABLE, STANDBY_MONITOR_MESSAGE); return;/* w w w. j av a 2 s. com*/ } String redir = null; List<Cookie> cookiesToSet = Collections.emptyList(); try { String operation = req.getParameter("action"); redir = req.getParameter("redir"); if (operation != null) { for (Class<?> subclass : OperationServlet.class.getClasses()) { Object t; try { t = subclass.newInstance(); } catch (Exception e) { continue; } if (t instanceof WebOperation) { WebOperation op = (WebOperation) t; if (op.getClass().getSimpleName().equalsIgnoreCase(operation + "Operation")) { cookiesToSet = op.execute(req, log); break; } } } } } catch (Throwable t) { log.error(t, t); } finally { try { for (Cookie c : cookiesToSet) { resp.addCookie(c); } resp.sendRedirect(sanitizeRedirect(redir)); resp.flushBuffer(); } catch (Throwable t) { log.error(t, t); } } }
From source file:com.paperfood.controller.Authenticate.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) *//*ww w . j a va2s . co m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); JSONObject resp = new JSONObject(); MD5Hash md5; String status = ""; try { md5 = new MD5Hash(); String req_type = request.getParameter("type"); if (req_type.equalsIgnoreCase("login")) //Request of Login { String loginEmail = request.getParameter("loginEmail"); String loginPass = md5.getStringHash(request.getParameter("loginPass")); boolean loginRemember = request.getParameter("loginRemember").equalsIgnoreCase("true"); DatabaseManager dm = new DatabaseManager(); dm.open(); PaperFoodUser user = new PaperFoodUser(); user = (PaperFoodUser) dm.getLoggedUser(loginEmail, loginPass); dm.close(); if (user != null) //Credentials are valid, create session. { session.setAttribute("paperfooduseremail", user.getEmail()); if (loginRemember) { int time = 60 * 60 * 24 * 30; Cookie c = new Cookie("paperfood", user.getEmail()); c.setMaxAge(time); response.addCookie(c); } status = "success"; } else status = "invalid"; } else if (req_type.equalsIgnoreCase("cookielogin")) //Request for Cookie-based Login. { String loginEmail = request.getParameter("loginEmail"); session.setAttribute("paperfooduseremail", loginEmail); status = "success"; } else if (req_type.equalsIgnoreCase("sessionlogin")) //Request for Session-based Login. { String useremail = (String) session.getAttribute("paperfooduseremail"); if (useremail != null) status = "success"; } else if (req_type.equalsIgnoreCase("logout")) //Request for Logout. { session.invalidate(); Cookie[] c = request.getCookies(); if (c != null) { for (int i = 0; i < c.length; i++) { Cookie curr = c[i]; String cnm = curr.getName(); if (cnm.equalsIgnoreCase("paperfood")) { curr.setMaxAge(0); response.addCookie(curr); } } } status = "success"; } } catch (CommunicationsException e) { status = "unavailable"; } catch (Exception e) { status = "fail"; e.printStackTrace(); } try { resp.put("status", status); } catch (JSONException e) { e.printStackTrace(); } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); out.println(resp); }
From source file:com.salesmanager.core.util.www.SalesManagerInterceptor.java
private MerchantStore setMerchantStore(HttpServletRequest req, HttpServletResponse resp, String merchantId) throws Exception { // different merchantId int iMerchantId = 1; try {/*from ww w. j a v a 2 s . co m*/ iMerchantId = Integer.parseInt(merchantId); } catch (Exception e) { log.error("Cannot parse merchantId to Integer " + merchantId); } // get MerchantStore MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService); MerchantStore mStore = mservice.getMerchantStore(iMerchantId); if (mStore == null) { // forward to error page log.error("MerchantStore does not exist for merchantId " + merchantId); return null; } req.getSession().setAttribute("STORE", mStore); req.setAttribute("STORE", mStore); //get store configuration for template ReferenceService rservice = (ReferenceService) ServiceFactory.getService(ServiceFactory.ReferenceService); Map storeConfiguration = rservice.getModuleConfigurationsKeyValue(mStore.getTemplateModule(), mStore.getCountry()); if (storeConfiguration != null) { req.getSession().setAttribute("STORECONFIGURATION", storeConfiguration); } Cookie c = new Cookie("STORE", merchantId); c.setMaxAge(365 * 24 * 60 * 60); resp.addCookie(c); if (!RefCache.isLoaded()) { RefCache.createCache(); } return mStore; }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Carry out login rituals after a successful execution of login service * // ww w. ja v a 2 s. c om * @param req * @param resp * @param data * @return */ private boolean doLogin(HttpServletRequest req, HttpServletResponse resp, ServiceData data) { if (data.getErrorStatus() != CommonFieldNames.SEVERITY_SUCCESS) { return false; } req.getSession().setAttribute(AP.loggedInUserFieldName, data.getValue(AP.loggedInUserFieldName)); // set cookies Cookie cookie = new Cookie(AP.loggedInUserFieldName, data.getValue(AP.loggedInUserFieldName)); Date now = DateUtility.addDays(new Date(), 400); cookie.setMaxAge((int) now.getTime()); resp.addCookie(cookie); if (AP.setCookies != null) { for (String name : AP.setCookies) { cookie = new Cookie(name, data.getValue(name)); cookie.setPath(req.getContextPath()); if (data.hasValue(name)) { Spit.out(" cookie " + name + " is set with value = " + data.getValue(name)); cookie.setMaxAge((int) now.getTime()); } else { // we have to remove the cookie Spit.out(name + " does not have value and hence cookie is not set"); cookie.setMaxAge(-12); } resp.addCookie(cookie); } } data.addValue("*_usersession", req.getSession().getId()); this.addGlobalDataToSession(req, data); // TEXTILE needs the following four lines /* * ExilityInterface.Bridge br = new ExilityInterface.Bridge(); * DataCollection dc = new DataCollection(); dc.CopyFrom(data); * br.AddoldVersionGlobalValues(dc, ctx); */ if (AP.cleanserName != null) { ServiceCleanserInterface serviceCleanser = ServiceCleansers.getCleanser(AP.cleanserName); if (serviceCleanser == null) { data.addError(AP.cleanserName + " is not a valid cleanser name."); return false; } if (!serviceCleanser.cleanseAfterService(req, data)) { { data.addMessage("cleanseAfterServiceFailed", AP.cleanserName); return false; } } } return true; }
From source file:memedb.httpd.MemeDBHandler.java
protected Credentials getCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException { Credentials cred = null;// ww w. j av a 2s . co m if (request.getRequestURI().equals("/_auth")) { String username = request.getParameter("username"); String password = request.getParameter("password"); log.debug("login attempt for {}", username); if (!allowAnonymous && "anonymous".equals(username)) { sendNoAuthError(response, "Bad username / password combination"); return null; } if (username != null) { if (password == null) { password = ""; } if (allowAnonymous && allowAnonymousAsSa && "anonymous".equals(username)) { return new SACredentials("anonymous", "", timeout); } cred = memeDB.getAuthentication().authenticate(username, password); if (cred != null) { if (request.getParameter("setcookie") == null || request.getParameter("setcookie").toLowerCase().equals("false")) { Cookie cookie = new Cookie(COOKIE_ID, cred.getToken()); cookie.setMaxAge(timeout); response.addCookie(cookie); } return cred; } else { log.warn("Bad login attempt for {}", username); sendNoAuthError(response, "Bad username / password combination"); return null; } } } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(COOKIE_ID)) { cred = memeDB.getAuthentication().getCredentialsFromToken(cookie.getValue()); if (cred != null) { log.debug("Got credentials from cookie token: {}", cookie.getValue()); return cred; } } } } String param = request.getParameter("token"); if (param != null && !param.equals("")) { cred = memeDB.getAuthentication().getCredentialsFromToken(param); if (cred != null) { log.debug("Authenticated as {} => {} via Req param", cred.getUsername(), cred.getToken()); addCredentialedCookie(response, cred); return cred; } } String headerparam = request.getHeader("MemeDB-Token"); if (headerparam != null && !headerparam.equals("")) { log.info("Attempting authentication with token {}", headerparam); cred = memeDB.getAuthentication().getCredentialsFromToken(headerparam); if (cred != null) { log.info("Got credentials!"); log.debug("Authenticated as {} => {} via HTTP-Header", cred.getUsername(), cred.getToken()); addCredentialedCookie(response, cred); return cred; } } String authHeader = request.getHeader("Authorization"); if (authHeader != null) { String[] authSplit = authHeader.split(" "); if (authSplit.length == 2) { String userpass = new String(Base64.decodeBase64(authSplit[1].getBytes())); if (userpass != null) { String[] ar = userpass.split(":"); if (ar.length > 0) { String u = ar[0]; String p = ""; if (ar.length > 1) { p = ar[1]; } if (!allowAnonymous && "anonymous".equals(u)) { } else { cred = memeDB.getAuthentication().authenticate(u, p); if (cred != null) { log.debug("Authenticated as {} => {} via HTTP-AUTH", cred.getUsername(), cred.getToken()); addCredentialedCookie(response, cred); } return cred; } } } } response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\""); sendNoAuthError(response, "You need a username and password"); return null; } if (allowAnonymous) { if (allowAnonymousAsSa) return new SACredentials("anonymous", "", timeout); return new AnonCredentials("", timeout); } log.warn("Error authenticating"); response.addHeader("WWW-Authenticate", " Basic realm=\"" + realm + "\""); sendNoAuthError(response, "You need a username and password"); return null; }
From source file:com.bosch.cr.examples.jwt.auth.ImAuthenticationServlet.java
@Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { try {//from w w w. ja v a 2s . c om final String body = req.getReader().lines().collect(Collectors.joining()); final JsonObject jsonObject = JsonFactory.newObject(body); final String tenantNameOrId = jsonObject.getValue(TENANT_NAME_OR_ID).map(JsonValue::asString) .orElse(configurationProperties.getPropertyAsString(ConfigurationProperty.IM_DEFAULT_TENANT)); final String userName = jsonObject.getValue(USERNAME).map(JsonValue::asString) .orElseThrow(() -> new JsonMissingFieldException(USERNAME.getPointer())); final String password = jsonObject.getValue(PASSWORD).map(JsonValue::asString) .orElseThrow(() -> new JsonMissingFieldException(PASSWORD.getPointer())); final AuthenticationDto authenticationDto = authenticationHelper.authenticate(tenantNameOrId, userName, password); final AuthorizationDto authorizationDto = authenticationHelper.authorize(authenticationDto); final String authorizationToken = authorizationDto.getAuthorizationToken(); final boolean secure = configurationProperties .getPropertyAsBoolean(ConfigurationProperty.SECURE_COOKIE); final int maxAge = -1; // cookie is deleted when browser is closed final Cookie cookie = CookieUtil.getJwtAuthenticationCookie(authorizationToken, secure, maxAge); resp.addCookie(cookie); resp.setStatus(HttpStatus.SC_NO_CONTENT); } catch (final IOException e) { resp.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } catch (final JsonMissingFieldException e) { resp.setStatus(HttpStatus.SC_BAD_REQUEST); resp.getOutputStream().print(e.getMessage()); } catch (final AuthenticationDeniedException e) { resp.setStatus(HttpStatus.SC_UNAUTHORIZED); resp.getOutputStream().print(e.getMessage()); } }
From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. * Replaces cookie path to local path and renames cookie to avoid collisions. *//*from w w w.java 2 s . co m*/ protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, String header) { List<HttpCookie> cookies = HttpCookie.parse(header); String path = servletRequest.getContextPath(); // path starts with / or is empty string path += servletRequest.getServletPath(); // servlet path starts with / or is empty string for (HttpCookie cookie : cookies) { //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = getCookieNamePrefix() + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); //set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:m.c.m.proxyma.resource.ProxymaServletResponse.java
/** * This private method serilizes the response data into the passed http response. * * @param responseData the data to send//w w w . ja v a 2 s. c om * @param theResponse the response implementation to use to send the data * @return the status code of the operation. */ private int serializeAndSendResponseData(ProxymaResponseDataBean responseData, HttpServletResponse theResponse) { //set the returnCode int exitStatus = responseData.getStatus(); theResponse.setStatus(exitStatus); //set all the headers of the response data into the http servlet response.. log.finer("Sending headers.."); Iterator<String> stringIterarot = responseData.getHeaderNames().iterator(); String headerName = null; ProxymaHttpHeader header = null; Collection<ProxymaHttpHeader> multiHeader = null; while (stringIterarot.hasNext()) { headerName = stringIterarot.next(); if (responseData.isMultipleHeader(headerName)) { //Process multiple values header. multiHeader = responseData.getMultivalueHeader(headerName); Iterator<ProxymaHttpHeader> headers = multiHeader.iterator(); while (headers.hasNext()) { header = headers.next(); theResponse.setHeader(header.getName(), header.getValue()); } } else { //Process Sungle value header header = responseData.getHeader(headerName); theResponse.setHeader(header.getName(), header.getValue()); } } //set the cookies into the http servlet response. log.finer("Sending cookies.."); Iterator<Cookie> cookieIterator = responseData.getCookies().iterator(); while (cookieIterator.hasNext()) { theResponse.addCookie(cookieIterator.next()); } //Serialize the data of the ByteBuffer into the servlet response.. if (responseData.getData() != null) { BufferedOutputStream bos = null; log.finer("Sending data.."); try { bos = new BufferedOutputStream(theResponse.getOutputStream()); ByteBufferReader data = ByteBufferFactory.createNewByteBufferReader(responseData.getData()); byte[] buffer = new byte[WRITE_BUFFER_SIZE]; int count; while ((count = data.readBytes(buffer, WRITE_BUFFER_SIZE)) >= 0) bos.write(buffer, 0, count); } catch (Exception e) { log.severe("Error in writing buffer data into the response!"); e.printStackTrace(); exitStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } finally { try { if (bos != null) { bos.flush(); bos.close(); } } catch (IOException e) { log.severe("Error closing response output buffer!"); e.printStackTrace(); exitStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } } return exitStatus; }
From source file:com.balero.controllers.LoginController.java
/** * Process user credentials//from ww w.java 2 s . c o m * and sets the' magic' cookie * * @param baleroAdmin Magic credentials * @param response HTTP headers * @param request HTTP headers * @param redirectAttributes Pass to message center * @return View */ @RequestMapping(method = RequestMethod.POST) public String login(@CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin, HttpServletResponse response, HttpServletRequest request, RedirectAttributes redirectAttributes) { // Inputs String inputUsername = request.getParameter("inputUsername"); String inputPassword = request.getParameter("inputPassword"); // Debug logger.debug("param user: " + request.getParameter("inputUsername")); logger.debug("param pwd: " + request.getParameter("inputPassword")); logger.debug("cookie: " + baleroAdmin); // Init 'Users' List<Users> users; // Case switch (inputUsername) { // Admin case "admin": users = UsersDAO.administrator(); break; // Users default: users = UsersDAO.user(); } // Catch unregistered user try { if (users.isEmpty()) { throw new Exception("User do not exists!."); } } catch (Exception e) { redirectAttributes.addFlashAttribute("message", e.getMessage()); return "redirect:/"; } for (Users obj : users) { // Remote username = obj.getUsername(); password = obj.getPassword(); // Find register if (username.equals(inputUsername)) { if (password.equals(inputPassword)) { // create cookie and set it in response Cookie cookie = new Cookie("baleroAdmin", inputUsername + ":" + inputPassword); response.addCookie(cookie); logger.debug("Cookie Value: " + baleroAdmin); } else { redirectAttributes.addFlashAttribute("message", "Login failed! Wrong password."); } } } return "redirect:/"; }