2 * Copyright (c) 2018-2019. Developed by Hedgecode.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.hedgecode.chess.img;
19 import java.awt.image.BufferedImage;
21 import java.net.URISyntaxException;
22 import java.nio.file.DirectoryStream;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.util.HashMap;
28 import org.hedgecode.chess.img.fs.FileSystemDetector;
29 import org.hedgecode.chess.img.fs.FileSystemContractor;
32 * Abstract common image loader with type state of saved resources.
34 * @author Dmitry Samoshin aka gotty
36 public abstract class AbstractImageLoader implements ImageLoader {
38 private static final String IMAGES_DIR =
39 ImageConstants.RESOURCE_ROOT_DIR.concat(ImageConstants.RESOURCE_IMAGES_DIR);
41 private static final int DEF_IMAGE_SIZE = 100;
43 private Type loadType;
45 private URI imageResourceUri;
47 public AbstractImageLoader() {
48 loadType = Type.STATELESS;
50 if (FileSystemDetector.detectJar(getImageResourceUri())) {
51 loadType = Type.STATEFUL;
53 } catch (ImageException ignored) {
57 protected abstract void clear();
60 public Type loadType() {
64 protected void setLoadType(Type loadType) {
65 if (Type.STATELESS.equals(loadType)) {
68 this.loadType = loadType;
71 protected URI getImageResourceUri() throws ImageException {
72 if (imageResourceUri == null) {
74 imageResourceUri = getClass().getResource(IMAGES_DIR).toURI();
75 } catch (URISyntaxException e) {
76 throw new ImageException("image.unable.access.resource");
79 return imageResourceUri;
82 protected Map<String, BufferedImage> loadImages(String imagesPath, ImageFilter filter)
85 return loadImages(imagesPath, filter, DEF_IMAGE_SIZE);
88 protected Map<String, BufferedImage> loadImages(String imagesPath, ImageFilter filter, int size)
91 Map<String, BufferedImage> images = new HashMap<>();
92 try (FileSystemContractor fsc = FileSystemDetector.detect(getImageResourceUri())) {
93 try (DirectoryStream<Path> ds =
94 Files.newDirectoryStream(
95 fsc.getPath(imagesPath), filter
98 ImageFormatShaper formatShaper = ImageFormatShaper.getInstance();
99 for (Path file : ds) {
100 String fileName = file.getFileName().toString();
101 String baseName = FilenameUtils.getBaseName(fileName).toLowerCase();
102 String imageFormat = FilenameUtils.getExtension(fileName).toLowerCase();
107 fsc.getResourceAsStream(file),
113 } catch (Exception e) {
114 throw new ImageException("image.unable.access.resource", e.getMessage());