summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java
blob: 0d25e68d9457a7ec9a1e3bf4a199104b63a2a6a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package bjc.utils.components;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import bjc.utils.funcdata.FunctionalList;

/**
 * A component repository that loads its components from files in a
 * directory
 * 
 * @author ben
 *
 * @param <E>
 *            The type of component being read in
 */
public class FileComponentRepository<E extends IDescribedComponent>
		implements IComponentRepository<E> {

	/**
	 * The internal storage of components
	 */
	private Map<String, E>	comps;

	/**
	 * The path that all the components came from
	 */
	private String			sourcePath;

	/**
	 * Create a new component repository sourcing components from files in
	 * a directory
	 * 
	 * @param dir
	 *            The directory to read component files from
	 * @param reader
	 *            The function to use to convert files to components
	 */
	public FileComponentRepository(File dir,
			Function<InputStream, E> reader) {
		comps = new HashMap<>();
		sourcePath = dir.getAbsolutePath();

		for (File fle : dir.listFiles()) {
			if (fle.isDirectory()) {
				// Do nothing with directories. They probably contain
				// support files for components
			} else {
				try {
					E comp = reader.apply(new FileInputStream(fle));

					comps.put(comp.getName(), comp);
				} catch (FileNotFoundException fnfx) {
					System.err.println("Couldn't read component file: "
							+ fle.getAbsolutePath() + "\nReason: "
							+ fnfx.getMessage());

					fnfx.printStackTrace(System.err);
				}
			}
		}
	}

	@Override
	public FunctionalList<E> getComponentList() {
		FunctionalList<E> ret = new FunctionalList<>();

		comps.forEach((name, comp) -> {
			ret.add(comp);
		});

		return ret;
	}

	@Override
	public Map<String, E> getComponents() {
		return comps;
	}

	@Override
	public String getSource() {
		return "Read from directory " + sourcePath + ".";
	}
}