Example usage for java.net Authenticator setDefault

List of usage examples for java.net Authenticator setDefault

Introduction

In this page you can find the example usage for java.net Authenticator setDefault.

Prototype

public static synchronized void setDefault(Authenticator a) 

Source Link

Document

Sets the authenticator that will be used by the networking code when a proxy or an HTTP server asks for authentication.

Usage

From source file:org.couchpotato.CouchPotato.java

private CouchPotato(String scheme, String hostname, int port, String path, String api, String username,
        String password, boolean trustAll, String trustMe) {
    this.scheme = scheme;
    this.hostName = hostname;
    this.port = port;
    this.path = path;
    this.api = api;
    this.username = username;
    this.password = password;
    this.trustAll = trustAll;

    if (this.username == null)
        this.username = "";
    if (this.password == null)
        this.password = "";

    // Configure SSL behavior based on user preferences
    Authenticator.setDefault(new CouchAuthenticator(username, password, hostname));
    HostnameVerifier verifier;/*from w  w w. j  a  va  2 s  . c  om*/
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (NoSuchAlgorithmException e) {

    } catch (KeyManagementException e) {

    } catch (KeyStoreException e) {

    }
}

From source file:com.adaptris.core.http.client.net.HttpRequestServiceImpl.java

public HttpRequestServiceImpl() {
    super();//  w  w  w . jav  a2s . co m
    Authenticator.setDefault(AdapterResourceAuthenticator.getInstance());
    setResponseHeaderHandler(new DiscardResponseHeaders());
    setRequestHeaderProvider(new NoRequestHeaders());
    setContentType("text/plain");
    setMethod("POST");
}

From source file:com.motorola.studio.android.common.utilities.HttpUtils.java

private InputStream getInputStreamForUrl(String url, IProgressMonitor monitor, boolean returnStream)
        throws IOException {
    SubMonitor subMonitor = SubMonitor.convert(monitor);

    subMonitor.beginTask(UtilitiesNLS.HttpUtils_MonitorTask_PreparingConnection, 300);

    StudioLogger.debug(HttpUtils.class, "Verifying proxy usage for opening http connection"); //$NON-NLS-1$

    // Try to retrieve proxy configuration to use if necessary
    IProxyService proxyService = ProxyManager.getProxyManager();
    IProxyData proxyData = null;/*from  ww w  .  ja  v a2s  .c  o m*/
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new NetAuthenticator());
        if (url.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            StudioLogger.debug(HttpUtils.class, "Using https proxy"); //$NON-NLS-1$
        } else if (url.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            StudioLogger.debug(HttpUtils.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            StudioLogger.debug(HttpUtils.class, "Not using any proxy"); //$NON-NLS-1$
        }
    }

    // Creates the http client and the method to be executed
    HttpClient client = null;
    client = new HttpClient();

    // If there is proxy data, work with it
    if (proxyData != null) {
        if (proxyData.getHost() != null) {
            // Sets proxy host and port, if any
            client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort());
        }

        if ((proxyData.getUserId() != null) && (proxyData.getUserId().trim().length() > 0)) {
            // Sets proxy user and password, if any
            Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(),
                    proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$
            client.getState().setProxyCredentials(AuthScope.ANY, cred);
        }
    }

    InputStream streamForUrl = null;
    getMethod = new GetMethod(url);
    getMethod.setFollowRedirects(true);

    // set a 30 seconds timeout
    HttpMethodParams params = getMethod.getParams();
    params.setSoTimeout(15 * ONE_SECOND);
    getMethod.setParams(params);

    boolean trying = true;
    Credentials credentials = null;
    subMonitor.worked(100);
    subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_ContactingSite);
    do {
        StudioLogger.info(HttpUtils.class, "Attempting to make a connection"); //$NON-NLS-1$

        // retry to connect to the site once, also set the timeout for 5 seconds
        HttpClientParams clientParams = client.getParams();
        clientParams.setIntParameter(HttpClientParams.MAX_REDIRECTS, 1);
        clientParams.setSoTimeout(5 * ONE_SECOND);
        client.setParams(clientParams);

        client.executeMethod(getMethod);
        if (subMonitor.isCanceled()) {
            break;
        } else {
            AuthState authorizationState = getMethod.getHostAuthState();
            String authenticationRealm = authorizationState.getRealm();

            if (getMethod.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                StudioLogger.debug(HttpUtils.class, "Client requested authentication; retrieving credentials"); //$NON-NLS-1$

                credentials = authenticationRealmCache.get(authenticationRealm);

                if (credentials == null) {
                    StudioLogger.debug(HttpUtils.class,
                            "Credentials not found; prompting user for login/password"); //$NON-NLS-1$

                    subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_WaitingAuthentication);

                    LoginPasswordDialogCreator dialogCreator = new LoginPasswordDialogCreator(url);
                    if (dialogCreator.openLoginPasswordDialog() == LoginPasswordDialogCreator.OK) {

                        credentials = new UsernamePasswordCredentials(dialogCreator.getTypedLogin(),
                                dialogCreator.getTypedPassword());
                    } else {
                        // cancel pressed; stop trying
                        trying = false;

                        // set the monitor canceled to be able to stop process
                        subMonitor.setCanceled(true);
                    }

                }

                if (credentials != null) {
                    AuthScope scope = new AuthScope(null, -1, authenticationRealm);
                    client.getState().setCredentials(scope, credentials);
                }

                subMonitor.worked(100);
            } else if (getMethod.getStatusCode() == HttpStatus.SC_OK) {
                StudioLogger.debug(HttpUtils.class, "Http connection suceeded"); //$NON-NLS-1$

                subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_RetrievingSiteContent);
                if ((authenticationRealm != null) && (credentials != null)) {
                    authenticationRealmCache.put(authenticationRealm, credentials);
                } else {
                    // no authentication was necessary, just work the monitor
                    subMonitor.worked(100);
                }

                StudioLogger.info(HttpUtils.class, "Retrieving site content"); //$NON-NLS-1$

                // if the stream should not be returned (ex: only testing the connection is
                // possible), then null will be returned
                if (returnStream) {
                    streamForUrl = getMethod.getResponseBodyAsStream();
                }

                // succeeded; stop trying
                trying = false;

                subMonitor.worked(100);
            } else {
                // unhandled return status code
                trying = false;

                subMonitor.worked(200);
            }
        }
    } while (trying);

    subMonitor.done();

    return streamForUrl;
}

From source file:org.eclipse.andmore.android.common.utilities.HttpUtils.java

private InputStream getInputStreamForUrl(String url, IProgressMonitor monitor, boolean returnStream)
        throws IOException {
    SubMonitor subMonitor = SubMonitor.convert(monitor);

    subMonitor.beginTask(UtilitiesNLS.HttpUtils_MonitorTask_PreparingConnection, 300);

    AndmoreLogger.debug(HttpUtils.class, "Verifying proxy usage for opening http connection"); //$NON-NLS-1$

    // Try to retrieve proxy configuration to use if necessary
    IProxyService proxyService = ProxyManager.getProxyManager();
    IProxyData proxyData = null;/*from w w w.java  2  s. c o  m*/
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new NetAuthenticator());
        if (url.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            AndmoreLogger.debug(HttpUtils.class, "Using https proxy"); //$NON-NLS-1$
        } else if (url.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            AndmoreLogger.debug(HttpUtils.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            AndmoreLogger.debug(HttpUtils.class, "Not using any proxy"); //$NON-NLS-1$
        }
    }

    // Creates the http client and the method to be executed
    HttpClient client = null;
    client = new HttpClient();

    // If there is proxy data, work with it
    if (proxyData != null) {
        if (proxyData.getHost() != null) {
            // Sets proxy host and port, if any
            client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort());
        }

        if ((proxyData.getUserId() != null) && (proxyData.getUserId().trim().length() > 0)) {
            // Sets proxy user and password, if any
            Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(),
                    proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$
            client.getState().setProxyCredentials(AuthScope.ANY, cred);
        }
    }

    InputStream streamForUrl = null;
    getMethod = new GetMethod(url);
    getMethod.setFollowRedirects(true);

    // set a 30 seconds timeout
    HttpMethodParams params = getMethod.getParams();
    params.setSoTimeout(15 * ONE_SECOND);
    getMethod.setParams(params);

    boolean trying = true;
    Credentials credentials = null;
    subMonitor.worked(100);
    subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_ContactingSite);
    do {
        AndmoreLogger.info(HttpUtils.class, "Attempting to make a connection"); //$NON-NLS-1$

        // retry to connect to the site once, also set the timeout for 5
        // seconds
        HttpClientParams clientParams = client.getParams();
        clientParams.setIntParameter(HttpClientParams.MAX_REDIRECTS, 1);
        clientParams.setSoTimeout(5 * ONE_SECOND);
        client.setParams(clientParams);

        client.executeMethod(getMethod);
        if (subMonitor.isCanceled()) {
            break;
        } else {
            AuthState authorizationState = getMethod.getHostAuthState();
            String authenticationRealm = authorizationState.getRealm();

            if (getMethod.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                AndmoreLogger.debug(HttpUtils.class, "Client requested authentication; retrieving credentials"); //$NON-NLS-1$

                credentials = authenticationRealmCache.get(authenticationRealm);

                if (credentials == null) {
                    AndmoreLogger.debug(HttpUtils.class,
                            "Credentials not found; prompting user for login/password"); //$NON-NLS-1$

                    subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_WaitingAuthentication);

                    LoginPasswordDialogCreator dialogCreator = new LoginPasswordDialogCreator(url);
                    if (dialogCreator.openLoginPasswordDialog() == LoginPasswordDialogCreator.OK) {

                        credentials = new UsernamePasswordCredentials(dialogCreator.getTypedLogin(),
                                dialogCreator.getTypedPassword());
                    } else {
                        // cancel pressed; stop trying
                        trying = false;

                        // set the monitor canceled to be able to stop
                        // process
                        subMonitor.setCanceled(true);
                    }

                }

                if (credentials != null) {
                    AuthScope scope = new AuthScope(null, -1, authenticationRealm);
                    client.getState().setCredentials(scope, credentials);
                }

                subMonitor.worked(100);
            } else if (getMethod.getStatusCode() == HttpStatus.SC_OK) {
                AndmoreLogger.debug(HttpUtils.class, "Http connection suceeded"); //$NON-NLS-1$

                subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_RetrievingSiteContent);
                if ((authenticationRealm != null) && (credentials != null)) {
                    authenticationRealmCache.put(authenticationRealm, credentials);
                } else {
                    // no authentication was necessary, just work the
                    // monitor
                    subMonitor.worked(100);
                }

                AndmoreLogger.info(HttpUtils.class, "Retrieving site content"); //$NON-NLS-1$

                // if the stream should not be returned (ex: only testing
                // the connection is
                // possible), then null will be returned
                if (returnStream) {
                    streamForUrl = getMethod.getResponseBodyAsStream();
                }

                // succeeded; stop trying
                trying = false;

                subMonitor.worked(100);
            } else {
                // unhandled return status code
                trying = false;

                subMonitor.worked(200);
            }
        }
    } while (trying);

    subMonitor.done();

    return streamForUrl;
}

From source file:com.cisco.dvbu.ps.common.util.wsapi.CisApiFactory.java

/**
 * Returns the ResourcePort of AdminAPI/*w w w . j av a 2 s  .  co  m*/
 * @param server Composite Server
 * @return ResourcePort of AdminAPI
 */
public static ResourcePortType getResourcePort(CompositeServer server) {

    Authenticator.setDefault(new BasicAuthenticator(server));

    URL url = null;
    String protocol = "http";
    int wsPort = server.getPort();
    if (server.isUseHttps()) {
        protocol = "https";
        wsPort += 2;
    }
    try {
        url = new URL(protocol + "://" + server.getHostname() + ":" + wsPort + "/services/system/admin?wsdl");
        if (logger.isDebugEnabled()) {
            logger.debug("Entering CisApiFactory.getResourcePort() with following params " + " url: " + url);
        }
    } catch (MalformedURLException e) {
        String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                "Creating Resource Port", "Admin API", "ExecutePort", server);
        CompositeLogger.logException(e, errorMessage);
        throw new CompositeException(errorMessage, e);
    }

    int retry = 0;
    while (retry < numRetries) {
        retry++;
        try {
            Resource res = new Resource(url, new QName(nsResourceUrl, nsResourceName)); // Get the connection to the server.      
            if (logger.isDebugEnabled()) {
                if (res != null)
                    logger.debug("Entering CisApiFactory.getResourcePort(). Resource acquired " + " Resource: "
                            + res.toString());
            }
            ResourcePortType port = res.getResourcePort(); // Get the server port
            if (logger.isDebugEnabled()) {
                if (port != null)
                    logger.debug("Entering CisApiFactory.getResourcePort(). Port acquired " + " Port: "
                            + port.toString());
            }
            return port; // Return the port connection to the server.
        } catch (Exception e) {
            String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                    "Getting Server Port, [CONNECT ATTEMPT=" + retry + "]", "Admin API", "ServerPort", server);
            if (retry == numRetries) {
                throw new CompositeException(errorMessage, e);
            } else {
                // Log the error and sleep before retrying
                CompositeLogger.logException(e, errorMessage);
                Sleep.sleep(sleepDebug, sleepRetry);
            }
        }
    }
    throw new CompositeException(
            "Maximum connection attempts reached without connecting to the Composite Information Server.");

}

From source file:com.liferay.ide.server.remote.RemoteLogStream.java

protected static InputStream openInputStream(IServerManagerConnection remote, URL url) throws IOException {
    String username = remote.getUsername();
    String password = remote.getPassword();

    String authString = username + ":" + password; //$NON-NLS-1$
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    final IProxyService proxyService = LiferayCore.getProxyService();
    URLConnection conn = null;//from w  ww . j a  v  a  2s  . c o  m

    try {
        URI uri = new URI("HTTP://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
        IProxyData[] proxyDataForHost = proxyService.select(uri);

        for (IProxyData data : proxyDataForHost) {
            if (data.getHost() != null) {
                System.setProperty("http.proxyHost", data.getHost()); //$NON-NLS-1$
                System.setProperty("http.proxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$

                break;
            }
        }

        uri = new URI("SOCKS://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
        proxyDataForHost = proxyService.select(uri);

        for (IProxyData data : proxyDataForHost) {
            if (data.getHost() != null) {
                System.setProperty("socksProxyHost", data.getHost()); //$NON-NLS-1$
                System.setProperty("socksProxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$

                break;
            }
        }
    } catch (URISyntaxException e) {
        LiferayServerCore.logError("Could not read proxy data", e); //$NON-NLS-1$
    }

    conn = url.openConnection();
    conn.setRequestProperty("Authorization", "Basic " + authStringEnc); //$NON-NLS-1$ //$NON-NLS-2$
    Authenticator.setDefault(null);
    conn.setAllowUserInteraction(false);

    return conn.getInputStream();
}

From source file:net.sf.jabref.JabRef.java

public void start(String[] args) {
    JabRefPreferences preferences = JabRefPreferences.getInstance();

    ProxyPreferences proxyPreferences = ProxyPreferences.loadFromPreferences(preferences);
    ProxyRegisterer.register(proxyPreferences);
    if (proxyPreferences.isUseProxy() && proxyPreferences.isUseAuthentication()) {
        Authenticator.setDefault(new ProxyAuthenticator());
    }//from   ww w.  j  ava  2 s  .c o m

    Globals.startBackgroundTasks();
    Globals.prefs = preferences;
    Localization.setLanguage(preferences.get(JabRefPreferences.LANGUAGE));
    Globals.prefs.setLanguageDependentDefaultValues();

    // Update which fields should be treated as numeric, based on preferences:
    InternalBibtexFields.setNumericFieldsFromPrefs();

    /* Build list of Import and Export formats */
    Globals.importFormatReader.resetImportFormats();
    CustomEntryTypesManager.loadCustomEntryTypes(preferences);
    ExportFormats.initAllExports();

    // Read list(s) of journal names and abbreviations
    Globals.journalAbbreviationLoader = new JournalAbbreviationLoader(Globals.prefs);

    // Check for running JabRef
    RemotePreferences remotePreferences = new RemotePreferences(Globals.prefs);
    if (remotePreferences.useRemoteServer()) {

        Globals.remoteListener.open(new JabRefMessageHandler(this), remotePreferences.getPort());

        if (Globals.remoteListener.isOpen()) {
            Globals.remoteListener.start(); // we are alone, we start the server
        } else {
            // we are not alone, there is already a server out there, try to contact already running JabRef:
            if (RemoteListenerClient.sendToActiveJabRefInstance(args, remotePreferences.getPort())) {
                /*
                 * We have successfully sent our command line options
                 * through the socket to another JabRef instance. So we
                 * assume it's all taken care of, and quit.
                 */
                System.out.println(
                        Localization.lang("Arguments passed on to running JabRef instance. Shutting down."));
                JabRefExecutorService.INSTANCE.shutdownEverything();
                return;
            }
        }
    }

    // override used newline character with the one stored in the preferences
    // The preferences return the system newline character sequence as default
    Globals.NEWLINE = Globals.prefs.get(JabRefPreferences.NEWLINE);

    Optional<Vector<ParserResult>> loaded = processArguments(args, true);

    if ((!(loaded.isPresent())) || cli.isDisableGui() || cli.isShowVersion()) {
        JabRefExecutorService.INSTANCE.shutdownEverything();
        return;
    }

    SwingUtilities.invokeLater(() -> openWindow(loaded.get()));
}

From source file:org.broad.igv.util.HttpUtils.java

private HttpUtils() {

    org.broad.tribble.util.ParsingUtils.registerHelperClass(IGVUrlHelper.class);

    disableCertificateValidation();/*from  ww w .  j  a va  2  s .co  m*/
    CookieHandler.setDefault(new IGVCookieManager());
    Authenticator.setDefault(new IGVAuthenticator());

    try {
        System.setProperty("java.net.useSystemProxies", "true");
    } catch (Exception e) {
        log.info("Couldn't set useSystemProxies=true");
    }

    byteRangeTestMap = Collections.synchronizedMap(new HashMap());
}

From source file:io.takari.maven.testing.executor.junit.MavenVersionResolver.java

public void resolve(String[] versions) throws Exception {
    List<Repository> repositories = null;
    TestProperties properties = new TestProperties();
    for (String version : versions) {
        // refuse to test with SNAPSHOT maven version when build RELEASE plugins
        if (isSnapshot(version) && !isSnapshot(properties.getPluginVersion())) {
            String msg = String.format("Cannot test %s plugin release with %s maven",
                    properties.getPluginVersion(), version);
            error(version, new IllegalStateException(msg));
        }//  w  w w .  jav  a  2  s.  c  om
        File basdir = new File("target/maven-installation").getCanonicalFile();
        File mavenHome = new File(basdir, "apache-maven-" + version).getCanonicalFile();
        if (!mavenHome.isDirectory()) {
            if (repositories == null) {
                repositories = getRepositories(properties);
            }
            Authenticator defaultAuthenticator = getDefaultAuthenticator();
            try {
                createMavenInstallation(repositories, version, properties.getLocalRepository(), basdir);
            } catch (Exception e) {
                error(version, e);
            } finally {
                Authenticator.setDefault(defaultAuthenticator);
            }
        }
        if (mavenHome.isDirectory()) {
            resolved(mavenHome, version);
        }
    }
}

From source file:org.sickbeard.SickBeard.java

public SickBeard(String hostname, String port, String api, boolean https, String extraPath, String user,
        String password, boolean trustAll, String trustMe) {
    this.hostname = hostname;
    this.port = port;
    this.extraPath = "/" + extraPath + "/";
    this.path = this.extraPath + "/api/" + api + "/";
    try {//from  ww w  .j  av a 2 s. co m
        this.https = https;
        this.scheme = https ? "https" : "http";

        Authenticator.setDefault(new SickAuthenticator(user, password, hostname));
        HostnameVerifier verifier;
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (Exception e) {
        ;
    }
    /***********************************************************
     * ANDROID SPECIFIC START                                  *
     ***********************************************************/
    // start a AsyncTask to try and find the actual api version number
    AsyncTask<Void, Void, CommandsJson> task = new AsyncTask<Void, Void, CommandsJson>() {
        @Override
        protected CommandsJson doInBackground(Void... arg0) {
            try {
                return SickBeard.this.sbGetCommands();
            } catch (Exception e) {
                Log.e("SickBeard", e.getMessage(), e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(CommandsJson result) {
            // do nothing because this is a network error
            if (result == null)
                return;
            try {
                // if we get a version use it
                SickBeard.this.apiVersion = Integer.valueOf(result.api_version);
            } catch (NumberFormatException e) {
                // 2 was the odd float so assume its 2 if we cant get an int
                SickBeard.this.apiVersion = 2;
            }
        }
    };
    task.execute();
    /***********************************************************
     * ANDROID SPECIFIC END                                    *
     ***********************************************************/
}