View Javadoc
1   /*
2    * Copyright 2020-2022  the original author or authors.
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  
17  package org.bremersee.xml;
18  
19  import java.io.StringReader;
20  import java.io.StringWriter;
21  import java.util.ArrayList;
22  import java.util.Collection;
23  import java.util.HashSet;
24  import java.util.LinkedHashMap;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.Optional;
28  import java.util.Set;
29  import jakarta.xml.bind.SchemaOutputResolver;
30  import javax.xml.transform.Result;
31  import javax.xml.transform.Source;
32  import javax.xml.transform.stream.StreamResult;
33  import javax.xml.transform.stream.StreamSource;
34  import lombok.AccessLevel;
35  import lombok.NoArgsConstructor;
36  
37  /**
38   * The schema sources resolver.
39   *
40   * @author Christian Bremer
41   */
42  @SuppressWarnings("SameNameButDifferent")
43  @NoArgsConstructor(access = AccessLevel.PACKAGE)
44  class SchemaSourcesResolver extends SchemaOutputResolver {
45  
46    private final Map<String, StreamResult> buffers = new LinkedHashMap<>();
47  
48    @Override
49    public Result createOutput(String namespaceUri, String suggestedFileName) {
50      StringWriter out = new StringWriter();
51      StreamResult res = new StreamResult(out);
52      res.setSystemId(suggestedFileName);
53      buffers.put(namespaceUri, res);
54      return res;
55    }
56  
57    /**
58     * To sources.
59     *
60     * @param excludedNameSpaces the excluded name spaces
61     * @return the list with the schema sources
62     */
63    List<Source> toSources(Collection<String> excludedNameSpaces) {
64      Set<String> excluded = Optional.ofNullable(excludedNameSpaces)
65          .map(HashSet::new)
66          .orElseGet(HashSet::new);
67      List<Source> sources = new ArrayList<>(buffers.size());
68      for (Map.Entry<String, StreamResult> result : buffers.entrySet()) {
69        if (!excluded.contains(result.getKey())) {
70          String systemId = result.getValue().getSystemId();
71          String schema = result.getValue().getWriter().toString();
72          StreamSource source = new StreamSource(new StringReader(schema), systemId);
73          sources.add(source);
74        }
75      }
76      return sources;
77    }
78  
79  }