01 /*
02 * Java GPX Library (jpx-3.1.0).
03 * Copyright (c) 2016-2023 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19 */
20 package io.jenetics.jpx.format;
21
22 import java.text.ParsePosition;
23 import java.util.List;
24 import java.util.Optional;
25 import java.util.stream.Collectors;
26
27 /**
28 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
29 * @version 2.2
30 * @since 1.4
31 */
32 class CompositeFormat implements Format {
33
34 private final List<Format> _formats;
35
36 private CompositeFormat(final List<Format> formats) {
37 _formats = List.copyOf(formats);
38 }
39
40 @Override
41 public Optional<String> format(final Location value) {
42 final List<Optional<String>> strings = _formats.stream()
43 .map(format -> format.format(value))
44 .toList();
45
46 final boolean complete = strings.stream().allMatch(Optional::isPresent);
47 return complete
48 ? Optional.of(
49 strings.stream()
50 .map(s -> s.orElseThrow(AssertionError::new))
51 .collect(Collectors.joining()))
52 : Optional.empty();
53 }
54
55 @Override
56 public void parse(
57 final CharSequence in,
58 final ParsePosition pos,
59 final LocationBuilder builder
60 ) {
61 for(var format : _formats) {
62 format.parse(in, pos, builder);
63 }
64 }
65
66 @Override
67 public String toPattern() {
68 return _formats.stream()
69 .map(Format::toPattern)
70 .collect(Collectors.joining());
71 }
72
73 static CompositeFormat of(final List<Format> formats) {
74 return new CompositeFormat(formats);
75 }
76
77 }
|