001/* 002 * JGrapes Event Driven Framework 003 * Copyright (C) 2018 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.io.IOException; 022import java.io.InputStream; 023import java.io.UnsupportedEncodingException; 024import java.net.JarURLConnection; 025import java.net.URI; 026import java.net.URISyntaxException; 027import java.net.URL; 028import java.net.URLConnection; 029import java.nio.file.FileSystemNotFoundException; 030import java.nio.file.Files; 031import java.nio.file.Path; 032import java.nio.file.Paths; 033import java.text.ParseException; 034import java.time.Instant; 035import java.time.temporal.ChronoField; 036import java.util.Optional; 037import java.util.function.Function; 038import java.util.jar.JarEntry; 039import java.util.regex.Pattern; 040import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus; 041import org.jdrupes.httpcodec.protocols.http.HttpField; 042import org.jdrupes.httpcodec.protocols.http.HttpRequest; 043import org.jdrupes.httpcodec.protocols.http.HttpResponse; 044import org.jdrupes.httpcodec.types.CacheControlDirectives; 045import org.jdrupes.httpcodec.types.Converters; 046import org.jdrupes.httpcodec.types.Directive; 047import org.jdrupes.httpcodec.types.MediaType; 048import org.jgrapes.core.Event; 049import org.jgrapes.http.events.Request; 050import org.jgrapes.http.events.Response; 051import org.jgrapes.io.IOSubchannel; 052import org.jgrapes.io.events.Output; 053import org.jgrapes.io.util.InputStreamPipeline; 054 055/** 056 * Provides methods that support the creation of a {@link Response} events. 057 */ 058@SuppressWarnings({ "PMD.AbstractClassWithoutAbstractMethod" }) 059public abstract class ResponseCreationSupport { 060 061 /** A default implementation for the max-age calculator. */ 062 @SuppressWarnings("PMD.LongVariable") 063 public static final MaxAgeCalculator DEFAULT_MAX_AGE_CALCULATOR 064 = new DefaultMaxAgeCalculator(); 065 066 /** 067 * Send a response to the given request with the given status code 068 * and reason phrase, including a `text/plain` body with the status 069 * code and reason phrase. 070 * 071 * @param request the request 072 * @param channel for responding; events will be sent using 073 * {@link IOSubchannel#respond(org.jgrapes.core.Event)} 074 * @param statusCode the status code to send 075 * @param reasonPhrase the reason phrase to send 076 */ 077 @SuppressWarnings("PMD.EmptyCatchBlock") 078 public static void sendResponse(HttpRequest request, 079 IOSubchannel channel, int statusCode, String reasonPhrase) { 080 HttpResponse response = request.response().get(); 081 response.setStatusCode(statusCode).setReasonPhrase(reasonPhrase) 082 .setHasPayload(true).setField( 083 HttpField.CONTENT_TYPE, 084 MediaType.builder().setType("text", "plain") 085 .setParameter("charset", "utf-8").build()); 086 // Act like a sub-component, i.e. generate events that are 087 // handled by this HTTP server as if sent from a sub-component. 088 channel.respond(new Response(response)); 089 try { 090 channel.respond(Output.from((statusCode + " " + reasonPhrase) 091 .getBytes("utf-8"), true)); 092 } catch (UnsupportedEncodingException e) { 093 // Supported by definition 094 } 095 } 096 097 /** 098 * Shorthand for invoking 099 * {@link #sendResponse(HttpRequest, IOSubchannel, int, String)} 100 * with a predefined HTTP status. 101 * 102 * @param request the request 103 * @param channel the channel 104 * @param status the status 105 */ 106 public static void sendResponse(HttpRequest request, 107 IOSubchannel channel, HttpStatus status) { 108 sendResponse(request, channel, status.statusCode(), 109 status.reasonPhrase()); 110 } 111 112 /** 113 * Creates and sends a response with static content. The content 114 * is looked up by invoking the resolver with the path from the request. 115 * 116 * The response includes a max-age header with a default value of 117 * 600. The value may be modified by specifying validity infos. 118 * 119 * @param request the request 120 * @param channel the channel 121 * @param resolver the resolver 122 * @param maxAgeCalculator the max age calculator, if `null` 123 * the default calculator is used. 124 * @return `true` if a response was sent 125 */ 126 @SuppressWarnings({ "PMD.NcssCount", "PMD.UseStringBufferForStringAppends", 127 "PMD.ExceptionAsFlowControl" }) 128 public static boolean sendStaticContent( 129 HttpRequest request, IOSubchannel channel, 130 Function<String, URL> resolver, MaxAgeCalculator maxAgeCalculator) { 131 String path = request.requestUri().getPath(); 132 URL resourceUrl = resolver.apply(path); 133 ResourceInfo info; 134 URLConnection resConn; 135 @SuppressWarnings("PMD.CloseResource") 136 InputStream resIn; 137 try { 138 if (resourceUrl == null) { 139 throw new IOException(); 140 } 141 info = resourceInfo(resourceUrl); 142 if (Boolean.TRUE.equals(info.isDirectory())) { 143 throw new IOException(); 144 } 145 resConn = resourceUrl.openConnection(); 146 resIn = resConn.getInputStream(); 147 } catch (IOException e1) { 148 try { 149 if (!path.endsWith("/")) { 150 path += "/"; 151 } 152 path += "index.html"; 153 resourceUrl = resolver.apply(path); 154 if (resourceUrl == null) { 155 return false; 156 } 157 info = resourceInfo(resourceUrl); 158 resConn = resourceUrl.openConnection(); 159 resIn = resConn.getInputStream(); 160 } catch (IOException e2) { 161 return false; 162 } 163 } 164 HttpResponse response = request.response().get(); 165 response.setField(HttpField.LAST_MODIFIED, 166 Optional.ofNullable(info.getLastModifiedAt()) 167 .orElseGet(Instant::now)); 168 169 // Get content type and derive max age 170 MediaType mediaType = HttpResponse.contentType(uriFromUrl(resourceUrl)); 171 setMaxAge(response, 172 (maxAgeCalculator == null ? DEFAULT_MAX_AGE_CALCULATOR 173 : maxAgeCalculator).maxAge(request, mediaType)); 174 175 // Check if sending is really required. 176 Optional<Instant> modifiedSince = request 177 .findValue(HttpField.IF_MODIFIED_SINCE, Converters.DATE_TIME); 178 if (modifiedSince.isPresent() && info.getLastModifiedAt() != null 179 && !info.getLastModifiedAt().isAfter(modifiedSince.get())) { 180 response.setStatus(HttpStatus.NOT_MODIFIED); 181 channel.respond(new Response(response)); 182 } else { 183 response.setContentType(mediaType); 184 response.setStatus(HttpStatus.OK); 185 channel.respond(new Response(response)); 186 // Start sending content (Output events as resonses) 187 new InputStreamPipeline(resIn, channel).suppressClosed().run(); 188 } 189 return true; 190 } 191 192 /** 193 * Shorthand for invoking 194 * {@link #sendStaticContent(HttpRequest, IOSubchannel, Function, MaxAgeCalculator)} 195 * with the {@link HttpRequest} from the event. Also sets the result 196 * of the event to `true` and invokes {@link Event#stop()} 197 * if a response was sent. 198 * 199 * @param event the event 200 * @param channel the channel 201 * @param resolver the resolver 202 * @param maxAgeCalculator the max age calculator, if `null` 203 * the default calculator is used. 204 * @return `true` if a response was sent 205 * @throws ParseException the parse exception 206 */ 207 public static boolean sendStaticContent( 208 Request.In event, IOSubchannel channel, 209 Function<String, URL> resolver, MaxAgeCalculator maxAgeCalculator) { 210 if (sendStaticContent( 211 event.httpRequest(), channel, resolver, maxAgeCalculator)) { 212 event.setResult(true); 213 event.stop(); 214 return true; 215 } 216 return false; 217 } 218 219 /** 220 * Combines the known information about a resource. 221 */ 222 @SuppressWarnings("PMD.DataClass") 223 public static class ResourceInfo { 224 public Boolean isDirectory; 225 public Instant lastModifiedAt; 226 227 /** 228 * @param isDirectory 229 * @param lastModifiedAt 230 */ 231 public ResourceInfo(Boolean isDirectory, Instant lastModifiedAt) { 232 this.isDirectory = isDirectory; 233 this.lastModifiedAt = lastModifiedAt; 234 } 235 236 /** 237 * @return the isDirectory 238 */ 239 public Boolean isDirectory() { 240 return isDirectory; 241 } 242 243 /** 244 * @return the lastModifiedAt 245 */ 246 public Instant getLastModifiedAt() { 247 return lastModifiedAt; 248 } 249 } 250 251 /** 252 * Attempts to lookup the additional resource information for the 253 * given URL. 254 * 255 * If a {@link URL} references a file, it is easy to find out if 256 * the resource referenced is a directory and to get its last 257 * modification time. Getting the same information 258 * for a {@link URL} that references resources in a jar is a bit 259 * more difficult. This method handles both cases. 260 * 261 * @param resource the resource URL 262 * @return the resource info 263 */ 264 @SuppressWarnings({ "PMD.EmptyCatchBlock", 265 "PMD.AvoidLiteralsInIfCondition" }) 266 public static ResourceInfo resourceInfo(URL resource) { 267 try { 268 Path path = Paths.get(resource.toURI()); 269 return new ResourceInfo(Files.isDirectory(path), 270 Files.getLastModifiedTime(path).toInstant() 271 .with(ChronoField.NANO_OF_SECOND, 0)); 272 } catch (FileSystemNotFoundException | IOException 273 | URISyntaxException e) { 274 // Fall through 275 } 276 if ("jar".equals(resource.getProtocol())) { 277 try { 278 JarURLConnection conn 279 = (JarURLConnection) resource.openConnection(); 280 JarEntry entry = conn.getJarEntry(); 281 return new ResourceInfo(entry.isDirectory(), 282 entry.getLastModifiedTime().toInstant() 283 .with(ChronoField.NANO_OF_SECOND, 0)); 284 } catch (IOException e) { 285 // Fall through 286 } 287 } 288 try { 289 URLConnection conn = resource.openConnection(); 290 long lastModified = conn.getLastModified(); 291 if (lastModified != 0) { 292 return new ResourceInfo(null, Instant.ofEpochMilli( 293 lastModified).with(ChronoField.NANO_OF_SECOND, 0)); 294 } 295 } catch (IOException e) { 296 // Fall through 297 } 298 return new ResourceInfo(null, null); 299 } 300 301 /** 302 * Create a {@link URI} from a path. This is similar to calling 303 * `new URI(null, null, path, null)` with the {@link URISyntaxException} 304 * converted to a {@link IllegalArgumentException}. 305 * 306 * @param path the path 307 * @return the uri 308 * @throws IllegalArgumentException if the string violates 309 * RFC 2396 310 */ 311 @SuppressWarnings("PMD.AvoidUncheckedExceptionsInSignatures") 312 public static URI uriFromPath(String path) throws IllegalArgumentException { 313 try { 314 return new URI(null, null, path, null); 315 } catch (URISyntaxException e) { 316 throw new IllegalArgumentException(e); 317 } 318 } 319 320 /** 321 * Create a {@link URI} from a {@link URL}. This is similar to calling 322 * `url.toURI()` with the {@link URISyntaxException} 323 * converted to a {@link IllegalArgumentException}. 324 * 325 * @param url the url 326 * @return the uri 327 * @throws IllegalArgumentException if the url violates RFC 2396 328 */ 329 @SuppressWarnings("PMD.AvoidUncheckedExceptionsInSignatures") 330 public static URI uriFromUrl(URL url) throws IllegalArgumentException { 331 try { 332 return url.toURI(); 333 } catch (URISyntaxException e) { 334 throw new IllegalArgumentException(e); 335 } 336 } 337 338 /** 339 * Sets the cache control header in the given response. 340 * 341 * @param response the response 342 * @param maxAge the max age 343 * @return the value set 344 */ 345 public static long setMaxAge(HttpResponse response, int maxAge) { 346 CacheControlDirectives directives = new CacheControlDirectives(); 347 directives.add(new Directive("max-age", maxAge)); 348 response.setField(HttpField.CACHE_CONTROL, directives); 349 return maxAge; 350 } 351 352 /** 353 * Describes a calculator for the max-age property. 354 */ 355 @FunctionalInterface 356 public interface MaxAgeCalculator { 357 358 /** 359 * Calculate a max age value for a response using the given 360 * request and the media type of the repsonse. 361 * 362 * @param request the request, usually only the URI is 363 * considered for the calculation 364 * @param mediaType the media type of the response 365 * @return the max age value to be used in the response 366 */ 367 int maxAge(HttpRequest request, MediaType mediaType); 368 } 369 370 /** 371 * DefaultMaxAgeCalculator provides an implementation that 372 * tries to guess a good max age value by looking at the 373 * path of the requested resource. If the path contains 374 * the pattern "dash, followed by a number, followed by 375 * a dot and a number" it is assumed that the resource 376 * is versioned, i.e. its path changes if the resource 377 * changes. In this case a max age of one year is returned. 378 * In all other cases, a max age value of 60 (one minute) 379 * is returned. 380 */ 381 public static class DefaultMaxAgeCalculator implements MaxAgeCalculator { 382 383 public static final Pattern VERSION_PATTERN 384 = Pattern.compile("-[0-9]+\\.[0-9]+"); 385 386 @Override 387 public int maxAge(HttpRequest request, MediaType mediaType) { 388 if (VERSION_PATTERN.matcher( 389 request.requestUri().getPath()).find()) { 390 return 365 * 24 * 3600; 391 } 392 return 60; 393 } 394 395 } 396}