Convert an HTTP Range header to a Range object
@param source the source
@return range object
9957
public static Range convert(final String source) {

        final Matcher matcher = rangePattern.matcher(source);

        if (!matcher.matches()) {
            return new Range();
        }

        final String from = matcher.group(1);
        final String to = matcher.group(2);

        final long start;

        if (from.equals("")) {
            start = 0;
        } else {
            start = parseLong(from);
        }

        final long end;
        if (to.equals("")) {
            end = -1;
        } else {
            end = parseLong(to);
        }

        return new Range(start, end);
    }
315833
static HttpResponse executeHeadRequest(URI uri, SerializationFormat format) throws IOException {

        HttpHead headMethod = new HttpHead(uri);
        MyRedirectHandler redirectHandler = new MyRedirectHandler(uri);

        String acceptHeader = format.getMimeType() != null && ! format.getMimeType().trim().isEmpty() ? format.getMimeType() : "*/*";
        CloseableHttpClient httpClient = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(requestConfig)
            .setConnectionManager(poolingConnManager)
            .setSSLContext(ssl)
            .setRedirectStrategy(redirectHandler)
            .setDefaultHeaders(Arrays.asList(
                new BasicHeader("Accept", acceptHeader), //if default request we try to pretend to be a browser, else we accept everything
                new BasicHeader("User-Agent", "Mozilla/5.0"),
                new BasicHeader("Upgrade-Insecure-Requests", "1")       // we are an all trusting client...
            ))
            .build();

        HttpResponse httpResponse = httpClient.execute(headMethod);
        redirectHandler.lastRedirectedUri.forEach(x -> httpResponse.setHeader(HEADERKEY, String.valueOf(x)));
        return httpResponse;
    }
1163207
private void copyHeadersToClient(HttpURLConnection pRemoteConnection, HttpServletResponse pResponse) {
        // NOTE: There is no getHeaderFieldCount method or similar...
        // Also, the getHeaderFields() method was introduced in J2SE 1.4, and
        // we want to be 1.2 compatible.
        // So, just try to loop until there are no more headers.
        int i = 0;
        while (true) {
            String key = pRemoteConnection.getHeaderFieldKey(i);
            // NOTE: getHeaderField(String) returns only the last value
            String value = pRemoteConnection.getHeaderField(i);

            // If the key is not null, life is simple, and Sun is shining
            // However, the default implementations includes the HTTP response
            // code ("HTTP/1.1 200 Ok" or similar) as a header field with
            // key "null" (why..?)...
            // In addition, we want to skip the original "Server" header
            if (key != null && !HTTP_RESPONSE_HEADER_SERVER.equalsIgnoreCase(key)) {
                //System.out.println("client <<<-- remote: " + key + ": " + value);
                pResponse.setHeader(key, value);
            }
            else if (value == null) {
                // If BOTH key and value is null, there are no more header fields
                break;
            }

            i++;
        }

        /* 1.4+ version below....
        Map headers = pRemoteConnection.getHeaderFields();
        for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry header = (Map.Entry) iterator.next();

            List values = (List) header.getValue();

            for (Iterator valueIter = values.iterator(); valueIter.hasNext();) {
                String value = (String) valueIter.next();
                String key = (String) header.getKey();

                // Skip the server header
                if (HTTP_RESPONSE_HEADER_SERVER.equalsIgnoreCase(key)) {
                    key = null;
                }

                // The default implementations includes the HTTP response code
                // ("HTTP/1.1 200 Ok" or similar) as a header field with
                // key "null" (why..?)...
                if (key != null) {
                    //System.out.println("client <<<-- remote: " + key + ": " + value);
                    pResponse.setHeader(key, value);
                }
            }
        }
        */
    }
547507
private MIMETypedStream getFromWeb(String url, String user, String pass,
            String knownMimeType, boolean headOnly, Context context)
            throws GeneralException, RangeNotSatisfiableException {
        logger.debug("DefaultExternalContentManager.getFromWeb({})", url);
        if (url == null) throw new GeneralException("null url");
        HttpInputStream response = null;
        try {
            if (headOnly) {
                response = m_http.head(url, true, user, pass,
                        context.getHeaderValue(HttpHeaders.IF_NONE_MATCH),
                        context.getHeaderValue(HttpHeaders.IF_MODIFIED_SINCE),
                        context.getHeaderValue("Range"));
            } else {
                response = m_http.get(
                        url, true, user, pass,
                        context.getHeaderValue(HttpHeaders.IF_NONE_MATCH),
                        context.getHeaderValue(HttpHeaders.IF_MODIFIED_SINCE),
                        context.getHeaderValue("Range"));
            }
            String mimeType =
                    response.getResponseHeaderValue(HttpHeaders.CONTENT_TYPE,
                                                    knownMimeType);
            long length = Long.parseLong(response.getResponseHeaderValue(HttpHeaders.CONTENT_LENGTH,"-1"));
            Property[] headerArray =
                    toPropertyArray(response.getResponseHeaders());
            if (mimeType == null || mimeType.isEmpty()) {
                mimeType = DEFAULT_MIMETYPE;
            }
            if (response.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
                response.close();
                Header[] respHeaders = response.getResponseHeaders();
                Property[] properties = new Property[respHeaders.length];
                for (int i = 0; i < respHeaders.length; i++){
                    properties[i] =
                        new Property(respHeaders[i].getName(), respHeaders[i].getValue());
                }
                return MIMETypedStream.getNotModified(properties);
            } else if (response.getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) {
            	MIMETypedStream pc_response = new MIMETypedStream(mimeType, response,
                        headerArray, length);
            	pc_response.setStatusCode(HttpStatus.SC_PARTIAL_CONTENT);
            	return pc_response;
            } else if (response.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
            	response.close();
            	throw new RangeNotSatisfiableException("External URL datastream request returned 416 Range Not Satisfiable");
            } else {
                if (headOnly) {
                    try {
                        response.close();
                    } catch (IOException ioe) {
                        logger.warn("problem closing HEAD response: {}", ioe.getMessage());
                    }
                    
                    return new MIMETypedStream(mimeType, NullInputStream.NULL_STREAM,
                            headerArray, length);
                } else {
                    return new MIMETypedStream(mimeType, response, headerArray, length);
                }
            }
        } catch (RangeNotSatisfiableException re){
        	logger.error(re.getMessage(), re);
        	throw re;                    
        } catch (Exception e) {
            throw new GeneralException("Error getting " + url, e);
        }
    }
498445
public final Source source(final Source source) {
    return new Source() {
      @Override public long read(Buffer sink, long byteCount) throws IOException {
        boolean throwOnTimeout = false;
        enter();
        try {
          long result = source.read(sink, byteCount);
          throwOnTimeout = true;
          return result;
        } catch (IOException e) {
          throw exit(e);
        } finally {
          exit(throwOnTimeout);
        }
      }

      @Override public void close() throws IOException {
        boolean throwOnTimeout = false;
        try {
          source.close();
          throwOnTimeout = true;
        } catch (IOException e) {
          throw exit(e);
        } finally {
          exit(throwOnTimeout);
        }
      }

      @Override public Timeout timeout() {
        return AsyncTimeout.this;
      }

      @Override public String toString() {
        return "AsyncTimeout.source(" + source + ")";
      }
    };
  }
1303210
@SuppressWarnings({ "unchecked", "rawtypes" })
    public static Object convert(Object source, Class<?> target) throws ConversionException {
        if (target == null) {
            throw new ConversionException("Unable to perform conversion, target was null");
        }
        if (source == null) {
            if (target.isPrimitive()) {
                throw new ConversionException(String.format("Unable to convert null to primitive value of %s", target));
            }
            return source;
        } else if ((source instanceof Float && ((Float) source).isNaN()) || (source instanceof Double && ((Double) source).isNaN())) {
            // Don't convert NaN values
            return source;
        }
        //		if (BaseConnection.class.isAssignableFrom(source.getClass()) && !target.equals(IConnection.class)) {
        //			log.debug("Conversion failure - source: {} target: {}", source.getClass(), target);
        //			throw new ConversionException("Source is not assignable and target is not equal to IConnection");
        //		}
        if (target.isInstance(source)) {
            return source;
        }
        if (target.isAssignableFrom(source.getClass())) {
            return source;
        }
        if (target.isArray()) {
            return convertToArray(source, target);
        }
        if (target.equals(String.class)) {
            return source.toString();
        }
        if (target.isPrimitive()) {
            return convertToWrappedPrimitive(source, primitiveMap.get(target));
        }
        if (wrapperMap.containsKey(target)) {
            return convertToWrappedPrimitive(source, target);
        }
        if (target.equals(Map.class)) {
            return convertBeanToMap(source);
        }
        if (target.equals(List.class) || target.equals(Collection.class)) {
            if (source.getClass().equals(LinkedHashMap.class)) {
                return convertMapToList((LinkedHashMap<?, ?>) source);
            } else if (source.getClass().isArray()) {
                return convertArrayToList((Object[]) source);
            }
        }
        if (target.equals(Set.class) && source.getClass().isArray()) {
            return convertArrayToSet((Object[]) source);
        }
        if (target.equals(Set.class) && source instanceof List) {
            return new HashSet((List) source);
        }
        if (source instanceof Map) {
            return convertMapToBean((Map) source, target);
        }
        throw new ConversionException(String.format("Unable to preform conversion from %s to %s", source, target));
    }
975515
def range_return(request, items):
    
    if ('Range' in request.headers):
        range = parse_range_header(request.headers['Range'])
    elif 'X-Range' in request.headers:
        range = parse_range_header(request.headers['X-Range'])
    else:
        range = {
            'start': 0,
            'finish': MAX_NUMBER_ITEMS - 1,
            'count': MAX_NUMBER_ITEMS
        }
    filtered = items[range['start']:range['finish'] + 1]
    if len(filtered) < range['count']:
        # Something was stripped, deal with it
        range['count'] = len(filtered)
        range['finish'] = range['start'] + range['count'] - 1
    if range['finish'] - range['start'] + 1 >= MAX_NUMBER_ITEMS:
        range['finish'] = range['start'] + MAX_NUMBER_ITEMS - 1
        filtered = items[range['start']:range['finish'] + 1]

    request.response.headers['Content-Range'] = 'items %d-%d/%d' % (range['start'], range['finish'], len(items))
    request.response.headers['X-Content-Range'] = request.response.headers['Content-Range']
    return filtered
1075120
public Object javaToSql(Object source)
    {
        if (source == null)
            return null;
        try
        {
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            GZIPOutputStream gos = new GZIPOutputStream(bao);
            ObjectOutputStream oos = new ObjectOutputStream(gos);
            oos.writeObject(source);
            oos.close();
            gos.close();
            bao.close();
            byte[] result = bao.toByteArray();
            return result;
        }
        catch (Throwable t)
        {
            throw new ConversionException(t);
        }
    }
362955
public static <T> Range<T> from(Boundary<T> lower, Boundary<T> upper) {
        return new Range<T>(lower, upper);
    }
1067989
@Nonnull
  @ReturnsMutableCopy
  public static HttpHeaderMap getResponseHeaderMap (@Nonnull final HttpServletResponse aHttpResponse)
  {
    ValueEnforcer.notNull (aHttpResponse, "HttpResponse");

    final HttpHeaderMap ret = new HttpHeaderMap ();
    for (final String sName : aHttpResponse.getHeaderNames ())
      for (final String sValue : aHttpResponse.getHeaders (sName))
        ret.addHeader (sName, sValue);
    return ret;
  }
800369
public static long[][] getRange(Map<String, String> headers) {
		String rangeValue = getHeaderValue(headers, HTTP_RANGE_HEADER_UP);
		if (rangeValue == null) return null;
		rangeValue = rangeValue.trim();
		return parseRanges(rangeValue);
	}
722882
@Override
	public BitStore range(int from, int to) {
		return store.range(from, to).immutableView();
	}
1153439
public static <S, T> Convert<S, T> to(Class<T> targetType, Position.Readable<S> sourcePosition) {
        return new Convert<>(sourcePosition, targetType);
    }
370124
public static RangeImpl range(
            EvaluationContext ctx,
            Range.RangeBoundary lowBoundary,
            Object lowEndPoint,
            Object highEndPoint,
            Range.RangeBoundary highBoundary) {

        Comparable left = asComparable(lowEndPoint);
        Comparable right = asComparable(highEndPoint);
        if (left == null || right == null || !compatible(left, right)) {
            ctx.notifyEvt(() -> new ASTEventBase(
                    FEELEvent.Severity.ERROR,
                    Msg.createMessage(
                            Msg.INCOMPATIBLE_TYPE_FOR_RANGE,
                            left.getClass().getSimpleName()
                    ),
                    null));
            return null;
        }
        return new RangeImpl(
                lowBoundary,
                left,
                right,
                highBoundary);
    }
176817
public static RubyRange<String> range(String start, String end) {
    return new RubyRange<>(StringSuccessor.getInstance(), start, end,
        Interval.CLOSED);
  }
715843
public static LongStream rangeValues(Collection<Protos.Resource> resources) {
		checkNotNull(resources);
		return resources.stream()
			.filter(Protos.Resource::hasRanges)
			.flatMap(r -> r.getRanges().getRangeList().stream())
			.flatMapToLong(Utils::rangeValues);
	}
563719
public Object javaToSql(Object source)
    {
        synchronized (byteOut)
        {
            try
            {
                if (gzipOut == null)
                {
                    gzipOut = new GZIPOutputStream(uuOut);
                    objOut = new ObjectOutputStream(gzipOut);
                }

                /*
                ** Clear out the byte array
                */
                byteOut.reset();

                objOut.writeObject(source);
                objOut.flush();
                gzipOut.finish();
                gzipOut.flush();

                return (byteOut.toString());
            }
            catch (Throwable t)
            {
                throw new ConversionException(t);
            }
        }
    }