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.base.Strings; 021import com.google.common.io.ByteSource; 022import com.google.common.io.CharSource; 023import com.google.common.net.MediaType; 024 025import org.jspecify.annotations.Nullable; 026 027import java.net.URI; 028import java.util.Objects; 029 030/** Resource based on String with a given URI and MediaType. */ 031public class StringResource2 extends BaseResource implements ReadableButNotWritableResource { 032 033 private final String string; 034 035 public static Resource of(@Nullable String text, MediaType mediaType, URI uri) { 036 return new StringResource2(Strings.nullToEmpty(text), mediaType, uri); 037 } 038 039 private StringResource2(String text, MediaType mediaType, URI uri) { 040 super(uri, mediaType); 041 this.string = Objects.requireNonNull(text, "text"); 042 if (!mediaType.charset().isPresent()) { 043 throw new IllegalArgumentException( 044 "MediaType is missing required charset: " + mediaType); 045 } 046 } 047 048 @Override 049 public ByteSource byteSource() { 050 return charSource().asByteSource(mediaType().charset().get()); 051 } 052 053 @Override 054 public CharSource charSource() { 055 return CharSource.wrap(string); 056 } 057}