001/*
002 * SPDX-License-Identifier: Apache-2.0
003 *
004 * Copyright 2023-2026 The Enola <https://enola.dev> Authors
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *     https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package dev.enola.common.io.resource;
019
020import com.google.common.net.MediaType;
021
022import dev.enola.common.io.iri.URIs;
023
024import java.io.IOException;
025import java.net.URI;
026import java.util.HashMap;
027import java.util.Map;
028import java.util.concurrent.atomic.AtomicLong;
029
030public class TestResource extends MemoryResource implements CloseableResource {
031
032    private static final String SCHEME = "test";
033
034    private static final Map<Long, TestResource> pool = new HashMap<>();
035    private static final AtomicLong counter = new AtomicLong();
036    private final long id;
037
038    private TestResource(MediaType mediaType, URI uri, long id) {
039        super(uri, mediaType);
040        this.id = id;
041    }
042
043    public static CloseableResource create(MediaType mediaType) {
044        // TODO Unify this with MemoryResource constructor
045        var id = counter.get();
046        var uri = URI.create(SCHEME + ":" + id);
047        var r = new TestResource(mediaType, uri, id);
048        pool.put(id, r);
049        return r;
050    }
051
052    @Override
053    public void close() throws IOException {
054        pool.remove(id);
055    }
056
057    public static class Provider implements ResourceProvider {
058
059        @Override
060        public Resource getResource(URI uri) {
061            if (!SCHEME.equals(uri.getScheme())) return null;
062
063            var id = URIs.getPath(uri);
064            var i = Long.parseLong(id);
065            var r = pool.get(i);
066            if (r == null) {
067                throw new IllegalStateException("TestResource already closed? URI=" + uri);
068            }
069            return r;
070        }
071    }
072}