ReplicationContentFactoryProviderImpl.java 21.1 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Binary
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.commons.JcrUtils
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.apache.sling.settings.SlingSettingsService
 *  org.osgi.framework.BundleContext
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.replication.impl;

import com.day.cq.replication.ReplicationContent;
import com.day.cq.replication.ReplicationContentFacade;
import com.day.cq.replication.ReplicationContentFactory;
import com.day.cq.replication.impl.AbstractReplicationContent;
import com.day.cq.replication.impl.FileContentFactory;
import com.day.cq.replication.impl.ReplicationContentFactoryProvider;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate=1, metatype=1)
@Service(value={ReplicationContentFactoryProvider.class})
public class ReplicationContentFactoryProviderImpl
implements ReplicationContentFactoryProvider {
    private static final Logger log = LoggerFactory.getLogger(ReplicationContentFactoryProviderImpl.class);
    private static final String CONTENT_PATH = "/var/replication/data";
    @Reference
    private SlingRepository repository = null;
    @Reference
    private SlingSettingsService settingsService = null;
    private String dataRoot;
    private File dataDir;
    @Property(boolValue={0})
    private static final String OSGI_PROP_USE_FILE_STORAGE = "replication.content.useFileStorage";

    @Activate
    protected void activate(ComponentContext context) {
        boolean useFileStorage = PropertiesUtil.toBoolean(context.getProperties().get("replication.content.useFileStorage"), (boolean)false);
        if (useFileStorage) {
            File dir;
            String shared = this.repository.getDescriptor("com.day.crx.cluster.home");
            if (shared == null) {
                log.info("No shared directory information available from repository.");
                dir = new File(context.getBundleContext().getProperty("sling.home"));
                File tmp = new File(dir.getParentFile(), "repository");
                if (tmp.isDirectory() && (tmp = new File(tmp, "shared")).isDirectory()) {
                    dir = tmp;
                }
            } else {
                log.info("Using shared directory information from repository: {}", (Object)shared);
                dir = new File(shared);
            }
            this.dataDir = new File(dir, "replication");
            log.info("Data directory is {}", (Object)this.dataDir.getPath());
        } else {
            String nodeId = this.settingsService.getSlingId();
            if (nodeId == null || nodeId.length() == 0) {
                log.warn("No sling id? using random.");
                nodeId = UUID.randomUUID().toString();
            }
            this.dataRoot = "/var/replication/data/" + nodeId;
            log.info("Repository content root: {}", (Object)this.dataRoot);
        }
        log.info("ReplicationContentFactoryProvider service activated.");
    }

    @Deactivate
    protected void deactivate() {
    }

    @Override
    public ReplicationContentFactory create(String agentId) throws RepositoryException {
        if (this.dataDir == null) {
            Session agentSession = this.repository.loginService("replicationService", null);
            return new Factory(agentSession, agentId);
        }
        return new FileContentFactory(this.dataDir, agentId);
    }

    private void refreshAndWait(Session session) {
        try {
            session.refresh(false);
        }
        catch (RepositoryException var2_2) {
            // empty catch block
        }
        try {
            Thread.sleep(10);
        }
        catch (InterruptedException var2_3) {
            // empty catch block
        }
    }

    private Node getNewStorageNode(Session session) throws RepositoryException {
        String name = UUID.randomUUID().toString();
        String path = this.dataRoot + "/" + name.substring(0, 2);
        Node parent = null;
        int num = 0;
        while (parent == null) {
            try {
                parent = JcrUtils.getOrCreateByPath((String)path, (String)"sling:Folder", (String)"sling:Folder", (Session)session, (boolean)true);
            }
            catch (RepositoryException e) {
                log.warn("Error while creating storage parent (retrying): {}", (Object)e.toString());
                if (num++ > 10) {
                    throw e;
                }
                this.refreshAndWait(session);
            }
        }
        return JcrUtils.getOrCreateUniqueByPath((Node)parent, (String)name, (String)"nt:file");
    }

    static /* synthetic */ Node access$300(ReplicationContentFactoryProviderImpl x0, Session x1) throws RepositoryException {
        return x0.getNewStorageNode(x1);
    }

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

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

    protected void bindSettingsService(SlingSettingsService slingSettingsService) {
        this.settingsService = slingSettingsService;
    }

    protected void unbindSettingsService(SlingSettingsService slingSettingsService) {
        if (this.settingsService == slingSettingsService) {
            this.settingsService = null;
        }
    }

    private final class Factory
    implements ReplicationContentFactory {
        private final Session agentSession;

        private Factory(Session agentSession, String agentId) {
            this.agentSession = agentSession;
            log.info("RepositoryContentFactory for {} initialized.", (Object)agentId);
        }

        @Override
        public ReplicationContent create(String mimeType, File file, boolean isTemp) throws IOException {
            return this.create(mimeType, file, file.lastModified(), isTemp);
        }

        /*
         * Exception decompiling
         */
        @Override
        public ReplicationContent create(String mimeType, File file, long lastModified, boolean isTemp) throws IOException {
            // This method has failed to decompile.  When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file.
            // org.benf.cfr.reader.util.ConfusedCFRException: Started 2 blocks at once
            // org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.getStartingBlocks(Op04StructuredStatement.java:374)
            // org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.buildNestedBlocks(Op04StructuredStatement.java:452)
            // org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement.createInitialStructuredBlock(Op03SimpleStatement.java:2877)
            // org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:825)
            // org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:217)
            // org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:162)
            // org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:95)
            // org.benf.cfr.reader.entities.Method.analyse(Method.java:355)
            // org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:768)
            // org.benf.cfr.reader.entities.ClassFile.analyseInnerClassesPass1(ClassFile.java:681)
            // org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:764)
            // org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:700)
            // org.benf.cfr.reader.Main.doJar(Main.java:134)
            // org.benf.cfr.reader.Main.main(Main.java:189)
            throw new IllegalStateException("Decompilation failed");
        }

        @Override
        public ReplicationContent create(ReplicationContentFacade facade) {
            if (facade == null) {
                return ReplicationContent.VOID;
            }
            return new RepositoryContent(this, facade);
        }

        @Override
        public void close() {
            if (this.agentSession.isLive()) {
                this.agentSession.logout();
            }
        }

        private class RepositoryContent
        extends AbstractReplicationContent {
            private static final long serialVersionUID = 6506881886574345693L;
            final /* synthetic */ Factory this$1;

            RepositoryContent(Factory factory, String path, String contentType, long size) {
                this.this$1 = factory;
                super(path, contentType, size);
            }

            RepositoryContent(Factory factory, ReplicationContentFacade facade) {
                this.this$1 = factory;
                super(facade);
            }

            @Override
            public InputStream getInputStream() throws IOException {
                try {
                    return this.getNode(this.this$1.agentSession).getProperty("jcr:content/jcr:data").getBinary().getStream();
                }
                catch (FileNotFoundException e) {
                    log.error("Unable to read replication content stored in {}. Node is missing.", (Object)this.facade.getPath());
                    return null;
                }
                catch (RepositoryException e) {
                    IOException e1 = new IOException("Error while reading replication content in " + this.facade.getPath());
                    e1.initCause((Throwable)e);
                    throw e1;
                }
            }

            @Override
            public long getLastModified() {
                try {
                    return this.getNode(this.this$1.agentSession).getProperty("jcr:content/jcr:lastModified").getDate().getTimeInMillis();
                }
                catch (Exception e) {
                    log.warn("unable to retrieve last modified date of " + this.facade.getPath(), (Throwable)e);
                    return -1;
                }
            }

            private Node getNode(Session s) throws IOException {
                try {
                    if (!s.isLive()) {
                        log.warn("Service already stopped. unable to create replication content.");
                        throw new IOException("Service Stopped.");
                    }
                    s.refresh(false);
                    if (!s.nodeExists(this.facade.getPath())) {
                        throw new FileNotFoundException(this.facade.getPath());
                    }
                    return s.getNode(this.facade.getPath());
                }
                catch (RepositoryException e) {
                    IOException e1 = new IOException(e.toString());
                    e1.initCause((Throwable)e);
                    throw e1;
                }
            }

            /*
             * WARNING - Removed try catching itself - possible behaviour change.
             * Loose catch block
             * Enabled aggressive exception aggregation
             */
            @Override
            public void acquire(String agentName) {
                if (this.this$1.ReplicationContentFactoryProviderImpl.this.repository == null) {
                    log.warn("Service already stopped. unable to update replication content.");
                    return;
                }
                Session session = null;
                try {
                    session = this.this$1.ReplicationContentFactoryProviderImpl.this.repository.loginService("replicationService", null);
                    int attempts = 0;
                    while (attempts++ < 10) {
                        if (!session.nodeExists(this.facade.getPath())) {
                            log.warn("Replication content node does not exist {}.", (Object)this.facade.getPath());
                            return;
                        }
                        Node node = session.getNode(this.facade.getPath() + "/jcr:content");
                        HashSet<String> ret = new HashSet<String>();
                        if (node.hasProperty("cq:agents")) {
                            for (Value v : node.getProperty("cq:agents").getValues()) {
                                ret.add(v.getString());
                            }
                        }
                        if (ret.add(agentName)) {
                            node.setProperty("cq:agents", ret.toArray(new String[ret.size()]));
                            try {
                                session.save();
                                return;
                            }
                            catch (RepositoryException e) {
                                this.this$1.ReplicationContentFactoryProviderImpl.this.refreshAndWait(session);
                                continue;
                            }
                        }
                        return;
                    }
                    log.error("Unable to update 'agents' property of {} after {} attempts", (Object)this.facade.getPath(), (Object)attempts);
                    {
                        catch (RepositoryException e) {
                            log.warn("unable to update agents of " + this.facade.getPath(), (Throwable)e);
                        }
                        catch (Throwable throwable) {
                            throw throwable;
                        }
                    }
                }
                finally {
                    if (session != null) {
                        session.logout();
                    }
                }
            }

            /*
             * WARNING - Removed try catching itself - possible behaviour change.
             */
            @Override
            public void release(String agentName) {
                if (this.this$1.ReplicationContentFactoryProviderImpl.this.repository == null) {
                    log.warn("Service already stopped. unable to update replication content.");
                    return;
                }
                Session session = null;
                try {
                    session = this.this$1.ReplicationContentFactoryProviderImpl.this.repository.loginService("replicationService", null);
                    int attempts = 0;
                    HashSet<String> ret = new HashSet<String>();
                    while (attempts++ < 10) {
                        if (!session.nodeExists(this.facade.getPath())) {
                            log.warn("Replication content node does not exist {}.", (Object)this.facade.getPath());
                            return;
                        }
                        ret.clear();
                        Node node = session.getNode(this.facade.getPath() + "/jcr:content");
                        if (node.hasProperty("cq:agents")) {
                            for (Value v : node.getProperty("cq:agents").getValues()) {
                                ret.add(v.getString());
                            }
                        }
                        if (!ret.remove(agentName) || ret.isEmpty()) break;
                        node.setProperty("cq:agents", ret.toArray(new String[ret.size()]));
                        try {
                            session.save();
                            break;
                        }
                        catch (RepositoryException e) {
                            this.this$1.ReplicationContentFactoryProviderImpl.this.refreshAndWait(session);
                            continue;
                        }
                    }
                    if (attempts == 10) {
                        log.error("Unable to update 'agents' property of {} after {} attempts", (Object)this.facade.getPath(), (Object)attempts);
                    }
                    if (ret.isEmpty()) {
                        this.destroy(session);
                    }
                }
                catch (RepositoryException e) {
                    log.warn("unable to update agents of " + this.facade.getPath(), (Throwable)e);
                }
                finally {
                    if (session != null) {
                        session.logout();
                    }
                }
            }

            /*
             * WARNING - Removed try catching itself - possible behaviour change.
             */
            @Override
            public Collection<String> getAcquiredBy() {
                Session session = null;
                try {
                    if (this.this$1.ReplicationContentFactoryProviderImpl.this.repository == null) {
                        log.warn("Service already stopped. unable to create replication content.");
                        Set<String> set = Collections.emptySet();
                        return set;
                    }
                    session = this.this$1.ReplicationContentFactoryProviderImpl.this.repository.loginService("replicationService", null);
                    if (!session.nodeExists(this.facade.getPath())) {
                        log.warn("Replication content node does not exist {}.", (Object)this.facade.getPath());
                        Set<String> set = Collections.emptySet();
                        return set;
                    }
                    Node node = session.getNode(this.facade.getPath() + "/jcr:content");
                    Value[] ret = new Value[]();
                    if (node.hasProperty("cq:agents")) {
                        for (Value v : node.getProperty("cq:agents").getValues()) {
                            ret.add(v.getString());
                        }
                    }
                    Value[] arrvalue = ret;
                    return arrvalue;
                }
                catch (RepositoryException e) {
                    log.warn("unable to retrieve agents of " + this.facade.getPath(), (Throwable)e);
                    Set<String> ret = Collections.emptySet();
                    return ret;
                }
                finally {
                    if (session != null) {
                        session.logout();
                    }
                }
            }

            @Override
            public void destroy() {
                if (this.this$1.ReplicationContentFactoryProviderImpl.this.repository == null) {
                    log.warn("Service already stopped. unable to destroy replication content.");
                    return;
                }
                Session session = null;
                try {
                    session = this.this$1.ReplicationContentFactoryProviderImpl.this.repository.loginService("replicationService", null);
                    this.destroy(session);
                }
                catch (RepositoryException e) {
                    log.warn("Error while login.", (Throwable)e);
                }
                finally {
                    if (session != null) {
                        session.logout();
                    }
                }
            }

            private void destroy(Session session) {
                int num = 0;
                while (num++ < 10) {
                    try {
                        if (!session.nodeExists(this.facade.getPath())) continue;
                        session.removeItem(this.facade.getPath());
                        session.save();
                        return;
                    }
                    catch (RepositoryException e) {
                        log.warn("Unable to destroy replication content", (Throwable)e);
                        this.this$1.ReplicationContentFactoryProviderImpl.this.refreshAndWait(session);
                        continue;
                    }
                }
                log.error("Unable to delete replication content of {} after {} attempts", (Object)this.facade.getPath(), (Object)num);
            }
        }

    }

}