/
ODataFilter.java
293 lines (255 loc) · 12 KB
/
ODataFilter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teiid.olingo.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ref.SoftReference;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.server.api.ODataHttpHandler;
import org.teiid.core.TeiidProcessingException;
import org.teiid.core.util.LRUCache;
import org.teiid.core.util.PropertiesUtils;
import org.teiid.deployers.CompositeVDB;
import org.teiid.deployers.VDBLifeCycleListener;
import org.teiid.jdbc.ConnectionImpl;
import org.teiid.logging.LogConstants;
import org.teiid.logging.LogManager;
import org.teiid.odata.api.Client;
import org.teiid.olingo.ODataPlugin;
import org.teiid.olingo.service.LocalClient;
import org.teiid.olingo.service.OlingoBridge;
import org.teiid.transport.LocalServerConnection;
import org.teiid.vdb.runtime.VDBKey;
public class ODataFilter implements Filter, VDBLifeCycleListener {
protected String proxyBaseURI;
protected Properties initProperties;
protected Map<VDBKey, SoftReference<OlingoBridge>> contextMap = Collections
.synchronizedMap(new LRUCache<VDBKey, SoftReference<OlingoBridge>>());
private volatile boolean listenerRegistered = false;
//default odata behavior requires explicit versioning
private String defaultVdbVersion = "1"; //$NON-NLS-1$
@Override
public void init(FilterConfig config) throws ServletException {
// handle proxy-uri in the case of cloud environments
String proxyURI = config.getInitParameter("proxy-base-uri"); //$NON-NLS-1$
if (proxyURI != null && proxyURI.startsWith("${") && proxyURI.endsWith("}")) { //$NON-NLS-1$ //$NON-NLS-2$
proxyURI = proxyURI.substring(2, proxyURI.length() - 1);
proxyURI = PropertiesUtils.getHierarchicalProperty(proxyURI, null);
}
if (proxyURI != null) {
this.proxyBaseURI = proxyURI;
}
String value = config.getInitParameter("explicit-vdb-version"); //$NON-NLS-1$
if (value != null && !Boolean.valueOf(value)) {
defaultVdbVersion = null;
}
Properties props = new Properties();
Enumeration<String> names = config.getServletContext().getInitParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
props.setProperty(name, config.getServletContext().getInitParameter(name));
}
names = config.getInitParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
props.setProperty(name, config.getInitParameter(name));
}
this.initProperties = props;
}
public String getDefaultVdbVersion() {
return defaultVdbVersion;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
internalDoFilter(request, response, chain);
} catch (TeiidProcessingException e) {
//TODO: use engine style logic to determine if the stack should be logged
LogManager.logWarning(LogConstants.CTX_ODATA, e, ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16047, e.getMessage()));
HttpServletResponse httpResponse = (HttpServletResponse)response;
writeError(request, e, httpResponse, 404);
}
}
static void writeError(ServletRequest request, TeiidProcessingException e,
HttpServletResponse httpResponse, int statusCode) throws IOException {
httpResponse.setStatus(statusCode);
ContentType contentType = ContentType.parse(request.getContentType());
PrintWriter writer = httpResponse.getWriter();
String code = e.getCode()==null?"":e.getCode(); //$NON-NLS-1$
String message = e.getMessage()==null?"":e.getMessage(); //$NON-NLS-1$
if (contentType == null || contentType.isCompatible(ContentType.APPLICATION_JSON)) {
httpResponse.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_JSON.toContentTypeString());
writer.write("{ \"error\": { \"code\": \""+StringEscapeUtils.escapeJson(code)+"\", \"message\": \""+StringEscapeUtils.escapeJson(message)+"\" } }"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else {
httpResponse.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_XML.toContentTypeString());
writer.write("<m:error xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\"><m:code>"+StringEscapeUtils.escapeXml10(code)+"</m:code><m:message>"+StringEscapeUtils.escapeXml10(message)+"</m:message></m:error>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
writer.close();
}
public void internalDoFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException, TeiidProcessingException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String proxyURI = this.proxyBaseURI;
if (proxyURI != null) {
httpRequest = new ProxyHttpServletRequest(httpRequest, proxyURI);
}
VDBKey key = null;
String vdbName = null;
String version = null;
String modelName = null;
String uri = httpRequest.getRequestURI().toString();
String fullURL = httpRequest.getRequestURL().toString();
if (uri.startsWith("/odata4/static/") || uri.startsWith("/odata4/keycloak/")){ //$NON-NLS-1$ //$NON-NLS-2$
chain.doFilter(httpRequest, response);
return;
}
String contextPath = httpRequest.getContextPath();
String baseURI = fullURL.substring(0, fullURL.indexOf(contextPath));
int endIdx = uri.indexOf('/', contextPath.length() + 1);
int beginIdx = contextPath.length() + 1;
if (contextPath.equals("/odata4")) { //$NON-NLS-1$
if (endIdx == -1) {
throw new TeiidProcessingException(ODataPlugin.Event.TEIID16020, ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16020));
}
baseURI = baseURI+"/odata4"; //$NON-NLS-1$
vdbName = uri.substring(beginIdx, endIdx);
int modelIdx = uri.indexOf('/', endIdx + 1);
if (modelIdx == -1) {
modelName = uri.substring(endIdx + 1).trim();
if (modelName.isEmpty()) {
throw new TeiidProcessingException(ODataPlugin.Event.TEIID16019, ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16019));
}
} else {
modelName = uri.substring(endIdx + 1, modelIdx);
}
contextPath = contextPath + "/" + vdbName + "/" + modelName; //$NON-NLS-1$ //$NON-NLS-2$
vdbName = vdbName.trim();
if (vdbName.isEmpty()) {
throw new TeiidProcessingException(ODataPlugin.Event.TEIID16008, ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16008));
}
} else {
if (this.initProperties.getProperty("vdb-name") == null) { //$NON-NLS-1$
throw new TeiidProcessingException(ODataPlugin.Event.TEIID16018, ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16018));
}
vdbName = this.initProperties.getProperty("vdb-name"); //$NON-NLS-1$
version = this.initProperties.getProperty("vdb-version"); //$NON-NLS-1$
if (endIdx == -1) {
modelName = uri.substring(beginIdx).trim();
if (modelName.isEmpty()) {
throw new TeiidProcessingException(ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16021));
}
} else {
modelName = uri.substring(beginIdx, endIdx);
}
contextPath = contextPath + "/" + modelName; //$NON-NLS-1$
}
ContextAwareHttpSerlvetRequest contextAwareRequest = new ContextAwareHttpSerlvetRequest(httpRequest);
contextAwareRequest.setContextPath(contextPath);
httpRequest = contextAwareRequest;
key = new VDBKey(vdbName, version);
if (key.isAtMost()) {
if (key.getVersion() != null) {
throw new TeiidProcessingException(ODataPlugin.Event.TEIID16044, ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16044, key));
}
key = new VDBKey(vdbName, defaultVdbVersion);
}
SoftReference<OlingoBridge> ref = this.contextMap.get(key);
OlingoBridge context = null;
if (ref != null) {
context = ref.get();
}
if (context == null) {
context = new OlingoBridge();
ref = new SoftReference<OlingoBridge>(context);
this.contextMap.put(key, ref);
}
Client client = buildClient(key.getName(), key.getVersion(), this.initProperties);
try {
Connection connection = client.open();
registerVDBListener(client, connection);
ODataHttpHandler handler = context.getHandler(baseURI, client, modelName);
httpRequest.setAttribute(ODataHttpHandler.class.getName(), handler);
httpRequest.setAttribute(Client.class.getName(), client);
chain.doFilter(httpRequest, response);
} catch(SQLException e) {
throw new TeiidProcessingException(e);
} finally {
try {
client.close();
} catch (SQLException e) {
//ignore
}
}
}
protected void registerVDBListener(Client client, Connection conn) {
if (!this.listenerRegistered) {
synchronized (this) {
if (!this.listenerRegistered) {
if (client instanceof LocalClient) {
try {
ConnectionImpl connection = (ConnectionImpl)conn;
LocalServerConnection lsc = (LocalServerConnection) connection.getServerConnection();
lsc.addListener(this);
this.listenerRegistered = true;
} catch (SQLException e) {
LogManager.logWarning(LogConstants.CTX_ODATA, ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16014));
}
}
}
}
}
}
public Client buildClient(String vdbName, String version, Properties props) {
return new LocalClient(vdbName, version, props);
}
@Override
public void destroy() {
this.contextMap.clear();
}
@Override
public void removed(String name, CompositeVDB vdb) {
this.contextMap.remove(vdb.getVDBKey());
}
@Override
public void finishedDeployment(String name, CompositeVDB vdb) {
this.contextMap.remove(vdb.getVDBKey());
}
@Override
public void beforeRemove(String name, CompositeVDB vdb) {
}
@Override
public void added(String name, CompositeVDB vdb) {
}
}