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.constructor.SafeConstructor; 023import org.yaml.snakeyaml.error.YAMLException; 024import org.yaml.snakeyaml.nodes.Node; 025import org.yaml.snakeyaml.nodes.Tag; 026 027import java.util.LinkedHashMap; 028import java.util.Map; 029 030public class YamlConstructor extends SafeConstructor { 031 032 YamlConstructor() { 033 yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); 034 } 035 036 private class ConstructCustomObject extends ConstructYamlMap { 037 038 @Override 039 public Object construct(final Node node) { 040 if (node.isTwoStepsConstruction()) { 041 throw new YAMLException("Unexpected referential mapping structure. Node: " + node); 042 } 043 044 final Map<?, ?> raw = (Map<?, ?>) super.construct(node); 045 046 if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { 047 final Map<String, Object> typed = new LinkedHashMap<>(raw.size()); 048 for (final Map.Entry<?, ?> entry : raw.entrySet()) { 049 typed.put(entry.getKey().toString(), entry.getValue()); 050 } 051 052 try { 053 return ConfigurationSerialization.deserializeObject(typed); 054 } catch (final IllegalArgumentException ex) { 055 throw new YAMLException("Could not deserialize object", ex); 056 } 057 } 058 059 return raw; 060 } 061 062 @Override 063 public void construct2ndStep(final Node node, final Object object) { 064 throw new YAMLException("Unexpected referential mapping structure. Node: " + node); 065 } 066 067 } 068 069}