1 // 2 // ======================================================================== 3 // Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd. 4 // ------------------------------------------------------------------------ 5 // All rights reserved. This program and the accompanying materials 6 // are made available under the terms of the Eclipse Public License v1.0 7 // and Apache License v2.0 which accompanies this distribution. 8 // 9 // The Eclipse Public License is available at 10 // http://www.eclipse.org/legal/epl-v10.html 11 // 12 // The Apache License v2.0 is available at 13 // http://www.opensource.org/licenses/apache2.0.php 14 // 15 // You may elect to redistribute this code under either of these licenses. 16 // ======================================================================== 17 // 18 19 package org.eclipse.jetty.rewrite.handler; 20 21 import java.io.IOException; 22 23 import javax.servlet.http.Cookie; 24 import javax.servlet.http.HttpServletRequest; 25 import javax.servlet.http.HttpServletResponse; 26 27 28 /** 29 * Sets the cookie in the response whenever the rule finds a match. 30 * 31 * @see Cookie 32 */ 33 public class CookiePatternRule extends PatternRule 34 { 35 private String _name; 36 private String _value; 37 38 /* ------------------------------------------------------------ */ 39 public CookiePatternRule() 40 { 41 _handling = false; 42 _terminating = false; 43 } 44 45 /* ------------------------------------------------------------ */ 46 /** 47 * Assigns the cookie name. 48 * 49 * @param name a <code>String</code> specifying the name of the cookie. 50 */ 51 public void setName(String name) 52 { 53 _name = name; 54 } 55 56 /* ------------------------------------------------------------ */ 57 /** 58 * Assigns the cookie value. 59 * 60 * @param value a <code>String</code> specifying the value of the cookie 61 * @see Cookie#setValue(String) 62 */ 63 public void setValue(String value) 64 { 65 _value = value; 66 } 67 68 /* ------------------------------------------------------------ */ 69 /* 70 * (non-Javadoc) 71 * @see org.eclipse.jetty.server.server.handler.rules.RuleBase#apply(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 72 */ 73 @Override 74 public String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException 75 { 76 // Check that cookie is not already set 77 Cookie[] cookies = request.getCookies(); 78 if (cookies!=null) 79 { 80 for (Cookie cookie:cookies) 81 { 82 if (_name.equals(cookie.getName()) && _value.equals(cookie.getValue())) 83 return target; 84 } 85 } 86 87 // set it 88 response.addCookie(new Cookie(_name, _value)); 89 return target; 90 } 91 92 /* ------------------------------------------------------------ */ 93 /** 94 * Returns the cookie contents. 95 */ 96 @Override 97 public String toString() 98 { 99 return super.toString()+"["+_name+","+_value + "]"; 100 } 101 }