Adds the authorization header to the given URL connection object.
@param urlConnection The URL connection to add the header to.
960403
public static void addAuthorizationHeader(URLConnection urlConnection, String header) {
        if (header != null) {
            urlConnection.setRequestProperty(AUTHORIZATION_HEADER, header);
        }
    }
890503
protected HttpURLConnection openConnection(URL requestTokenURL) {
    try {
      HttpURLConnection connection = (HttpURLConnection) requestTokenURL.openConnection(selectProxy(requestTokenURL));
      connection.setConnectTimeout(getConnectionTimeout());
      connection.setReadTimeout(getReadTimeout());
      return connection;
    }
    catch (IOException e) {
      throw new OAuthRequestFailedException("Failed to open an OAuth connection.", e);
    }
  }
347641
protected synchronized void decorateWithTLS(TLSClientParameters tlsClientParameters,
                                                HttpURLConnection connection) throws GeneralSecurityException {

        int hash = tlsClientParameters.hashCode();
        if (hash != lastTlsHash) {
            lastTlsHash = hash;
            socketFactory = null;
        }

        // always reload socketFactory from HttpsURLConnection.defaultSSLSocketFactory and
        // tlsClientParameters.sslSocketFactory to allow runtime configuration change
        if (tlsClientParameters.isUseHttpsURLConnectionDefaultSslSocketFactory()) {
            socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

        } else if (tlsClientParameters.getSSLSocketFactory() != null) {
            // see if an SSLSocketFactory was set. This allows easy interop
            // with not-yet-commons-ssl.jar, or even just people who like doing their
            // own JSSE.
            socketFactory = tlsClientParameters.getSSLSocketFactory();

        } else if (socketFactory == null) {
            // ssl socket factory not yet instantiated, create a new one with tlsClientParameters's Trust
            // Managers, Key Managers, etc

            SSLContext ctx = org.apache.cxf.transport.https.SSLUtils.getSSLContext(tlsClientParameters);

            String[] cipherSuites = SSLUtils.getCiphersuitesToInclude(tlsClientParameters.getCipherSuites(),
                                                                      tlsClientParameters.getCipherSuitesFilter(),
                                                                      ctx.getSocketFactory().getDefaultCipherSuites(),
                                                                      SSLUtils.getSupportedCipherSuites(ctx),
                                                                      LOG);
            // The SSLSocketFactoryWrapper enables certain cipher suites
            // from the policy.
            String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters.getSecureSocketProtocol() : "TLS";
            socketFactory = new SSLSocketFactoryWrapper(ctx.getSocketFactory(), cipherSuites, protocol);
            //recalc the hashcode since some of the above MAY have changed the tlsClientParameters
            lastTlsHash = tlsClientParameters.hashCode();
        } else {
            // ssl socket factory already initialized, reuse it to benefit of keep alive
        }

        HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils.getHostnameVerifier(tlsClientParameters);

        if (connection instanceof HttpsURLConnection) {
            // handle the expected case (javax.net.ssl)
            final HttpsURLConnection conn = (HttpsURLConnection) connection;
            conn.setHostnameVerifier(verifier);
            AccessController.doPrivileged(new PrivilegedAction<Void>() {

                @Override
                public Void run() {
                    conn.setSSLSocketFactory(socketFactory);
                    return null;
                }
            });
        } else {
            // handle the deprecated sun case and other possible hidden API's
            // that are similar to the Sun cases
            try {
                Method method = connection.getClass().getMethod("getHostnameVerifier");

                InvocationHandler handler = new ReflectionInvokationHandler(verifier) {
                    @Override
                    public Object invoke(Object proxy,
                                         Method method,
                                         Object[] args) throws Throwable {
                        try {
                            return super.invoke(proxy, method, args);
                        } catch (Exception ex) {
                            return false;
                        }
                    }
                };
                Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(),
                                                                        new Class[] { method.getReturnType() },
                                                                        handler);

                method = connection.getClass().getMethod("setHostnameVerifier", method.getReturnType());
                method.invoke(connection, proxy);
            } catch (Exception ex) {
                //Ignore this one
            }
            try {
                Method getSSLSocketFactory = connection.getClass().getMethod("getSSLSocketFactory");
                Method setSSLSocketFactory = connection.getClass().getMethod("setSSLSocketFactory", getSSLSocketFactory.getReturnType());
                if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) {
                    setSSLSocketFactory.invoke(connection, socketFactory);
                } else {
                    //need to see if we can create one - mostly the weblogic case.   The
                    //weblogic SSLSocketFactory has a protected constructor that can take
                    //a JSSE SSLSocketFactory so we'll try and use that
                    Constructor<?> c = getSSLSocketFactory.getReturnType().getDeclaredConstructor(SSLSocketFactory.class);
                    ReflectionUtil.setAccessible(c);
                    setSSLSocketFactory.invoke(connection, c.newInstance(socketFactory));
                }
            } catch (Exception ex) {
                if (connection.getClass().getName().contains("weblogic")) {
                    if (!weblogicWarned) {
                        weblogicWarned = true;
                        LOG.warning("Could not configure SSLSocketFactory on Weblogic.  "
                                    + " Use the Weblogic control panel to configure the SSL settings.");
                    }
                    return;
                }
                //if we cannot set the SSLSocketFactor, we're in serious trouble.
                throw new IllegalArgumentException("Error decorating connection class "
                                                   + connection.getClass().getName(), ex);
            }
        }
    }
306745
public void authenticate(HttpURLConnection httpConn, String url) {
        String authorization = null;
        if (hasAccessToken() && isOperationOauth(url)) {
            logger.debug("Using OAuth token to authenticate");
            authorization = getAccessTokenType() + " " + getAccessToken();
        } else if (hasApiKey()) {
            logger.debug("Using API Key to authenticate");
            String apiKey = getApiKey() + ":";
            authorization = "Basic " + DatatypeConverter.printBase64Binary(apiKey.getBytes()).trim();
        }
        if (authorization != null) {
            logger.debug("Authorization: " + authorization);
            httpConn.setRequestProperty("authorization", authorization);
        }
    }
1085948
@Override
    public boolean authorizeURLRequest(Request.Builder builder) {
        if (authUserInfo() == null)
            return false;
        String credential = Credentials.basic(username, password);
        builder.addHeader("Authorization", credential);
        return true;
    }
71634
private void addHttpBasicAuth(final ChannelHandlerContext ctx, final HttpRequest request) {
    ByteBuf raw = ctx.alloc().buffer(username.length() + password.length() + 1);
    raw.writeBytes((username + ":" + password).getBytes(CharsetUtil.UTF_8));
    ByteBuf encoded = Base64.encode(raw, false);
    request.headers().add(HttpHeaders.Names.AUTHORIZATION, "Basic " + encoded.toString(CharsetUtil.UTF_8));
    encoded.release();
    raw.release();
  }
381910
public void associateConnection(Object connection) throws ResourceException
   {
      if (connection == null)
         throw new ResourceException("Null connection handle");

      if (!(connection instanceof HelloWorldConnectionImpl))
         throw new ResourceException("Wrong connection handle");

      HelloWorldConnectionImpl handle = (HelloWorldConnectionImpl)connection;
      handle.setManagedConnection(this);
      connections.add(handle);
   }
158362
@Override
    public void send(@NonNull URL url, @NonNull T content) throws IOException {

        final HttpURLConnection urlConnection = createConnection(url);
        if (urlConnection instanceof HttpsURLConnection) {
            try {
                configureHttps((HttpsURLConnection) urlConnection);
            } catch (GeneralSecurityException e) {
                ACRA.log.e(LOG_TAG, "Could not configure SSL for ACRA request to " + url, e);
            }
        }
        configureTimeouts(urlConnection, connectionTimeOut, socketTimeOut);
        configureHeaders(urlConnection, login, password, headers, content);
        if (ACRA.DEV_LOGGING) {
            ACRA.log.d(LOG_TAG, "Sending request to " + url);
            ACRA.log.d(LOG_TAG, "Http " + method.name() + " content : ");
            ACRA.log.d(LOG_TAG, content.toString());
        }
        try {
            writeContent(urlConnection, method, content);
            handleResponse(urlConnection.getResponseCode(), urlConnection.getResponseMessage());
            urlConnection.disconnect();
        } catch (SocketTimeoutException e) {
            if (senderConfiguration.dropReportsOnTimeout()) {
                Log.w(ACRA.LOG_TAG, "Dropped report due to timeout");
            } else {
                throw e;
            }
        }
    }
572095
protected void configureEndpointAccessByFormLogin(final ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests) throws Exception {
        requests.and()
            .formLogin()
            .loginPage(ENDPOINT_URL_ADMIN_FORM_LOGIN)
            .permitAll();
    }
103272
public void addConnectionEventListener(
            final ConnectionEventListener listener) {

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, "addConnectionEventListener", listener);
        }

        _eventListeners.add(listener);

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, "addConnectionEventListener");
        }

    }
771090
protected void sendRequest(HttpURLConnection connection, Request request) throws IOException {
        // Set up the request.
        connection.setRequestMethod(request.method);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", request.authorization);

        // If a different HttpHandler is used, we won't get this header. We would need to refactor
        // to a delegation pattern to give the client code's HttpHandler a chance to process the
        // Request first, then attach our custom headers, which would likely be a breaking change.
        connection.setRequestProperty("Keen-Sdk", "java-" + KeenVersion.getSdkVersion());

        // If the request has a body, send it. Otherwise just connect.
        if (request.body != null) {
            if (HttpMethods.GET.equals(request.method) ||
                HttpMethods.DELETE.equals(request.method)) {
                throw new IllegalStateException("Trying to send a GET request with a request " +
                                                "body, which would result in sending a POST.");
            }

            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            request.body.writeTo(connection.getOutputStream());
        } else {
            connection.connect();
        }
    }
1347452
void setSICoreConnection(final SICoreConnection connection) {

        if (TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, "setSICoreConnection", connection);
        }

        _coreConnection = connection;

        if (TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, "setSICoreConnection");             //412795
        }

    }
1155456
public void setRequestHeader(String header, String value) {
        LOG.entering(CLASS_NAME, "setRequestHeader", new Object[] {header, value});
        HttpRequestUtil.validateHeader(header);
        connection.addRequestProperty(header, value);
    }
417683
public void setMemberServicesUrl(String url, String pem) throws CertificateException {
        this.setMemberServices(new MemberServicesImpl(url,pem));
    }
120640
public static URLConnection prepareForSSL( final URLConnection connection )
    {
        NullArgumentException.validateNotNull( connection, "url connection cannot be null" );
        URLConnection conn = connection;
        if( conn instanceof JarURLConnection )
        {
            try
            {
                conn = ( (JarURLConnection) connection ).getJarFileURL().openConnection();
                conn.connect();
            }
            catch( IOException e )
            {
                throw new RuntimeException( "Could not prepare connection for HTTPS.", e );
            }
        }
        if( conn instanceof HttpsURLConnection )
        {
            try
            {
                SSLContext ctx = SSLContext.getInstance( "SSLv3" );
                ctx.init( null, new TrustManager[]{ new AllCertificatesTrustManager() }, null );
                ( (HttpsURLConnection) conn ).setSSLSocketFactory( ctx.getSocketFactory() );
            }
            catch( KeyManagementException e )
            {
                throw new RuntimeException( "Could not prepare connection for HTTPS.", e );
            }
            catch( NoSuchAlgorithmException e )
            {
                throw new RuntimeException( "Could not prepare connection for HTTPS.", e );
            }

        }
        return connection;
    }
1097662
protected HttpURLConnection openConnection(String url, Map<String, String> header) throws IOException {
		// Initialize connection
		URL urlObj = null;
		HttpURLConnection conn = null;

		int redirectCount = 0;
		boolean redirect = true;
		while (redirect) {
			if (redirectCount > 10) {
				throw new ProtocolException("Too many redirects: " + redirectCount);
			}

			if (conn == null) {
				urlObj = new URL(url);
			} else {
				// get redirect url from "location" header field
				urlObj = new URL(conn.getHeaderField("Location"));
			}

			// open the new connection again
			conn = (HttpURLConnection) urlObj.openConnection();
			conn.setRequestMethod(header.get("method"));
			conn.setInstanceFollowRedirects(true);

			// Set output if PUT or POST
			if (conn.getRequestMethod() == "POST" || conn.getRequestMethod() == "PUT") {
				conn.setDoOutput(true);
			}

			// Set request header
			for (Map.Entry<String, String> headerAttr : header.entrySet()) {
				conn.addRequestProperty(headerAttr.getKey(), headerAttr.getValue());
			}

			// Check if redirect
			redirect = false;
			if (conn.getRequestMethod() == "GET") {
				int status = conn.getResponseCode();
				if (status != HttpURLConnection.HTTP_OK) {
					if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)
						redirect = true;
					redirectCount++;
				}
			}
		}

		return conn;
	}
317609
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
        HttpURLConnection connection = createConnection(url);

        int timeoutMs = request.getTimeoutMs();
        connection.setConnectTimeout(timeoutMs);
        connection.setReadTimeout(timeoutMs);
        connection.setUseCaches(false);
        connection.setDoInput(true);

        // use caller-provided custom SslSocketFactory, if any, for HTTPS
        if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
            ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
        }

        return connection;
    }