|
| 1 | +/* |
| 2 | + * Copyright 2021 - 2022 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.springframework.sbm.utils; |
| 17 | + |
| 18 | +import org.springframework.core.io.Resource; |
| 19 | + |
| 20 | +import java.io.IOException; |
| 21 | +import java.io.InputStream; |
| 22 | +import java.nio.file.Files; |
| 23 | +import java.nio.file.Path; |
| 24 | +import java.util.List; |
| 25 | + |
| 26 | +public class ResourceUtil { |
| 27 | + public ResourceUtil() { |
| 28 | + } |
| 29 | + |
| 30 | + public static Path getPath(Resource resource) { |
| 31 | + try { |
| 32 | + return resource.getFile().toPath(); |
| 33 | + } catch (IOException var2) { |
| 34 | + throw new RuntimeException(var2); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public static InputStream getInputStream(Resource resource) { |
| 39 | + try { |
| 40 | + return resource.getInputStream(); |
| 41 | + } catch (IOException var2) { |
| 42 | + throw new RuntimeException(var2); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public static void write(Path basePath, List<Resource> resources) { |
| 47 | + resources.stream() |
| 48 | + .forEach(r -> ResourceUtil.persistResource(basePath, r)); |
| 49 | + } |
| 50 | + |
| 51 | + private static void persistResource(Path basePath, Resource r) { |
| 52 | + Path resourcePath = ResourceUtil.getPath(r); |
| 53 | + if(resourcePath.isAbsolute()) { |
| 54 | + Path relativize = resourcePath.relativize(basePath); |
| 55 | + } else { |
| 56 | + resourcePath = basePath.resolve(resourcePath).toAbsolutePath().normalize(); |
| 57 | + } |
| 58 | + if(resourcePath.toFile().exists()) { |
| 59 | + return; |
| 60 | + } |
| 61 | + try { |
| 62 | + if(!resourcePath.getParent().toFile().exists()) { |
| 63 | + Files.createDirectories(resourcePath.getParent()); |
| 64 | + } |
| 65 | + Files.writeString(resourcePath, ResourceUtil.getContent(r)); |
| 66 | + } catch (IOException e) { |
| 67 | + throw new RuntimeException(e); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + public static String getContent(Resource r) { |
| 72 | + try { |
| 73 | + return new String(getInputStream(r).readAllBytes()); |
| 74 | + } catch (IOException e) { |
| 75 | + throw new RuntimeException(e); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments