OptionalFormat.java
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 static java.util.Objects.requireNonNull;
23 
24 import java.text.ParsePosition;
25 import java.util.List;
26 import java.util.Optional;
27 
28 /**
29  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
30  @version 2.2
31  @since 1.4
32  */
33 class OptionalFormat implements Format {
34 
35     private final Format _format;
36 
37     private OptionalFormat(final Format format) {
38         _format = requireNonNull(format);
39     }
40 
41     @Override
42     public Optional<String> format(final Location value) {
43         return Optional.of(_format.format(value).orElse(""));
44     }
45 
46     @Override
47     public void parse(
48         final CharSequence in,
49         final ParsePosition pos,
50         final LocationBuilder builder
51     ) {
52         int index = pos.getIndex();
53         int errorIndex = pos.getErrorIndex();
54         LocationBuilder before = builder.copy();
55 
56         try {
57             _format.parse(in, pos, builder);
58         catch (ParseException e){
59             builder.copy(before);
60             pos.setIndex(index);
61             pos.setErrorIndex(errorIndex);
62         }
63     }
64 
65     @Override
66     public String toPattern() {
67         return String.format("[%s]", _format.toPattern());
68     }
69 
70     static OptionalFormat of(final List<Format> formats) {
71         return new OptionalFormat(CompositeFormat.of(formats));
72     }
73 
74 }