View Javadoc
1   /*
2    * Copyright 2008, 2009 Ange Optimization ApS
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 eu.simuline.octave.io;
17  
18  import static eu.simuline.octave.io.OctaveIO.readerReadLine;
19  
20  import java.io.BufferedReader;
21  import java.io.Reader;
22  import java.util.Map;
23  
24  import eu.simuline.octave.exception.OctaveParseException;
25  import eu.simuline.octave.exec.ReadFunctor;
26  import eu.simuline.octave.type.OctaveObject;
27  
28  /**
29   * Functor that reads a single variable named {@link #name} 
30   * into {@link #data} via {@link #doReads(Reader)}. 
31   */
32  // ER: Very strange: whereas this read functor reads a single variable only 
33  // the according write functor writes a map: 
34  // see OctaveIO 
35  final class DataReadFunctor implements ReadFunctor {
36  
37      /**
38       * The name of the variable to be read. 
39       */
40      private final String name;
41  
42      /**
43       * After {@link #doReads(Reader)} returns, this contains the read data. 
44       */
45      private OctaveObject data;
46  
47      /**
48       * @param name
49       */
50      DataReadFunctor(final String name) {
51          this.name = name;
52      }
53  
54      /**
55       * @param reader
56       */
57      @Override
58      public void doReads(final Reader reader) {
59          final BufferedReader bufferedReader = new BufferedReader(reader);
60          final String createByOctaveLine = readerReadLine(bufferedReader);
61          if (createByOctaveLine == null || 
62  	    !createByOctaveLine.startsWith("# Created by Octave")) {
63              throw new OctaveParseException
64  		("Not created by Octave?: '" + createByOctaveLine + "'");
65          }
66          final Map<String, OctaveObject> map = 
67  	    OctaveIO.readWithName(bufferedReader);
68          if (map.size() != 1) {
69              throw new OctaveParseException
70  		("Expected map of size 1 but got " + map + "'");
71          }
72          if (!map.containsKey(this.name)) {
73              throw new OctaveParseException
74  		("Expected variable named '" + this.name + 
75  		 "' but got '" + map + "'");
76          }
77          this.data = map.get(this.name);
78      }
79  
80      /**
81       * @return the data
82       */
83      public OctaveObject getData() {
84          return this.data;
85      }
86  
87  }