View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.plugins.shade.pom;
20  
21  import java.io.IOException;
22  import java.io.Writer;
23  
24  import org.apache.maven.model.Model;
25  import org.jdom2.Document;
26  import org.jdom2.Element;
27  import org.jdom2.Namespace;
28  import org.jdom2.output.Format;
29  
30  /**
31   * @author Jason van Zyl
32   */
33  public class PomWriter {
34      public static void write(Writer w, Model newModel) throws IOException {
35          write(w, newModel, false);
36      }
37  
38      public static void write(Writer w, Model newModel, boolean namespaceDeclaration) throws IOException {
39          Element root = new Element("project");
40  
41          if (namespaceDeclaration) {
42              String modelVersion = newModel.getModelVersion();
43  
44              Namespace pomNamespace = Namespace.getNamespace("", "http://maven.apache.org/POM/" + modelVersion);
45  
46              root.setNamespace(pomNamespace);
47  
48              Namespace xsiNamespace = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
49  
50              root.addNamespaceDeclaration(xsiNamespace);
51  
52              if (root.getAttribute("schemaLocation", xsiNamespace) == null) {
53                  root.setAttribute(
54                          "schemaLocation",
55                          "http://maven.apache.org/POM/" + modelVersion + " http://maven.apache.org/maven-v"
56                                  + modelVersion.replace('.', '_') + ".xsd",
57                          xsiNamespace);
58              }
59          }
60  
61          Document doc = new Document(root);
62  
63          MavenJDOMWriter writer = new MavenJDOMWriter();
64  
65          String encoding = newModel.getModelEncoding() != null ? newModel.getModelEncoding() : "UTF-8";
66  
67          Format format = Format.getPrettyFormat().setEncoding(encoding);
68  
69          writer.write(newModel, doc, w, format);
70      }
71  }