
br.com.objectos.io.Resource Maven / Gradle / Ivy
/*
* Copyright (C) 2011-2021 Objectos Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.com.objectos.io;
import static br.com.objectos.lang.Lang.checkArgument;
import br.com.objectos.lang.Lang;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class Resource extends AbstractInputStreamSource implements FileName {
private final String resourceName;
private final URL url;
private Resource(URL url, String resourceName) {
this.url = url;
this.resourceName = resourceName;
}
public static Resource getResource(Class> contextClass, String resourceName) {
URL url = contextClass.getResource(resourceName);
checkUrl(url, resourceName);
Package pkg = contextClass.getPackage();
pkg.getName().replace('.', '/');
return new Resource(
url,
pkg.getName().replace('.', '/') + '/' + resourceName
);
}
public static Resource getResource(String resourceName) {
checkArgument(!resourceName.startsWith("/"), "resourceName MUST NOT start with a '/'");
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource(resourceName);
checkUrl(url, resourceName);
return new Resource(url, resourceName);
}
private static void checkUrl(URL url, String resourceName) {
if (url == null) {
throw new IllegalArgumentException("Resource " + resourceName + " not found.");
}
}
@Override
public final boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Resource)) {
return false;
}
Resource that = (Resource) obj;
return url.equals(that.url);
}
@Override
public final String getExtension() {
return Io.getExtension(resourceName);
}
@Override
public final String getName() {
return url.getFile();
}
@Override
public final int hashCode() {
return url.hashCode();
}
@Override
public final InputStream openInputStream() throws IOException {
return url.openStream();
}
public final String resourceName() {
return resourceName;
}
@Override
public final String toString() {
return Lang.toString(
this,
"resourceName", resourceName
);
}
public final URI toUri() throws URISyntaxException {
return url.toURI();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy