001/*
002 * Copyright 2022-2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.soklet;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import javax.annotation.concurrent.ThreadSafe;
023import java.util.Objects;
024import java.util.Optional;
025
026import static java.lang.String.format;
027import static java.util.Objects.requireNonNull;
028
029/**
030 * Immutable representation of one HTTP entity tag.
031 * <p>
032 * Values use the HTTP opaque-tag byte grammar: {@code 0x21}, {@code 0x23-0x7E},
033 * and {@code 0x80-0xFF} (obs-text). Characters above {@code 0xFF}, including
034 * surrogate code units, are not valid field octets. Factories reject invalid
035 * values; {@link #fromHeaderValue(String)} returns {@link Optional#empty()}.
036 *
037 * @author <a href="https://www.revetkn.com">Mark Allen</a>
038 */
039@ThreadSafe
040public final class EntityTag {
041        @NonNull
042        private final String value;
043        @NonNull
044        private final Boolean weak;
045
046        @NonNull
047        public static EntityTag fromStrongValue(@NonNull String value) {
048                requireNonNull(value);
049                return new EntityTag(value, false);
050        }
051
052        @NonNull
053        public static EntityTag fromWeakValue(@NonNull String value) {
054                requireNonNull(value);
055                return new EntityTag(value, true);
056        }
057
058        @NonNull
059        public static Optional<@NonNull EntityTag> fromHeaderValue(@Nullable String headerValue) {
060                String trimmed = Utilities.trimAggressivelyToNull(headerValue);
061
062                if (trimmed == null || "*".equals(trimmed))
063                        return Optional.empty();
064
065                Boolean weak = false;
066                String remaining = trimmed;
067
068                if (remaining.regionMatches(true, 0, "W/", 0, 2)) {
069                        weak = true;
070                        remaining = remaining.substring(2);
071                }
072
073                if (remaining.length() < 2 || remaining.charAt(0) != '"' || remaining.charAt(remaining.length() - 1) != '"')
074                        return Optional.empty();
075
076                String value = remaining.substring(1, remaining.length() - 1);
077
078                if (!isValidOpaqueTag(value))
079                        return Optional.empty();
080
081                return Optional.of(new EntityTag(value, weak));
082        }
083
084        private EntityTag(@NonNull String value,
085                                                                                @NonNull Boolean weak) {
086                requireNonNull(value);
087                requireNonNull(weak);
088
089                if (!isValidOpaqueTag(value))
090                        throw new IllegalArgumentException(format("Invalid entity-tag value '%s'.", value));
091
092                this.value = value;
093                this.weak = weak;
094        }
095
096        @NonNull
097        public Boolean isWeak() {
098                return this.weak;
099        }
100
101        @NonNull
102        public String getValue() {
103                return this.value;
104        }
105
106        @NonNull
107        public String toHeaderValue() {
108                return format("%s\"%s\"", isWeak() ? "W/" : "", getValue());
109        }
110
111        @NonNull
112        public Boolean stronglyMatches(@NonNull EntityTag other) {
113                requireNonNull(other);
114                return !isWeak() && !other.isWeak() && getValue().equals(other.getValue());
115        }
116
117        @NonNull
118        public Boolean weaklyMatches(@NonNull EntityTag other) {
119                requireNonNull(other);
120                return getValue().equals(other.getValue());
121        }
122
123        @Override
124        @NonNull
125        public String toString() {
126                return format("%s{value=%s, weak=%s}", getClass().getSimpleName(), getValue(), isWeak());
127        }
128
129        @Override
130        public boolean equals(@Nullable Object object) {
131                if (this == object)
132                        return true;
133
134                if (!(object instanceof EntityTag entityTag))
135                        return false;
136
137                return Objects.equals(getValue(), entityTag.getValue())
138                                && Objects.equals(isWeak(), entityTag.isWeak());
139        }
140
141        @Override
142        public int hashCode() {
143                return Objects.hash(getValue(), isWeak());
144        }
145
146        private static boolean isValidOpaqueTag(@NonNull String value) {
147                requireNonNull(value);
148
149                for (int i = 0; i < value.length(); i++) {
150                        char c = value.charAt(i);
151
152                        if (c == '"' || c < 0x21 || c == 0x7F || c > 0xFF)
153                                return false;
154                }
155
156                return true;
157        }
158}