| /* |
| ******************************************************************************* |
| * Copyright (c) 2018 Contributors to the Eclipse Foundation |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License v. 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0. |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ******************************************************************************* |
| */ |
| |
| package org.eclipse.openk.common.util; |
| |
| import java.io.IOException; |
| import java.io.InputStream; |
| import java.io.StringWriter; |
| import java.net.URI; |
| import java.net.URISyntaxException; |
| import java.net.URL; |
| import java.nio.file.Files; |
| import java.nio.file.Path; |
| import java.nio.file.Paths; |
| import org.apache.commons.io.ByteOrderMark; |
| import org.apache.commons.io.IOUtils; |
| import org.apache.commons.io.input.BOMInputStream; |
| import org.apache.log4j.Logger; |
| |
| public class ResourceLoaderBase { |
| |
| public static final Logger LOGGER = Logger.getLogger(ResourceLoaderBase.class.getName()); |
| |
| private String stream2String(InputStream is, String filename) { |
| StringWriter writer = new StringWriter(); |
| BOMInputStream bomInputStream = new BOMInputStream(is, false, ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, |
| ByteOrderMark.UTF_32BE, ByteOrderMark.UTF_32LE); |
| |
| try { |
| IOUtils.copy(bomInputStream, writer, "UTF-8"); |
| } catch (IOException e) { |
| LOGGER.error("Fehler in stream2String()", e); |
| return ""; |
| } |
| |
| LOGGER.info("Datei erfolgreich eingelesen: " + filename); |
| return writer.toString(); |
| } |
| |
| public String loadStringFromResource(String filename) { |
| ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); |
| InputStream jsonstream = classLoader.getResourceAsStream(filename); |
| if (jsonstream==null){ |
| LOGGER.error("Datei nicht gefunden: " + filename); |
| return null; |
| } |
| LOGGER.debug("Datei existiert und wurde selektiert: " + filename); |
| try { |
| URL resource = classLoader.getResource(filename); |
| if (resource != null) { |
| URI uri = resource.toURI(); |
| LOGGER.debug("Uniform Resource Identifier (URI): " + uri); |
| } |
| } catch (URISyntaxException e) { |
| LOGGER.error("Fehler in loadStringFromResource: " + filename, e); |
| } |
| |
| return stream2String(jsonstream, filename); |
| } |
| |
| public String loadFromPath(String path) { |
| try { |
| Path paths = Paths.get(path); |
| LOGGER.info("paths: " + path); |
| try (InputStream inputStream = Files.newInputStream(Paths.get(path))) { |
| return stream2String(inputStream, paths.getFileName().toString()); |
| } |
| } catch (IOException e) { |
| LOGGER.error("Fehler in loadFromPath", e); |
| return null; |
| } |
| } |
| } |