/*
(non-Javadoc)

@see com.ibm.ws.sib.processor.impl.interfaces.DestinationHandler#getProxyReferenceStream()
772704
@Override
    public ProxyReferenceStream getProxyReferenceStream()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "getProxyReferenceStream");

        ProxyReferenceStream proxyReferenceStream = _targetDestinationHandler.getProxyReferenceStream();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "getProxyReferenceStream", proxyReferenceStream);

        return proxyReferenceStream;
    }
1020793
@SuppressWarnings("unchecked")
    private ThreadLocalProxyCopyOnWriteArraySet<ThreadLocalProxy<?>> getProxySet() {
        Object property = null;
        property = bus.getProperty(PROXY_SET);
        if (property == null) {
            ThreadLocalProxyCopyOnWriteArraySet<ThreadLocalProxy<?>> proxyMap = new ThreadLocalProxyCopyOnWriteArraySet<ThreadLocalProxy<?>>();

            bus.setProperty(PROXY_SET, proxyMap);
            property = proxyMap;
        }
        return (ThreadLocalProxyCopyOnWriteArraySet<ThreadLocalProxy<?>>) property;
    }
544025
public InputStream getInputStream()
    {
        InputStream stream=null;
        try
        {
            stream=this.commPort.getInputStream();
        }
        catch(IOException exception)
        {
            throw new FaxException("Unable to extract input stream.",exception);
        }
        
        return stream;
    }
1222480
@Override
	public Object getService(IServiceReference serviceReference) {
		final String sourceMethod = "getService"; //$NON-NLS-1$
		boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(PlatformServicesImpl.class.getName(), sourceMethod, serviceReference);
		}
		Object result = null;
		BundleContext bundleContext = Activator.getBundleContext();
		if (bundleContext != null) {
			result = bundleContext
					.getService((ServiceReference<?>) serviceReference.getPlatformObject());
		}
		if (isTraceLogging) {
			log.exiting(PlatformServicesImpl.class.getName(), sourceMethod, result);
		}
		return result;
	}
158841
@Deprecated
  public static FileSystem getProxiedFileSystemUsingKeytab(@NonNull final String userNameToProxyAs,
      final String superUserName, final Path superUserKeytabLocation, final URI fsURI, final Configuration conf)
      throws ExecutionException {
    try {
      return getProxiedFileSystemUsingKeytab(userNameToProxyAs, superUserName, superUserKeytabLocation, fsURI, conf,
          null);
    } catch (IOException ioe) {
      throw new ExecutionException(ioe);
    }
  }
561738
public InputStream getInputStream() {
        try
        {
            int responseCode = this.urlConnection.getResponseCode();

            try
            {
                // HACK: manually follow redirects, for the login to work
                // HTTPUrlConnection auto redirect doesn't respect the provided headers
                if(responseCode ==302)
                {
                    HttpClient redirectClient =
                            new HttpClient(proxyHost,proxyPort, urlConnection.getHeaderField("Location"),
                                    headers, urlConnection.getRequestMethod(), callback, authHeader);
                    redirectClient.getInputStream().close();
                }
            }
            catch (Throwable e)
            {
                System.out.println("Following redirect failed");
            }

            setCookieHeader = this.urlConnection.getHeaderField("Set-Cookie");


            InputStream in = responseCode != HttpURLConnection.HTTP_OK ?
                    this.urlConnection.getErrorStream() : this.urlConnection.getInputStream();

            return in;
        } catch (Exception e) {
            return null;
        }
    }
243910
protected ConnectionProxy getConnectionProxy()
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getConnectionProxy");

      if (connectionProxy == null)
      {
         // Someone is trying to use the connection proxy associated with this proxy object but it
         // has not been set or has been nulled out.
         SIErrorException e = new SIErrorException(
            nls.getFormattedMessage("CONNECTION_PROXY_NOT_SET_SICO1053", null, null)
         );

         FFDCFilter.processException(e, CLASS_NAME + ".getConnectionProxy",
                                     CommsConstants.PROXY_GETCONNECTIONPROXY_01, this);

         throw e;
      }

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getConnectionProxy", connectionProxy);
      return connectionProxy;
   }
540242
public static Proxy getProxy(final IProxyProvider provider, final boolean test) throws IOException {
    LOGGER.info("Getting proxy...");

    List<Proxy> proxies = provider.getProxies(-1, false, true);
    LOGGER.info("Total Proxies: " + proxies.size());

    final CountDownLatch countDown = new CountDownLatch(proxies.size());
    final AtomicReference<Proxy> useProxy = new AtomicReference<>();
    
    int threadCount = proxies.size() > 10 ? 10 : proxies.size();
    if (threadCount <= 0) {
      threadCount = 1;
    }
    
    final ExecutorService testService = Executors.newFixedThreadPool(threadCount);

    for (final Proxy proxy : proxies) {

      Thread validate = new Thread() {
        @Override
        public void run() {
          try {

            if (test) {
              
              if (proxy.isBlackListed()) {
                return;
              }
              
              proxy.updateStatus();
              if (!proxy.isOnline()) {
                return;
              }

              proxy.updateAnonymity();
              if (!proxy.isAnonymous()) {
                return;
              }
            }

            if (useProxy.get() == null) {
              LOGGER.info("Using Proxy: " + proxy.toString());
              useProxy.set(proxy);

              // count to 0
              while (countDown.getCount() > 0) {
                countDown.countDown();
              }

            }

          } catch (Exception e) {
            LOGGER.info("Proxy validation returned error: " + e.getClass().getName() + " - " + e.getMessage());
          } finally {
            countDown.countDown();
          }
        }
      };
      testService.submit(validate);

    }

    try {
      countDown.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    testService.shutdownNow();

    if (useProxy.get() == null) {
      //if null, use another provider
      return getProxy(test);
    }
    
    return useProxy.get();

  }
946161
@Builder(builderClassName = "ProxiedFileSystemFromKeytab", builderMethodName = "fromKeytab")
  private static FileSystem getProxiedFileSystemUsingKeytab(@NonNull final String userNameToProxyAs,
      final String superUserName, final Path superUserKeytabLocation, final URI fsURI, final Configuration conf,
      FileSystem referenceFS) throws IOException, ExecutionException {
    Preconditions.checkNotNull(userNameToProxyAs, "Must provide a user name to proxy as.");
    Preconditions.checkNotNull(superUserName, "Must provide a super user name.");
    Preconditions.checkNotNull(superUserKeytabLocation, "Must provide a keytab location.");
    URI actualURI = resolveUri(fsURI, conf, referenceFS);
    Configuration actualConfiguration = resolveConfiguration(conf, referenceFS);

    return USER_NAME_TO_FILESYSTEM_CACHE.get(getFileSystemKey(actualURI, userNameToProxyAs, referenceFS),
        new CreateProxiedFileSystemFromKeytab(userNameToProxyAs, superUserName, superUserKeytabLocation, actualURI,
            actualConfiguration, referenceFS));
  }
702711
@Override
	public InputStream getResourceAsStream(String resourceName, boolean processingBundle)
			throws ResourceNotFoundException {

		if (ThreadLocalJawrContext.isInterruptingProcessingBundle()) {
			throw new InterruptBundlingProcessException();
		}

		generatorRegistry.loadGeneratorIfNeeded(resourceName);
		InputStream is = null;

		String resourceExtension = FileNameUtils.getExtension(resourceName);
		boolean generatedPath = generatorRegistry.isPathGenerated(resourceName);
		if (generatedPath || allowedExtensions.contains(resourceExtension.toLowerCase())) {
			List<StreamResourceReader> list = new ArrayList<>();
			list.addAll(streamResourceReaders);
			for (StreamResourceReader rsReader : list) {
				if (!(rsReader instanceof ResourceGenerator)
						|| ((ResourceGenerator) rsReader).getResolver().matchPath(resourceName)) {
					try {
						is = rsReader.getResourceAsStream(resourceName);
					} catch (Exception e) {
						if (LOGGER.isDebugEnabled()) {
							LOGGER.debug("An exception occured while trying to read resource '" + resourceName
									+ "'. Continuing with other readers. Error : ", e);
						} else if (LOGGER.isInfoEnabled()) {
							LOGGER.info("An exception occured while trying to read resource '" + resourceName
									+ "'. Continuing with other readers. Error : " + e.getMessage());
						}
					}
					if (is != null) {
						break;
					}
				}
			}
		} else {
			LOGGER.warn("The resource '" + resourceName + "' will not be read as its extension is not an allowed one.");
		}
		if (is == null) {
			throw new ResourceNotFoundException(resourceName);
		}

		return is;
	}
684724
@Deprecated
    public ProxySelector getOriginalProxySelector() {
        return new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                InetSocketAddress address = originalProxies.get(uri.getScheme());
                if (address != null && !(originalNonProxyHosts.contains(uri.getHost()))) {
                    return Collections.singletonList(new Proxy(HTTP, address));
                } else {
                    return Collections.singletonList(Proxy.NO_PROXY);
                }
            }

            @Override
            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            }
        };
    }
629412
protected int getProxyPort(Dsn dsn) {
        return Util.parseInteger(Lookup.lookup(HTTP_PROXY_PORT_OPTION, dsn), HTTP_PROXY_PORT_DEFAULT);
    }
428935
public InputStream getStream(String url, RasterLayer layer) throws IOException {
		if (layer instanceof ProxyLayerSupport) {
			ProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;
			if (proxyLayer.isUseCache() && null != cacheManagerService) {
				Object cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url);
				if (null != cachedObject) {
					testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE);
					return new ByteArrayInputStream((byte[]) cachedObject);
				} else {
					testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE);
					InputStream stream = super.getStream(url, proxyLayer);
					ByteArrayOutputStream os = new ByteArrayOutputStream();
					int b;
					while ((b = stream.read()) >= 0) {
						os.write(b);
					}
					cacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(),
							getLayerEnvelope(proxyLayer));
					return new ByteArrayInputStream((byte[]) os.toByteArray());
				}
			}
		}
		return super.getStream(url, layer);
	}
836039
public static <T extends VersionedProtocol> ProtocolProxy<T> getProtocolProxy(
      Class<T> protocol,
      long clientVersion, InetSocketAddress addr, Configuration conf)
      throws IOException {

    return getProtocolProxy(protocol, clientVersion, addr, conf, NetUtils
        .getDefaultSocketFactory(conf));
  }
807843
@Override
	public final Reference getReference() throws NamingException
    {
    	Reference ref = new Reference(getClass().getName(),JNDIObjectFactory.class.getName(),null);
    	ref.add(new StringRefAddr("providerURL",getProviderURL()));
    	if (clientID != null)
    		ref.add(new StringRefAddr("clientID",clientID));
    	
    	return ref;
    }
155504
public void getProxyInfos(Collection<ProxyInfo> result) {
        for (Map.Entry<String, DistributedObjectFuture> entry : proxies.entrySet()) {
            DistributedObjectFuture future = entry.getValue();
            if (future.isSetAndInitialized()) {
                String proxyName = entry.getKey();
                result.add(new ProxyInfo(serviceName, proxyName));
            }
        }
    }
513207
public static <V extends VersionedProtocol> V getProxy(Class<V> protocol, InetSocketAddress addr,
			SocketFactory factory) throws IOException {

		@SuppressWarnings("unchecked")
		V proxy = (V) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(addr, factory));

		return proxy;
	}