List of usage examples for javax.servlet.http Cookie setDomain
public void setDomain(String domain)
From source file:com.google.gsa.valve.modules.ldap.LDAPSSO.java
/** * Sets the LDAP authentication cookie/*from w w w. j a v a 2 s . c o m*/ * * @return the LDAP authentication cookie */ public Cookie settingCookie() { // Instantiate a new cookie Cookie extAuthCookie = new Cookie(SSO_COOKIE_NAME, "true"); String authCookieDomain = null; String authCookiePath = null; // Cache cookie properties authCookieDomain = valveConf.getAuthCookieDomain(); authCookiePath = valveConf.getAuthCookiePath(); // Set extra cookie parameters extAuthCookie.setDomain(authCookieDomain); extAuthCookie.setPath(authCookiePath); extAuthCookie.setMaxAge(authMaxAge); // Log info logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure()); return extAuthCookie; }
From source file:de.hska.ld.etherpad.controller.DocumentEtherpadController.java
@Secured(Core.ROLE_USER) @RequestMapping(method = RequestMethod.GET, value = "/edit/{documentId}") //@Transactional(readOnly = true) public Callable editDocumentContent(HttpServletResponse response, @PathVariable Long documentId) { return () -> { Document document = documentService.findById(documentId); boolean readOnly = false; // check if the User is allowed to access the current Document if (document != null) { documentService.checkPermission(document, Access.Permission.READ); try { documentService.checkPermission(document, Access.Permission.WRITE); } catch (Exception e) { readOnly = true;/*from w w w . ja va 2s. c om*/ } } else { throw new NotFoundException("id"); } // for the given User check whether there is an AuthorId registered in Etherpad UserEtherpadInfo firstUserEtherPadInfoCheck = userEtherpadInfoService .getUserEtherpadInfoForCurrentUser(); String authorId = null; if (firstUserEtherPadInfoCheck != null) { authorId = firstUserEtherPadInfoCheck.getAuthorId(); } // look up if there is an existing AuthorId associated with the current user if (authorId == null) { // if there is no AuthorId present register an AuthorId for the current User authorId = etherpadClient.createAuthor(Core.currentUser().getFullName()); userEtherpadInfoService.storeAuthorIdForCurrentUser(authorId); } // is the GroupPad available for the Document : String groupPadId = documentEtherpadInfoService.getGroupPadIdForDocument(document); if (groupPadId == null && !"".equals(groupPadId)) { // otherwise create a GroupPad String groupId = etherpadClient.createGroup(); Attachment mainContent = document.getAttachmentList().get(0); byte[] mainSource = mainContent.getSource(); try { //String urlEncodedDocumentTitle = URLEncoder.encode(URLEncoder.encode(document.getTitle(), "UTF-8"), "UTF-8"); String groupPadTitle = UUID.randomUUID().toString();//StringUtils.left(urlEncodedDocumentTitle, 50); while (groupPadTitle.endsWith("%")) { groupPadTitle = groupPadTitle.substring(0, groupPadTitle.length() - 1); } if (mainSource != null) { String discussionText = new String(mainSource, "UTF-8"); if (!"".equals(discussionText)) { groupPadId = etherpadClient.createGroupPad(groupId, groupPadTitle); //groupPadId = etherpadClient.createGroupPad(groupId, document.getTitle(), discussionText); etherpadClient.setGroupPadContent(groupPadId, discussionText); //setHTML(padID, html) } else { groupPadId = etherpadClient.createGroupPad(groupId, groupPadTitle); } } else { groupPadId = etherpadClient.createGroupPad(groupId, groupPadTitle); } } catch (Exception e) { System.out.println(e.getMessage()); } // groupPad is available associate GroupPadId for the Document documentEtherpadInfoService.storeGroupPadIdForDocument(groupPadId, document); } String readOnlyId = null; if (readOnly) { readOnlyId = documentEtherpadInfoService.getReadOnlyIdForDocument(document); if (readOnlyId == null) { readOnlyId = etherpadClient.getReadOnlyID(groupPadId); if (readOnlyId == null) { throw new ValidationException("Read only id is null"); // TODO change exception type } else { documentEtherpadInfoService.storeReadOnlyIdForDocument(readOnlyId, document); } } } // create a session between Author and GroupPad String groupId = groupPadId.split("\\$")[0]; long currentTime = System.currentTimeMillis() / 1000L; // current time long validUntil = currentTime + 86400L; String sessionId = null; UserEtherpadInfo userEtherpadInfo = userEtherpadInfoService.getUserEtherpadInfoForCurrentUser(); sessionId = userEtherpadInfo.getSessionId(); Long currentValidUntil = userEtherpadInfo.getValidUntil(); // retrieve sessionID from db if available boolean newSessionRequired = false; if (sessionId == null) { newSessionRequired = true; } else { boolean isStillValid = false; // check if valid until is still valid for more than 3h // check if sessionID is still valid (valid for more than 3h) /*boolean sameGroupId = userEtherpadInfo.getGroupId().equals(groupId); if (sameGroupId && userEtherpadInfo.getGroupId().equals(groupId) && currentValidUntil - currentTime >= 10800) { // if sessionID is still valid longer than 3h // then send the sessionID to the client isStillValid = true; } else if (currentValidUntil - currentTime < 10800) { newSessionRequired = true; } else if (isStillValid) {*/ // check if the session still exists on the etherpad server (GET) isStillValid = etherpadClient.checkIfSessionStillValid(currentTime, sessionId, groupId); if (!isStillValid) { newSessionRequired = true; } //} } if (newSessionRequired) { sessionId = etherpadClient.createSession(groupId, authorId, validUntil); // store the sessionID into UserEtherpadInfo object // store the validUntil value also User currentUser = Core.currentUser(); User dbUser = userService.findById(currentUser.getId()); userEtherpadInfoService.storeSessionForUser(sessionId, groupId, validUntil, userEtherpadInfo); } // we need return types, cookie with sessionId and the URL of Etherpads Pad javax.servlet.http.Cookie myCookie = new javax.servlet.http.Cookie("sessionID", sessionId); myCookie.setPath("/"); if (!"localhost".equals(env.getProperty("module.core.oidc.server.endpoint.main.domain"))) { myCookie.setDomain(env.getProperty("module.core.oidc.server.endpoint.main.domain")); } response.addCookie(myCookie); // return Etherpad URL path String padURL = null; if (readOnly) { padURL = etherpadEndpointExternal + "/p/" + readOnlyId; } else { padURL = etherpadEndpointExternal + "/p/" + groupPadId; } return new ResponseEntity<>(padURL, HttpStatus.CREATED); }; }
From source file:org.jboss.web.loadbalancer.Loadbalancer.java
protected HttpClient prepareServerRequest(HttpServletRequest request, HttpServletResponse response, HttpMethod method) {//from w ww . j a v a 2 s. c om // clear state HttpClient client = new HttpClient(connectionManager); client.setStrictMode(false); client.setTimeout(connectionTimeout); method.setFollowRedirects(false); method.setDoAuthentication(false); client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); Enumeration reqHeaders = request.getHeaderNames(); while (reqHeaders.hasMoreElements()) { String headerName = (String) reqHeaders.nextElement(); String headerValue = request.getHeader(headerName); if (!ignorableHeader.contains(headerName.toLowerCase())) { method.setRequestHeader(headerName, headerValue); } } //Cookies Cookie[] cookies = request.getCookies(); HttpState state = client.getState(); for (int i = 0; cookies != null && i < cookies.length; ++i) { Cookie cookie = cookies[i]; org.apache.commons.httpclient.Cookie reqCookie = new org.apache.commons.httpclient.Cookie(); reqCookie.setName(cookie.getName()); reqCookie.setValue(cookie.getValue()); if (cookie.getPath() != null) { reqCookie.setPath(cookie.getPath()); } else { reqCookie.setPath("/"); } reqCookie.setSecure(cookie.getSecure()); reqCookie.setDomain(method.getHostConfiguration().getHost()); state.addCookie(reqCookie); } return client; }
From source file:com.tremolosecurity.proxy.filter.PostProcess.java
protected void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpResponse response, String finalURL, HttpFilterChain curChain, HttpRequestBase httpRequest) throws IOException, Exception { boolean isText; HttpEntity entity = null;//from w ww .j ava 2s . c o m try { entity = response.getEntity(); /*if (entity != null) { entity = new BufferedHttpEntity(entity); }*/ } catch (Throwable t) { throw new Exception(t); } InputStream ins = null; boolean entExists = false; if (entity == null) { resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); ins = new StringBufferInputStream(""); } else { try { ins = entity.getContent(); resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); entExists = true; } catch (IllegalStateException e) { //do nothing } } if (entExists) { org.apache.http.Header hdr = response.getFirstHeader("Content-Type"); org.apache.http.Header encoding = response.getFirstHeader("Content-Encoding"); /*if (hdr == null) { isText = false; } else { isText = response.getFirstHeader("Content-Type").getValue().startsWith("text"); if (encoding != null ) { isText = (! encoding.getValue().startsWith("gzip")) && (! encoding.getValue().startsWith("deflate")); } if (isText) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); resp.setLocale(response.getLocale()); } }*/ isText = false; try { resp.setCharacterEncoding(null); } catch (Throwable t) { //we're not doing anything } StringBuffer stmp = new StringBuffer(); if (response.getFirstHeader("Content-Type") != null) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); } if (response.getLocale() != null) { resp.setLocale(response.getLocale()); } org.apache.http.Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { org.apache.http.Header header = headers[i]; if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Length")) { if (!header.getValue().equals("0")) { continue; } } else if (header.getName().equals("Transfer-Encoding")) { continue; } else if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) { //System.out.println(header.getValue()); String cookieVal = header.getValue(); /*if (cookieVal.endsWith("HttpOnly")) { cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly")); } //System.out.println(cookieVal);*/ List<HttpCookie> cookies = HttpCookie.parse(cookieVal); Iterator<HttpCookie> it = cookies.iterator(); while (it.hasNext()) { HttpCookie cookie = it.next(); String cookieFinalName = cookie.getName(); if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) { stmp.setLength(0); stmp.append("JSESSIONID").append('-') .append(holder.getApp().getName().replaceAll(" ", "|")); cookieFinalName = stmp.toString(); } Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue()); respcookie.setComment(cookie.getComment()); if (cookie.getDomain() != null) { respcookie.setDomain(cookie.getDomain()); } if (cookie.hasExpired()) { respcookie.setMaxAge(0); } else { respcookie.setMaxAge((int) cookie.getMaxAge()); } respcookie.setPath(cookie.getPath()); respcookie.setSecure(cookie.getSecure()); respcookie.setVersion(cookie.getVersion()); resp.addCookie(respcookie); } } else if (header.getName().equals("Location")) { if (holder.isOverrideHost()) { fixRedirect(req, resp, finalURL, header); } else { resp.addHeader("Location", header.getValue()); } } else { resp.addHeader(header.getName(), header.getValue()); } } curChain.setIns(ins); curChain.setText(isText); curChain.setEntity(entity); curChain.setHttpRequestBase(httpRequest); //procData(req, resp, holder, isText, entity, ins); } else { isText = false; } }
From source file:org.nunux.poc.portal.ProxyServlet.java
/** * Retrieves all of the cookies from the servlet request and sets them on * the proxy request/*from w ww. j a v a 2 s .c o m*/ * * @param httpServletRequest The request object representing the client's * request to the servlet engine * @param httpMethodProxyRequest The request that we are about to send to * the proxy host */ @SuppressWarnings("unchecked") private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) { // Get an array of all of all the cookies sent by the client Cookie[] cookies = httpServletRequest.getCookies(); if (cookies == null) { return; } if (httpServletRequest.getSession().getAttribute("jsessionid" + this.getProxyHostAndPort()) != null) { String jsessionid = (String) httpServletRequest.getSession() .getAttribute("jsessionid" + this.getProxyHostAndPort()); httpMethodProxyRequest.setRequestHeader("Cookie", "JSESSIONID=" + jsessionid); debug("redirecting: setting jsessionid: " + jsessionid); } for (Cookie cookie : cookies) { if (!cookie.getName().equalsIgnoreCase("jsessionid")) { cookie.setDomain(stringProxyHost); cookie.setPath(httpServletRequest.getServletPath()); httpMethodProxyRequest.setRequestHeader("Cookie", cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath()); } } }
From source file:org.apache.jetspeed.modules.actions.JLoginUser.java
public void doPerform(RunData rundata) throws Exception { JetspeedRunData data = (JetspeedRunData) rundata; String username = data.getParameters().getString("username", ""); String password = data.getParameters().getString("password", ""); boolean newUserApproval = JetspeedResources.getBoolean("newuser.approval.enable", false); String secretkey = (String) data.getParameters().getString("secretkey", null); if (secretkey != null) { // its the first logon - we are verifying the secretkey // handle the buttons on the ConfirmRegistration page String button1 = data.getParameters().getString("submit1", null); if (button1 != null && button1.equalsIgnoreCase("Cancel")) { data.setScreenTemplate(TurbineTemplate.getDefaultScreen()); return; }/*from w w w. ja v a2 s.c om*/ // check to make sure the user entered the right confirmation key // if not, then send them to the ConfirmRegistration screen JetspeedUser user = JetspeedSecurity.getUser(username); if (user == null) { logger.warn("JLogin User: Unexpected condition : user is NULL"); return; } String confirm_value = user.getConfirmed(); if (!secretkey.equals(confirm_value) && !confirm_value.equals(JetspeedResources.CONFIRM_VALUE)) { if (newUserApproval) { data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID")); data.setScreenTemplate("NewUserAwaitingAcceptance"); return; } else { if (user.getConfirmed().equals(JetspeedResources.CONFIRM_VALUE_REJECTED)) { data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID")); data.setScreenTemplate("NewUserRejected"); return; } else { data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID")); data.setScreenTemplate("ConfirmRegistration"); return; } } } user.setConfirmed(JetspeedResources.CONFIRM_VALUE); data.setMessage(Localization.getString(rundata, "JLOGINUSER_WELCOME")); JetspeedSecurity.saveUser(user); } JetspeedUser user = null; try { user = JetspeedSecurity.login(username, password); JetspeedSecurity.saveUser(user); } catch (LoginException e) { data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_LOGIN)); String message = e.getMessage() != null ? e.getMessage() : e.toString(); data.setMessage(message); data.setUser(JetspeedSecurity.getAnonymousUser()); data.getUser().setHasLoggedIn(new Boolean(false)); if (e instanceof FailedLoginException) { if (!disableCheck(data)) { logger.info("JLoginUser: Credential Failure on login for user: " + username); data.setMessage(Localization.getString(rundata, "PASSWORDFORM_FAILED_MSG")); } } else if (e instanceof AccountExpiredException) { logger.info("JLoginUser: Account Expired for user " + username); } else if (e instanceof CredentialExpiredException) { logger.info("JLoginUser: Credentials expired for user: " + username); data.setScreenTemplate( JetspeedResources.getString(JetspeedResources.CHANGE_PASSWORD_TEMPLATE, "ChangePassword")); data.setMessage(Localization.getString(rundata, "PASSWORDFORM_EXPIRED_MSG")); data.getParameters().setString("username", username); } return; } catch (Throwable other) { data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_ERROR)); String message = other.getMessage() != null ? other.getMessage() : other.toString(); data.setMessage(message); data.setStackTrace(org.apache.turbine.util.StringUtils.stackTrace(other), other); JetspeedUser juser = new FakeJetspeedUser(JetspeedSecurity.getAnonymousUserName(), false); data.setUser(juser); return; } if ("T".equals(user.getDisabled())) { data.setMessage(Localization.getString(rundata, "JLOGINUSER_ACCOUNT_DISABLED")); data.setScreenTemplate(JetspeedResources.getString("logon.disabled.form")); data.getUser().setHasLoggedIn(new Boolean(false)); return; } // check for being confirmed before allowing someone to finish logging in if (data.getUser().hasLoggedIn()) { if (JetspeedSecurity.isDisableAccountCheckEnabled()) { // dst: this needs some refactoring. I don't believe this api is necessary JetspeedSecurity.resetDisableAccountCheck(data.getParameters().getString("username", "")); } String confirmed = data.getUser().getConfirmed(); if (confirmed == null || !confirmed.equals(JetspeedResources.CONFIRM_VALUE)) { if (confirmed != null && confirmed.equals(JetspeedResources.CONFIRM_VALUE_REJECTED)) { data.setMessage(Localization.getString(rundata, "JLOGINUSER_KEYNOTVALID")); data.setScreenTemplate("NewUserRejected"); data.getUser().setHasLoggedIn(new Boolean(false)); return; } else { data.setMessage(Localization.getString(rundata, "JLOGINUSER_CONFIRMFIRST")); data.setScreenTemplate("ConfirmRegistration"); data.getUser().setHasLoggedIn(new Boolean(false)); return; } } // user has logged in successfully at this point boolean automaticLogonEnabled = JetspeedResources.getBoolean("automatic.logon.enable", false); if (automaticLogonEnabled) { //Does the user want to use this facility? boolean userRequestsRememberMe = data.getParameters().getBoolean("rememberme", false); if (userRequestsRememberMe) { //save cookies on the users machine. int maxage = JetspeedResources.getInt("automatic.logon.cookie.maxage", -1); String comment = JetspeedResources.getString("automatic.logon.cookie.comment", ""); String domain = JetspeedResources.getString("automatic.logon.cookie.domain"); String path = JetspeedResources.getString("automatic.logon.cookie.path", "/"); if (domain == null) { String server = data.getServerName(); domain = "." + server; } String loginCookieValue = null; if (JetspeedResources.getString("automatic.logon.cookie.generation", "everylogon") .equals("everylogon")) { loginCookieValue = "" + Math.random(); data.getUser().setPerm("logincookie", loginCookieValue); JetspeedSecurity.saveUser(data.getJetspeedUser()); } else { loginCookieValue = (String) data.getUser().getPerm("logincookie"); if (loginCookieValue == null || loginCookieValue.length() == 0) { loginCookieValue = "" + Math.random(); data.getUser().setPerm("logincookie", loginCookieValue); JetspeedSecurity.saveUser(data.getJetspeedUser()); } } Cookie userName = new Cookie("username", data.getUser().getUserName()); Cookie loginCookie = new Cookie("logincookie", loginCookieValue); userName.setMaxAge(maxage); userName.setComment(comment); userName.setDomain(domain); userName.setPath(path); loginCookie.setMaxAge(maxage); loginCookie.setComment(comment); loginCookie.setDomain(domain); loginCookie.setPath(path); data.getResponse().addCookie(userName); data.getResponse().addCookie(loginCookie); } } } else { disableCheck(data); } }
From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java
/** * Setup a cookie: expiration date, path, domain + send it to the response. * //from w w w .j av a 2 s .com * @param cookie The cookie to setup. * @param sessionCookie Whether the cookie is only for this session, or for a longer period. * @param cookieDomain The domain for which the cookie is set. * @param response The servlet response. */ public void setupCookie(Cookie cookie, boolean sessionCookie, String cookieDomain, HttpServletResponse response) { if (!sessionCookie) { setMaxAge(cookie); } cookie.setPath(this.cookiePath); if (cookieDomain != null) { cookie.setDomain(cookieDomain); } addCookie(response, cookie); }
From source file:org.apache.coyote.tomcat5.CoyoteAdapter.java
/** * Parse cookies./*from w w w .j a va 2s .c o m*/ */ protected void parseCookies(Request req, CoyoteRequest request) { Cookies serverCookies = req.getCookies(); int count = serverCookies.getCookieCount(); if (count <= 0) return; Cookie[] cookies = new Cookie[count]; int idx = 0; for (int i = 0; i < count; i++) { ServerCookie scookie = serverCookies.getCookie(i); if (scookie.getName().equals(Globals.SESSION_COOKIE_NAME)) { // Override anything requested in the URL if (!request.isRequestedSessionIdFromCookie()) { // Accept only the first session id cookie request.setRequestedSessionId(scookie.getValue().toString()); request.setRequestedSessionCookie(true); request.setRequestedSessionURL(false); if (log.isDebugEnabled()) log.debug(" Requested cookie session id is " + ((HttpServletRequest) request.getRequest()).getRequestedSessionId()); } } try { Cookie cookie = new Cookie(scookie.getName().toString(), scookie.getValue().toString()); cookie.setPath(scookie.getPath().toString()); cookie.setVersion(scookie.getVersion()); String domain = scookie.getDomain().toString(); if (domain != null) { cookie.setDomain(scookie.getDomain().toString()); } cookies[idx++] = cookie; } catch (Exception ex) { log.error("Bad Cookie Name: " + scookie.getName() + " /Value: " + scookie.getValue(), ex); } } if (idx < count) { Cookie[] ncookies = new Cookie[idx]; System.arraycopy(cookies, 0, ncookies, 0, idx); cookies = ncookies; } request.setCookies(cookies); }
From source file:com.jolira.testing.CachingRESTProxy.java
private Cookie parseCookie(final String value) { final StringTokenizer izer = new StringTokenizer(value, ";"); final String _value = izer.nextToken(); final int pos = _value.indexOf('='); final String name = _value.substring(0, pos); final String val = _value.substring(pos + 1); final Cookie cookie = new Cookie(name, val); while (izer.hasMoreTokens()) { final String token = izer.nextToken(); final int _pos = token.indexOf('='); final String directive = _pos == -1 ? token : token.substring(0, _pos); final String _val = _pos == -1 ? null : token.substring(_pos + 1); if ("Domain".equalsIgnoreCase(directive)) { cookie.setDomain(_val); } else if ("Secure".equalsIgnoreCase(directive)) { cookie.setSecure(true);//from w w w. ja v a 2s .com } else if ("Path".equalsIgnoreCase(directive)) { cookie.setPath(_val); } } return cookie; }