Home | History | Annotate | Download | only in partialconstruct
      1 /**
      2  * Copyright (c) 2008, http://www.snakeyaml.org
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *     http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package org.yaml.snakeyaml.partialconstruct;
     17 
     18 import org.yaml.snakeyaml.composer.Composer;
     19 import org.yaml.snakeyaml.nodes.MappingNode;
     20 import org.yaml.snakeyaml.nodes.Node;
     21 import org.yaml.snakeyaml.nodes.NodeTuple;
     22 import org.yaml.snakeyaml.nodes.ScalarNode;
     23 import org.yaml.snakeyaml.parser.Parser;
     24 import org.yaml.snakeyaml.resolver.Resolver;
     25 
     26 class FragmentComposer extends Composer {
     27     String nodeName;
     28 
     29     public FragmentComposer(Parser parser, Resolver resolver, String nodeName) {
     30         super(parser, resolver);
     31         this.nodeName = nodeName;
     32     }
     33 
     34     @Override
     35     public Node getSingleNode() {
     36         Node node = super.getSingleNode();
     37         if (!MappingNode.class.isAssignableFrom(node.getClass())) {
     38             throw new RuntimeException(
     39                     "Document is not structured as expected.  Root element should be a map!");
     40         }
     41         MappingNode root = (MappingNode) node;
     42         for (NodeTuple tuple : root.getValue()) {
     43             Node keyNode = tuple.getKeyNode();
     44             if (ScalarNode.class.isAssignableFrom(keyNode.getClass())) {
     45                 if (((ScalarNode) keyNode).getValue().equals(nodeName)) {
     46                     return tuple.getValueNode();
     47                 }
     48             }
     49         }
     50         throw new RuntimeException("Did not find key \"" + nodeName + "\" in document-level map");
     51     }
     52 }