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 jakarta.xml.bind.SchemaOutputResolver;
20  import java.io.StringReader;
21  import java.io.StringWriter;
22  import java.util.ArrayList;
23  import java.util.Collection;
24  import java.util.HashSet;
25  import java.util.LinkedHashMap;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.Optional;
29  import java.util.Set;
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  @NoArgsConstructor(access = AccessLevel.PACKAGE)
43  class SchemaSourcesResolver extends SchemaOutputResolver {
44  
45    private final Map<String, StreamResult> buffers = new LinkedHashMap<>();
46  
47    @Override
48    public Result createOutput(String namespaceUri, String suggestedFileName) {
49      StringWriter out = new StringWriter();
50      StreamResult res = new StreamResult(out);
51      res.setSystemId(suggestedFileName);
52      buffers.put(namespaceUri, res);
53      return res;
54    }
55  
56    /**
57     * To sources.
58     *
59     * @param excludedNameSpaces the excluded name spaces
60     * @return the list with the schema sources
61     */
62    List<Source> toSources(Collection<String> excludedNameSpaces) {
63      Set<String> excluded = Optional.ofNullable(excludedNameSpaces)
64          .map(HashSet::new)
65          .orElseGet(HashSet::new);
66      List<Source> sources = new ArrayList<>(buffers.size());
67      for (Map.Entry<String, StreamResult> result : buffers.entrySet()) {
68        if (!excluded.contains(result.getKey())) {
69          String systemId = result.getValue().getSystemId();
70          String schema = result.getValue().getWriter().toString();
71          StreamSource source = new StreamSource(new StringReader(schema), systemId);
72          sources.add(source);
73        }
74      }
75      return sources;
76    }
77  
78  }