argos/dmp-backend/web/src/main/java/eu/eudat/logic/proxy/Proxy.java

64 lines
2.5 KiB
Java
Raw Normal View History

2018-06-27 12:29:21 +02:00
package eu.eudat.logic.proxy;
2017-09-29 14:13:21 +02:00
2018-02-16 11:34:02 +01:00
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
2017-09-29 14:13:21 +02:00
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
2018-02-16 11:34:02 +01:00
import java.net.*;
2017-09-29 14:13:21 +02:00
@RestController
public class Proxy {
2018-02-16 11:34:02 +01:00
private String allowedHost;
public Proxy(String allowedHost) throws MalformedURLException {
this.allowedHost = new URL(allowedHost).getHost();
}
public Proxy() {
2017-12-15 00:01:26 +01:00
2018-02-16 11:34:02 +01:00
}
2018-06-27 12:29:21 +02:00
@RequestMapping(method = RequestMethod.GET, value = {"/eu/eudat/logic/proxy"}, produces = "application/json")
2018-02-16 11:34:02 +01:00
public @ResponseBody
ResponseEntity<Object> proxy(@RequestParam("url") String remoteUrl) {
StringBuffer response = new StringBuffer();
URL url;
try {
URL tempUrl = new URL(remoteUrl);
2017-09-29 14:13:21 +02:00
// URI uri = new URI(scheme, userInfo, host, port, path, query, fragment);
2018-02-16 11:34:02 +01:00
URI uri = new URI(tempUrl.getProtocol(), null, tempUrl.getHost(), tempUrl.getPort(), tempUrl.getPath(), (tempUrl.getQuery() != null) ? URLEncoder.encode(tempUrl.getQuery()) : null, tempUrl.getRef());
url = uri.toURL();
if (!url.getHost().equals(allowedHost))
2018-06-27 12:29:21 +02:00
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{'reason': 'You are not allowed to eu.eudat.logic.proxy -> " + url.getHost() + "'}");
2018-02-16 11:34:02 +01:00
//if allowed, proceed
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/vnd.api+json; charset=utf-8");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return ResponseEntity.status(HttpStatus.OK).body(response.toString());
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{'reason': 'Remote server responded with: " + responseCode + "'}");
}
} catch (IOException | URISyntaxException e) {
2018-06-27 12:29:21 +02:00
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{'reason': 'Could not eu.eudat.logic.proxy to given host'}");
2018-02-16 11:34:02 +01:00
}
}
2017-09-29 14:13:21 +02:00
}