001/* 002 * JGrapes Event Driven Framework 003 * Copyright (C) 2017-2022 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Affero General Public License as published by 007 * the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 013 * for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License along 016 * with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jgrapes.http; 020 021import java.beans.ConstructorProperties; 022import java.io.Serializable; 023import java.lang.ref.WeakReference; 024import java.net.HttpCookie; 025import java.text.ParseException; 026import java.time.Duration; 027import java.util.ArrayList; 028import java.util.Arrays; 029import java.util.Collections; 030import java.util.List; 031import java.util.Locale; 032import java.util.Optional; 033import org.jdrupes.httpcodec.protocols.http.HttpField; 034import org.jdrupes.httpcodec.protocols.http.HttpRequest; 035import org.jdrupes.httpcodec.types.Converters; 036import org.jdrupes.httpcodec.types.Converters.SameSiteAttribute; 037import org.jdrupes.httpcodec.types.CookieList; 038import org.jdrupes.httpcodec.types.DefaultMultiValueConverter; 039import org.jdrupes.httpcodec.types.ParameterizedValue; 040import org.jgrapes.core.Associator; 041import org.jgrapes.core.Channel; 042import org.jgrapes.core.Component; 043import org.jgrapes.core.annotation.Handler; 044import org.jgrapes.http.annotation.RequestHandler; 045import org.jgrapes.http.events.ProtocolSwitchAccepted; 046import org.jgrapes.http.events.Request; 047import org.jgrapes.io.IOSubchannel; 048 049/** 050 * A component that attempts to derive information about language preferences 051 * from requests in the specified scope (usually "/") and make them 052 * available as a {@link Selection} object associated with the request 053 * event using `Selection.class` as association identifier. 054 * 055 * The component first checks if the event has an associated {@link Session} 056 * and whether that session has a value with key `Selection.class`. If 057 * such an entry exists, its value is assumed to be a {@link Selection} object 058 * which is (re-)used for all subsequent operations. Else, a new 059 * {@link Selection} object is created (and associated with the session, if 060 * a session exists). 061 * 062 * If the {@link Selection} represents explicitly set values, it is used as 063 * result (i.e. as object associated with the event by `Selection.class`). 064 * 065 * Else, the selector tries to derive the language preferences from the 066 * request. It first checks for a cookie with the specified name 067 * (see {@link #cookieName()}). If a cookie is found, its value is 068 * used to set the preferred locales. If no cookie is found, 069 * the values derived from the `Accept-Language header` are set 070 * as fall-backs. 071 * 072 * Whenever the language preferences 073 * change (see {@link Selection#prefer(Locale)}), a cookie with the 074 * specified name and a path value set to the scope is created and 075 * added to the request's response. This new cookie is then sent with 076 * the response to the browser. 077 * 078 * Note that this scheme does not work in a SPA where browser and 079 * server only communicate over a WebSocket. 080 */ 081public class LanguageSelector extends Component { 082 083 private String path; 084 private static final DefaultMultiValueConverter<List<Locale>, 085 Locale> LOCALE_LIST = new DefaultMultiValueConverter<>( 086 ArrayList<Locale>::new, Converters.LANGUAGE); 087 private String cookieName = LanguageSelector.class.getName(); 088 private long cookieMaxAge = Duration.ofDays(365).toSeconds(); 089 private SameSiteAttribute cookieSameSite = SameSiteAttribute.LAX; 090 091 /** 092 * Creates a new language selector component with its channel set to 093 * itself and the scope set to "/". The handler's priority 094 * is set to 990. 095 */ 096 public LanguageSelector() { 097 this("/"); 098 } 099 100 /** 101 * Creates a new language selector component with its channel set to 102 * itself and the scope set to the given value. The handler's priority 103 * is set to 990. 104 * 105 * @param scope the scope 106 */ 107 public LanguageSelector(String scope) { 108 this(SELF, scope); 109 } 110 111 /** 112 * Creates a new language selector component with its channel set 113 * to the given channel and the scope to "/". The handler's priority 114 * is set to 990. 115 * 116 * @param componentChannel the component channel 117 */ 118 public LanguageSelector(Channel componentChannel) { 119 this(componentChannel, "/"); 120 } 121 122 /** 123 * Creates a new language selector component with its channel set 124 * to the given channel and the scope to the given scope. The 125 * handler's priority is set to 990. 126 * 127 * @param componentChannel the component channel 128 * @param scope the scope 129 */ 130 public LanguageSelector(Channel componentChannel, String scope) { 131 this(componentChannel, scope, 990); 132 } 133 134 /** 135 * Creates a new language selector component with its channel set 136 * to the given channel and the scope to the given scope. The 137 * handler's priority is set to the given value. 138 * 139 * @param componentChannel the component channel 140 * @param scope the scope 141 * @param priority the priority 142 */ 143 @SuppressWarnings("PMD.AvoidLiteralsInIfCondition") 144 public LanguageSelector(Channel componentChannel, String scope, 145 int priority) { 146 super(componentChannel); 147 if ("/".equals(scope) || !scope.endsWith("/")) { 148 path = scope; 149 } else { 150 path = scope.substring(0, scope.length() - 1); 151 } 152 String pattern; 153 if ("/".equals(path)) { 154 pattern = "/**"; 155 } else { 156 pattern = path + "," + path + "/**"; 157 } 158 RequestHandler.Evaluator.add(this, "onRequest", pattern, priority); 159 } 160 161 /** 162 * Sets the name of the cookie used to store the locale. 163 * 164 * @param cookieName the cookie name to use 165 * @return the locale selector for easy chaining 166 */ 167 public LanguageSelector setCookieName(String cookieName) { 168 this.cookieName = cookieName; 169 return this; 170 } 171 172 /** 173 * Returns the cookie name. Defaults to the class name. 174 * 175 * @return the cookie name 176 */ 177 public String cookieName() { 178 return cookieName; 179 } 180 181 /** 182 * Sets the max age of the cookie used to store the preferences. 183 * Defaults to one year. 184 * 185 * @param maxAge the max age 186 * @return the language selector 187 * @see HttpCookie#setMaxAge(long) 188 */ 189 public LanguageSelector setCookieMaxAge(Duration maxAge) { 190 cookieMaxAge = maxAge.toSeconds(); 191 return this; 192 } 193 194 /** 195 * Returns the max age of the cookie used to store the preferences. 196 * 197 * @return the duration 198 */ 199 public Duration cookieMaxAge() { 200 return Duration.ofSeconds(cookieMaxAge); 201 } 202 203 /** 204 * Sets the same site attribute for the locale cookie defaults to 205 * `Lax`. 206 * 207 * @param attribute the attribute 208 * @return the language selector 209 */ 210 public LanguageSelector setSameSiteAttribute(SameSiteAttribute attribute) { 211 cookieSameSite = attribute; 212 return this; 213 } 214 215 /** 216 * Returns the value of the same site attribute. 217 * 218 * @return the same site attribute 219 */ 220 public SameSiteAttribute sameSiteAttribute() { 221 return cookieSameSite; 222 } 223 224 /** 225 * Associates the event with a {@link Selection} object 226 * using `Selection.class` as association identifier. 227 * Does nothing if the request has already been fulfilled. 228 * 229 * @param event the event 230 */ 231 @SuppressWarnings({ "PMD.EmptyCatchBlock" }) 232 @RequestHandler(dynamic = true) 233 public void onRequest(Request.In event) { 234 if (event.fulfilled()) { 235 return; 236 } 237 final Selection selection 238 = (Selection) Session.from(event).computeIfAbsent(Selection.class, 239 newKey -> new Selection(cookieName, path, cookieMaxAge, 240 cookieSameSite)); 241 selection.setCurrentEvent(event); 242 event.setAssociated(Selection.class, selection); 243 if (selection.isExplicitlySet()) { 244 return; 245 } 246 247 // Try to get locale from cookies 248 final HttpRequest request = event.httpRequest(); 249 Optional<String> localeNames = request.findValue( 250 HttpField.COOKIE, Converters.COOKIE_LIST) 251 .flatMap(cookieList -> cookieList.valueForName(cookieName)); 252 if (localeNames.isPresent()) { 253 try { 254 List<Locale> cookieLocales = LOCALE_LIST 255 .fromFieldValue(localeNames.get()); 256 if (!cookieLocales.isEmpty()) { 257 Collections.reverse(cookieLocales); 258 cookieLocales.stream().forEach(selection::prefer); 259 return; 260 } 261 } catch (ParseException e) { 262 // Unusable 263 } 264 } 265 266 // Last resport: Accept-Language header field 267 Optional<List<ParameterizedValue<Locale>>> accepted = request.findValue( 268 HttpField.ACCEPT_LANGUAGE, Converters.LANGUAGE_LIST); 269 if (accepted.isPresent()) { 270 Locale[] locales = accepted.get().stream() 271 .sorted(ParameterizedValue.WEIGHT_COMPARATOR) 272 .map(ParameterizedValue::value).toArray(Locale[]::new); 273 selection.updateFallbacks(locales); 274 } 275 } 276 277 /** 278 * Handles a procotol switch by associating the language selection 279 * with the channel. 280 * 281 * @param event the event 282 * @param channel the channel 283 */ 284 @Handler(priority = 1000) 285 public void onProtocolSwitchAccepted( 286 ProtocolSwitchAccepted event, IOSubchannel channel) { 287 event.requestEvent().associated(Selection.class) 288 .ifPresent( 289 selection -> channel.setAssociated(Selection.class, selection)); 290 } 291 292 /** 293 * Convenience method to retrieve a locale from an associator. 294 * 295 * @param assoc the associator 296 * @return the locale 297 */ 298 public static Locale associatedLocale(Associator assoc) { 299 return assoc.associated(Selection.class) 300 .map(sel -> sel.get()[0]).orElse(Locale.getDefault()); 301 } 302 303 /** 304 * Represents a locale selection. 305 */ 306 @SuppressWarnings({ "serial" }) 307 public static final class Selection implements Serializable { 308 private transient WeakReference<Request.In> currentEvent; 309 private final String cookieName; 310 private final String cookiePath; 311 private final long cookieMaxAge; 312 private final SameSiteAttribute cookieSameSite; 313 private boolean explicitlySet; 314 private Locale[] locales; 315 316 @ConstructorProperties({ "cookieName", "cookiePath", "cookieMaxAge", 317 "cookieSameSite" }) 318 private Selection(String cookieName, String cookiePath, 319 long cookieMaxAge, SameSiteAttribute cookieSameSite) { 320 this.cookieName = cookieName; 321 this.cookiePath = cookiePath; 322 this.cookieMaxAge = cookieMaxAge; 323 this.cookieSameSite = cookieSameSite; 324 this.currentEvent = new WeakReference<>(null); 325 explicitlySet = false; 326 locales = new Locale[] { Locale.getDefault() }; 327 } 328 329 /** 330 * Gets the cookie name. 331 * 332 * @return the cookieName 333 */ 334 public String getCookieName() { 335 return cookieName; 336 } 337 338 /** 339 * Gets the cookie path. 340 * 341 * @return the cookiePath 342 */ 343 public String getCookiePath() { 344 return cookiePath; 345 } 346 347 /** 348 * Gets the cookie max age. 349 * 350 * @return the cookie max age 351 */ 352 public long getCookieMaxAge() { 353 return cookieMaxAge; 354 } 355 356 /** 357 * Gets the cookie same site. 358 * 359 * @return the cookie same site 360 */ 361 public SameSiteAttribute getCookieSameSite() { 362 return cookieSameSite; 363 } 364 365 /** 366 * Checks if is explicitly set. 367 * 368 * @return the explicitlySet 369 */ 370 public boolean isExplicitlySet() { 371 return explicitlySet; 372 } 373 374 /** 375 * 376 * @param locales 377 */ 378 @SuppressWarnings("PMD.UseVarargs") 379 private void updateFallbacks(Locale[] locales) { 380 if (explicitlySet) { 381 return; 382 } 383 this.locales = Arrays.copyOf(locales, locales.length); 384 } 385 386 /** 387 * @param currentEvent the currentEvent to set 388 */ 389 private Selection setCurrentEvent(Request.In currentEvent) { 390 this.currentEvent = new WeakReference<>(currentEvent); 391 return this; 392 } 393 394 /** 395 * Return the current locale. 396 * 397 * @return the value; 398 */ 399 public Locale[] get() { 400 return Arrays.copyOf(locales, locales.length); 401 } 402 403 /** 404 * Updates the current locale. 405 * 406 * @param locale the locale 407 * @return the selection for easy chaining 408 */ 409 public Selection prefer(Locale locale) { 410 explicitlySet = true; 411 List<Locale> list = new ArrayList<>(Arrays.asList(locales)); 412 list.remove(locale); 413 list.add(0, locale); 414 this.locales = list.toArray(new Locale[0]); 415 Request.In req = currentEvent.get(); 416 if (req != null) { 417 req.httpRequest().response().ifPresent(resp -> { 418 resp.computeIfAbsent(HttpField.SET_COOKIE, 419 () -> new CookieList(cookieSameSite)) 420 .value().add(getCookie()); 421 }); 422 } 423 return this; 424 } 425 426 /** 427 * Returns a cookie that reflects the current selection. 428 * 429 * @return the cookie 430 */ 431 public HttpCookie getCookie() { 432 HttpCookie localesCookie = new HttpCookie(cookieName, 433 LOCALE_LIST.asFieldValue(Arrays.asList(locales))); 434 localesCookie.setPath(cookiePath); 435 localesCookie.setMaxAge(cookieMaxAge); 436 return localesCookie; 437 } 438 439 /* 440 * (non-Javadoc) 441 * 442 * @see java.lang.Object#toString() 443 */ 444 @Override 445 public String toString() { 446 StringBuilder builder = new StringBuilder(50); 447 builder.append("Selection ["); 448 if (locales != null) { 449 builder.append("locales=").append(Arrays.toString(locales)) 450 .append(", "); 451 } 452 builder.append("explicitlySet=").append(explicitlySet).append(']'); 453 return builder.toString(); 454 } 455 456 } 457}