<commit_before>/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.util.net;

import com.btr.proxy.search.ProxySearch;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.util.PopupUtil;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.*;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Irina.Chernushina
 * Date: 1/21/13
 * Time: 12:39 PM
 */
public class CommonProxy extends ProxySelector {
  private final static CommonProxy ourInstance = new CommonProxy();
  private final IdeaWideProxySelector myIDEAWide;
  private final static List<Proxy> ourNoProxy = Collections.singletonList(Proxy.NO_PROXY);
  private volatile static ProxySelector ourWrong;
  private static final Map<String, String> ourProps = new HashMap<String, String>();
  static {
    ProxySelector.setDefault(ourInstance);
  }

  private static final Logger LOG = Logger.getInstance("#com.intellij.util.net.CommonProxy");
  private final Object myLock;
  private final Set<HostInfo> myNoProxy;

  private final Map<String, ProxySelector> myCustom;
  private final Map<Pair<String, Integer>, NonStaticAuthenticator> myCustomAuth;

  public static CommonProxy getInstance() {
    return ourInstance;
  }

  public CommonProxy() {
    myLock = new Object();
    myNoProxy = new HashSet<HostInfo>();
    myCustom = new HashMap<String, ProxySelector>();
    myCustomAuth = new HashMap<Pair<String, Integer>, NonStaticAuthenticator>();
    myIDEAWide = new IdeaWideProxySelector();
  }

  public static void isInstalledAssertion() {
    final ProxySelector aDefault = ProxySelector.getDefault();
    if (ourInstance != aDefault) {
      // to report only once
      if (ourWrong != aDefault) {
        LOG.error("ProxySelector.setDefault() was changed to [" + aDefault.toString() + "] - other than com.intellij.util.net.CommonProxy.ourInstance.\n" +
                  "This will make some " + ApplicationNamesInfo.getInstance().getProductName() + " network calls fail.\n" +
                  "Instead, methods of com.intellij.util.net.CommonProxy should be used for proxying.");
        ourWrong = aDefault;
      }
      ProxySelector.setDefault(ourInstance);
      ourInstance.ensureAuthenticator();
    }
    assertSystemPropertiesSet();
  }

  private static void assertSystemPropertiesSet() {
    final Map<String, String> props = new HashMap<String, String>();
    props.put(JavaProxyProperty.HTTP_HOST, System.getProperty(JavaProxyProperty.HTTP_HOST));
    props.put(JavaProxyProperty.HTTPS_HOST, System.getProperty(JavaProxyProperty.HTTPS_HOST));
    props.put(JavaProxyProperty.SOCKS_HOST, System.getProperty(JavaProxyProperty.SOCKS_HOST));

    if (Comparing.equal(ourProps, props)) return;
    ourProps.clear();
    ourProps.putAll(props);

    for (Map.Entry<String, String> entry : props.entrySet()) {
      if (! StringUtil.isEmptyOrSpaces(entry.getValue())) {
        final String message = "You have JVM property '" + entry.getKey() + "' set to '" + entry.getValue() + "'.\n" +
                               "This may lead to incorrect behaviour. Proxy should be set in Settings | " + HTTPProxySettingsPanel.NAME;
        PopupUtil.showBalloonForActiveComponent(message, MessageType.WARNING);
        LOG.info(message);
      }
    }
  }

  public void ensureAuthenticator() {
    myIDEAWide.resetAuthenticator();
  }

  public void noProxy(@NotNull final String protocol, @NotNull final String host, final int port) {
    synchronized (myLock) {
      LOG.debug("no proxy added: " + protocol + "://" + host + ":" + port);
      myNoProxy.add(new HostInfo(protocol, host, port));
    }
  }

  public void removeNoProxy(@NotNull final String protocol, @NotNull final String host, final int port) {
    synchronized (myLock) {
      LOG.debug("no proxy removed: " + protocol + "://" + host + ":" + port);
      myNoProxy.remove(new HostInfo(protocol, host, port));
    }
  }

  public void setCustom(@NotNull final String key, @NotNull final ProxySelector proxySelector) {
    synchronized (myLock) {
      LOG.debug("custom set: " + key + ", " + proxySelector.toString());
      myCustom.put(key, proxySelector);
    }
  }

  public void setCustomAuth(@NotNull final String host, final int port, final NonStaticAuthenticator authenticator) {
    synchronized (myLock) {
      LOG.debug("custom auth set: " + host + ":" + port + ", " + authenticator.toString());
      myCustomAuth.put(Pair.create(host, port), authenticator);
    }
  }

  public void removeCustomAuth(@NotNull final String host, final int port) {
    synchronized (myLock) {
      LOG.debug("custom auth removed: " + host + ":" + port);
      myCustomAuth.remove(Pair.create(host, port));
    }
  }

  public void removeCustom(@NotNull final String key) {
    synchronized (myLock) {
      LOG.debug("custom set: " + key);
      myCustom.remove(key);
    }
  }

  public List<Proxy> select(@NotNull URL url) {
    return select(createUri(url));
  }

  @Override
  public List<Proxy> select(URI uri) {
    LOG.debug("CommonProxy.select called for " + uri.toString());
    isInstalledAssertion();
    myIDEAWide.resetAuthenticator();

    final String host = uri.getHost() == null ? "" : uri.getHost();
    final int port = uri.getPort();
    final String protocol = uri.getScheme();

    final HostInfo info = new HostInfo(protocol, host, port);
    final Map<String, ProxySelector> copy;
    synchronized (myLock) {
      if (myNoProxy.contains(info)) {
        LOG.debug("CommonProxy.select returns no proxy (in no proxy list) for " + uri.toString());
        return ourNoProxy;
      }
      copy = new HashMap<String, ProxySelector>(myCustom);
    }
    for (Map.Entry<String, ProxySelector> entry : copy.entrySet()) {
      final List<Proxy> proxies = entry.getValue().select(uri);
      if (proxies != null && proxies.size() > 0) {
        LOG.debug("CommonProxy.select returns custom proxy for " + uri.toString() + ", " + proxies.toString());
        return proxies;
      }
    }
    // delegate to IDEA-wide behaviour
    final List<Proxy> selected = myIDEAWide.select(uri);
    final HttpConfigurable configurable;
    final Application application = ApplicationManager.getApplication();
    if (application != null && ! application.isDisposed()) {
      configurable = application.runReadAction(new Computable<HttpConfigurable>() {
        @Override
        public HttpConfigurable compute() {
          return HttpConfigurable.getInstance();
        }
      });
      if (configurable != null && configurable.USE_HTTP_PROXY) {
        configurable.LAST_ERROR = null;
      }
    }
    LOG.debug("CommonProxy.select returns something after common platform check for " + uri.toString() + ", " + selected.toString());
    return selected;
  }

  @Override
  public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
    LOG.info("connect failed to " + uri.toString() + ", sa: " + sa.toString(), ioe);
    final HttpConfigurable configurable = HttpConfigurable.getInstance();
    if (configurable == null) return;
    configurable.removeGeneric(new HostInfo(uri.getScheme(), uri.getHost(), uri.getPort()));
    final InetSocketAddress isa = sa instanceof InetSocketAddress ? (InetSocketAddress) sa : null;
    if (configurable.USE_HTTP_PROXY && isa != null && Comparing.equal(configurable.PROXY_HOST, isa.getHostName())) {
      LOG.debug("connection failed message passed to http configurable");
      configurable.LAST_ERROR = ioe.getMessage();
    }
  }

  private class CommonAuthenticator extends Authenticator {
    private final HttpConfigurable myHttpConfigurable;
<commit_msg>correctly check when getting instance<commit_after>/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.util.net;

import com.btr.proxy.search.ProxySearch;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.util.PopupUtil;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.*;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Irina.Chernushina
 * Date: 1/21/13
 * Time: 12:39 PM
 */
public class CommonProxy extends ProxySelector {
  private final static CommonProxy ourInstance = new CommonProxy();
  private final IdeaWideProxySelector myIDEAWide;
  private final static List<Proxy> ourNoProxy = Collections.singletonList(Proxy.NO_PROXY);
  private volatile static ProxySelector ourWrong;
  private static final Map<String, String> ourProps = new HashMap<String, String>();
  static {
    ProxySelector.setDefault(ourInstance);
  }

  private static final Logger LOG = Logger.getInstance("#com.intellij.util.net.CommonProxy");
  private final Object myLock;
  private final Set<HostInfo> myNoProxy;

  private final Map<String, ProxySelector> myCustom;
  private final Map<Pair<String, Integer>, NonStaticAuthenticator> myCustomAuth;

  public static CommonProxy getInstance() {
    return ourInstance;
  }

  public CommonProxy() {
    myLock = new Object();
    myNoProxy = new HashSet<HostInfo>();
    myCustom = new HashMap<String, ProxySelector>();
    myCustomAuth = new HashMap<Pair<String, Integer>, NonStaticAuthenticator>();
    myIDEAWide = new IdeaWideProxySelector();
  }

  public static void isInstalledAssertion() {
    final ProxySelector aDefault = ProxySelector.getDefault();
    if (ourInstance != aDefault) {
      // to report only once
      if (ourWrong != aDefault) {
        LOG.error("ProxySelector.setDefault() was changed to [" + aDefault.toString() + "] - other than com.intellij.util.net.CommonProxy.ourInstance.\n" +
                  "This will make some " + ApplicationNamesInfo.getInstance().getProductName() + " network calls fail.\n" +
                  "Instead, methods of com.intellij.util.net.CommonProxy should be used for proxying.");
        ourWrong = aDefault;
      }
      ProxySelector.setDefault(ourInstance);
      ourInstance.ensureAuthenticator();
    }
    assertSystemPropertiesSet();
  }

  private static void assertSystemPropertiesSet() {
    final Map<String, String> props = new HashMap<String, String>();
    props.put(JavaProxyProperty.HTTP_HOST, System.getProperty(JavaProxyProperty.HTTP_HOST));
    props.put(JavaProxyProperty.HTTPS_HOST, System.getProperty(JavaProxyProperty.HTTPS_HOST));
    props.put(JavaProxyProperty.SOCKS_HOST, System.getProperty(JavaProxyProperty.SOCKS_HOST));

    if (Comparing.equal(ourProps, props)) return;
    ourProps.clear();
    ourProps.putAll(props);

    for (Map.Entry<String, String> entry : props.entrySet()) {
      if (! StringUtil.isEmptyOrSpaces(entry.getValue())) {
        final String message = "You have JVM property '" + entry.getKey() + "' set to '" + entry.getValue() + "'.\n" +
                               "This may lead to incorrect behaviour. Proxy should be set in Settings | " + HTTPProxySettingsPanel.NAME;
        PopupUtil.showBalloonForActiveComponent(message, MessageType.WARNING);
        LOG.info(message);
      }
    }
  }

  public void ensureAuthenticator() {
    myIDEAWide.resetAuthenticator();
  }

  public void noProxy(@NotNull final String protocol, @NotNull final String host, final int port) {
    synchronized (myLock) {
      LOG.debug("no proxy added: " + protocol + "://" + host + ":" + port);
      myNoProxy.add(new HostInfo(protocol, host, port));
    }
  }

  public void removeNoProxy(@NotNull final String protocol, @NotNull final String host, final int port) {
    synchronized (myLock) {
      LOG.debug("no proxy removed: " + protocol + "://" + host + ":" + port);
      myNoProxy.remove(new HostInfo(protocol, host, port));
    }
  }

  public void setCustom(@NotNull final String key, @NotNull final ProxySelector proxySelector) {
    synchronized (myLock) {
      LOG.debug("custom set: " + key + ", " + proxySelector.toString());
      myCustom.put(key, proxySelector);
    }
  }

  public void setCustomAuth(@NotNull final String host, final int port, final NonStaticAuthenticator authenticator) {
    synchronized (myLock) {
      LOG.debug("custom auth set: " + host + ":" + port + ", " + authenticator.toString());
      myCustomAuth.put(Pair.create(host, port), authenticator);
    }
  }

  public void removeCustomAuth(@NotNull final String host, final int port) {
    synchronized (myLock) {
      LOG.debug("custom auth removed: " + host + ":" + port);
      myCustomAuth.remove(Pair.create(host, port));
    }
  }

  public void removeCustom(@NotNull final String key) {
    synchronized (myLock) {
      LOG.debug("custom set: " + key);
      myCustom.remove(key);
    }
  }

  public List<Proxy> select(@NotNull URL url) {
    return select(createUri(url));
  }

  @Override
  public List<Proxy> select(URI uri) {
    LOG.debug("CommonProxy.select called for " + uri.toString());
    isInstalledAssertion();
    myIDEAWide.resetAuthenticator();

    final String host = uri.getHost() == null ? "" : uri.getHost();
    final int port = uri.getPort();
    final String protocol = uri.getScheme();

    final HostInfo info = new HostInfo(protocol, host, port);
    final Map<String, ProxySelector> copy;
    synchronized (myLock) {
      if (myNoProxy.contains(info)) {
        LOG.debug("CommonProxy.select returns no proxy (in no proxy list) for " + uri.toString());
        return ourNoProxy;
      }
      copy = new HashMap<String, ProxySelector>(myCustom);
    }
    for (Map.Entry<String, ProxySelector> entry : copy.entrySet()) {
      final List<Proxy> proxies = entry.getValue().select(uri);
      if (proxies != null && proxies.size() > 0) {
        LOG.debug("CommonProxy.select returns custom proxy for " + uri.toString() + ", " + proxies.toString());
        return proxies;
      }
    }
    // delegate to IDEA-wide behaviour
    final List<Proxy> selected = myIDEAWide.select(uri);
    final HttpConfigurable configurable;
    final Application application = ApplicationManager.getApplication();
    if (application != null && ! application.isDisposed()) {
      configurable = application.runReadAction(new Computable<HttpConfigurable>() {
        @Override
        public HttpConfigurable compute() {
          if (application.isDisposeInProgress() || application.isDisposed()) return null;
          return HttpConfigurable.getInstance();
        }
      });
      if (configurable != null && configurable.USE_HTTP_PROXY) {
        configurable.LAST_ERROR = null;
      }
    }
    LOG.debug("CommonProxy.select returns something after common platform check for " + uri.toString() + ", " + selected.toString());
    return selected;
  }

  @Override
  public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
    LOG.info("connect failed to " + uri.toString() + ", sa: " + sa.toString(), ioe);
    final HttpConfigurable configurable = HttpConfigurable.getInstance();
    if (configurable == null) return;
    configurable.removeGeneric(new HostInfo(uri.getScheme(), uri.getHost(), uri.getPort()));
    final InetSocketAddress isa = sa instanceof InetSocketAddress ? (InetSocketAddress) sa : null;
    if (configurable.USE_HTTP_PROXY && isa != null && Comparing.equal(configurable.PROXY_HOST, isa.getHostName())) {
      LOG.debug("connection failed message passed to http configurable");
      configurable.LAST_ERROR = ioe.getMessage();
    }
  }

  private class CommonAuthenticator extends Authenticator {
    private final HttpConfigurable myHttpConfigurable;

{'fraction_non_alphanumeric': 0.11515816208727776, 'fraction_numerical': 0.002539829138767028, 'mean_word_length': 3.727148703956344, 'pattern_counts': {'":': 12, '<': 47, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4626682', 'n_tokens_mistral': 4970, 'n_tokens_neox': 4909, 'n_words': 1287}