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

The following examples show how to use com.electronwill.nightconfig.core.Config#inMemory() . 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: ObjectConverterTest2.java    From night-config with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSupportBasic() {
	ObjectConverter converter = new ObjectConverter();
	Config config = Config.inMemory();
	MyObject object = new MyObject();
	converter.toConfig(object, config);

	System.out.println("MyObject mapped to a SimpleConfig with basic strategy:");
	System.out.println(config);

	assertEquals(object.integer, (int)config.get("integer"));
	assertEquals(object.decimal, (double)config.get("decimal"));
	assertEquals(object.string, config.get("string"));
	assertEquals(object.stringList, config.get("stringList"));
	assertEquals(object.objList.size(), config.<List<?>>get("objList").size());
	assertEquals(object.config, config.get("config"));
	assertTrue(config.get("subObject") instanceof Config);
	Config sub = config.get("subObject");
	assertEquals(object.subObject.integer, (int)sub.get("integer"));
	assertEquals(object.subObject.decimal, (double)sub.get("decimal"));
	assertEquals(object.subObject.string, sub.get("string"));
	assertEquals(object.subObject.stringList, sub.get("stringList"));
	assertEquals(object.subObject.objList.size(), sub.<List<?>>get("objList").size());
	assertNull(sub.get("subObject"));
}
 
Example 2
Source File: ObjectConverterTest2.java    From night-config with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSupportBasic() {
	ObjectConverter converter = new ObjectConverter();
	Config config = Config.inMemory();
	MyObject object = new MyObject();
	converter.toConfig(object, config);

	System.out.println("MyObject mapped to a SimpleConfig with basic strategy:");
	System.out.println(config);

	assertEquals(object.integer, (int)config.get("integer"));
	assertEquals(object.decimal, (double)config.get("decimal"));
	assertEquals(object.string, config.get("string"));
	assertEquals(object.stringList, config.get("stringList"));
	assertEquals(object.objList.size(), config.<List<?>>get("objList").size());
	assertEquals(object.config, config.get("config"));
	assertTrue(config.get("subObject") instanceof Config);
	Config sub = config.get("subObject");
	assertEquals(object.subObject.integer, (int)sub.get("integer"));
	assertEquals(object.subObject.decimal, (double)sub.get("decimal"));
	assertEquals(object.subObject.string, sub.get("string"));
	assertEquals(object.subObject.stringList, sub.get("stringList"));
	assertEquals(object.subObject.objList.size(), sub.<List<?>>get("objList").size());
	assertNull(sub.get("subObject"));
}
 
Example 3
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 4
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 5
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 6
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 7
Source File: ObjectConverterTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void configToObjectToConfigToObject() throws Exception {
	ObjectConverter converter = new ObjectConverter();
	MyObject object = converter.toObject(config, MyObject::new);
	Config newConfig = Config.inMemory();
	converter.toConfig(object, newConfig);

	MyObject newObject = new MyObject();
	converter.toObject(newConfig, newObject);

	System.out.println("Original config: " + config);
	System.out.println("New config: " + newConfig);
	System.out.println("\nOriginal object: " + object);
	System.out.println("New object: " + object);

       // test the enum values
       assertEquals(TestEnum.A, config.getEnum("enumValue", TestEnum.class));
       assertEquals(TestEnum.C, config.getEnum("subObject.enumValue", TestEnum.class, EnumGetMethod.ORDINAL_OR_NAME));

       // Replace string and integer by enum values in order to compare the configs properly
       // (the object converter should have put enum values in the new config)
       config.set("enumValue", TestEnum.A);
       config.set("subObject.enumValue", TestEnum.C);

       // ensure that the conversion was well done
       assertEquals(config, newConfig, "Invalid conversion");
	assertEquals(object, newObject, "Invalid conversion");
}
 
Example 8
Source File: ObjectConverterTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void configToObjectToConfigToObject() throws Exception {
	ObjectConverter converter = new ObjectConverter();
	MyObject object = converter.toObject(config, MyObject::new);
	Config newConfig = Config.inMemory();
	converter.toConfig(object, newConfig);

	MyObject newObject = new MyObject();
	converter.toObject(newConfig, newObject);

	System.out.println("Original config: " + config);
	System.out.println("New config: " + newConfig);
	System.out.println("\nOriginal object: " + object);
	System.out.println("New object: " + object);

       // test the enum values
       assertEquals(TestEnum.A, config.getEnum("enumValue", TestEnum.class));
       assertEquals(TestEnum.C, config.getEnum("subObject.enumValue", TestEnum.class, EnumGetMethod.ORDINAL_OR_NAME));

       // Replace string and integer by enum values in order to compare the configs properly
       // (the object converter should have put enum values in the new config)
       config.set("enumValue", TestEnum.A);
       config.set("subObject.enumValue", TestEnum.C);

       // ensure that the conversion was well done
       assertEquals(config, newConfig, "Invalid conversion");
	assertEquals(object, newObject, "Invalid conversion");
}
 
Example 9
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 10
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);
}