}
@Test
public void testFollowsRedirects() throws Exception {
final int port = 29484;
InetSocketAddress address = new InetSocketAddress(port);
HttpServer httpServer = HttpServer.create(address, 0);
final Element expectedResponse = new Element("resource").addContent(new Element("id").setText("test"));
HttpHandler finalHandler = new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
byte[] response = Xml.getString(expectedResponse).getBytes();
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK,
response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
};
final String finalUrlPath = "/final.xml";
httpServer.createContext(finalUrlPath, finalHandler);
HttpHandler permRedirectHandler = new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
byte[] response = finalUrlPath.getBytes();
exchange.getResponseHeaders().add("location", finalUrlPath);
exchange.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_PERM,
response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
};
final String permUrlPath = "/permRedirect.xml";
httpServer.createContext(permUrlPath, permRedirectHandler);
HttpHandler tempRedirectHandler = new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
byte[] response = finalUrlPath.getBytes();
exchange.getResponseHeaders().add("location", finalUrlPath);
exchange.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_TEMP,
response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
};
final String tempUrlPath = "/tempRedirect.xml";
httpServer.createContext(tempUrlPath, tempRedirectHandler);
try {
httpServer.start();
XmlRequest xmlRequest = new GeonetHttpRequestFactory().createXmlRequest(new URL ("http://localhost:"+port+ permUrlPath));
Element response = xmlRequest.execute();
assertEquals(Xml.getString(expectedResponse), Xml.getString(response));
xmlRequest = new GeonetHttpRequestFactory().createXmlRequest(new URL ("http://localhost:"+port+ tempUrlPath));
response = xmlRequest.execute();
assertEquals(Xml.getString(expectedResponse), Xml.getString(response));
} finally {
httpServer.stop(0);
}
}