001/* 002 * PlotSquared, a land and world management plugin for Minecraft. 003 * Copyright (C) IntellectualSites <https://intellectualsites.com> 004 * Copyright (C) IntellectualSites team and contributors 005 * 006 * This program is free software: you can redistribute it and/or modify 007 * it under the terms of the GNU General Public License as published by 008 * the Free Software Foundation, either version 3 of the License, or 009 * (at your option) any later version. 010 * 011 * This program is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 014 * GNU General Public License for more details. 015 * 016 * You should have received a copy of the GNU General Public License 017 * along with this program. If not, see <https://www.gnu.org/licenses/>. 018 */ 019package com.plotsquared.core.configuration.file; 020 021import com.plotsquared.core.configuration.serialization.ConfigurationSerialization; 022import org.yaml.snakeyaml.LoaderOptions; 023import org.yaml.snakeyaml.constructor.SafeConstructor; 024import org.yaml.snakeyaml.error.YAMLException; 025import org.yaml.snakeyaml.nodes.Node; 026import org.yaml.snakeyaml.nodes.Tag; 027 028import java.util.LinkedHashMap; 029import java.util.Map; 030 031public class YamlConstructor extends SafeConstructor { 032 033 YamlConstructor() { 034 super(new LoaderOptions()); 035 yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); 036 } 037 038 private class ConstructCustomObject extends ConstructYamlMap { 039 040 @Override 041 public Object construct(final Node node) { 042 if (node.isTwoStepsConstruction()) { 043 throw new YAMLException("Unexpected referential mapping structure. Node: " + node); 044 } 045 046 final Map<?, ?> raw = (Map<?, ?>) super.construct(node); 047 048 if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { 049 final Map<String, Object> typed = new LinkedHashMap<>(raw.size()); 050 for (final Map.Entry<?, ?> entry : raw.entrySet()) { 051 typed.put(entry.getKey().toString(), entry.getValue()); 052 } 053 054 try { 055 return ConfigurationSerialization.deserializeObject(typed); 056 } catch (final IllegalArgumentException ex) { 057 throw new YAMLException("Could not deserialize object", ex); 058 } 059 } 060 061 return raw; 062 } 063 064 @Override 065 public void construct2ndStep(final Node node, final Object object) { 066 throw new YAMLException("Unexpected referential mapping structure. Node: " + node); 067 } 068 069 } 070 071}