View Javadoc
1   /*
2    * Copyright 2020-2022 Foreseeti AB <https://foreseeti.com>
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    *     http://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  
17  package org.mal_lang.langspec.builders;
18  
19  import static java.util.Objects.requireNonNull;
20  import static org.mal_lang.langspec.Utils.requireIdentifier;
21  
22  import jakarta.json.JsonObject;
23  import java.util.LinkedHashMap;
24  import java.util.Map;
25  
26  /**
27   * A builder for creating {@link org.mal_lang.langspec.Meta} objects.
28   *
29   * @since 1.0.0
30   */
31  public final class MetaBuilder {
32    private final Map<String, String> entries = new LinkedHashMap<>();
33  
34    /**
35     * Constructs a new {@code MetaBuilder} object.
36     *
37     * @since 1.0.0
38     */
39    public MetaBuilder() {}
40  
41    /**
42     * Returns all entries in this {@code MetaBuilder} object.
43     *
44     * @return all entries in this {@code MetaBuilder} object
45     * @since 1.0.0
46     */
47    public Map<String, String> getEntries() {
48      return Map.copyOf(this.entries);
49    }
50  
51    /**
52     * Adds an entry to this {@code MetaBuilder} object.
53     *
54     * @param key the key of the entry
55     * @param value the value of the entry
56     * @return this {@code MetaBuilder} object
57     * @throws java.lang.NullPointerException if {@code key} or {@code value} is {@code null}
58     * @throws java.lang.IllegalArgumentException if {@code key} is not a valid identifier
59     * @since 1.0.0
60     */
61    public MetaBuilder addEntry(String key, String value) {
62      this.entries.put(requireIdentifier(key), requireNonNull(value));
63      return this;
64    }
65  
66    /**
67     * Adds entries to this {@code MetaBuilder} from a {@link jakarta.json.JsonObject}.
68     *
69     * @param jsonMeta the {@link jakarta.json.JsonObject}
70     * @return this {@code MetaBuilder} object
71     * @throws java.lang.NullPointerException if {@code jsonMeta} is {@code null}
72     * @since 1.0.0
73     */
74    public MetaBuilder fromJson(JsonObject jsonMeta) {
75      requireNonNull(jsonMeta);
76      for (var key : jsonMeta.keySet()) {
77        this.addEntry(key, jsonMeta.getString(key));
78      }
79      return this;
80    }
81  }