Initial EGit contribution to eclipse.org
[egit.git] / org.eclipse.egit.ui / src / org / eclipse / egit / ui / EclipseAuthenticator.java
blob0aebe09c1cdab7ba0c5da8afd27c4d27555ffb60
1 /*******************************************************************************
2 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *******************************************************************************/
9 package org.eclipse.egit.ui;
11 import java.net.Authenticator;
12 import java.net.InetAddress;
13 import java.net.PasswordAuthentication;
14 import java.net.UnknownHostException;
16 import org.eclipse.core.net.proxy.IProxyData;
17 import org.eclipse.core.net.proxy.IProxyService;
19 class EclipseAuthenticator extends Authenticator {
20 private final IProxyService service;
22 EclipseAuthenticator(final IProxyService s) {
23 service = s;
26 @Override
27 protected PasswordAuthentication getPasswordAuthentication() {
28 final IProxyData[] data = service.getProxyData();
29 if (data == null)
30 return null;
31 for (final IProxyData d : data) {
32 if (d.getUserId() == null || d.getHost() == null)
33 continue;
34 if (d.getPort() == getRequestingPort() && hostMatches(d))
35 return auth(d);
37 return null;
40 private PasswordAuthentication auth(final IProxyData d) {
41 final String user = d.getUserId();
42 final String pass = d.getPassword();
43 final char[] passChar = pass != null ? pass.toCharArray() : new char[0];
44 return new PasswordAuthentication(user, passChar);
47 private boolean hostMatches(final IProxyData d) {
48 try {
49 final InetAddress dHost = InetAddress.getByName(d.getHost());
50 InetAddress rHost = getRequestingSite();
51 if (rHost == null)
52 rHost = InetAddress.getByName(getRequestingHost());
53 return dHost.equals(rHost);
54 } catch (UnknownHostException err) {
55 return false;