ProxyImpl.java 24.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Binary
 *  javax.jcr.RepositoryException
 *  javax.servlet.http.HttpServletRequest
 *  org.apache.commons.io.IOUtils
 *  org.apache.http.Header
 *  org.apache.http.HttpEntity
 *  org.apache.http.HttpHost
 *  org.apache.http.NameValuePair
 *  org.apache.http.StatusLine
 *  org.apache.http.auth.AuthScheme
 *  org.apache.http.auth.AuthScope
 *  org.apache.http.auth.Credentials
 *  org.apache.http.client.AuthCache
 *  org.apache.http.client.CredentialsProvider
 *  org.apache.http.client.config.RequestConfig
 *  org.apache.http.client.config.RequestConfig$Builder
 *  org.apache.http.client.methods.CloseableHttpResponse
 *  org.apache.http.client.methods.HttpGet
 *  org.apache.http.client.methods.HttpPost
 *  org.apache.http.client.methods.HttpUriRequest
 *  org.apache.http.client.protocol.HttpClientContext
 *  org.apache.http.client.utils.URIBuilder
 *  org.apache.http.entity.ContentType
 *  org.apache.http.entity.mime.MultipartEntityBuilder
 *  org.apache.http.impl.auth.BasicScheme
 *  org.apache.http.impl.client.BasicAuthCache
 *  org.apache.http.impl.client.BasicCredentialsProvider
 *  org.apache.http.impl.client.CloseableHttpClient
 *  org.apache.http.message.BasicHeader
 *  org.apache.http.message.BasicNameValuePair
 *  org.apache.http.protocol.HttpContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.crx.packaging.impl.proxy;

import com.day.crx.packaging.Proxy;
import com.day.crx.packaging.ProxyTracker;
import com.day.crx.packaging.TrackingInputStream;
import com.day.crx.packaging.impl.proxy.AttributeList;
import com.day.crx.packaging.impl.proxy.DocumentHandler;
import com.day.crx.packaging.impl.proxy.HtmlParser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jcr.Binary;
import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProxyImpl
implements DocumentHandler,
Proxy {
    private static final Logger log = LoggerFactory.getLogger(ProxyImpl.class);
    private static Pattern URL_PATTERN = Pattern.compile("url\\(\\s*(['\"]?)([^'\")]*)(['\"]?\\s*)\\)");
    private final String rewritePath;
    private final String spoolPath;
    private URI targetURL;
    private Writer writer;
    private boolean ignoreTypeAttribute;
    private List<NameValuePair> extraParams = new LinkedList<NameValuePair>();
    private MultipartEntityBuilder mpBuilder = null;
    private List<Header> extraHeaders = new LinkedList<Header>();
    private final CloseableHttpClient httpClient;
    private final HttpHost targetHost;
    private CloseableHttpResponse response;
    private String contentType;
    private String lastModified;
    private Credentials credentials;
    private ProxyTracker tracker;
    private String contextPath = "";
    private String idString = null;
    private boolean followRedirects = false;

    public ProxyImpl(CloseableHttpClient httpClient, HttpHost targetHost, String rewritePath, String spoolPath) {
        this.httpClient = httpClient;
        this.targetHost = targetHost;
        this.rewritePath = rewritePath;
        this.spoolPath = spoolPath;
    }

    @Override
    public ProxyTracker getTracker() {
        return this.tracker;
    }

    @Override
    public void setFollowRedirects(boolean followRedirects) {
        this.followRedirects = followRedirects;
    }

    @Override
    public void setTracker(ProxyTracker tracker) {
        this.tracker = tracker;
    }

    @Override
    public void setIdString(String id) {
        this.idString = id;
    }

    @Override
    public void setContextPath(String path) {
        if (path.length() > 0 && path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        this.contextPath = path;
    }

    @Override
    public void addExtraParameter(String name, String value) {
        this.extraParams.add((NameValuePair)new BasicNameValuePair(name, value));
    }

    @Override
    public void addExtraHeader(String name, String value) {
        this.extraHeaders.add((Header)new BasicHeader(name, value));
    }

    @Override
    public void addExtraParameters(HttpServletRequest request) {
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            String name = e.nextElement().toString();
            for (String p : request.getParameterValues(name)) {
                this.extraParams.add((NameValuePair)new BasicNameValuePair(name, p));
            }
        }
    }

    @Override
    public void addExtraFile(String name, File file) throws FileNotFoundException {
        if (this.mpBuilder == null) {
            this.mpBuilder = MultipartEntityBuilder.create();
        }
        this.mpBuilder.addBinaryBody(name, file);
    }

    @Override
    public void addExtraFile(String name, File file, String fileName) throws FileNotFoundException {
        if (this.mpBuilder == null) {
            this.mpBuilder = MultipartEntityBuilder.create();
        }
        this.mpBuilder.addBinaryBody(name, file, ContentType.APPLICATION_OCTET_STREAM, fileName);
    }

    @Override
    public void addExtraFile(String name, Binary data, String filename) throws FileNotFoundException {
        if (this.mpBuilder == null) {
            this.mpBuilder = MultipartEntityBuilder.create();
        }
        this.mpBuilder.addBinaryBody(name, (InputStream)new BinaryInputStream(data), ContentType.APPLICATION_OCTET_STREAM, filename);
    }

    @Override
    public boolean isIgnoreTypeAttribute() {
        return this.ignoreTypeAttribute;
    }

    @Override
    public void setIgnoreTypeAttribute(boolean ignoreTypeAttribute) {
        this.ignoreTypeAttribute = ignoreTypeAttribute;
    }

    @Override
    public void setWriter(PrintWriter writer) {
        this.writer = writer;
    }

    @Override
    public Credentials getCredentials() {
        return this.credentials;
    }

    @Override
    public void setCredentials(Credentials credentials) {
        this.credentials = credentials;
    }

    @Override
    public void onStart() throws IOException {
    }

    @Override
    public void onStartElement(String name, AttributeList attList, char[] ch, int off, int len, boolean endSlash) throws IOException {
        String suffix = null;
        String upperName = name.toUpperCase();
        if ("A".equals(upperName)) {
            boolean spool = !this.ignoreTypeAttribute && attList.containsAttribute("type");
            this.rewriteRef(attList, "HREF", spool);
        } else if ("AREA".equals(upperName)) {
            this.rewriteRef(attList, "HREF", false);
        } else if ("FORM".equals(upperName)) {
            suffix = this.rewriteForm(attList);
        } else if ("FRAME".equals(upperName)) {
            this.rewriteRef(attList, "SRC", true);
        } else if ("IFRAME".equals(upperName)) {
            this.rewriteRef(attList, "SRC", true);
        } else if ("IMG".equals(upperName)) {
            this.rewriteRef(attList, "SRC", true);
        } else if ("INPUT".equals(upperName)) {
            this.rewriteRef(attList, "SRC", true);
        } else if ("LINK".equals(upperName)) {
            this.rewriteRef(attList, "HREF", true);
        } else if ("SCRIPT".equals(upperName)) {
            this.rewriteRef(attList, "SRC", true);
        } else if ("TABLE".equals(upperName)) {
            this.rewriteRef(attList, "BACKGROUND", true);
        } else if ("TD".equals(upperName)) {
            this.rewriteRef(attList, "BACKGROUND", true);
        } else if ("TR".equals(upperName)) {
            this.rewriteRef(attList, "BACKGROUND", true);
        }
        if (attList.isModified()) {
            this.writer.write(this.serialize(name, attList, endSlash));
        } else {
            this.writer.write(ch, off, len);
        }
        if (suffix != null) {
            this.writer.write(suffix);
        }
    }

    private String serialize(String name, AttributeList attList, boolean endSlash) {
        StringBuffer buffer = new StringBuffer(256);
        buffer.append("<");
        buffer.append(name);
        Iterator<String> attNames = attList.attributeNames();
        while (attNames.hasNext()) {
            String attName = attNames.next();
            String attValue = attList.getQuotedValue(attName);
            buffer.append(" ");
            buffer.append(attName);
            if (attValue == null) continue;
            buffer.append('=');
            buffer.append(attValue);
        }
        if (endSlash) {
            buffer.append(" /");
        }
        buffer.append(">");
        return buffer.toString();
    }

    @Override
    public void characters(char[] ch, int off, int len) throws IOException {
        this.writer.write(ch, off, len);
    }

    public void characters(String c) throws IOException {
        this.writer.write(c);
    }

    @Override
    public void onEndElement(String name, char[] ch, int off, int len) {
        try {
            this.writer.write(ch, off, len);
        }
        catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void onEnd() throws IOException {
        this.writer.flush();
    }

    private String rewriteForm(AttributeList attList) {
        String action = attList.getValue("ACTION");
        if (action != null && action.length() > 0) {
            String method = attList.getValue("METHOD");
            action = this.rewriteURL(action, "POST".equalsIgnoreCase(method));
            attList.setValue("ACTION", action);
        }
        return null;
    }

    private void rewriteRef(AttributeList attList, String attName, boolean spool) {
        String ref = attList.getValue(attName);
        if (ref != null) {
            attList.setValue(attName, this.rewriteURL(ref, spool));
        }
    }

    @Override
    public String rewriteURL(String url, boolean spool) {
        if (url.startsWith("#")) {
            return url;
        }
        int firstSlash = url.indexOf(47);
        int firstColon = url.indexOf(58);
        if (firstColon >= 0 && (firstSlash < 0 || firstColon < firstSlash)) {
            return url;
        }
        if (firstSlash != 0) {
            url = this.targetURL.resolve(url).getPath();
        }
        StringBuilder newValue = new StringBuilder(this.contextPath);
        if (spool) {
            newValue.append(this.spoolPath);
        } else {
            newValue.append(this.rewritePath);
        }
        newValue.append(url);
        return newValue.toString();
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void rewriteHtml(InputStream in) throws IOException {
        String encoding = "8859_1";
        int charsetIndex = this.contentType.indexOf("charset=");
        if (charsetIndex != -1) {
            encoding = this.contentType.substring(charsetIndex + "charset=".length()).trim();
        }
        HashSet<String> inclusionSet = new HashSet<String>();
        inclusionSet.add("A");
        inclusionSet.add("AREA");
        inclusionSet.add("FORM");
        inclusionSet.add("FRAME");
        inclusionSet.add("IFRAME");
        inclusionSet.add("IMG");
        inclusionSet.add("INPUT");
        inclusionSet.add("LINK");
        inclusionSet.add("SCRIPT");
        inclusionSet.add("TABLE");
        inclusionSet.add("TD");
        inclusionSet.add("TR");
        inclusionSet.add("NOREWRITE");
        HtmlParser parser = new HtmlParser();
        parser.setTagInclusionSet(inclusionSet);
        parser.setDocumentHandler(this);
        BufferedReader reader = null;
        try {
            int len;
            reader = new BufferedReader(new InputStreamReader(in, encoding));
            char[] buf = new char[2048];
            while ((len = reader.read(buf)) != -1) {
                parser.update(buf, 0, len);
            }
            parser.finished();
        }
        finally {
            IOUtils.closeQuietly((Reader)reader);
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public void spoolCss(Writer out) throws IOException {
        String encoding = "8859_1";
        int charsetIndex = this.contentType.indexOf("charset=");
        if (charsetIndex != -1) {
            encoding = this.contentType.substring(charsetIndex + "charset=".length()).trim();
        }
        long start = System.currentTimeMillis();
        String css = "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(this.response.getEntity().getContent(), encoding));
            css = IOUtils.toString((Reader)reader);
        }
        finally {
            IOUtils.closeQuietly((Reader)reader);
        }
        long end = System.currentTimeMillis();
        log.debug("read css in {}ms {} bytes", (Object)(end - start), (Object)css.length());
        Matcher m = URL_PATTERN.matcher(css);
        StringBuffer result = new StringBuffer();
        while (m.find()) {
            String url = m.group(2);
            if (url.startsWith("absolute:")) {
                url = url.substring(9);
            } else if (!url.endsWith(".htc") && !url.startsWith("//")) {
                url = this.rewriteURL(url, true);
            }
            m.appendReplacement(result, "url($1" + url + "$3)");
        }
        m.appendTail(result);
        out.write(result.toString());
        out.flush();
    }

    private URI prepare(String path) throws IOException, URISyntaxException {
        if (this.response != null) {
            throw new IllegalStateException("already connected");
        }
        if (!path.startsWith("/")) {
            throw new IllegalArgumentException("Invalid path " + path);
        }
        try {
            this.targetURL = new URI(path);
        }
        catch (URISyntaxException e) {
            throw new IOException(e);
        }
        LinkedList<NameValuePair> ps = new LinkedList<NameValuePair>(this.extraParams);
        if (this.idString != null) {
            ps.add((NameValuePair)new BasicNameValuePair("daypsid", this.idString));
        }
        if (this.credentials != null && path.indexOf("sling:authRequestLogin") < 0) {
            ps.add((NameValuePair)new BasicNameValuePair("sling:authRequestLogin", "1"));
        }
        URIBuilder uri = new URIBuilder((Object)this.targetHost + path);
        if (!ps.isEmpty()) {
            uri.addParameters(ps);
        }
        return uri.build();
    }

    private int postProcessResponse() {
        Header hdr = this.response.getFirstHeader("Content-Type");
        this.contentType = hdr == null ? "text/plain" : hdr.getValue();
        Header h = this.response.getFirstHeader("Last-Modified");
        this.lastModified = h == null ? null : h.getValue();
        return this.response.getStatusLine().getStatusCode();
    }

    @Override
    public int doGet(String path) throws IOException {
        HttpGet request;
        try {
            URI uri = this.prepare(path);
            request = new HttpGet(uri);
        }
        catch (URISyntaxException e) {
            throw new IOException(e);
        }
        for (Header h : this.extraHeaders) {
            request.addHeader(h);
        }
        request.addHeader("User-Agent", "Day cq-packageshare-client");
        request.setConfig(RequestConfig.custom().setRedirectsEnabled(this.followRedirects).build());
        HttpClientContext context = HttpClientContext.create();
        if (this.credentials != null) {
            BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, this.credentials);
            context.setCredentialsProvider((CredentialsProvider)credsProvider);
            BasicAuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(this.targetHost, (AuthScheme)basicAuth);
            context.setAuthCache((AuthCache)authCache);
        }
        this.response = this.httpClient.execute((HttpUriRequest)request, (HttpContext)context);
        return this.postProcessResponse();
    }

    @Override
    public int doPost(String path) throws IOException {
        HttpPost request;
        try {
            URI uri = this.prepare(path);
            request = new HttpPost(uri);
        }
        catch (URISyntaxException e) {
            throw new IOException(e);
        }
        if (this.mpBuilder != null) {
            request.setEntity(this.mpBuilder.build());
        }
        for (Header h : this.extraHeaders) {
            request.addHeader(h);
        }
        request.addHeader("User-Agent", "Day cq-packageshare-client");
        HttpClientContext context = HttpClientContext.create();
        if (this.credentials != null) {
            BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, this.credentials);
            context.setCredentialsProvider((CredentialsProvider)credsProvider);
            BasicAuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(this.targetHost, (AuthScheme)basicAuth);
            context.setAuthCache((AuthCache)authCache);
        }
        this.response = this.httpClient.execute((HttpUriRequest)request, (HttpContext)context);
        return this.postProcessResponse();
    }

    @Override
    public void close() {
        if (this.response != null) {
            try {
                this.response.close();
            }
            catch (IOException e) {
                log.error("error while closing response", (Throwable)e);
            }
        }
        this.response = null;
        this.mpBuilder = null;
    }

    @Override
    public boolean isHtml() {
        return this.contentType != null && this.contentType.startsWith("text/html");
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public String getLastModified() {
        return this.lastModified;
    }

    @Override
    public void setLastModified(String lastModified) {
        this.lastModified = lastModified;
    }

    @Override
    public long getContentLength() {
        return this.response.getEntity().getContentLength();
    }

    @Override
    public String getLocation(boolean rewrite, boolean spool) {
        String location = this.getResponseHeaderValue("Location");
        if (location == null) {
            log.error("No location header in response.");
            return null;
        }
        if (rewrite) {
            if (!location.startsWith("/")) {
                log.error("Location must not be absolute url.");
                return null;
            }
            location = this.rewriteURL(location, spool);
        }
        return location;
    }

    @Override
    public Header getResponseHeader(String name) {
        return this.response.getFirstHeader(name);
    }

    @Override
    public String getResponseHeaderValue(String name) {
        Header header = this.getResponseHeader(name);
        return header == null ? null : header.getValue();
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public void rewrite(Writer writer) throws IOException {
        if (this.writer == null) {
            this.writer = writer;
        }
        InputStream in = this.response.getEntity().getContent();
        try {
            if (in != null) {
                this.rewriteHtml(in);
            }
        }
        finally {
            IOUtils.closeQuietly((InputStream)in);
            this.close();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public int spool(OutputStream out) throws IOException {
        InputStream in = this.response.getEntity().getContent();
        try {
            if (in != null) {
                int n;
                long len = this.response.getEntity().getContentLength();
                byte[] buffer = new byte[8192];
                long count = 0;
                while (-1 != (n = in.read(buffer))) {
                    out.write(buffer, 0, n);
                    count += (long)n;
                    if (this.tracker == null) continue;
                    this.tracker.onProgress(count, len);
                }
                int n2 = (int)count;
                return n2;
            }
            int len = -1;
            return len;
        }
        finally {
            IOUtils.closeQuietly((InputStream)in);
            this.close();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public String fetch() throws IOException {
        try {
            Header hdr = this.response.getEntity().getContentEncoding();
            String encoding = hdr == null ? null : hdr.getValue();
            String string = IOUtils.toString((InputStream)this.response.getEntity().getContent(), (String)(encoding == null ? "utf-8" : encoding));
            return string;
        }
        finally {
            this.close();
        }
    }

    public class BinaryInputStream
    extends InputStream {
        private final Binary data;
        private InputStream delegatee;

        public BinaryInputStream(Binary data) {
            this.data = data;
        }

        @Override
        public int read() throws IOException {
            return this.getInputStream().read();
        }

        @Override
        public int read(byte[] b) throws IOException {
            return this.getInputStream().read(b);
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            return this.getInputStream().read(b, off, len);
        }

        @Override
        public long skip(long n) throws IOException {
            return this.getInputStream().skip(n);
        }

        @Override
        public int available() throws IOException {
            return this.getInputStream().available();
        }

        @Override
        public void close() throws IOException {
            this.getInputStream().close();
        }

        public long getLength() {
            try {
                return this.data.getSize();
            }
            catch (RepositoryException e) {
                return -1;
            }
        }

        private InputStream getInputStream() throws IOException {
            if (this.delegatee == null) {
                try {
                    this.delegatee = this.data.getStream();
                    if (ProxyImpl.this.tracker != null) {
                        this.delegatee = new TrackingInputStream(this.delegatee, this.getLength(), ProxyImpl.this.tracker);
                    }
                }
                catch (RepositoryException e) {
                    throw new IOException("Error while retrieving string", (Throwable)e);
                }
            }
            return this.delegatee;
        }
    }

}