Skip to content
Snippets Groups Projects
KeyValueFileParser.java 18.1 KiB
Newer Older
noeljanes's avatar
noeljanes committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
/* Copyright 2002-2019 CS Systèmes d'Information
 * Licensed to CS Systèmes d'Information (CS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * CS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package fr.cs.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hipparchus.exception.DummyLocalizable;
import org.hipparchus.exception.Localizable;
import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.util.FastMath;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitMessages;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.frames.Predefined;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeComponents;
import org.orekit.time.TimeScale;

/** Simple parser for key/value files.
 * @param Key type of the parameter keys
 */
public class KeyValueFileParser<Key extends Enum<Key>> {

    /** Error message for unknown frame. */
    private static final Localizable UNKNOWN_FRAME =
        new DummyLocalizable("unknown frame {0}");

    /** Error message for not Earth frame. */
    private static final Localizable NOT_EARTH_FRAME =
        new DummyLocalizable("frame {0} is not an Earth frame");

    /** Enum type. */
    private final Class<Key> enumType;

    /** Key/scalar value map. */
    private final Map<Key, String> scalarMap;

    /** Key/array value map. */
    private final Map<Key, List<String>> arrayMap;

    /** Simple constructor.
     * @param enumType type of the parameters keys enumerate
     */
    public KeyValueFileParser(Class<Key> enumType) {
        this.enumType  = enumType;
        this.scalarMap = new HashMap<Key, String>();
        this.arrayMap  = new HashMap<Key, List<String>>();
    }

    /** Parse an input file.
     * <p>
     * The input file syntax is a set of {@code key=value} lines or
     * {@code key[i]=value} lines. Blank lines and lines starting with '#'
     * (after whitespace trimming) are silently ignored. The equal sign may
     * be surrounded by space characters. Keys must correspond to the
     * {@link Key} enumerate constants, given that matching is not case
     * sensitive and that '_' characters may appear as '.' characters in
     * the file. This means that the lines:
     * <pre>
     *   # this is the semi-major axis
     *   orbit.circular.a   = 7231582
     * </pre>
     * are perfectly right and correspond to key {@code Key#ORBIT_CIRCULAR_A} if
     * such a constant exists in the enumerate.
     * </p>
     * <p>
     * When the key[i] notation is used, all the values extracted from lines
     * with the same key will be put in a general array that will be retrieved
     * using one of the {@code getXxxArray(key)} methods. They will <em>not</em>
     * be available with the {@code getXxx(key)} methods without the {@code Array}.
     * </p>
     * @param input input stream
     * @exception IOException if input file cannot be read
     */
    public void parseInput(final String name, final InputStream input)
        throws IOException, OrekitException {

        final Pattern        arrayPattern = Pattern.compile("([\\w\\.]+)\\s*\\[([0-9]+)\\]");
        try (final BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"))) {
            int lineNumber = 0;
            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                ++lineNumber;
                line = line.trim();
                // we ignore blank lines and line starting with '#'
                if ((line.length() > 0) && !line.startsWith("#")) {
                    String[] fields = line.split("\\s*=\\s*");
                    if (fields.length != 2) {
                        throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
                                                  lineNumber, name, line);
                    }
                    final Matcher matcher = arrayPattern.matcher(fields[0]);
                    if (matcher.matches()) {
                        // this is a key[i]=value line
                        String canonicalized = matcher.group(1).toUpperCase().replaceAll("\\.", "_");
                        Key key = Key.valueOf(enumType, canonicalized);
                        Integer index = Integer.valueOf(matcher.group(2));
                        List<String> list = arrayMap.get(key);
                        if (list == null) {
                            list = new ArrayList<String>();
                            arrayMap.put(key, list);
                        }
                        while (index >= list.size()) {
                            // insert empty strings for missing elements
                            list.add("");
                        }
                        list.set(index, fields[1]);
                    } else {
                        // this is a key=value line
                        String canonicalized = fields[0].toUpperCase().replaceAll("\\.", "_");
                        Key key = Key.valueOf(enumType, canonicalized);
                        scalarMap.put(key, fields[1]);
                    }
                }
            }
        }

    }

    /** Check if a key is contained in the map.
     * @param key parameter key
     * @return true if the key is contained in the map
     */
    public boolean containsKey(final Key key) {
        return scalarMap.containsKey(key) || arrayMap.containsKey(key);
    }

    /** Get a raw string value from a parameters map.
     * @param key parameter key
     * @return string value corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public String getString(final Key key) throws NoSuchElementException {
        final String value = scalarMap.get(key);
        if (value == null) {
            throw new NoSuchElementException(key.toString());
        }
        return value.trim();
    }

    /** Get a raw string values array from a parameters map.
     * @param key parameter key
     * @return string values array corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public String[] getStringArray(final Key key) throws NoSuchElementException {
        final List<String> list = arrayMap.get(key);
        if (list == null) {
            throw new NoSuchElementException(key.toString());
        }
        String[] array = new String[list.size()];
        for (int i = 0; i < array.length; ++i) {
            array[i] = list.get(i).trim();
        }
        return array;
    }

    /** Get a raw double value from a parameters map.
     * @param key parameter key
     * @return double value corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public double getDouble(final Key key) throws NoSuchElementException {
        return Double.parseDouble(getString(key));
    }

    /** Get a raw double values array from a parameters map.
     * @param key parameter key
     * @return double values array corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public double[] getDoubleArray(final Key key) throws NoSuchElementException {
        String[] strings = getStringArray(key);
        double[] array = new double[strings.length];
        for (int i = 0; i < array.length; ++i) {
            if (!strings[i].isEmpty())
                array[i] = Double.parseDouble(strings[i]);
            else {
                array[i] = 0.;
            }
        }
        return array;
    }

    /** Get a raw int value from a parameters map.
     * @param key parameter key
     * @return int value corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public int getInt(final Key key) throws NoSuchElementException {
        return Integer.parseInt(getString(key));
    }

    /** Get a raw int values array from a parameters map.
     * @param key parameter key
     * @return int values array corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public int[] getIntArray(final Key key) throws NoSuchElementException {
        String[] strings = getStringArray(key);
        int[] array = new int[strings.length];
        for (int i = 0; i < array.length; ++i) {
            array[i] = Integer.parseInt(strings[i]);
        }
        return array;
    }

    /** Get a raw boolean value from a parameters map.
     * @param key parameter key
     * @return boolean value corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public boolean getBoolean(final Key key) throws NoSuchElementException {
        return Boolean.parseBoolean(getString(key));
    }

    /** Get a raw boolean values array from a parameters map.
     * @param key parameter key
     * @return boolean values array corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public boolean[] getBooleanArray(final Key key) throws NoSuchElementException {
        String[] strings = getStringArray(key);
        boolean[] array = new boolean[strings.length];
        for (int i = 0; i < array.length; ++i) {
            array[i] = Boolean.parseBoolean(strings[i]);
        }
        return array;
    }

    /** Get an angle value from a parameters map.
     * <p>
     * The angle is considered to be in degrees in the file, it will be returned in radians
     * </p>
     * @param key parameter key
     * @return angular value corresponding to the key, in radians
     * @exception NoSuchElementException if key is not in the map
     */
    public double getAngle(final Key key) throws NoSuchElementException {
        return FastMath.toRadians(getDouble(key));
    }

    /** Get an angle values array from a parameters map.
     * @param key parameter key
     * @return angle values array corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public double[] getAngleArray(final Key key) throws NoSuchElementException {
        double[] array = getDoubleArray(key);
        for (int i = 0; i < array.length; ++i) {
            array[i] = FastMath.toRadians(array[i]);
        }
        return array;
    }

    /** Get a date value from a parameters map.
     * @param key parameter key
     * @param scale time scale in which the date is to be parsed
     * @return date value corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public AbsoluteDate getDate(final Key key, TimeScale scale) throws NoSuchElementException {
        return new AbsoluteDate(getString(key), scale);
    }

    /** Get a date values array from a parameters map.
     * @param key parameter key
     * @param scale time scale in which the date is to be parsed
     * @return date values array corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public AbsoluteDate[] getDateArray(final Key key, TimeScale scale) throws NoSuchElementException {
        String[] strings = getStringArray(key);
        AbsoluteDate[] array = new AbsoluteDate[strings.length];
        for (int i = 0; i < array.length; ++i) {
            array[i] = new AbsoluteDate(strings[i], scale);
        }
        return array;
    }

    /** Get a time value from a parameters map.
     * @param key parameter key
     * @return time value corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public TimeComponents getTime(final Key key) throws NoSuchElementException {
        return TimeComponents.parseTime(getString(key));
    }

    /** Get a time values array from a parameters map.
     * @param key parameter key
     * @return time values array corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public TimeComponents[] getTimeArray(final Key key) throws NoSuchElementException {
        String[] strings = getStringArray(key);
        TimeComponents[] array = new TimeComponents[strings.length];
        for (int i = 0; i < array.length; ++i) {
            array[i] = TimeComponents.parseTime(strings[i]);
        }
        return array;
    }

    /** Get a vector value from a parameters map.
     * @param xKey parameter key for abscissa
     * @param yKey parameter key for ordinate
     * @param zKey parameter key for height
     * @param scale time scale in which the date is to be parsed
     * @return date value corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public Vector3D getVector(final Key xKey, final Key yKey, final Key zKey)
        throws NoSuchElementException {
        return new Vector3D(getDouble(xKey), getDouble(yKey), getDouble(zKey));
    }

    /** Get a vector values array from a parameters map.
     * @param xKey parameter key for abscissa
     * @param yKey parameter key for ordinate
     * @param zKey parameter key for height
     * @param scale time scale in which the date is to be parsed
     * @return date value corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public Vector3D[] getVectorArray(final Key xKey, final Key yKey, final Key zKey)
        throws NoSuchElementException {
        String[] xStrings = getStringArray(xKey);
        String[] yStrings = getStringArray(yKey);
        String[] zStrings = getStringArray(zKey);
        Vector3D[] array = new Vector3D[xStrings.length];
        for (int i = 0; i < array.length; ++i) {
            array[i] = new Vector3D(Double.parseDouble(xStrings[i]),
                                    Double.parseDouble(yStrings[i]),
                                    Double.parseDouble(zStrings[i]));
        }
        return array;
    }

    /** Get a strings list from a parameters map.
     * @param key parameter key
     * @param separator elements separator
     * @return strings list value corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public List<String> getStringsList(final Key key, final char separator)
        throws NoSuchElementException {
        final String value = scalarMap.get(key);
        if (value == null) {
            throw new NoSuchElementException(key.toString());
        }
        return Arrays.asList(value.trim().split("\\s*" + separator + "\\s*"));
    }

    /** Get a strings list array from a parameters map.
     * @param key parameter key
     * @param separator elements separator
     * @return strings list array corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public List<String>[] getStringsListArray(final Key key, final char separator)
        throws NoSuchElementException {
        final String[] strings = getStringArray(key);
        @SuppressWarnings("unchecked")
        final List<String>[] array = (List<String>[]) Array.newInstance(List.class, strings.length);
        for (int i = 0; i < array.length; ++i) {
            array[i] = Arrays.asList(strings[i].trim().split("\\s*" + separator + "\\s*"));
        }
        return array;
    }

    /** Get an inertial frame from a parameters map.
     * @param key parameter key
     * @return inertial frame corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public Frame getInertialFrame(final Key key) throws NoSuchElementException, OrekitException {

        // get the name of the desired frame
        final String frameName = getString(key);

        // check the name against predefined frames
        for (Predefined predefined : Predefined.values()) {
            if (frameName.equals(predefined.getName())) {
                if (FramesFactory.getFrame(predefined).isPseudoInertial()) {
                    return FramesFactory.getFrame(predefined);
                } else {
                    throw new OrekitException(OrekitMessages.NON_PSEUDO_INERTIAL_FRAME,
                                              frameName);
                }
            }
        }

        // none of the frames match the name
        throw new OrekitException(UNKNOWN_FRAME, frameName);

    }

    /** Get an Earth frame from a parameters map.
     * <p>
     * We consider Earth frames are the frames with name starting with "ITRF".
     * </p>
     * @param key parameter key
     * @param parameters key/value map containing the parameters
     * @return Earth frame corresponding to the key
     * @exception NoSuchElementException if key is not in the map
     */
    public Frame getEarthFrame(final Key key)
            throws NoSuchElementException, OrekitException {

        // get the name of the desired frame
        final String frameName = getString(key);

        // check the name against predefined frames
        for (Predefined predefined : Predefined.values()) {
            if (frameName.equals(predefined.getName())) {
                if (predefined.toString().startsWith("ITRF") ||
                    predefined.toString().startsWith("GTOD")) {
                    return FramesFactory.getFrame(predefined);
                } else {
                    throw new OrekitException(NOT_EARTH_FRAME, frameName);
                }
            }
        }

        // none of the frames match the name
        throw new OrekitException(UNKNOWN_FRAME, frameName);

    }

}