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.io.ByteSink;
021import com.google.common.io.ByteSource;
022import com.google.common.net.MediaType;
023
024import java.io.IOException;
025import java.io.OutputStream;
026import java.net.URI;
027
028public class ErrorResource extends BaseResource implements Resource {
029
030    public static class Provider implements ResourceProvider {
031
032        @Override
033        public Resource getResource(URI uri) {
034            if (SCHEME.equals(uri.getScheme())) return ErrorResource.INSTANCE;
035            else return null;
036        }
037    }
038
039    static final String SCHEME = "error";
040
041    private static final URI ERROR_URI = URI.create("error:-");
042
043    private static final MediaType MEDIA_TYPE = MediaType.OCTET_STREAM;
044
045    // Must be *AFTER* above! static field initialization in Java is dumb...
046    public static final ErrorResource INSTANCE = new ErrorResource();
047
048    private ErrorResource() {
049        super(ERROR_URI, MEDIA_TYPE);
050    }
051
052    @Override
053    public ByteSink byteSink() {
054        return ErrorByteSink.INSTANCE;
055    }
056
057    @Override
058    public ByteSource byteSource() {
059        return new ErrorByteSource(new IOException());
060    }
061
062    private static final class ErrorByteSink extends ByteSink {
063        public static final ByteSink INSTANCE = new ErrorByteSink();
064
065        private ErrorByteSink() {}
066
067        @Override
068        public OutputStream openStream() throws IOException {
069            return new ErrorOutputStream();
070        }
071    }
072
073    private static final class ErrorOutputStream extends OutputStream {
074        @Override
075        public void write(int i) throws IOException {
076            throw new IOException();
077        }
078
079        @Override
080        public void write(byte[] b, int off, int len) throws IOException {
081            throw new IOException();
082        }
083    }
084}