Http.java 45.7 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 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.auth.oauth.AccessTokenProvider
 *  com.adobe.granite.keystore.KeyStoreService
 *  com.day.durbo.DurboInput
 *  com.day.durbo.DurboInput$Element
 *  com.day.durbo.DurboInput$Property
 *  com.day.durbo.DurboValue
 *  javax.jcr.Credentials
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.SimpleCredentials
 *  org.apache.commons.httpclient.Credentials
 *  org.apache.commons.httpclient.DefaultHttpMethodRetryHandler
 *  org.apache.commons.httpclient.Header
 *  org.apache.commons.httpclient.HostConfiguration
 *  org.apache.commons.httpclient.HttpClient
 *  org.apache.commons.httpclient.HttpConnectionManager
 *  org.apache.commons.httpclient.HttpMethod
 *  org.apache.commons.httpclient.HttpMethodBase
 *  org.apache.commons.httpclient.HttpState
 *  org.apache.commons.httpclient.HttpVersion
 *  org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
 *  org.apache.commons.httpclient.NTCredentials
 *  org.apache.commons.httpclient.StatusLine
 *  org.apache.commons.httpclient.UsernamePasswordCredentials
 *  org.apache.commons.httpclient.auth.AuthScope
 *  org.apache.commons.httpclient.methods.EntityEnclosingMethod
 *  org.apache.commons.httpclient.methods.GetMethod
 *  org.apache.commons.httpclient.methods.InputStreamRequestEntity
 *  org.apache.commons.httpclient.methods.PostMethod
 *  org.apache.commons.httpclient.methods.PutMethod
 *  org.apache.commons.httpclient.methods.RequestEntity
 *  org.apache.commons.httpclient.params.HttpClientParams
 *  org.apache.commons.httpclient.params.HttpConnectionManagerParams
 *  org.apache.commons.httpclient.params.HttpMethodParams
 *  org.apache.commons.httpclient.protocol.Protocol
 *  org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory
 *  org.apache.commons.io.FileUtils
 *  org.apache.commons.io.IOUtils
 *  org.apache.commons.lang.StringUtils
 *  org.apache.commons.lang.text.StrSubstitutor
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.PropertyUnbounded
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferenceCardinality
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.util.ISO8601
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.apache.sling.commons.osgi.ServiceUtil
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.replication.impl.transport;

import com.adobe.granite.auth.oauth.AccessTokenProvider;
import com.adobe.granite.keystore.KeyStoreService;
import com.day.cq.replication.AgentConfig;
import com.day.cq.replication.PollingTransportHandler;
import com.day.cq.replication.ReplicationAction;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationContent;
import com.day.cq.replication.ReplicationContentFactory;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.ReplicationLog;
import com.day.cq.replication.ReplicationResult;
import com.day.cq.replication.ReplicationTransaction;
import com.day.cq.replication.ReverseReplication;
import com.day.cq.replication.TransportContext;
import com.day.cq.replication.TransportException;
import com.day.cq.replication.TransportHandler;
import com.day.cq.replication.UnrecoverableReplicationException;
import com.day.cq.replication.impl.transport.AuthSSLProtocolSocketFactory;
import com.day.cq.replication.impl.transport.EasySSLProtocolSocketFactory;
import com.day.durbo.DurboInput;
import com.day.durbo.DurboValue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListMap;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.net.ssl.KeyManager;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpVersion;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.StatusLine;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrSubstitutor;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.util.ISO8601;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.commons.osgi.ServiceUtil;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1)
@Service(value={TransportHandler.class})
@Reference(name="accessTokenProvider", referenceInterface=AccessTokenProvider.class, bind="bindAccessTokenProvider", unbind="unbindAccessTokenProvider", cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC)
public class Http
implements TransportHandler,
PollingTransportHandler {
    static final String ACCESS_TOKEN_PROPERTY = "accessTokenProvider";
    @Property(label="%disabled.cipher.suites.name", description="%disabled.cipher.suites.description", unbounded=PropertyUnbounded.ARRAY)
    public static final String DISABLED_CIPHER_SUITES = "disabled.cipher.suites";
    @Property(label="%enabled.cipher.suites.name", description="%enabled.cipher.suites.description", unbounded=PropertyUnbounded.ARRAY)
    public static final String ENABLED_CIPHER_SUITES = "enabled.cipher.suites";
    @Reference
    private KeyStoreService keyStoreService;
    @Reference
    private ResourceResolverFactory rrf;
    @Reference
    private SlingRepository slingRepository;
    protected String[] disabledSuites;
    protected String[] enabledSuites;
    public static final String DEFAULT_HTTP_METHOD = "POST";
    private static final String PN_TIMELINE = "timeline";
    private static final String BEARER_AUTHENTICATION_FORMAT = "Bearer %s";
    private static final String AUTHORIZATION_HEADER = "Authorization";
    private Map<String, Comparable<Object>> accessTokenProvidersProps = new ConcurrentSkipListMap(Collections.reverseOrder());
    private Map<Comparable<Object>, AccessTokenProvider> accessTokenProviders = new ConcurrentSkipListMap(Collections.reverseOrder());
    public static final String[] DEFAULT_HTTP_HEADERS = new String[]{"Action: {action}", "Path: {path}", "Handle: {path}"};
    private static final ReplicationAction DEFAULT_ACTION = new ReplicationAction(ReplicationActionType.ACTIVATE, "");
    private static final ReverseReplication[] EMPTY = new ReverseReplication[0];

    @Override
    public boolean canHandle(AgentConfig config) {
        String uri = config == null ? null : config.getTransportURI();
        return uri != null && (uri.startsWith("http://") || uri.startsWith("https://")) && !uri.contains("binaryless=true");
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public ReplicationResult deliver(TransportContext ctx, ReplicationTransaction tx) throws ReplicationException {
        Object client;
        State state = (State)ctx.getAttribute(Http.class.getName());
        if (state == null) {
            client = this.createHttpClient(ctx.getName(), ctx.getConfig(), tx.getLog());
            state = new State((HttpClient)client);
            ctx.setAttribute(Http.class.getName(), state);
        }
        if (state.action != null) {
            throw new ReplicationException("Only 1 replication per agent allowed. already replicating : " + state.action);
        }
        state.action = tx.getAction();
        try {
            client = this.deliver(state.client, ctx.getConfig(), tx.getLog(), tx.getAction(), tx.getContent());
            return client;
        }
        finally {
            state.action = null;
        }
    }

    public ReplicationResult poll(TransportContext ctx, ReplicationTransaction tx, List<ReplicationContent> result, ReplicationContentFactory factory) throws ReplicationException {
        try {
            ReverseReplication[] reps;
            for (ReverseReplication rep : reps = this.poll(ctx, tx, factory)) {
                result.add(rep.getContent());
            }
            return ReplicationResult.OK;
        }
        catch (TransportException e) {
            return e.getResult();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public ReverseReplication[] poll(TransportContext ctx, ReplicationTransaction tx, ReplicationContentFactory factory) throws ReplicationException {
        ReverseReplication[] client;
        State state = (State)ctx.getAttribute(Http.class.getName());
        if (state == null) {
            client = this.createHttpClient(ctx.getName(), ctx.getConfig(), tx.getLog());
            state = new State((HttpClient)client);
            ctx.setAttribute(Http.class.getName(), state);
        }
        if (state.action != null) {
            throw new ReplicationException("Only 1 retrieval per agent allowed. already retrieving : " + state.action);
        }
        state.action = tx.getAction();
        try {
            client = this.poll(state.client, ctx.getConfig(), tx.getLog(), tx.getAction(), factory);
            return client;
        }
        finally {
            state.action = null;
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private HttpClient createHttpClient(String name, AgentConfig config, ReplicationLog log) throws ReplicationException {
        DefaultHeaderHttpClient client;
        block41 : {
            String localAddress;
            ValueMap conf;
            String version;
            log.info("Create new HttpClient for %s", name);
            client = new DefaultHeaderHttpClient();
            String user = config.getTransportUser();
            if (user != null && user.length() > 0) {
                String pass = config.getTransportPassword();
                if (pass == null) {
                    pass = "";
                }
                log.info("* Auth User: %s", user);
                client.getParams().setAuthenticationPreemptive(true);
                client.getState().setCredentials(AuthScope.ANY, (Credentials)new UsernamePasswordCredentials(user, pass));
            }
            if ("0.9".equals(version = (String)(conf = config.getProperties()).get("protocolVersion", (Object)"1.1"))) {
                log.info("* HTTP Version: 0.9");
                client.getParams().setVersion(HttpVersion.HTTP_0_9);
            } else if ("1.0".equals(version)) {
                log.info("* HTTP Version: 1.0");
                client.getParams().setVersion(HttpVersion.HTTP_1_0);
            } else {
                log.info("* HTTP Version: 1.1");
                client.getParams().setVersion(HttpVersion.HTTP_1_1);
            }
            int timeout = (Integer)conf.get("protocolConnectTimeout", (Object)0);
            if (timeout > 0) {
                log.info("* Connect Timeout: %d", timeout);
                client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
            }
            if ((timeout = ((Integer)conf.get("protocolSocketTimeout", (Object)0)).intValue()) > 0) {
                log.info("* Socket Timeout: %d", timeout);
                client.getParams().setSoTimeout(timeout);
            }
            if ((localAddress = (String)conf.get("protocolInterface", (Object)"")).length() > 0) {
                try {
                    client.getHostConfiguration().setLocalAddress(InetAddress.getByName(localAddress));
                }
                catch (UnknownHostException e) {
                    log.info("Cannot set local address to %s: %s", localAddress, e.toString());
                }
            }
            String proxyHost = (String)conf.get("proxyHost", (Object)"");
            int proxyPort = (Integer)conf.get("proxyPort", (Object)0);
            if (proxyHost.length() > 0 && proxyPort > 0) {
                log.info("* Proxy Host: %s", proxyHost);
                log.info("* Proxy Port: %d", proxyPort);
                client.getHostConfiguration().setProxy(proxyHost, proxyPort);
                String proxyUser = (String)conf.get("proxyUser", (Object)"");
                String proxyPass = (String)conf.get("proxyPassword", (Object)"");
                String ntlmHost = (String)conf.get("proxyNTLMHost", (Object)"");
                String ntlmDomain = (String)conf.get("proxyNTLMDomain", (Object)"");
                if (proxyUser.length() > 0) {
                    UsernamePasswordCredentials creds;
                    log.info("* Proxy User: %s", proxyUser);
                    if (ntlmHost.length() > 0) {
                        log.info("* Proxy NTLM Host: %s", ntlmHost);
                        log.info("* Proxy NTLM Domain: %s", ntlmDomain);
                        creds = new NTCredentials(proxyUser, proxyPass, ntlmHost, ntlmDomain);
                    } else {
                        creds = new UsernamePasswordCredentials(proxyUser, proxyPass);
                    }
                    client.getState().setProxyCredentials(AuthScope.ANY, (Credentials)creds);
                }
            }
            HashMap<String, String> props = new HashMap<String, String>();
            props.put("path", "/");
            props.put("action", "activate");
            StrSubstitutor replace = new StrSubstitutor(props, "{", "}");
            ResourceResolver resolver = null;
            Session userSession = null;
            try {
                URI uri = new URI(replace.replace(config.getTransportURI()));
                if ("https".equals(uri.getScheme())) {
                    HashMap<String, Session> map;
                    String agentUserID;
                    if (config.isOAuthEnabled()) {
                        log.info("* Using OAuth 2.0 Authorization Grants");
                        AccessTokenProvider accessTokenProvider = null;
                        String providerPid = (String)conf.get("accessTokenProviderPid", String.class);
                        if (this.accessTokenProvidersProps.size() > 0 && this.accessTokenProviders.size() > 0) {
                            if (StringUtils.isNotBlank((String)providerPid) && null != this.accessTokenProvidersProps.get(providerPid)) {
                                accessTokenProvider = this.accessTokenProviders.get(this.accessTokenProvidersProps.get(providerPid));
                            }
                            if (null == accessTokenProvider) {
                                accessTokenProvider = (AccessTokenProvider)this.accessTokenProviders.values().toArray()[0];
                            }
                        }
                        if (accessTokenProvider != null) {
                            agentUserID = (String)conf.get("userId", (Object)"");
                            log.info("* OAuth 2.0 User: %s", agentUserID);
                            userSession = this.slingRepository.impersonateFromService("replicationService", (javax.jcr.Credentials)new SimpleCredentials(agentUserID, new char[0]), null);
                            map = new HashMap();
                            map.put("user.jcr.session", userSession);
                            resolver = this.rrf.getResourceResolver(map);
                            try {
                                String accessToken = accessTokenProvider.getAccessToken(resolver, agentUserID, null);
                                String authorization = String.format("Bearer %s", accessToken);
                                client.setDefaultHeader(new Header("Authorization", authorization));
                            }
                            catch (Exception e) {
                                log.error("Failed to get an access token for user: %s msg: %s", agentUserID, e.getMessage());
                            }
                        } else {
                            log.error("Access token provider is not bind");
                        }
                    }
                    Protocol myhttps = Protocol.getProtocol((String)"https");
                    String sslConfig = config.getSSLConfig();
                    if (sslConfig.equals("relaxed")) {
                        log.debug("* Using Relaxed SSL configuration *");
                        boolean allowExpired = config.allowsExpiredCertificates();
                        log.debug("* Accept expired SSL certificates: %s", allowExpired);
                        myhttps = new Protocol("https", (SecureProtocolSocketFactory)new EasySSLProtocolSocketFactory(allowExpired, this.disabledSuites, this.enabledSuites), 443);
                    } else if (sslConfig.equals("clientauth")) {
                        log.info("* Using Client Auth SSL configuration *");
                        agentUserID = config.getAgentUserId();
                        if (StringUtils.isNotEmpty((String)agentUserID)) {
                            userSession = this.slingRepository.impersonateFromService("replicationService", (javax.jcr.Credentials)new SimpleCredentials(agentUserID, new char[0]), null);
                            map = new HashMap<String, Session>();
                            map.put("user.jcr.session", userSession);
                            resolver = this.rrf.getResourceResolver(map);
                        } else {
                            resolver = this.rrf.getServiceResourceResolver((Map)new HashMap<String, Object>(){});
                        }
                        KeyManager keyManager = this.keyStoreService.getKeyManager(resolver);
                        TrustManager trustManager = this.keyStoreService.getTrustManager(resolver);
                        myhttps = new Protocol("https", (SecureProtocolSocketFactory)new AuthSSLProtocolSocketFactory(keyManager, trustManager, this.disabledSuites, this.enabledSuites), 443);
                    }
                    client.getHostConfiguration().setHost(uri.getHost(), uri.getPort(), myhttps);
                    break block41;
                }
                if (config.isOAuthEnabled()) {
                    log.warn("OAuth 2.0 Authorization Grants requires SSL");
                }
                client.getHostConfiguration().setHost(uri.getHost(), uri.getPort());
            }
            catch (LoginException e) {
                log.error("Unable to retrieve a session.", new Object[]{e});
            }
            catch (RepositoryException e) {
                log.error("Unable to retrieve a session.", new Object[]{e});
            }
            catch (URISyntaxException e) {
                log.error("Transport uri not valid: ", e);
            }
            finally {
                if (userSession != null && userSession.isLive()) {
                    userSession.logout();
                }
                if (resolver != null && resolver.isLive()) {
                    resolver.close();
                }
            }
        }
        return client;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private ReplicationResult deliver(HttpClient httpClient, AgentConfig config, ReplicationLog log, ReplicationAction action, ReplicationContent content) throws ReplicationException {
        Conversation conv;
        GetMethod httpMethod;
        block50 : {
            URI uri;
            Header[] hdrs;
            String relUri;
            String[] headers;
            HashMap<String, String> props = new HashMap<String, String>();
            props.put("path", Text.escapePath((String)action.getPath()));
            props.put("action", action.getType().getName());
            StrSubstitutor replace = new StrSubstitutor(props, "{", "}");
            try {
                uri = new URI(replace.replace(config.getTransportURI()));
                relUri = new URI(null, null, uri.getPath(), uri.getQuery(), uri.getFragment()).toString();
            }
            catch (URISyntaxException e) {
                throw new ReplicationException(e);
            }
            String method = (String)config.getProperties().get("protocolHTTPMethod", (Object)"POST");
            if ("GET".equals(method)) {
                httpMethod = new GetMethod(relUri);
            } else if ("POST".equals(method)) {
                httpMethod = new PostMethod(relUri);
            } else if ("PUT".equals(method)) {
                httpMethod = new PutMethod(relUri);
            } else {
                throw new ReplicationException("Unsupported http method " + method);
            }
            httpMethod.getParams().setParameter("http.method.retry-handler", (Object)new DefaultHttpMethodRetryHandler(0, false));
            for (String header : headers = (String[])config.getProperties().get("protocolHTTPHeaders", (Object)DEFAULT_HTTP_HEADERS)) {
                int idx = (header = replace.replace(header)).indexOf(58);
                if (idx <= 0) continue;
                String name = header.substring(0, idx).trim();
                String value = header.substring(idx + 1).trim();
                if ("host".equalsIgnoreCase(name)) {
                    httpMethod.getParams().setVirtualHost(value);
                } else {
                    httpMethod.addRequestHeader(name, value);
                }
                log.debug("adding header: %s:%s", name, value);
            }
            if (httpMethod.getRequestHeader("Referer") == null) {
                httpMethod.addRequestHeader("Referer", "about:blank");
            }
            if (((Boolean)config.getProperties().get("protocolHTTPConnectionClose", (Object)false)).booleanValue()) {
                log.debug("forcing connection close.");
                httpMethod.setRequestHeader("Connection", "close");
            }
            httpMethod.setFollowRedirects(false);
            log.debug("deserialize content for delivery");
            long contentLength = 0;
            InputStream contentStream = null;
            if (content == null || content.getContentLength() == 0) {
                if (content == null) {
                    log.debug("No message body: No content to deliver");
                } else {
                    log.debug("No message body: Content %s is empty", content);
                }
                httpMethod.addRequestHeader("Content-Length", "0");
                httpMethod.addRequestHeader("Content-Type", "application/octet-stream");
            } else {
                try {
                    EntityEnclosingMethod eMethod = (EntityEnclosingMethod)httpMethod;
                    contentLength = content.getContentLength();
                    String contentType = content.getContentType();
                    contentStream = content.getInputStream();
                    if (contentStream == null) {
                        return new ReplicationResult(true, 410, "Replication content gone.");
                    }
                    Header[] re = new Header[](contentStream, contentLength, contentType);
                    eMethod.setRequestEntity((RequestEntity)re);
                    log.debug("set %d bytes of post body.", contentLength);
                }
                catch (IOException e) {
                    IOUtils.closeQuietly((InputStream)contentStream);
                    throw new UnrecoverableReplicationException(method + " can't read replication content " + content, e);
                }
                catch (ClassCastException e) {
                    IOUtils.closeQuietly((InputStream)contentStream);
                    throw new ReplicationException(method + " can't have message body. Use POST or PUT", e);
                }
            }
            conv = new Conversation(uri.getHost() + ":" + uri.getPort(), method, uri.getPath());
            for (Header hdr1 : hdrs = httpMethod.getRequestHeaders()) {
                conv.out(hdr1.getName() + ": " + hdr1.getValue());
            }
            String vHost = httpMethod.getParams().getVirtualHost();
            if (vHost != null) {
                conv.out("Host: " + vHost);
            }
            if (contentLength > 0) {
                conv.out("...spooling " + contentLength + " bytes...");
            }
            try {
                log.info("Sending %s request to %s", method, uri);
                httpClient.executeMethod((HttpMethod)httpMethod);
            }
            catch (IOException e) {
                log.error("Error while sending request: %s", e);
                httpMethod.releaseConnection();
                this.error(log, action, conv, e);
                ReplicationResult replicationResult = new ReplicationResult(false, 0, e.getMessage());
                return replicationResult;
            }
            finally {
                IOUtils.closeQuietly((InputStream)contentStream);
            }
            conv.addLine("--");
            conv.in(httpMethod.getStatusLine().toString());
            for (Header hdr : hdrs = httpMethod.getResponseHeaders()) {
                conv.in(hdr.getName() + ": " + hdr.getValue());
            }
            InputStream in = null;
            try {
                in = httpMethod.getResponseBodyAsStream();
                if (in != null) {
                    int read;
                    byte[] buffer = new byte[8192];
                    int pos = 0;
                    conv.in("");
                    while ((read = in.read(buffer, pos, buffer.length - pos)) >= 0) {
                        int start = 0;
                        for (int i = 0; i < (pos += read); ++i) {
                            if (buffer[i] != 13 && buffer[i] != 10) continue;
                            conv.in(new String(buffer, start, i - start));
                            while (i < pos && (buffer[i] == 13 || buffer[i] == 10)) {
                                ++i;
                            }
                            start = i;
                        }
                        if (start == 0) {
                            conv.in(new String(buffer, 0, pos));
                            pos = 0;
                            continue;
                        }
                        System.arraycopy(buffer, start, buffer, 0, pos - start);
                        pos -= start;
                    }
                    break block50;
                }
                log.info("send: No data in response");
            }
            catch (IOException e) {
                log.info("IOException while reading response: %s", e.getMessage());
            }
            finally {
                if (in != null) {
                    try {
                        in.close();
                    }
                    catch (IOException e) {}
                }
            }
        }
        conv.end();
        try {
            ReplicationResult e = this.createReplicationResult(log, action, (HttpMethodBase)httpMethod, conv);
            return e;
        }
        finally {
            httpMethod.releaseConnection();
        }
    }

    protected ReplicationResult createReplicationResult(ReplicationLog log, ReplicationAction action, HttpMethodBase httpMethod, Conversation conv) {
        int statusCode = httpMethod.getStatusCode();
        String statusMsg = httpMethod.getStatusText();
        log.info("sent. Response: %d %s", statusCode, statusMsg);
        if (statusCode != 200) {
            this.error(log, action, conv, null);
            log.info("Replication (%s) of %s not successful.", new Object[]{action.getType(), action.getPath()});
        } else {
            Iterator<String> citer = conv.messages();
            while (citer.hasNext()) {
                log.info(citer.next());
            }
            log.info("Replication (%s) of %s successful.", new Object[]{action.getType(), action.getPath()});
        }
        return new ReplicationResult(statusCode == 200, statusCode, statusMsg);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private ReverseReplication[] poll(HttpClient httpClient, AgentConfig config, ReplicationLog log, ReplicationAction action, ReplicationContentFactory factory) throws ReplicationException {
        int statusCode;
        GetMethod httpMethod;
        String statusMsg;
        ReverseReplication[] result;
        Conversation conv;
        block28 : {
            Header[] hdrs;
            block27 : {
                String qs;
                String[] headers;
                URI uri;
                String relUri;
                HashMap<String, String> props = new HashMap<String, String>();
                props.put("path", Text.escapePath((String)action.getPath()));
                props.put("action", action.getType().getName());
                StrSubstitutor replace = new StrSubstitutor(props, "{", "}");
                try {
                    uri = new URI(replace.replace(config.getTransportURI()));
                    relUri = new URI(null, null, uri.getPath(), uri.getQuery(), uri.getFragment()).toString();
                }
                catch (URISyntaxException e) {
                    throw new ReplicationException(e);
                }
                String method = (String)config.getProperties().get("protocolHTTPMethod", (Object)"POST");
                StringBuffer queryString = new StringBuffer();
                if ("GET".equals(method)) {
                    String revision;
                    httpMethod = new GetMethod(relUri);
                    if (httpMethod.getQueryString() != null) {
                        queryString.append(httpMethod.getQueryString());
                    }
                    if ((revision = action.getRevision()) != null) {
                        if (queryString.length() > 0) {
                            queryString.append("&");
                        }
                        queryString.append("timeline").append("=").append(Text.escape((String)revision));
                        httpMethod.setQueryString(queryString.toString());
                    }
                } else {
                    throw new ReplicationException("Unsupported http method " + method);
                }
                httpMethod.getParams().setParameter("http.method.retry-handler", (Object)new DefaultHttpMethodRetryHandler(0, false));
                for (String header : headers = (String[])config.getProperties().get("protocolHTTPHeaders", (Object)DEFAULT_HTTP_HEADERS)) {
                    header = replace.replace(header);
                    int idx = header.indexOf(58);
                    if (idx <= 0) continue;
                    String name = header.substring(0, idx).trim();
                    String value = header.substring(idx + 1).trim();
                    if ("host".equalsIgnoreCase(name)) {
                        httpMethod.getParams().setVirtualHost(value);
                    } else {
                        httpMethod.addRequestHeader(name, value);
                    }
                    log.debug("adding header: %s:%s", name, value);
                }
                httpMethod.setFollowRedirects(false);
                if (((Boolean)config.getProperties().get("protocolHTTPConnectionClose", (Object)false)).booleanValue()) {
                    log.debug("forcing connection close.");
                    httpMethod.setRequestHeader("Connection", "close");
                }
                if ((qs = queryString.toString()).length() > 0) {
                    qs = "?" + qs;
                }
                conv = new Conversation(uri.getHost() + ":" + uri.getPort(), method, uri.getPath() + qs);
                for (Header hdr1 : hdrs = httpMethod.getRequestHeaders()) {
                    conv.out(hdr1.getName() + ": " + hdr1.getValue());
                }
                try {
                    log.info("Sending %s request to %s", method, uri);
                    int res = httpClient.executeMethod((HttpMethod)httpMethod);
                    if (res != 301 && res != 302) break block27;
                    Header locationHeader = httpMethod.getResponseHeader("location");
                    String movedResource = locationHeader.getValue();
                    log.warn("Redirecting ... resource moved to %s", movedResource);
                    StringBuilder transportBaseUri = new StringBuilder(uri.getScheme()).append("://").append(uri.getHost());
                    if (uri.getPort() > 0 && uri.getPort() != 80) {
                        transportBaseUri.append(':').append(uri.getPort());
                    }
                    if (movedResource.startsWith(transportBaseUri.toString())) {
                        httpMethod.setFollowRedirects(true);
                        httpClient.executeMethod((HttpMethod)httpMethod);
                        break block27;
                    }
                    throw new IOException("Polling replication is being redirected to an external resource : " + movedResource);
                }
                catch (IOException e) {
                    log.error("Error while sending request: %s", e);
                    httpMethod.releaseConnection();
                    this.error(log, action, conv, e);
                    throw new TransportException(0, e.getMessage());
                }
            }
            conv.addLine("--");
            conv.in(httpMethod.getStatusLine().toString());
            for (Header hdr : hdrs = httpMethod.getResponseHeaders()) {
                conv.in(hdr.getName() + ": " + hdr.getValue());
            }
            conv.end();
            statusCode = httpMethod.getStatusCode();
            statusMsg = httpMethod.getStatusText();
            log.info("sent. Response: %d %s", statusCode, statusMsg);
            result = EMPTY;
            if (statusCode == 200) {
                InputStream in = null;
                try {
                    in = httpMethod.getResponseBodyAsStream();
                    if (in != null) {
                        result = this.read(new DurboInput(in), factory);
                        break block28;
                    }
                    log.info("send: No data in response");
                }
                catch (IOException e) {
                    log.info("IOException while reading response: %s", e.getMessage());
                }
                finally {
                    IOUtils.closeQuietly((InputStream)in);
                }
            }
        }
        httpMethod.releaseConnection();
        if (statusCode != 200) {
            this.error(log, action, conv, null);
            throw new TransportException(statusCode, statusMsg);
        }
        Iterator<String> citer = conv.messages();
        while (citer.hasNext()) {
            log.info(citer.next());
        }
        log.info("Reverse replication successful.");
        return result;
    }

    private ReverseReplication[] read(DurboInput input, ReplicationContentFactory factory) throws ReplicationException, IOException {
        ArrayList<ReverseReplication> ret = new ArrayList<ReverseReplication>();
        DurboInput.Element element = input.read();
        if (!"outbox".equals(element.name())) {
            String msg = "Not an outbox.";
            throw new ReplicationException(msg);
        }
        ReplicationAction action = DEFAULT_ACTION;
        long lastModified = 0;
        String type = null;
        String path = null;
        HashMap<String, String> additionalProps = new HashMap<String, String>();
        while ((element = input.read()) != null) {
            if (!element.isProperty()) continue;
            DurboInput.Property p = (DurboInput.Property)element;
            String name = element.name();
            if ("jcr:lastModified".equals(name)) {
                lastModified = ISO8601.parse((String)p.getValues()[0].getString()).getTimeInMillis();
                continue;
            }
            if ("cq:repActionType".equals(name)) {
                type = p.getString();
                continue;
            }
            if ("cq:repPath".equals(name)) {
                path = p.getString();
                continue;
            }
            if ("jcr:data".equals(name)) {
                ReplicationContent content = this.createReplicationContent(factory, lastModified, p.getValues()[0].getStream());
                if (type != null && path != null) {
                    try {
                        action = new ReplicationAction(ReplicationActionType.valueOf(type), path);
                    }
                    catch (IllegalArgumentException e) {
                        throw new ReplicationException(e.getMessage());
                    }
                }
                ReverseReplication rev = new ReverseReplication(content, action);
                rev.getProperties().putAll(additionalProps);
                ret.add(rev);
                path = null;
                type = null;
                action = DEFAULT_ACTION;
                additionalProps.clear();
                continue;
            }
            additionalProps.put(name, p.getString());
        }
        return ret.toArray(new ReverseReplication[ret.size()]);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private ReplicationContent createReplicationContent(ReplicationContentFactory factory, long lastModified, InputStream in) throws IOException {
        File f = File.createTempFile("durbo", ".ser");
        FileOutputStream out = null;
        boolean spooled = false;
        try {
            out = FileUtils.openOutputStream((File)f);
            IOUtils.copy((InputStream)in, (OutputStream)out);
            spooled = true;
            ReplicationContent replicationContent = factory.create("application/cq5-replication-durbo", f, lastModified, true);
            return replicationContent;
        }
        finally {
            IOUtils.closeQuietly((InputStream)in);
            IOUtils.closeQuietly((OutputStream)out);
            if (!spooled && !f.delete()) {
                throw new IOException("could not delete file");
            }
        }
    }

    protected void error(ReplicationLog log, ReplicationAction action, Conversation conv, Exception e) {
        String msg;
        Iterator<String> iter = conv.messages();
        String string = msg = iter.hasNext() ? "Conversation follows" : "No Conversation !";
        if (e == null) {
            log.error("Replication (%s) of %s not successful. %s", new Object[]{action.getType(), action.getPath(), msg});
        } else {
            log.error("Replication (%s) of %s not successful: %s %s", new Object[]{action.getType(), action.getPath(), e, msg});
        }
        while (iter.hasNext()) {
            log.error(iter.next());
        }
    }

    @Activate
    protected void activate(ComponentContext ctx) throws RepositoryException {
        Dictionary props = ctx.getProperties();
        this.disabledSuites = PropertiesUtil.toStringArray(props.get("disabled.cipher.suites"));
        this.enabledSuites = PropertiesUtil.toStringArray(props.get("enabled.cipher.suites"));
    }

    protected void bindKeyStoreService(KeyStoreService kss) {
        this.keyStoreService = kss;
    }

    protected void unbindKeyStoreService(KeyStoreService kss) {
        if (this.keyStoreService == kss) {
            this.keyStoreService = null;
        }
    }

    protected void bindRrf(ResourceResolverFactory f) {
        this.rrf = f;
    }

    protected void unbindRrf(ResourceResolverFactory f) {
        if (this.rrf == f) {
            this.rrf = null;
        }
    }

    protected void bindAccessTokenProvider(AccessTokenProvider atp, Map<String, Object> properties) {
        String pid = (String)properties.get("service.pid");
        this.accessTokenProvidersProps.put(pid, ServiceUtil.getComparableForServiceRanking(properties));
        this.accessTokenProviders.put(ServiceUtil.getComparableForServiceRanking(properties), atp);
    }

    protected void unbindAccessTokenProvider(AccessTokenProvider atp, Map<String, Object> properties) {
        String pid = (String)properties.get("service.pid");
        this.accessTokenProviders.remove(this.accessTokenProvidersProps.get(pid));
        this.accessTokenProvidersProps.remove(pid);
    }

    protected void bindSlingRepository(SlingRepository slingRepository) {
        this.slingRepository = slingRepository;
    }

    protected void unbindSlingRepository(SlingRepository slingRepository) {
        if (this.slingRepository == slingRepository) {
            this.slingRepository = null;
        }
    }

    private static class DefaultHeaderHttpClient
    extends HttpClient {
        private static final Logger log = LoggerFactory.getLogger(DefaultHeaderHttpClient.class);
        private final Set<Header> headers = new HashSet<Header>();

        private DefaultHeaderHttpClient() {
        }

        public /* varargs */ void setDefaultHeader(Header ... headers) {
            this.headers.addAll(Arrays.asList(headers));
        }

        public int executeMethod(HttpMethod method) throws IOException {
            this.setHeaders(method);
            return super.executeMethod(method);
        }

        public int executeMethod(HostConfiguration hostConfiguration, HttpMethod method) throws IOException {
            this.setHeaders(method);
            return super.executeMethod(hostConfiguration, method);
        }

        public int executeMethod(HostConfiguration hostConfiguration, HttpMethod method, HttpState state) throws IOException {
            this.setHeaders(method);
            return super.executeMethod(hostConfiguration, method, state);
        }

        private void setHeaders(HttpMethod method) {
            for (Header header : this.headers) {
                log.debug("set header: %s:%s", (Object)header.getName(), (Object)header.getValue());
                method.setRequestHeader(header);
            }
        }
    }

    static final class Conversation {
        private static final Logger log = LoggerFactory.getLogger(Conversation.class);
        private final List<String> messages = new ArrayList<String>();

        private Conversation(String host, String method, String path) {
            this.addLine("------------------------------------------------");
            this.addLine("Sending message to " + host);
            this.out(method + " " + path + " HTTP/1.0");
        }

        public void end() {
            this.addLine("Message sent.");
            this.addLine("------------------------------------------------");
        }

        public void addLine(String line) {
            this.messages.add(line);
            log.debug(line);
        }

        public void out(String line) {
            this.addLine(">> " + line);
        }

        public void in(String line) {
            this.addLine("<< " + line);
        }

        public Iterator<String> messages() {
            return this.messages.iterator();
        }
    }

    private static class State
    implements TransportContext.Discardable {
        HttpClient client;
        ReplicationAction action;

        State(HttpClient client) {
            this.client = client;
        }

        @Override
        public void discard() {
            if (this.client != null) {
                HttpConnectionManager cMgr = this.client.getHttpConnectionManager();
                if (cMgr instanceof MultiThreadedHttpConnectionManager) {
                    ((MultiThreadedHttpConnectionManager)cMgr).shutdown();
                } else {
                    cMgr.closeIdleConnections(0);
                }
                this.client = null;
            }
        }
    }

}