1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.internal.impl;
20
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.io.Reader;
24 import java.io.Writer;
25
26 import org.apache.maven.api.annotations.Nonnull;
27 import org.apache.maven.api.di.Named;
28 import org.apache.maven.api.di.Singleton;
29 import org.apache.maven.api.services.xml.SettingsXmlFactory;
30 import org.apache.maven.api.services.xml.XmlReaderException;
31 import org.apache.maven.api.services.xml.XmlReaderRequest;
32 import org.apache.maven.api.services.xml.XmlWriterException;
33 import org.apache.maven.api.services.xml.XmlWriterRequest;
34 import org.apache.maven.api.settings.InputSource;
35 import org.apache.maven.api.settings.Settings;
36 import org.apache.maven.settings.v4.SettingsStaxReader;
37 import org.apache.maven.settings.v4.SettingsStaxWriter;
38
39 import static org.apache.maven.internal.impl.StaxLocation.getLocation;
40 import static org.apache.maven.internal.impl.StaxLocation.getMessage;
41
42 @Named
43 @Singleton
44 public class DefaultSettingsXmlFactory implements SettingsXmlFactory {
45 @Override
46 public Settings read(@Nonnull XmlReaderRequest request) throws XmlReaderException {
47 nonNull(request, "request");
48 Reader reader = request.getReader();
49 InputStream inputStream = request.getInputStream();
50 if (reader == null && inputStream == null) {
51 throw new IllegalArgumentException("reader or inputStream must be non null");
52 }
53 try {
54 InputSource source = null;
55 if (request.getModelId() != null || request.getLocation() != null) {
56 source = new InputSource(request.getLocation());
57 }
58 SettingsStaxReader xml = new SettingsStaxReader();
59 xml.setAddDefaultEntities(request.isAddDefaultEntities());
60 if (reader != null) {
61 return xml.read(reader, request.isStrict(), source);
62 } else {
63 return xml.read(inputStream, request.isStrict(), source);
64 }
65 } catch (Exception e) {
66 throw new XmlReaderException("Unable to read settings: " + getMessage(e), getLocation(e), e);
67 }
68 }
69
70 @Override
71 public void write(XmlWriterRequest<Settings> request) throws XmlWriterException {
72 nonNull(request, "request");
73 Settings content = nonNull(request.getContent(), "content");
74 OutputStream outputStream = request.getOutputStream();
75 Writer writer = request.getWriter();
76 if (writer == null && outputStream == null) {
77 throw new IllegalArgumentException("writer or outputStream must be non null");
78 }
79 try {
80 if (writer != null) {
81 new SettingsStaxWriter().write(writer, content);
82 } else {
83 new SettingsStaxWriter().write(outputStream, content);
84 }
85 } catch (Exception e) {
86 throw new XmlWriterException("Unable to write settings: " + getMessage(e), getLocation(e), e);
87 }
88 }
89
90 static <T> T nonNull(T t, String name) {
91 if (t == null) {
92 throw new IllegalArgumentException(name + " cannot be null");
93 }
94 return t;
95 }
96 }