2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.mielecloud.internal.config.servlet;
15 import java.io.FileNotFoundException;
16 import java.io.IOException;
17 import java.io.InputStream;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Scanner;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.osgi.framework.BundleContext;
26 * Provides access to resource files for servlets.
28 * @author Björn Lange - Initial Contribution
31 public final class ResourceLoader {
32 private static final String BEGINNING_OF_INPUT = "\\A";
34 private final String basePath;
35 private final BundleContext bundleContext;
38 * Creates a new {@link ResourceLoader}.
40 * @param basePath The base path to use for loading. A trailing {@code "/"} is removed.
41 * @param bundleContext {@link BundleContext} to load from.
43 public ResourceLoader(String basePath, BundleContext bundleContext) {
44 this.basePath = removeTrailingSlashes(basePath);
45 this.bundleContext = bundleContext;
48 private String removeTrailingSlashes(String value) {
50 while (ret.endsWith("/")) {
51 ret = ret.substring(0, ret.length() - 1);
57 * Opens a resource relative to the base path.
59 * @param filename The filename of the resource to load.
60 * @return A stream reading from the resource file.
61 * @throws FileNotFoundException If the requested resource file cannot be found.
62 * @throws IOException If an error occurs while opening a stream to the resource.
64 public InputStream openResource(String filename) throws IOException {
65 URL url = bundleContext.getBundle().getEntry(basePath + "/" + filename);
67 throw new FileNotFoundException("Cannot find '" + filename + "' relative to '" + basePath + "'");
70 return url.openStream();
74 * Loads the contents of a resource file as UTF-8 encoded {@link String}.
76 * @param filename The filename of the resource to load.
77 * @return The contents of the file.
78 * @throws FileNotFoundException If the requested resource file cannot be found.
79 * @throws IOException If an error occurs while opening a stream to the resource or reading from it.
81 public String loadResourceAsString(String filename) throws IOException {
82 try (Scanner scanner = new Scanner(openResource(filename), StandardCharsets.UTF_8.name())) {
83 return scanner.useDelimiter(BEGINNING_OF_INPUT).next();