summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java
blob: 5ab87bb31171deaa444807f7a7eb68a7a98af8ac (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
package bjc.utils.components;

import java.io.InputStream;

import bjc.utils.exceptions.PragmaFormatException;
import bjc.utils.funcutils.ListUtils;
import bjc.utils.parserutils.RuleBasedConfigReader;

/**
 * Read a component description from a file
 * 
 * @author ben
 *
 */
public class ComponentDescriptionFileParser {
	private static RuleBasedConfigReader<ComponentDescriptionState> reader;

	static {
		// This reader works entirely off of pragmas, so no need to handle
		// rules
		reader = new RuleBasedConfigReader<>((tokenizer, statePair) -> {
		}, (tokenizer, state) -> {
		}, (state) -> {
		});

		reader.addPragma("name", (tokenizer, state) -> {
			if (!tokenizer.hasMoreTokens()) {
				throw new PragmaFormatException(
						"Pragma name requires one string argument");
			} else {
				state.setName(ListUtils.collapseTokens(
						tokenizer.toList((strang) -> strang)));
			}
		});

		reader.addPragma("author", (tokenizer, state) -> {
			if (!tokenizer.hasMoreTokens()) {
				throw new PragmaFormatException(
						"Pragma author requires one string argument");
			} else {
				state.setAuthor(ListUtils.collapseTokens(
						tokenizer.toList((strang) -> strang)));
			}
		});

		reader.addPragma("description", (tokenizer, state) -> {
			if (!tokenizer.hasMoreTokens()) {
				throw new PragmaFormatException(
						"Pragma description requires one string argument");
			} else {
				state.setDescription(ListUtils.collapseTokens(
						tokenizer.toList((strang) -> strang)));
			}
		});

		reader.addPragma("version", (tokenizer, state) -> {
			if (!tokenizer.hasMoreTokens()) {
				throw new PragmaFormatException(
						"Pragma name requires one integer argument");
			} else {
				String token = tokenizer.nextToken();

				try {
					state.setVersion(Integer.parseInt(token));
				} catch (NumberFormatException nfex) {
					throw new PragmaFormatException("Argument " + token
							+ " to version pragma isn't a valid integer. "
							+ "This pragma requires a integer argument");
				}
			}
		});
	}

	/**
	 * Parse a component description from a stream
	 * 
	 * @param inputSource
	 *            The stream to parse from
	 * @return The description parsed from the stream
	 */
	public static ComponentDescription
			fromStream(InputStream inputSource) {
		ComponentDescriptionState readState = reader
				.fromStream(inputSource, new ComponentDescriptionState());

		return readState.toDescription();
	}
}