1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.mail2.jakarta.resolver;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.net.MalformedURLException;
22 import java.net.URL;
23
24 import org.apache.commons.mail2.core.EmailUtils;
25
26 import jakarta.activation.DataSource;
27 import jakarta.activation.URLDataSource;
28
29
30
31
32
33
34 public class DataSourceUrlResolver extends DataSourceBaseResolver {
35
36
37 private final URL baseUrl;
38
39
40
41
42
43
44 public DataSourceUrlResolver(final URL baseUrl) {
45 this.baseUrl = baseUrl;
46 }
47
48
49
50
51
52
53
54 public DataSourceUrlResolver(final URL baseUrl, final boolean lenient) {
55 super(lenient);
56 this.baseUrl = baseUrl;
57 }
58
59
60
61
62
63
64
65
66 protected URL createUrl(final String resourceLocation) throws MalformedURLException {
67
68
69 if (baseUrl == null) {
70 return new URL(resourceLocation);
71 }
72
73 if (EmailUtils.isEmpty(resourceLocation)) {
74 throw new IllegalArgumentException("No resource defined");
75 }
76
77 if (isFileUrl(resourceLocation) || isHttpUrl(resourceLocation)) {
78 return new URL(resourceLocation);
79 }
80 return new URL(getBaseUrl(), resourceLocation.replace("&", "&"));
81 }
82
83
84
85
86
87
88 public URL getBaseUrl() {
89 return baseUrl;
90 }
91
92
93 @Override
94 public DataSource resolve(final String resourceLocation) throws IOException {
95 return resolve(resourceLocation, isLenient());
96 }
97
98
99 @Override
100 public DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException {
101 DataSource result = null;
102 try {
103 if (!isCid(resourceLocation)) {
104 result = new URLDataSource(createUrl(resourceLocation));
105
106 try (InputStream inputStream = result.getInputStream()) {
107 inputStream.read();
108 }
109 }
110 return result;
111 } catch (final IOException e) {
112 if (isLenient) {
113 return null;
114 }
115 throw e;
116 }
117 }
118 }