/*
@see org.osgi.service.url.URLStreamHandlerService#openConnection(java.net.URL)
6538
@Override
    @SuppressWarnings("unused")
    public URLConnection openConnection(URL url) throws IOException {
        try {
            return (URLConnection) _openConnection.invoke(getInstance(), new Object[] { url });
        } catch (Exception e) {
            FFDCFilter.processException(e, getClass().getName(), "openConnection", url);
            return null;
        }
    }
1252687
final void realOpen() throws SQLException {
      if(conn == null) {
         conn = segment.createRealConnection();

         //Don't care about the exact value - randomize with some seconds to make
         //sure connections (if configured) don't expire at the same time even if they
         //are all created at once.
         realOpenTime = Clock.currTimeMillis + rnd.nextInt(120000);
         openStatements.clear(); //If reopen is a result of forceRealClose.
         reopenAttempts = 0;
      }
   }
616900
protected void newConnection()
        throws IOException
    {
        super.newConnection();
        
        _entry=null;
        _file=null;
        _jarFile=null;
        _list=null;
        
        int sep = _urlString.indexOf("!/");
        _jarUrl=_urlString.substring(0,sep+2);
        _path=_urlString.substring(sep+2);
        if (_path.length()==0)
            _path=null;   
        _jarFile=_jarConnection.getJarFile();
        _file=new File(_jarFile.getName());
    }
1029879
protected HttpURLConnection openConnection(final URL url, final RpcRequest request)
			throws IOException {
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		if (request.isPost()) {
			connection.setRequestMethod(POST);
			connection.setRequestProperty(CONTENT_TYPE_HEADER, APPLICATION_X_WWW_FORM_URLENCODED);
			connection.setDoOutput(true);
		} else {
			connection.setRequestMethod(GET);
		}
		return connection;
	}
1048040
@Override
  public StateConnection service()
    throws IOException
  {
    try {
      ConnectionProtocol request = requestOrCreate();

      if (request == null) {
        log.warning("Unexpected empty request: " + this);
        
        return StateConnection.CLOSE;
      }
      
      //_requestHttp.parseInvocation();
      
        
        /*
        if (requestFacade == null) {
          _requestHttp.startRequest();
          requestFacade = _requestHttp.getRequestFacade();
          
          //return NextState.CLOSE;
        }
        */

      StateConnection next = request.service();
      
      if (next != StateConnection.CLOSE) {
        return next;
      }
      else {
        return onCloseRead();
      }
    } catch (OutOfMemoryError e) {
      String msg = "Out of memory in RequestProtocolHttp";
        
      ShutdownSystem.shutdownOutOfMemory(msg);
        
      log.log(Level.WARNING, e.toString(), e);
    } catch (Throwable e) {
      e.printStackTrace();
      log.log(Level.WARNING, e.toString(), e);
    }

    return StateConnection.CLOSE;
  }
932077
protected URLConnection createURLConnection() throws Exception {
        URL url = getResourceURL();
        if (url == null) return null;
        URLConnection uc = url.openConnection();
        // encoding should be applied when connecting
        return uc;
    }
1249244
void establishConnection () throws IOException {
        synchronized (operationOnConnectionMonitor) {
            if (state == State.CLOSED) {
                throw new IOException("Attempt to establish a connection with a closed connection factory");
            } else if (state == State.CONNECTED) {
                LOGGER.warn("Establishing new connection although a connection is already established");
            }
            try {
                LOGGER.info("Trying to establish connection to {}:{}", getHost(), getPort());
                connection = super.newConnection(executorService);
                connection.addShutdownListener(connectionShutdownListener);
                LOGGER.info("Established connection to {}:{}", getHost(), getPort());
                changeState(State.CONNECTED);
            } catch (IOException e) {
                LOGGER.error("Failed to establish connection to {}:{}", getHost(), getPort());
                throw e;
            }
        }
    }
594835
@SuppressWarnings("unchecked")
   private ManagedConnection open(Subject s) throws ResourceException
   {
      log.debugf("Open managed connection (%s)", s);

      if (recoverMC == null)
         recoverMC = mcf.createManagedConnection(s, null);

      if (plugin == null)
      {
         try
         {
            ValidatingManagedConnectionFactory vmcf = (ValidatingManagedConnectionFactory)mcf;

            Set connectionSet = new HashSet(1);
            connectionSet.add(recoverMC);

            Set invalid = vmcf.getInvalidConnections(connectionSet);

            if (invalid != null && !invalid.isEmpty())
            {
               log.debugf("Invalid managed connection: %s", recoverMC);

               close(recoverMC);
               recoverMC = mcf.createManagedConnection(s, null);
            }
         }
         catch (ResourceException re)
         {
            log.debugf("Exception during invalid check", re);

            close(recoverMC);
            recoverMC = mcf.createManagedConnection(s, null);
         }
      }

      return recoverMC;
   }
768897
protected HttpURLConnection createConnection(URL url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // Workaround for HttpURLConnection not observing the
        // HttpURLConnection.setFollowRedirects() property.
        // Happening in Android M release
        // https://code.google.com/p/android/issues/detail?id=194495
        connection.setInstanceFollowRedirects(HttpURLConnection.getFollowRedirects());

        return connection;
    }
940450
public static InputStream openUncachedStream(URL url) throws IOException {
        URLConnection urlConnection = url.openConnection();
        urlConnection.setUseCaches(false);
        return urlConnection.getInputStream();
    }
1112716
public static ProtocolConnectionManager create(final ProtocolConnectionConfiguration configuration, final ConnectionOpenHandler openHandler) {
        return create(new EstablishingConnection(configuration, openHandler));
    }
730201
protected HttpURLConnection generateConn() throws IOException {
        HttpURLConnection conn;
        conn = (HttpURLConnection) new URL(url).openConnection();
        return conn;
    }
813439
private static InputStream openStream(String resource) throws IOException {
    HttpURLConnection
        connection =
        HttpURLConnection.class.cast(URI.create(resource).toURL().openConnection());
    connection.setConnectTimeout(1000 * 2);
    connection.setReadTimeout(1000 * 2);
    connection.setAllowUserInteraction(false);
    connection.setInstanceFollowRedirects(false);
    return connection.getInputStream();
  }
426361
@Override
    public URLStreamHandler createURLStreamHandler(final String protocol) {
        if (null == protocol) {
            throw new IllegalArgumentException("null protocol not allowed");
        }
        if (logger.isTraceEnabled()) {
            logger.trace("need to create URLStreamHandler for protocol {}", protocol);
        }

        final String proto = protocol.toLowerCase();
        if (PROTO_HTTP.equals(proto) || PROTO_HTTPS.equals(proto)) {
            return new URLStreamHandler() {
                @Override
                protected URLConnection openConnection(final URL url) throws IOException {
                    if (logger.isTraceEnabled()) {
                        logger.trace("should open connection to {}", url.toExternalForm());
                    }

                    // URLConnection only has a protected ctor, so we need to go through the URL ctor with the matching handler
                    final URLConnection defaultUrlConnection =
                            new URL(protocol, url.getHost(), url.getPort(), url.getFile(), handlers.get(protocol))
                                    .openConnection();

                    if (!cache.urlShouldBeCached(url)) {
                        if (logger.isTraceEnabled()) {
                            logger.trace("not using cache for {}", url);
                        }
                        return defaultUrlConnection;
                    }

                    final Path cacheFile = cache.filenameForURL(url);
                    // now wrap the defaultUrlConnection
                    if (cache.isCached(url)) {
                        // if cached, always use http connection to prevent ssl handshake. As we are reading from the
                        // cache, this is enough
                        return new CachingHttpURLConnection(cache, (HttpURLConnection) defaultUrlConnection);
                    } else {
                        switch (proto) {
                            case PROTO_HTTP:
                                return new CachingHttpURLConnection(cache, (HttpURLConnection) defaultUrlConnection);
                            case PROTO_HTTPS:
                                return new CachingHttpsURLConnection(cache, (HttpsURLConnection) defaultUrlConnection);
                        }
                    }
                    throw new IOException("no matching handler");
                }

                @Override
                protected URLConnection openConnection(final URL u, final Proxy p) throws IOException {
                    if (logger.isTraceEnabled()) {
                        logger.trace("should open connection to {} via {}", u.toExternalForm(), p);
                    }
                    // URLConnection only has a protected ctor, so we need to go through the URL ctor with the
                    // matching handler to get a default implementation of the needed URLStreamHandler
                    final URLConnection defaultUrlConnection =
                            new URL(protocol, u.getHost(), u.getPort(), u.getFile(), handlers.get(protocol))
                                    .openConnection(p);

                    return defaultUrlConnection;
                }
            };
        }
        // return null to use default ones
        return null;
    }
1063544
@Override
	protected void openConnection( IMessagingClient newMessagingClient ) throws IOException {
		newMessagingClient.setOwnerProperties( RecipientKind.DM, this.domain, null, null );
		newMessagingClient.openConnection();
	}
1115658
@Override
    public void openConnection(Map<String, String> properties) throws JdbcServerException {
        if (!endpointConfiguration.isAutoConnect()) {
            List<OpenConnection.Property> propertyList = convertToPropertyList(properties);
            handleMessageAndCheckResponse(JdbcMessage.openConnection(propertyList));
        }

        if (connections.get() == endpointConfiguration.getServerConfiguration().getMaxConnections()) {
            throw new JdbcServerException(String.format("Maximum number of connections (%s) reached",
                    endpointConfiguration.getServerConfiguration().getMaxConnections()));
        }

        connections.incrementAndGet();
    }
1239022
public URLConnection getResourceConnection (String name) throws ResourceException {
        name = removeNamePrefix(name).replace('\\', '/');

        //remove the leading / as we are trying with a leading / now
        if (name.startsWith("WEB-INF/groovy/")) {
            name = name.substring(15);//just for uniformity
        } else if (name.startsWith("/")) {
            name = name.substring(1);
        }

        /*
        * Try to locate the resource and return an opened connection to it.
        */
        try {
            URL url = servletContext.getResource('/' + name);
            if (url == null) {
                url = servletContext.getResource("/WEB-INF/groovy/" + name);
            }
            if (url == null) {
                throw new ResourceException("Resource \"" + name + "\" not found!");
            }
            return url.openConnection();
        } catch (IOException e) {
            throw new ResourceException("Problems getting resource named \"" + name + "\"!", e);
        }
    }