| package org.eclipse.userstorage.oauth; |
| |
| import static org.junit.Assert.fail; |
| |
| import java.net.URI; |
| |
| import org.apache.http.HttpRequest; |
| import org.apache.http.HttpResponse; |
| import org.apache.http.ProtocolException; |
| import org.apache.http.client.HttpClient; |
| import org.apache.http.client.RedirectStrategy; |
| import org.apache.http.client.fluent.Executor; |
| import org.apache.http.client.fluent.Request; |
| import org.apache.http.client.methods.HttpUriRequest; |
| import org.apache.http.impl.client.HttpClients; |
| import org.apache.http.protocol.HttpContext; |
| import org.eclipse.core.runtime.IStatus; |
| import org.eclipse.userstorage.internal.oauth.UIFacade; |
| |
| /** |
| * A non-UI facade that should never open any browser etc. |
| */ |
| public class HeadlessFacade extends UIFacade { |
| private static boolean DEBUG = Boolean.getBoolean("org.eclipse.userstorage.session.debug"); |
| |
| protected final Executor executor; |
| |
| public HeadlessFacade() { |
| RedirectStrategy redirectStrategy = new RedirectStrategy() { |
| @Override |
| public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) |
| throws ProtocolException { |
| return false; |
| } |
| |
| @Override |
| public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) |
| throws ProtocolException { |
| return null; |
| } |
| }; |
| HttpClient httpClient = HttpClients.custom().setRedirectStrategy(redirectStrategy).build(); |
| executor = Executor.newInstance(httpClient); |
| } |
| |
| @Override |
| public URI obtainAuthCode(String providerName, URI startURI, URI stopURI) { |
| URI next = startURI; |
| try { |
| for (int iteration = 0; iteration < 10; iteration++) { |
| Request request = Request.Get(next); |
| HttpResponse response = executor.execute(request).returnResponse(); |
| if (response.getStatusLine().getStatusCode() != 302) { |
| fail("should only receive 302s"); |
| } |
| String redirect = response.getFirstHeader("Location").getValue(); |
| if (redirect == null) { |
| fail("Missing Location field"); |
| } |
| next = new URI(redirect); |
| if (redirect.startsWith(stopURI.toString())) { |
| return next; |
| } |
| } |
| fail("too many redirects"); |
| } catch (Exception ex) { |
| fail(ex.toString()); |
| } |
| return null; |
| } |
| |
| @Override |
| public void showError(String title, String description, IStatus status) { |
| if (DEBUG) { |
| System.err.println("ERROR: " + title); |
| System.err.println(" " + description); |
| if (status != null) { |
| System.err.println(" " + status); |
| } |
| } |
| } |
| |
| } |