Java Code Examples for com.electronwill.nightconfig.core.Config#set()

The following examples show how to use com.electronwill.nightconfig.core.Config#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HoconWriterTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testWrite() throws IOException {
	Config subConfig = CommentedConfig.inMemory();
	subConfig.set("string", "test");
	subConfig.set("enum", BasicTestEnum.C);
	subConfig.set("sub", CommentedConfig.inMemory());

	List<Config> configList = new ArrayList<>();
	configList.add(subConfig);
	configList.add(subConfig);
	configList.add(subConfig);

	CommentedConfig config = CommentedConfig.inMemory();
	config.set("string", "\"value\"");
	config.set("integer", 2);
	config.set("long", 123456789L);
	config.set("double", 3.1415926535);
	config.set("bool_array", Arrays.asList(true, false, true, false));
	config.set("config", subConfig);
	config.set("config_list", configList);
	config.setComment("string", " Comment 1\n Comment 2\n Comment 3");
	config.set("enum", TestEnum.A);

	StringWriter sw = new StringWriter();
	HoconWriter writer = new HoconWriter();
	writer.write(config, sw);
	System.out.println("Written:");
	System.out.println(sw);
}
 
Example 2
Source File: YamlTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testReadWrite() {
	Config config = Config.inMemory();
	config.set("null", null);
	config.set("nullObject", NULL_OBJECT);
	config.set("string", "this is a string");
	config.set("sub.null", null);
	config.set("sub.nullObject", NULL_OBJECT);
	config.set("enum", BasicTestEnum.A); // complex enums doesn't appear to work with SnakeYAML

	System.out.println("Config: " + config);
	System.out.println("classOf[sub] = " + config.get("sub").getClass());
	System.out.println("sub.null = " + config.get("sub.null"));
	System.out.println("sub.nullObject = " + config.get("sub.nullObject"));
	YamlFormat yamlFormat = YamlFormat.defaultInstance();
	yamlFormat.writer().write(config, file, WritingMode.REPLACE);

	Config parsed = yamlFormat.createConcurrentConfig();
	yamlFormat.parser().parse(file, parsed, ParsingMode.REPLACE, THROW_ERROR);
	System.out.println("\nParsed: " + parsed);
	System.out.println("classOf[sub] = " + parsed.get("sub").getClass());
	assertNull(parsed.get("sub.null"));
	assertNull(parsed.get("sub.nullObject"));
	assertSame(NULL_OBJECT, parsed.valueMap().get("null"));
	assertSame(NULL_OBJECT,	parsed.valueMap().get("nullObject"));
	assertEquals(BasicTestEnum.A, parsed.getEnum("enum", BasicTestEnum.class));

	Assertions.assertEquals(config, parsed, "Error: written != parsed");
}
 
Example 3
Source File: TomlWriterTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void writeToString() {
	Config subConfig = TomlFormat.instance().createConfig();
	subConfig.set("string", "test");
	subConfig.set("dateTime", ZonedDateTime.now());
	subConfig.set("sub", TomlFormat.instance().createConfig());

	List<Config> tableArray = new ArrayList<>();
	tableArray.add(subConfig);
	tableArray.add(subConfig);
	tableArray.add(subConfig);

	Config config = TomlFormat.instance().createConfig();
	config.set("string", "\"value\"");
	config.set("integer", 2);
	config.set("long", 123456789L);
	config.set("double", 3.1415926535);
	config.set("bool_array", Arrays.asList(true, false, true, false));
	config.set("config", subConfig);
	config.set("table_array", tableArray);
	config.set("enum", TestEnum.A);

	StringWriter stringWriter = new StringWriter();
	TomlWriter writer = new TomlWriter();
	writer.setIndentArrayElementsPredicate(array -> array.size() > 3);
	writer.setWriteTableInlinePredicate(table -> table.size() <= 2);
	writer.write(config, stringWriter);

	System.out.println("Written:");
	System.out.println(stringWriter);
}
 
Example 4
Source File: TomlWriterTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void noNulls() {
	Config config = TomlFormat.newConfig();
	Executable tryToWrite = () -> TomlFormat.instance().writer().writeToString(config);

	config.set("null", null);
	Assertions.assertThrows(WritingException.class, tryToWrite);

	config.set("null", NullObject.NULL_OBJECT);
	Assertions.assertThrows(WritingException.class, tryToWrite);
}
 
Example 5
Source File: ConfigSpecExample.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
	// Creates the ConfigSpec and defines how the config must be:
	ConfigSpec spec = new ConfigSpec();
	// defines an entry "key" of type String with a default value
	spec.define("key", "defaultValue");

	// defines an integer in range [-1;1], default 0
	spec.defineInRange("number", 0, -1, 1);

	// defines an entry "letter" that must be either 'a', 'b' or 'c'; default 'a'
	spec.defineInList("letter", 'a', Arrays.asList('a', 'b', 'c'));

	// You can also use defineOfClass with an enum:
	// This defines an entry "letter" that must be Letter.A, Letter.B or Letter.C, default A
	spec.defineOfClass("letter", Letter.A, Letter.class);
	// Redefining an entry overrides the previous definition.

	// Let's create a Config to use the ConfigSpec:
	Config config = Config.inMemory();
	config.set("key", "the value");// this is a valid entry of type String
	config.set("number", 1234);// number isn't in range [-1;1]
	config.set("unwanted_key", "abcdefg");// an entry that isn't in the specification
	// -- no "letter" entry

	// Checks if the config respects the configuration:
	boolean correct = spec.isCorrect(config);
	System.out.println("Correct: " + correct);

	// Corrects the configuration by using the default values where necessary:
	spec.correct(config);
	System.out.println("Config after correction: " + config);
	/*
	Explanation of the output:
	 - The "key" entry wasn't valid: the spec required it to be a String, it is the case.
	 - The "number" value wasn't in the specified range, therefore it has been replaced by the
	 default value 0.
	 - The "unwanted_key" entry wasn't in the spec, therefore it has been deleted.
	 - The "letter" entry was missing, therefore it has been added with the default value A.
	*/
}
 
Example 6
Source File: ObjectConverterAnnotationsExample.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
	// Creates a config with some values:
	Config config = Config.inMemory();
	config.set("the.long.path.in.config", "theValue");
	config.set("e", Math.E);
	config.set("number", 125);
	config.set("name", "A");
	config.set("some", "...");
	config.set("point", "(1,2)");
	System.out.println("Config: " + config);

	// Converts the config to an object:
	ConfigData object = new ObjectConverter().toObject(config, ConfigData::new);
	System.out.println("Object: " + object);

	// Converts the object to a config:
	Config configFromObject = new ObjectConverter().toConfig(object, Config::inMemory);
	System.out.println("Config from object: " + configFromObject);

	/* Explanations:
	   - @Path defines that the corresponding value in the config is at the specified path
	   instead of the field's name
	   - @Spec...InRange specifies that the field's value must be in the given range (min
	   and max are included), like ConfigSpec#defineInRange. If the value isn't correct, an
	   exception is thrown by the toObject method.
	   - @SpecStringInArray specifies that the field's value must be contained in the given
	   array. If the value isn't correct, an exception is thrown by the toObject method.
	   - @SpecNotNull specifies that the field's value must not be null. Otherwise an
	   exception is thrown like with the other @Spec... annotations.
	   - @Conversion defines a conversion between the config value and the field. A
	    new instance of the specified class is created when calling toObject, therefore the
	    class need to have a constructor without arguments (access level doesn't matter: it
	    can be private)
	    - @SpecValidator defines that the value must be checked by a custom class. As for
	    @Conversion, the class need to have a constructor without arguments.
	 */
}
 
Example 7
Source File: ConversionTableExample.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
	// Creates a config with some value:
	Config config = Config.inMemory();
	config.set("coordinates", "0,0,0");

	// Creates a conversion table:
	ConversionTable conversionTable = new ConversionTable();
	// Adds a conversion that converts every String to an instance of Coordinates
	conversionTable.put(String.class, (String s) -> {
		List<String> splitted = StringUtils.split(s, ',');
		int x = Integer.parseInt(splitted.get(0));
		int y = Integer.parseInt(splitted.get(1));
		int z = Integer.parseInt(splitted.get(2));
		return new Coordinates(x, y, z);
	});

	// Gets a "wrapped" config that converts the value "just in time" when they are read:
	Config wrappedConfig = conversionTable.wrapRead(config);
	System.out.println("Original config: " + config);
	System.out.println("Wrapped config: " + wrappedConfig);
	System.out.println(
			"Type of 'coordinates' in the original config: " + config.get("coordinates")
																	 .getClass());
	System.out.println(
			"Type of 'coordinates' in the wrapped config: " + wrappedConfig.get("coordinates")
																		   .getClass());

	// You can also convert the config "in-place", replacing its values with the converted ones:
	conversionTable.convertShallow(config);
	System.out.println("Config after conversion: " + config);
}
 
Example 8
Source File: JsonParser.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void parseKeyValue(JsonTokenizer tokenizer, JsonToken keyToken, Config dst) {
	if (keyToken != VALUE_STRING)
		throw new ParsingException("");

	CharSequence key = tokenizer.textValue();
	JsonToken separator = tokenizer.next();
	if (separator != KV_SEPARATOR)
		throw new ParsingException("");

	Object value = parseValue(tokenizer, tokenizer.next());
	dst.set(single(key.toString()), value);
}
 
Example 9
Source File: ObjectBinderTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void writeToObjectTest() {
	MyObjectFinal subObject = new MyObjectFinal(0, 3.14159265358, "", null, null, null, null, null, null, null);
	MyObjectFinal object = new MyObjectFinal(123, 1.23, "initialV", list2, null, null, null, config2, subObject, TestEnum.C);
	ObjectBinder binder = new ObjectBinder();
	Config config = binder.bind(object);
	config.set("integer", 1234568790);
	config.set("decimal", Math.PI);
	config.set("string", "value");
	config.set("stringList", list1);
	config.set("config", config1);
	config.set("enumValue", "A");
	config.set("subObject.integer", -1);
	config.set("subObject.decimal", 0.5);
	config.set("subObject.string", "Hey!");
	config.set("subObject.stringList", list2);
	config.set("subObject.config", config2);
	config.set("subObject.subObject", null);
	config.set("subObject.enumValue", "B");

	// Checks that the object has been modified according to the config
	assertEquals((int)config.get("integer"), object.integer);
	assertEquals((double)config.get("decimal"), object.decimal);
	assertEquals(config.get("string"), object.string);
	assertEquals(config.get("stringList"), object.stringList);
	assertNull(object.objList);
	assertEquals(config.get("config"), object.config);
	assertEquals(config.getEnum("enumValue", TestEnum.class), object.enumValue);
	assertTrue(config.get("subObject") instanceof Config);

	Config sub = config.get("subObject");
	assertEquals((int)sub.get("integer"), object.subObject.integer);
	assertEquals((double)sub.get("decimal"), object.subObject.decimal);
	assertEquals(sub.get("string"), object.subObject.string);
	assertEquals(sub.get("stringList"), object.subObject.stringList);
	assertEquals(sub.getEnum("enumValue", TestEnum.class), object.subObject.enumValue);
	assertNull(object.subObject.objList);
	assertNull(sub.get("subObject"));
}
 
Example 10
Source File: ObjectBinder.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a bound config.
 *
 * @param object       the object to bind, or null to bind the static fields of the
 *                     class
 * @param clazz        the object class, or the class to bind if the object is null
 * @param configFormat the Config format
 * @return a config bound to the specified object or class
 */
private Config bind(Object object, Class<?> clazz, ConfigFormat<?> configFormat) {
	BoundConfig boundConfig = createBoundConfig(object, clazz, configFormat);
	List<String> annotatedPath = AnnotationUtils.getPath(clazz);
	if (annotatedPath != null) {
		Config parentConfig = configFormat.createConfig();
		parentConfig.set(annotatedPath, boundConfig);
		return parentConfig;
	}
	return boundConfig;
}
 
Example 11
Source File: ObjectBinderTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void writeToObjectTest() {
	MyObjectFinal subObject = new MyObjectFinal(0, 3.14159265358, "", null, null, null, null, null, null, null);
	MyObjectFinal object = new MyObjectFinal(123, 1.23, "initialV", list2, null, null, null, config2, subObject, TestEnum.C);
	ObjectBinder binder = new ObjectBinder();
	Config config = binder.bind(object);
	config.set("integer", 1234568790);
	config.set("decimal", Math.PI);
	config.set("string", "value");
	config.set("stringList", list1);
	config.set("config", config1);
	config.set("enumValue", "A");
	config.set("subObject.integer", -1);
	config.set("subObject.decimal", 0.5);
	config.set("subObject.string", "Hey!");
	config.set("subObject.stringList", list2);
	config.set("subObject.config", config2);
	config.set("subObject.subObject", null);
	config.set("subObject.enumValue", "B");

	// Checks that the object has been modified according to the config
	assertEquals((int)config.get("integer"), object.integer);
	assertEquals((double)config.get("decimal"), object.decimal);
	assertEquals(config.get("string"), object.string);
	assertEquals(config.get("stringList"), object.stringList);
	assertNull(object.objList);
	assertEquals(config.get("config"), object.config);
	assertEquals(config.getEnum("enumValue", TestEnum.class), object.enumValue);
	assertTrue(config.get("subObject") instanceof Config);

	Config sub = config.get("subObject");
	assertEquals((int)sub.get("integer"), object.subObject.integer);
	assertEquals((double)sub.get("decimal"), object.subObject.decimal);
	assertEquals(sub.get("string"), object.subObject.string);
	assertEquals(sub.get("stringList"), object.subObject.stringList);
	assertEquals(sub.getEnum("enumValue", TestEnum.class), object.subObject.enumValue);
	assertNull(object.subObject.objList);
	assertNull(sub.get("subObject"));
}
 
Example 12
Source File: FileConfigExample.java    From night-config with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) {
	// Creates the FileConfig:
	FileConfig config = FileConfig.of("config.toml");

	// Loads the config (reads the file):
	config.load();
	// Note: the load() call is always blocking: it returns when the reading operation terminates.
	// load() is also used to reload the configuration.

	System.out.println("Config: " + config);

	// Modifies the config:
	config.set("key", "value");
	config.set("number", 123456);
	config.set("floatingPoint", 3.1415926535);

	// You can also use sub configs!
	Config subConfig = Config.inMemory();
	subConfig.set("subKey", "value");
	config.set("subConfig", subConfig);

	// NightConfig supports dot-separated paths:
	config.set("subConfig.subKey", "newValue");

	// If you want to use a key that contains a dot in its name, use a list:
	config.set(Arrays.asList("subConfig", "127.0.0.1"),
			   "test");// the key "127.0.0.1" is in subConfig

	System.out.println("Config: " + config);

	// Saves the config:
	config.save();
	// Note: by default, the save operation is done in the background, and config.save()
	// returns immediately without waiting for the operation to terminates.

	/* Once you don't need the FileConfig anymore, remember to close it, in order to release
	the associated resources. There aren't always such resources, but it's a good practise to
	call the close() method anyway.
	Closing the FileConfig also ensures that all the data has been written, in particular it
	waits for the background saving operations to complete. */
	config.close();
}
 
Example 13
Source File: ObjectConverterExample.java    From night-config with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) {
	// Creates a config with some values:
	Config config = Config.inMemory();
	config.set("value", "The value");
	config.set("number", 100);
	config.set("subData.str", "data string");
	config.set("ignored", true);
	config.set("notAField", "abc");
	System.out.println("Config: " + config);

	// Converts the config to an instance of ConfigData:
	ObjectConverter converter = new ObjectConverter();
	ConfigData object = converter.toObject(config, ConfigData::new);
	System.out.println("Object: " + object);

	/* Explanation of the result:
	   - The values of the config are mapped to the fields of ConfigData. Custom field types
	   (like SubData in our example) are automatically supported, provided they have a
	   constructor without arguments (the access level doesn't matter, it can be private).

	   - Notice that the value of "withDefaultValue" is replaced by null after the conversion.
	   That's because the content of the config overrides everything by default. To keep the
	   default value when the config doesn't provide one (ie gives null), add the
	   @PreserveNotNull annotation to the field.

	   You can also add @PreserveNotNull to the class to appy it to all the fields.

	   - The value of "ignored" didn't change, even if it was in the configuration. That's
	   because transient fields are ignored by default by the ObjectConverter. This behavior
	   can be changed by using the alternative constructor of ObjectConverter.

	   - There is no field "notAField" in ConfigData. And it's impossible to add a field to a
	   class at runtime, so the entry "notAField" is simply ignored by the ObjectConverter.
	   */

	// Modifies the config:
	config.set("value", "Another value");
	System.out.println("\nmodified Config: " + config);
	System.out.println("Object: " + object);
	/* See that the created object isn't linked to the config. They are independant, so you
	can modify the config without affecting the object and vice-versa. */

	// Of course it is possible to do the inverse operation: to convert an object to a config:
	Config configFromObject = converter.toConfig(object, Config::inMemory);
	System.out.println("\nConfig from object: " + configFromObject);
}
 
Example 14
Source File: ObjectConverter.java    From night-config with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Converts an Object to a Config. The {@link #bypassTransient} setting applies.
 */
private void convertToConfig(Object object, Class<?> clazz, Config destination) {
	// This loop walks through the class hierarchy, see clazz = clazz.getSuperclass(); at the end
	while (clazz != Object.class) {
		for (Field field : clazz.getDeclaredFields()) {
			// --- Checks modifiers ---
			final int fieldModifiers = field.getModifiers();
			if (object == null && Modifier.isStatic(fieldModifiers)) {
				continue;// Don't process static fields of object instances
			}
			if (!bypassTransient && Modifier.isTransient(fieldModifiers)) {
				continue;// Don't process transient fields if configured so
			}
			if (!field.isAccessible()) {
				field.setAccessible(true);// Enforces field access if needed
			}

			// --- Applies annotations ---
			Object value;
			try {
				value = field.get(object);
			} catch (IllegalAccessException e) {// Unexpected: setAccessible is called if needed
				throw new ReflectionException("Unable to parse the field " + field, e);
			}
			AnnotationUtils.checkField(field, value);/* Checks that the value is conform to an
															eventual @SpecSometing annotation */
			Converter<Object, Object> converter = AnnotationUtils.getConverter(field);
			if (converter != null) {
				value = converter.convertFromField(value);
			}
			List<String> path = AnnotationUtils.getPath(field);
			ConfigFormat<?> format = destination.configFormat();

			// --- Writes the value to the configuration ---
			if (value == null) {
				destination.set(path, null);
			} else {
				Class<?> valueType = value.getClass();
                   if (Enum.class.isAssignableFrom(valueType)) {
                       // Enums must not be treated as objects to break down
                       // Note: isEnum() doesn't work with enum items that have a body
                       if (destination.configFormat().supportsType(Enum.class)) {
                           destination.set(path, value); // keep the enum value if supported
                       } else {
                           destination.set(path, value.toString()); // if not supported, serialize it
                       }
                   } else if (field.isAnnotationPresent(ForceBreakdown.class) || !format.supportsType(valueType)) {
					// We have to convert the value
					destination.set(path, value);
					Config converted = destination.createSubConfig();
					convertToConfig(value, valueType, converted);
					destination.set(path, converted);
				} else if (value instanceof Collection) {
					// Checks that the ConfigFormat supports the type of the collection's elements
					Collection<?> src = (Collection<?>)value;
					Class<?> bottomType = bottomElementType(src);
					if (format.supportsType(bottomType)) {
						// Everything is supported, no conversion needed
						destination.set(path, value);
					} else {
						// List of complex objects => the bottom elements need conversion
						Collection<Object> dst = new ArrayList<>(src.size());
						convertObjectsToConfigs(src, bottomType, dst, destination);
						destination.set(path, dst);
					}
				} else {
					// Simple value
					destination.set(path, value);
				}
			}
		}
		clazz = clazz.getSuperclass();
	}
}