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.URL;
22
23 import jakarta.activation.DataSource;
24 import jakarta.activation.FileTypeMap;
25 import jakarta.mail.util.ByteArrayDataSource;
26
27
28
29
30
31
32 public class DataSourceClassPathResolver extends DataSourceBaseResolver {
33
34 private final String classPathBase;
35
36
37
38
39 public DataSourceClassPathResolver() {
40 this("/");
41 }
42
43
44
45
46
47
48 public DataSourceClassPathResolver(final String classPathBase) {
49 this(classPathBase, false);
50 }
51
52
53
54
55
56
57
58 public DataSourceClassPathResolver(final String classPathBase, final boolean lenient) {
59 super(lenient);
60 this.classPathBase = classPathBase.endsWith("/") ? classPathBase : classPathBase + "/";
61 }
62
63
64
65
66
67
68 public String getClassPathBase() {
69 return classPathBase;
70 }
71
72
73
74
75
76
77
78
79 private String getResourceName(final String resourceLocation) {
80 return (getClassPathBase() + resourceLocation).replace("//", "/");
81 }
82
83
84 @Override
85 public DataSource resolve(final String resourceLocation) throws IOException {
86 return resolve(resourceLocation, isLenient());
87 }
88
89
90 @Override
91 public DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException {
92 try {
93 if (!isCid(resourceLocation) && !isHttpUrl(resourceLocation)) {
94 final String mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(resourceLocation);
95 final String resourceName = getResourceName(resourceLocation);
96 try (InputStream inputStream = DataSourceClassPathResolver.class.getResourceAsStream(resourceName)) {
97 if (inputStream == null) {
98 if (isLenient) {
99 return null;
100 }
101 throw new IOException("The following class path resource was not found : " + resourceLocation);
102 }
103 final ByteArrayDataSource ds = new ByteArrayDataSource(inputStream, mimeType);
104
105
106 final URL resource = DataSourceClassPathResolver.class.getResource(resourceName);
107 if (resource != null) {
108 ds.setName(resource.toString());
109 } else if (isLenient) {
110 return null;
111 } else {
112 throw new IOException("The following class path resource was not found : " + resourceName);
113 }
114 return ds;
115 }
116 }
117 return null;
118 } catch (final IOException e) {
119 if (isLenient) {
120 return null;
121 }
122 throw e;
123 }
124 }
125 }