public static SimpleConfigurationNode root() { return root(ConfigurationOptions.defaults()); }
@Override public CommentedConfigurationNode createEmptyNode(ConfigurationOptions options) { options = options.setAcceptedTypes(ImmutableSet.of(Map.class, List.class, Double.class, Long.class, Integer.class, Boolean.class, String.class, Number.class)); return SimpleCommentedConfigurationNode.root(options); }
@Override public void load() { try { ConfigurationOptions options = ConfigurationOptions.defaults(); options = options.setShouldCopyDefaults(true);
private ConfigurationOptions getLoadOptions() { ConfigurationOptions ret = ConfigurationOptions.defaults(); if (alphabetizeEntries) { ret = ret.setMapFactory(MapFactories.sortedNatural()); } return ret; }
public ConfigCategory loadConfig() { try { File file = new File(instance.configDir, "MagiBridge.conf"); if (!file.exists()) { file.createNewFile(); } ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setFile(file).build(); CommentedConfigurationNode config = loader.load(ConfigurationOptions.defaults().setObjectMapperFactory(instance.factory).setShouldCopyDefaults(true).setHeader(HEADER)); root = config.getValue(TypeToken.of(ConfigCategory.class), new ConfigCategory()); loader.save(config); return root; } catch (Exception e) { MagiBridge.getLogger().error("Could not load config.", e); return root; } }
private ConfigurationOptions getConfigurationOptions() { ConfigurationOptions defaults = ConfigurationOptions.defaults(); TypeSerializerCollection serializers = defaults.getSerializers().newChild(); serializers.registerType(TypeToken.of(Duration.class), new DurationSerializer()); //explicit set enum serializer because otherwise they will be interpreted as class with the requirement of //a public constructor TypeSerializer<Enum> enumSerializer = serializers.get(TypeToken.of(Enum.class)); serializers.registerType(TypeToken.of(StorageType.class), enumSerializer); serializers.registerType(TypeToken.of(HashingAlgorithm.class), enumSerializer); return defaults.setSerializers(serializers); }
@Override @SuppressWarnings("unchecked") public <T> T getValue(@NonNull TypeToken<T> type, @NonNull Supplier<T> defSupplier) throws ObjectMappingException { Object value = getValue(); if (value == null) { return storeDefault(defSupplier.get()); } TypeSerializer serial = getOptions().getSerializers().get(type); if (serial == null) { if (type.getRawType().isInstance(value)) { return (T) type.getRawType().cast(value); } else { return storeDefault(defSupplier.get()); } } return (T) serial.deserialize(type, this); }
public void load() { Path configFile = dataFolder.resolve("config.conf"); Path textFile = dataFolder.resolve("locale.conf"); try { if (Files.notExists(dataFolder)) { Files.createDirectories(dataFolder); } if (Files.notExists(configFile)) { Files.createFile(configFile); } if (Files.notExists(textFile)) { Files.createFile(textFile); } } catch (IOException ioEx) { logger.error("Failed to create default config file", ioEx); } loadMapper(configMapper, configFile, options); loadMapper(textMapper, textFile, options .setHeader("Visit: https://github.com/games647/FlexibleLogin/wiki for community given templates")); }
/** * Set this node's value to the given value. * If the provided value is a {@link java.util.Collection} or a {@link java.util.Map}, it will be unwrapped into * the appropriate configuration node structure. * This method will also perform serialization using the appropriate TypeSerializer for the given type, or casting if no type serializer is found. * * @param type The type to use for serialization type information * @param value The value to set * @param <T> The type to serialize to * @return this */ default <T> ConfigurationNode setValue(TypeToken<T> type, T value) throws ObjectMappingException { if (value == null) { setValue(null); return this; } TypeSerializer serial = getOptions().getSerializers().get(type); if (serial != null) { serial.serialize(type, value, this); } else if (getOptions().acceptsType(value.getClass())) { setValue(value); // Just write if no applicable serializer exists? } else { throw new ObjectMappingException("No serializer available for type " + type); } return this; }
@Override @SuppressWarnings("unchecked") public <T> T getValue(TypeToken<T> type, Supplier<T> defSupplier) throws ObjectMappingException { Object value = getValue(); if (value == null) { T def = defSupplier.get(); if (def != null && getOptions().shouldCopyDefaults()) { setValue(type, def); } return def; } TypeSerializer serial = getOptions().getSerializers().get(type); if (serial == null) { if (type.getRawType().isInstance(value)) { return (T) type.getRawType().cast(value); } else { T def = defSupplier.get(); if (def != null && getOptions().shouldCopyDefaults()) { setValue(type, def); } return def; } } return (T) serial.deserialize(type, this); }
@SuppressWarnings("unchecked") private ConcurrentMap<Object, SimpleConfigurationNode> newMap() { return holder.getOptions().getMapFactory().create(); }
@Inject //We will place more than one config there (i.e. H2/SQLite database) Settings(Logger logger, @ConfigDir(sharedRoot = false) Path dataFolder) { this.logger = logger; this.dataFolder = dataFolder; try { configMapper = options.getObjectMapperFactory().getMapper(General.class).bindToNew(); textMapper = options.getObjectMapperFactory().getMapper(TextConfig.class).bindToNew(); } catch (ObjectMappingException objMappingExc) { logger.error("Invalid plugin structure", objMappingExc); } }
@Override public void save(@NonNull ConfigurationNode node) throws IOException { if (sink == null) { throw new IOException("No sink present to write to!"); } try (Writer writer = sink.call()) { if (headerMode != HeaderMode.NONE) { String header = node.getOptions().getHeader(); if (header != null && !header.isEmpty()) { for (String line : getDefaultCommentHandler().toComment(ImmutableList.copyOf(LINE_SPLITTER.split(header)))) { writer.write(line); writer.write(SYSTEM_LINE_SEPARATOR); } writer.write(SYSTEM_LINE_SEPARATOR); } } saveInternal(node, writer); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } else { throw new IOException(e); } } }
private <T> void loadMapper(ObjectMapper<T>.BoundInstance mapper, Path file, ConfigurationOptions options) { ConfigurationNode rootNode; if (mapper != null) { HoconConfigurationLoader loader = HoconConfigurationLoader.builder().setPath(file).build(); try { rootNode = loader.load(options.setShouldCopyDefaults(true)); ConfigurationNode hashNode = rootNode.getNode("hashAlgo"); if ("bcrypt".equalsIgnoreCase(hashNode.getString())) { hashNode.setValue("BCrypt"); } //load the config into the object mapper.populate(rootNode); //add missing default values loader.save(rootNode); } catch (ObjectMappingException objMappingExc) { logger.error("Error loading the configuration", objMappingExc); } catch (IOException ioExc) { logger.error("Error saving the default configuration", ioExc); } } }
public static void loadConfig(VotifierPlugin pl) { plugin = pl; if (!plugin.getConfigDir().exists()) { plugin.getConfigDir().mkdirs(); } try { File file = new File(plugin.getConfigDir(), "config.yml"); if (!file.exists()) { file.createNewFile(); } ConfigurationLoader loader = YAMLConfigurationLoader.builder().setFile(file).build(); ConfigurationNode config = loader.load(ConfigurationOptions.defaults().setShouldCopyDefaults(true)); spongeConfig = config.getValue(TypeToken.of(SpongeConfig.class), new SpongeConfig()); loader.save(config); } catch (Exception e) { plugin.getLogger().error("Could not load config.", e); } }
@Test public void testSimpleLoading(@TempDirectory.TempDir Path tempDir) throws IOException { URL url = getClass().getResource("/example.json"); final Path tempFile = tempDir.resolve("text1.txt"); ConfigurationLoader loader = JSONConfigurationLoader.builder() .setSource(() -> new BufferedReader(new InputStreamReader(url.openStream(), UTF_8))) .setSink(AtomicFiles.createAtomicWriterFactory(tempFile, UTF_8)).build(); ConfigurationNode node = loader.load(ConfigurationOptions.defaults().setMapFactory(MapFactories.sortedNatural())); assertEquals("unicorn", node.getNode("test", "op-level").getValue()); assertEquals("dragon", node.getNode("other", "op-level").getValue()); assertEquals("dog park", node.getNode("other", "location").getValue()); /*CommentedConfigurationNode commentNode = SimpleCommentedConfigurationNode.root(); commentNode.getNode("childOne").setValue("a").setComment("Test comment"); commentNode.getNode("childTwo", "something").setValue("b").setComment("Test comment 2"); commentNode.getNode("childTwo", "another").setValue("b").setComment("Test comment 3"); */ loader.save(node); assertEquals(Resources.readLines(url, UTF_8), Files .readAllLines(tempFile, UTF_8)); }
@Override @SuppressWarnings("unchecked") public <T> T getValue(@NonNull TypeToken<T> type, @NonNull Supplier<T> defSupplier) throws ObjectMappingException { Object value = getValue(); if (value == null) { return storeDefault(type, defSupplier.get()); } TypeSerializer serial = getOptions().getSerializers().get(type); if (serial == null) { if (type.getRawType().isInstance(value)) { return (T) type.getRawType().cast(value); } else { return storeDefault(type, defSupplier.get()); } } return (T) serial.deserialize(type, this); }
@Override public NodeType load(ConfigurationOptions options) throws IOException { if (!canLoad()) { throw new IOException("No source present to read from!"); } try (BufferedReader reader = source.call()) { NodeType node; if (headerMode == HeaderMode.PRESERVE || headerMode == HeaderMode.NONE) { String comment = CommentHandlers.extractComment(reader, commentHandlers); if (comment != null && comment.length() > 0) { options = options.setHeader(comment); } } node = createEmptyNode(options); loadInternal(node, reader); return node; } catch (FileNotFoundException | NoSuchFileException e) { // Squash -- there's nothing to read } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } else { throw new IOException(e); } } return createEmptyNode(options); }
/** * Set this node's value to the given value. * * <p>If the provided value is a {@link Collection} or a {@link Map}, it will be unwrapped into * the appropriate configuration node structure.</p> * * <p>This method will also perform serialization using the appropriate TypeSerializer for the * given type, or casting if no type serializer is found.</p> * * @param type The type to use for serialization type information * @param value The value to set * @param <T> The type to serialize to * @return this */ @NonNull default <T> ConfigurationNode setValue(@NonNull TypeToken<T> type, @Nullable T value) throws ObjectMappingException { if (value == null) { setValue(null); return this; } TypeSerializer<T> serial = getOptions().getSerializers().get(type); if (serial != null) { serial.serialize(type, value, this); } else if (getOptions().acceptsType(value.getClass())) { setValue(value); // Just write if no applicable serializer exists? } else { throw new ObjectMappingException("No serializer available for type " + type); } return this; }