Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
@param connection
@return an HttpEntity populated with data from <code>connection</code>.
540238
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
        BasicHttpEntity entity = new BasicHttpEntity();
        InputStream inputStream;
        try {
            inputStream = connection.getInputStream();
        } catch (IOException ioe) {
            inputStream = connection.getErrorStream();
        }
        entity.setContent(inputStream);
        entity.setContentLength(connection.getContentLength());
        entity.setContentEncoding(connection.getContentEncoding());
        entity.setContentType(connection.getContentType());
        return entity;
    }
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;
    }
1227422
public Query queryEntityConnections(String connectingEntityType,
            String connectingEntityId, String connectionType, String ql) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("ql", ql);
        Query q = queryEntitiesRequest(HttpMethod.GET, params, null,
                organizationId, applicationId, connectingEntityType, connectingEntityId,
                connectionType);
        return q;
    }
29412
public Object openConnection(String endpointUri) throws ConnectionException {
        try {
            Map<String,String> params = getRequestParameters();
            if (params != null && !params.isEmpty()) {
                StringBuffer query = new StringBuffer();
                query.append(endpointUri.indexOf('?') < 0 ? '?' : '&');
                int count = 0;
                for (String name : params.keySet()) {
                    if (count > 0)
                        query.append('&');
                    String encoding = getUrlEncoding();
                    query.append(encoding == null ? name : URLEncoder.encode(name, encoding)).append("=");
                    query.append(encoding == null ? params.get(name) : URLEncoder.encode(params.get(name), encoding));
                    count++;
                }
                endpointUri += query;
            }
            URL url = new URL(endpointUri);

            HttpConnection httpConnection;
            if ("PATCH".equals(getHttpMethod()))
                httpConnection = new HttpAltConnection(url);
            else
                httpConnection = new HttpConnection(url);

            httpConnection.open();
            return httpConnection;
        }
        catch (Exception ex) {
            throw new ConnectionException(ConnectionException.CONNECTION_DOWN, ex.getMessage(), ex);
        }
    }
1179569
public static ConfigurableConnection of(Connection connection) {
    Assert.isTrue(connection instanceof ConfigurableConnection, "The connection {} was not created by Lyra", connection);
    return (ConfigurableConnection) connection;
  }
1268362
public static HttpRequestBase put(String path,
	                                  HttpEntity entity) {

		return put(path, null, null, entity, null);
	}
306536
public DatabaseConnectionRequest<T, U> setConnection(String connection) {
        request.addParameter(ParameterBuilder.CONNECTION_KEY, connection);
        return this;
    }
505996
private HttpURLConnection createConnection() {
        String urlString = getRequestInfo().getRequestUrl().toString();
        if( getRequestInfo().requestMethod == null ) {
            throw new KieServerHttpRequestException("Please specify (and execute?) a HTTP method first.");
        }
        try {
            final HttpURLConnection connection;
            if( this.httpProxyHost != null ) {
                Proxy proxy = new Proxy(HTTP, new InetSocketAddress(this.httpProxyHost, this.httpProxyPort));
                connection = CONNECTION_FACTORY.create(getRequestInfo().getRequestUrl(), proxy);
            } else {
                connection = CONNECTION_FACTORY.create(getRequestInfo().getRequestUrl());
            }
            // support for localhost and https
            if (getRequestInfo().getRequestUrl().getProtocol().equalsIgnoreCase("https") && getRequestInfo().getRequestUrl().getHost().equalsIgnoreCase("localhost")) {
                ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier(){

                    public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
                        if (hostname.equalsIgnoreCase("localhost")) {
                            return true;
                        }
                        return false;
                    }
                });
            }

            connection.setRequestMethod(getRequestInfo().requestMethod);
            return connection;
        } catch( IOException ioe ) {
            throw new KieServerHttpRequestException("Unable to create (" + getRequestInfo().requestMethod + ") connection to '"
                    + urlString + "'", ioe);
        }
    }
661864
public static synchronized HttpFileUploadManager getInstanceFor(XMPPConnection connection) {
        HttpFileUploadManager httpFileUploadManager = INSTANCES.get(connection);

        if (httpFileUploadManager == null) {
            httpFileUploadManager = new HttpFileUploadManager(connection);
            INSTANCES.put(connection, httpFileUploadManager);
        }

        return httpFileUploadManager;
    }
643644
protected final Connection<T> createConnectionForResource(T resource)
    {
        if(resource==null)
        {
            throw new FaxException("Connection resource not provided.");
        }

        //create new connection
        Connection<T> connection=new ConnectionImpl<T>(resource,this);
        
        return connection;
    }
221473
ServerSessionManager unregisterConnection(Connection connection) {
    Iterator<Map.Entry<String, Connection>> iterator = connections.entrySet().iterator();
    while (iterator.hasNext()) {
      Map.Entry<String, Connection> entry = iterator.next();
      if (entry.getValue().equals(connection)) {
        ServerSessionContext session = clients.get(entry.getKey());
        if (session != null) {
          session.setConnection(null);
        }
        iterator.remove();
      }
    }
    return this;
  }
962755
private void setupHeaders(HttpURLConnection connection) {
        for (Map.Entry<String, Object> entry : getHeaders().entrySet()) {
            connection.setRequestProperty(entry.getKey(), String.valueOf(entry.getValue()));
        }
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setAllowUserInteraction(false);
    }
1346015
private static HttpEntity toHttpEntity(Object value, String mimetype, String charset) throws IOException {
	if (value instanceof HttpEntity) return (HttpEntity) value;

	// content type
	ContentType ct = HTTPEngine.toContentType(mimetype, charset);
	try {
	    if (value instanceof TemporaryStream) {
		if (ct != null) return new TemporaryStreamHttpEntity((TemporaryStream) value, ct);
		return new TemporaryStreamHttpEntity((TemporaryStream) value, null);
	    }
	    else if (value instanceof InputStream) {
		if (ct != null) return new ByteArrayEntity(IOUtil.toBytes((InputStream) value), ct);
		return new ByteArrayEntity(IOUtil.toBytes((InputStream) value));
	    }
	    else if (Decision.isCastableToBinary(value, false)) {
		if (ct != null) return new ByteArrayEntity(Caster.toBinary(value), ct);
		return new ByteArrayEntity(Caster.toBinary(value));
	    }
	    else {
		boolean wasNull = false;
		if (ct == null) {
		    wasNull = true;
		    ct = ContentType.APPLICATION_OCTET_STREAM;
		}
		String str = Caster.toString(value);
		if (str.equals("<empty>")) {
		    return new EmptyHttpEntity(ct);
		}
		if (wasNull && !StringUtil.isEmpty(charset, true)) return new StringEntity(str, charset.trim());
		else return new StringEntity(str, ct);
	    }
	}
	catch (Exception e) {
	    throw ExceptionUtil.toIOException(e);
	}
    }
490011
@SuppressWarnings("unchecked")
    public static <T> T getEntity(InputStream in, TypeReference<T> reference) {
        // If the entity type is an iterator then return a streaming iterator to prevent Jackson instantiating
        // the entire response in memory.
        Type type = reference.getType();
        if (type instanceof ParameterizedType &&
                Iterator.class.isAssignableFrom((Class<?>) ((ParameterizedType) type).getRawType())) {
            Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
            return (T) streamingIterator(in, typeReferenceFrom(elementType));
        }

        // Use Jackson to deserialize the input stream.
        try {
            return JsonHelper.readJson(in, reference);
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
533406
public ApiResponse createEntity(Entity entity) {
        assertValidApplicationId();
        if (isEmpty(entity.getType())) {
            throw new IllegalArgumentException("Missing entity type");
        }
        ApiResponse response = apiRequest(HttpMethod.POST, null, entity,
                organizationId, applicationId, entity.getType());
        return response;
    }
348977
private HttpEntity populateEntity(RequestElements intuitRequest) throws FMSException {
        byte[] compressedData = intuitRequest.getCompressedData();

        if (null == compressedData) {
            // use postString to create httpEntity
            try {
                return new StringEntity(intuitRequest.getPostString());
            } catch (UnsupportedEncodingException e) {
                throw new FMSException("UnsupportedEncodingException", e);
            }
        }

        // use compressed data to create httpEntity
        return new InputStreamEntity( new ByteArrayInputStream(compressedData) , compressedData.length);
    }
34719
public HttpConnection execute(HttpConnection connection) {

        //set our HttpUrlFactory on the connection
        connection.connectionFactory = factory;

        // all CouchClient requests want to receive application/json responses
        connection.requestProperties.put("Accept", "application/json");
        connection.responseInterceptors.addAll(this.responseInterceptors);
        connection.requestInterceptors.addAll(this.requestInterceptors);
        InputStream es = null; // error stream - response from server for a 500 etc

        // first try to execute our request and get the input stream with the server's response
        // we want to catch IOException because HttpUrlConnection throws these for non-success
        // responses (eg 404 throws a FileNotFoundException) but we need to map to our own
        // specific exceptions
        try {
            try {
                connection = connection.execute();
            } catch (HttpConnectionInterceptorException e) {
                CouchDbException exception = new CouchDbException(connection.getConnection()
                        .getResponseMessage(), connection.getConnection().getResponseCode());
                if (e.deserialize) {
                    try {
                        JsonObject errorResponse = new Gson().fromJson(e.error, JsonObject
                                .class);
                        exception.error = getAsString(errorResponse, "error");
                        exception.reason = getAsString(errorResponse, "reason");
                    } catch (JsonParseException jpe) {
                        exception.error = e.error;
                    }
                } else {
                    exception.error = e.error;
                    exception.reason = e.reason;
                }
                throw exception;
            }
            int code = connection.getConnection().getResponseCode();
            String response = connection.getConnection().getResponseMessage();
            // everything ok? return the stream
            if (code / 100 == 2) { // success [200,299]
                return connection;
            } else {
                final CouchDbException ex;
                switch (code) {
                    case HttpURLConnection.HTTP_NOT_FOUND: //404
                        ex = new NoDocumentException(response);
                        break;
                    case HttpURLConnection.HTTP_CONFLICT: //409
                        ex = new DocumentConflictException(response);
                        break;
                    case HttpURLConnection.HTTP_PRECON_FAILED: //412
                        ex = new PreconditionFailedException(response);
                        break;
                    case 429:
                        // If a Replay429Interceptor is present it will check for 429 and retry at
                        // intervals. If the retries do not succeed or no 429 replay was configured
                        // we end up here and throw a TooManyRequestsException.
                        ex = new TooManyRequestsException(response);
                        break;
                    default:
                        ex = new CouchDbException(response, code);
                        break;
                }
                es = connection.getConnection().getErrorStream();
                //if there is an error stream try to deserialize into the typed exception
                if (es != null) {
                    try {
                        //read the error stream into memory
                        byte[] errorResponse = IOUtils.toByteArray(es);

                        Class<? extends CouchDbException> exceptionClass = ex.getClass();
                        //treat the error as JSON and try to deserialize
                        try {
                            // Register an InstanceCreator that returns the existing exception so
                            // we can just populate the fields, but not ignore the constructor.
                            // Uses a new Gson so we don't accidentally recycle an exception.
                            Gson g = new GsonBuilder().registerTypeAdapter(exceptionClass, new
                                    CouchDbExceptionInstanceCreator(ex)).create();
                            // Now populate the exception with the error/reason other info from JSON
                            g.fromJson(new InputStreamReader(new ByteArrayInputStream
                                    (errorResponse),
                                    "UTF-8"), exceptionClass);
                        } catch (JsonParseException e) {
                            // The error stream was not JSON so just set the string content as the
                            // error field on ex before we throw it
                            ex.error = new String(errorResponse, "UTF-8");
                        }
                    } finally {
                        close(es);
                    }
                }
                ex.setUrl(connection.url.toString());
                throw ex;
            }
        } catch (IOException ioe) {
            CouchDbException ex = new CouchDbException("Error retrieving server response", ioe);
            ex.setUrl(connection.url.toString());
            throw ex;
        }
    }