Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ce37831

Browse files
committed
Move my mods into a sub-class of ProxyServlet.java
1 parent 774a4c0 commit ce37831

File tree

2 files changed

+95
-18
lines changed

2 files changed

+95
-18
lines changed

src/main/java/snoopware/api/ProxyServlet.java

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,7 @@
4141
import java.util.BitSet;
4242
import java.util.Enumeration;
4343
import java.util.Formatter;
44-
import javax.servlet.annotation.WebInitParam;
45-
import javax.servlet.annotation.WebServlet;
44+
import java.util.logging.Level;
4645

4746
/**
4847
* An HTTP reverse proxy/gateway servlet. It is designed to be extended for customization if
@@ -62,16 +61,9 @@
6261
* </p>
6362
*
6463
* @author David Smiley [email protected]
65-
* @author Dave Johnson ([email protected]) - my mods are marked with DMJ
6664
*/
67-
@WebServlet( // DMJ
68-
name = "usergridProxy", urlPatterns = {"/api/*"},
69-
initParams={
70-
@WebInitParam(name="log", value="true"),
71-
@WebInitParam(name="targetUri", value="https://api.usergrid.com/")
72-
})
73-
public class ProxyServlet extends HttpServlet {
7465

66+
public class ProxyServlet extends HttpServlet {
7567
/* INIT PARAMETER NAME CONSTANTS */
7668
/**
7769
* A boolean parameter name to enable logging of input and target URLs to the servlet log.
@@ -174,7 +166,7 @@ protected void service(HttpServletRequest servletRequest, HttpServletResponse se
174166
try {
175167
// Execute the request
176168
if (doLog) {
177-
log("proxy " + method + " uri: " + servletRequest.getRequestURI()
169+
log("proxy " + method + " uri: " + servletRequest.getRequestURL().toString()
178170
+ " -- " + proxyRequest.getRequestLine().getUri());
179171
}
180172
HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);
@@ -256,7 +248,7 @@ protected void closeQuietly(Closeable closeable) {
256248
try {
257249
closeable.close();
258250
} catch (IOException e) {
259-
log(e.getMessage(), e);
251+
log(e.getMessage());
260252
}
261253
}
262254
/**
@@ -342,7 +334,7 @@ protected void copyResponseEntity(HttpResponse proxyResponse,
342334
* Reads the request URI from {@code servletRequest} and rewrites it, considering {@link
343335
* #targetUri}. It's used to make the new request.
344336
*/
345-
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
337+
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
346338
StringBuilder uri = new StringBuilder(500);
347339
uri.append(this.targetUri.toString());
348340
// Handle the path given to the servlet
@@ -452,9 +444,4 @@ protected static CharSequence encodeUriQuery(CharSequence in) {
452444

453445
asciiQueryChars.set((int) '%');//leave existing percent escapes in place
454446
}
455-
456-
@Override
457-
public void log(String msg) { // DMJ
458-
System.out.println(msg);
459-
}
460447
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
* Copyright 2013 David M. Johnson ([email protected]).
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package snoopware.api;
17+
18+
import java.io.IOException;
19+
import java.util.Properties;
20+
import java.util.logging.Level;
21+
import java.util.logging.Logger;
22+
import javax.servlet.ServletConfig;
23+
import javax.servlet.ServletException;
24+
import javax.servlet.annotation.WebInitParam;
25+
import javax.servlet.annotation.WebServlet;
26+
import javax.servlet.http.HttpServletRequest;
27+
import org.apache.http.HttpRequest;
28+
import org.usergrid.java.client.Client;
29+
30+
/**
31+
* Proxy all requests to UserGrid and to add credentials to /users GET and POST requests.
32+
* @author David M. Johnson ([email protected])
33+
*/
34+
@WebServlet(
35+
name = "usergridProxy", urlPatterns = {"/api/*"},
36+
initParams={
37+
@WebInitParam(name="log", value="true"),
38+
@WebInitParam(name="targetUri", value="https://api.usergrid.com")
39+
})
40+
@SuppressWarnings("serial")
41+
public class UserGridProxyServlet extends ProxyServlet {
42+
protected static final Logger log = Logger.getLogger(ProxyServlet.class.getName());
43+
44+
private Client userGridClient;
45+
private String applicationName;
46+
47+
/**
48+
* Override to authorized UserGrid client with creds from app.propeties.
49+
*/
50+
@Override
51+
public void init(ServletConfig servletConfig) throws ServletException {
52+
super.init(servletConfig);
53+
Properties properties = new Properties();
54+
try {
55+
properties.load(getClass().getResourceAsStream("/app.properties"));
56+
57+
applicationName = (String)properties.get("app.applicationName");
58+
String organizationId = (String)properties.get("app.organizationId");
59+
String applicationId = (String)properties.get("app.applicationId");
60+
userGridClient = new Client(organizationId, applicationId);
61+
62+
String clientId = (String)properties.get("app.clientId");
63+
String clientSecret = (String)properties.get("app.clientSecret");
64+
userGridClient.authorizeAppClient(clientId, clientSecret);
65+
66+
} catch (IOException ex) {
67+
log.log(Level.SEVERE, "Unable to load app.properties and authorize the client", ex);
68+
}
69+
}
70+
71+
/**
72+
* Override to add Authorization to requests that need it.
73+
*/
74+
@Override
75+
protected void copyRequestHeaders(HttpServletRequest req, HttpRequest proxyReq) {
76+
super.copyRequestHeaders(req, proxyReq);
77+
78+
boolean hasAccessToken = req.getQueryString() == null
79+
? false : req.getQueryString().contains("access_token=");
80+
81+
if (!hasAccessToken
82+
&& ("POST".equals(req.getMethod()) || "GET".equals(req.getMethod()))
83+
&& req.getPathInfo().contains("/" + applicationName + "/users")) {
84+
85+
String header = "Bearer " + userGridClient.getAccessToken();
86+
proxyReq.setHeader("Authorization", header);
87+
log.log(Level.INFO, "Added header = {0}", header);
88+
}
89+
}
90+
}

0 commit comments

Comments
 (0)