1 /*
2 * ====================================================================
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 * ====================================================================
20 *
21 * This software consists of voluntary contributions made by many
22 * individuals on behalf of the Apache Software Foundation. For more
23 * information on the Apache Software Foundation, please see
24 * <http://www.apache.org/>.
25 *
26 */
27 package org.apache.hc.client5.http.impl.cache;
28
29 import java.net.URI;
30 import java.util.Objects;
31
32 import org.apache.hc.client5.http.utils.URIUtils;
33 import org.apache.hc.core5.annotation.Internal;
34 import org.apache.hc.core5.http.Header;
35 import org.apache.hc.core5.http.MessageHeaders;
36 import org.apache.hc.core5.util.TextUtils;
37 import org.apache.hc.core5.util.TimeValue;
38
39 /**
40 * HTTP cache support utilities.
41 *
42 * @since 5.4
43 */
44 @Internal
45 public final class CacheSupport {
46
47 public static URI getLocationURI(final URI requestUri, final MessageHeaders response, final String headerName) {
48 final Header h = response.getFirstHeader(headerName);
49 if (h == null) {
50 return null;
51 }
52 final URI locationUri = CacheKeyGenerator.normalize(h.getValue());
53 if (locationUri == null) {
54 return requestUri;
55 }
56 if (locationUri.isAbsolute()) {
57 return locationUri;
58 }
59 return URIUtils.resolve(requestUri, locationUri);
60 }
61
62 public static boolean isSameOrigin(final URI requestURI, final URI targetURI) {
63 return targetURI.isAbsolute() && Objects.equals(requestURI.getAuthority(), targetURI.getAuthority());
64 }
65
66 public static final TimeValue MAX_AGE = TimeValue.ofSeconds(Integer.MAX_VALUE + 1L);
67
68 public static long deltaSeconds(final String s) {
69 if (TextUtils.isEmpty(s)) {
70 return -1;
71 }
72 try {
73 long ageValue = Long.parseLong(s);
74 if (ageValue < 0) {
75 ageValue = -1; // Handle negative age values as invalid
76 } else if (ageValue > Integer.MAX_VALUE) {
77 ageValue = MAX_AGE.toSeconds();
78 }
79 return ageValue;
80 } catch (final NumberFormatException ignore) {
81 }
82 return 0;
83 }
84
85 }