WcmWorkflowServiceImpl.java 21.9 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.replication.ReplicationAction
 *  com.day.cq.replication.ReplicationActionType
 *  com.day.cq.replication.ReplicationStatus
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.api.PageEvent
 *  com.day.cq.wcm.api.PageModification
 *  com.day.cq.wcm.api.PageModification$ModificationType
 *  com.day.cq.wcm.workflow.api.WcmWorkflowService
 *  com.day.cq.workflow.PayloadMap
 *  com.day.cq.workflow.WorkflowException
 *  com.day.cq.workflow.WorkflowService
 *  com.day.cq.workflow.WorkflowSession
 *  com.day.cq.workflow.exec.WorkItem
 *  com.day.cq.workflow.exec.Workflow
 *  com.day.cq.workflow.exec.WorkflowData
 *  com.day.cq.workflow.metadata.MetaDataMap
 *  com.day.cq.workflow.model.WorkflowModel
 *  com.day.cq.workflow.model.WorkflowNode
 *  javax.jcr.Credentials
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.SimpleCredentials
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.commons.osgi.OsgiUtil
 *  org.apache.sling.commons.threads.ModifiableThreadPoolConfig
 *  org.apache.sling.commons.threads.ThreadPool
 *  org.apache.sling.commons.threads.ThreadPoolConfig
 *  org.apache.sling.commons.threads.ThreadPoolConfig$ThreadPriority
 *  org.apache.sling.commons.threads.ThreadPoolManager
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.apache.sling.jcr.resource.JcrResourceResolverFactory
 *  org.osgi.service.component.ComponentContext
 *  org.osgi.service.event.Event
 *  org.osgi.service.event.EventHandler
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.workflow.impl;

import com.day.cq.replication.ReplicationAction;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationStatus;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageEvent;
import com.day.cq.wcm.api.PageModification;
import com.day.cq.wcm.workflow.api.WcmWorkflowService;
import com.day.cq.wcm.workflow.impl.WorkflowAutoAssignAllocator;
import com.day.cq.workflow.PayloadMap;
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowService;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.exec.Workflow;
import com.day.cq.workflow.exec.WorkflowData;
import com.day.cq.workflow.metadata.MetaDataMap;
import com.day.cq.workflow.model.WorkflowModel;
import com.day.cq.workflow.model.WorkflowNode;
import java.util.Calendar;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import javax.jcr.Credentials;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
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.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.commons.threads.ModifiableThreadPoolConfig;
import org.apache.sling.commons.threads.ThreadPool;
import org.apache.sling.commons.threads.ThreadPoolConfig;
import org.apache.sling.commons.threads.ThreadPoolManager;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.resource.JcrResourceResolverFactory;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1, label="%wcmworkflowwervice.name", description="%wcmworkflowwervice.description")
@Service(value={EventHandler.class, WcmWorkflowService.class})
@Properties(value={@Property(name="event.topics", value={"com/day/cq/workflow/event", "com/day/cq/wcm/core/page", "com/day/cq/wcm/workflow/req/for/activation", "com/day/cq/replication"}, propertyPrivate=1), @Property(name="event.filter", value={"(!(event.application=*))"})})
public class WcmWorkflowServiceImpl
implements WcmWorkflowService,
EventHandler {
    private static final Logger log = LoggerFactory.getLogger(WcmWorkflowServiceImpl.class);
    public static final String WORKSPACE = "cq.workflow.workspace";
    public static final String TYPE_JCR_PATH = "JCR_PATH";
    public static final String TYPE_JCR_UUID = "JCR_UUID";
    private static final String WORKFLOWNODE_TYPE_END = "END";
    private static final String WORKFLOWNODE_TYPE_PROCESS = "PROCESS";
    @Property(label="minThreadPoolSize", description="Minimum Thread pool size", intValue={5})
    private static final String MINIMUM_THREAD_POOL_SIZE = "minThreadPoolSize";
    private int minThreadPoolSize;
    @Property(label="maxThreadPoolSize", description="Maximum Thread pool size", intValue={10})
    private static final String MAXUIMUM_THREAD_POOL_SIZE = "maxThreadPoolSize";
    private int maxThreadPoolSize;
    @Property(value={"/etc/workflow/models/request_for_activation/jcr:content/model"}, label="Workflow Model Path", description="Workflow model used for request for activation", propertyPrivate=1)
    public static final String REQUEST_FOR_ACTIVATION_MODEL = "cq.wcm.workflow.req.activate";
    @Property(value={"/etc/workflow/models/request_for_deactivation/jcr:content/model"}, label="Workflow Model Path", description="Workflow model used for request for deactivation", propertyPrivate=1)
    public static final String REQUEST_FOR_DEACTIVATION_MODEL = "cq.wcm.workflow.req.deactivate";
    @Property(boolValue={1}, label="%wcmworkflowservice.terminate.label", description="%wcmworkflowservice.terminate.description")
    public static final String TERMINATE_ON_ACTIVATE = "cq.wcm.workflow.terminate.on.activate";
    @Property(value={"", ""}, label="%wcmworkflowservice.terminate.exclusion.label", description="%wcmworkflowservice.terminate.exclusion.description")
    public static final String TERMINATE_EXCLUSION_LIST = "cq.wcm.worklfow.terminate.exclusion.list";
    private static final String WCM_WORKFLOW_SERVICE = "wcm-workflow-service";
    @Reference
    private ThreadPoolManager threadPoolManager;
    private ThreadPool threadPool;
    @Reference
    private WorkflowService workflowService;
    @Reference
    private SlingRepository repository;
    @Reference
    private PayloadMap payloadMap;
    @Reference
    protected JcrResourceResolverFactory jcrResourceResolverFactory;
    private boolean isInitialized;
    private boolean terminateOnActivate = true;
    private HashSet<String> terminateExclusions = new HashSet();
    Dictionary config;
    private WorkflowAutoAssignAllocator wfAutoAssignAllocator;

    public boolean isInWorkflow(String pagePath) {
        return this.payloadMap.isInWorkflow(pagePath, true);
    }

    public WorkflowModel getRequestForReplicationWorkflowModel(ReplicationActionType replicationType) {
        WorkflowSession serviceWfSession = this.getWorkflowSession(null);
        return this.getRequestForReplicationWorkflowModel(serviceWfSession, replicationType);
    }

    public Workflow getWorkflowInstance(String pagePath) {
        List instances = this.payloadMap.getWorkflowInstances(pagePath, true);
        if (instances.size() > 0) {
            return (Workflow)instances.get(0);
        }
        return null;
    }

    public String getWcmConfigPath() {
        return "/etc/workflow/wcm";
    }

    public void handleEvent(final Event event) {
        this.threadPool.execute(new Runnable(){

            @Override
            public void run() {
                WcmWorkflowServiceImpl.this.process(event);
            }
        });
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     * Unable to fully structure code
     * Enabled aggressive block sorting
     * Enabled unnecessary exception pruning
     * Enabled aggressive exception aggregation
     * Lifted jumps to return sites
     */
    public boolean process(Event event) {
        WcmWorkflowServiceImpl.log.debug("Received event of topic: " + event.getTopic());
        topic = event.getTopic();
        serviceWfSession = null;
        serviceWfSession = this.getWorkflowSession(null);
        this.wfAutoAssignAllocator = new WorkflowAutoAssignAllocator(serviceWfSession, this.getWcmConfigPath() + "/templates");
        resourceResolver = this.jcrResourceResolverFactory.getResourceResolver(serviceWfSession.getSession());
        if (!topic.equals("com/day/cq/wcm/core/page")) {
            if (topic.equals("com/day/cq/wcm/workflow/req/for/activation")) {
                path = (String)event.getProperty("path");
                WcmWorkflowServiceImpl.log.debug("Request for de/activation event received for " + path);
                type = (ReplicationActionType)event.getProperty("replicationType");
                model = this.getRequestForReplicationWorkflowModel(type);
                if (model == null) {
                    WcmWorkflowServiceImpl.log.warn("No valid workflow model specified for request for de/activation");
                    return true;
                }
                userWfSession = this.getWorkflowSession((String)event.getProperty("userId"));
                wfData = userWfSession.newWorkflowData("JCR_PATH", (Object)path);
                try {
                    userWfSession.startWorkflow(model, wfData);
                    return true;
                }
                catch (WorkflowException we) {
                    WcmWorkflowServiceImpl.log.warn("Cannot start request for de/activation workflow " + model.getTitle() + " for " + path + ": " + we.getMessage());
                    return true;
                }
                finally {
                    userWfSession.logout();
                }
            } else {
                if (this.terminateOnActivate == false) return true;
                if (topic.equals("com/day/cq/replication") == false) return true;
                re = ReplicationAction.fromEvent((Event)event);
                if (re == null) return true;
                path = re.getPath();
                instances = this.payloadMap.getWorkflowInstances(path, true);
                i$ = instances.iterator();
                while (i$.hasNext() != false) {
                    instance = (Workflow)i$.next();
                    if (instance == null) continue;
                    if (this.terminateExclusions.contains(instance.getWorkflowModel().getId())) {
                        WcmWorkflowServiceImpl.log.debug("not terminating workflow {} because it is in the exclusion list.  modelId: {} ", (Object)instance.getId(), (Object)instance.getWorkflowModel().getId());
                        continue;
                    }
                    items = instance.getWorkItems();
                    if (items.size() > 0 && !((WorkItem)items.get(0)).getNode().getType().equals("END") && !((WorkItem)items.get(0)).getNode().getType().equals("PROCESS")) {
                        try {
                            msg = "Auto Terminated workflow  with payload " + instance.getWorkflowData().getPayload() + " for replicated page " + path;
                            instance.getMetaDataMap().put((Object)"terminateComment", (Object)msg);
                            instance.getWorkflowData().getMetaDataMap().put((Object)"terminateComment", (Object)msg);
                            serviceWfSession.terminateWorkflow(instance);
                            msg = "Terminated workflow " + instance.getId() + " with payload " + instance.getWorkflowData().getPayload() + " for replicated page " + path;
                            WcmWorkflowServiceImpl.log.debug(msg);
                        }
                        catch (WorkflowException we) {
                            WcmWorkflowServiceImpl.log.warn("Unable to terminate workflow " + instance.getId() + " for " + "replicated page " + path);
                        }
                        continue;
                    }
                    WcmWorkflowServiceImpl.log.debug("Not going to terminate workflow instance for " + path);
                }
                return true;
            }
        }
        ** GOTO lbl63
        {
            finally {
                if (serviceWfSession != null) {
                    serviceWfSession.logout();
                    this.wfAutoAssignAllocator = null;
                }
            }
        }
lbl63: // 1 sources:
        pageEvent = PageEvent.fromEvent((Event)event);
        pI = pageEvent.getModifications();
        while (pI.hasNext() != false) {
            pm = (PageModification)pI.next();
            eventType = pm.getType();
            if (eventType.equals((Object)PageModification.ModificationType.CREATED) && !this.isInWorkflow(pm.getPath())) {
                res = resourceResolver.getResource(pm.getPath());
                if (res == null || (page = (Page)res.adaptTo(Page.class)) == null) continue;
                this.autoAssignWorkflow(page, serviceWfSession, pm.getUserId());
                continue;
            }
            if (eventType.equals((Object)PageModification.ModificationType.DELETED)) {
                instance = this.getWorkflowInstance(pm.getPath());
                if (instance == null) continue;
                try {
                    serviceWfSession.terminateWorkflow(instance);
                    WcmWorkflowServiceImpl.log.debug("Terminated workflow " + instance.getId() + "for deleted page " + pm.getPath());
                }
                catch (WorkflowException we) {
                    WcmWorkflowServiceImpl.log.warn("Unable to terminate workflow " + instance.getId() + " for " + "deleted page " + pm.getPath());
                }
                continue;
            }
            if (!eventType.equals((Object)PageModification.ModificationType.MODIFIED)) continue;
            this.autoSubmitPageAfterModification(pm, serviceWfSession, pm.getUserId());
        }
        return true;
    }

    @Activate
    protected void activate(ComponentContext context) throws RepositoryException {
        this.isInitialized = false;
        this.config = context.getProperties();
        Object property = this.config.get("cq.wcm.workflow.terminate.on.activate");
        if (property != null && property instanceof Boolean) {
            this.terminateOnActivate = (Boolean)property;
        }
        if ((property = this.config.get("cq.wcm.worklfow.terminate.exclusion.list")) != null && property instanceof String[]) {
            String[] exclusions;
            for (String exclusion : exclusions = (String[])property) {
                this.terminateExclusions.add(exclusion);
            }
        }
        this.minThreadPoolSize = OsgiUtil.toInteger(this.config.get("minThreadPoolSize"), (int)5);
        this.maxThreadPoolSize = OsgiUtil.toInteger(this.config.get("maxThreadPoolSize"), (int)10);
        ModifiableThreadPoolConfig threadPoolConfig = new ModifiableThreadPoolConfig();
        if (threadPoolConfig.getMinPoolSize() < this.minThreadPoolSize) {
            threadPoolConfig.setMinPoolSize(this.minThreadPoolSize);
        }
        if (threadPoolConfig.getMaxPoolSize() < this.maxThreadPoolSize) {
            threadPoolConfig.setMaxPoolSize(this.maxThreadPoolSize);
        }
        threadPoolConfig.setPriority(ThreadPoolConfig.ThreadPriority.NORM);
        this.threadPool = this.threadPoolManager.create((ThreadPoolConfig)threadPoolConfig);
        if (this.threadPool == null) {
            throw new IllegalStateException("Could not get a ThreadPool");
        }
    }

    @Deactivate
    protected void deactivate(ComponentContext context) {
        if (this.threadPool != null) {
            this.threadPoolManager.release(this.threadPool);
            this.threadPoolManager = null;
            this.threadPool = null;
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void autoAssignWorkflow(Page page, WorkflowSession wfSession, String userId) {
        WorkflowModel model = this.wfAutoAssignAllocator.getAutoAssignWorkflowModel(page);
        if (model != null) {
            log.debug("Auto assign workflow: found model (" + model.getTitle() + ") for " + page.getPath());
            WorkflowData wfData = wfSession.newWorkflowData("JCR_PATH", (Object)page.getPath());
            try {
                boolean impersonate;
                block12 : {
                    impersonate = false;
                    if (userId != null && !userId.equals(wfSession.getSession().getUserID())) {
                        WorkflowSession userWfSession = null;
                        try {
                            userWfSession = this.getWorkflowSession(userId);
                            if (userWfSession != null) {
                                userWfSession.startWorkflow(model, wfData);
                                impersonate = true;
                                break block12;
                            }
                            log.warn("autoAssignWorkflow: Cannot impersonate user " + userId + ". will start workflow with service user session");
                            impersonate = false;
                        }
                        catch (WorkflowException we) {
                            log.warn("autoAssignWorkflow: Cannot start workflow with given user " + userId + ". will start workflow with service user session");
                            impersonate = false;
                        }
                        finally {
                            if (userWfSession != null) {
                                userWfSession.logout();
                            }
                        }
                    }
                }
                if (!impersonate) {
                    wfSession.startWorkflow(model, wfData);
                }
            }
            catch (WorkflowException we) {
                log.warn("Cannot start workflow " + model.getTitle() + " for " + page.getPath() + ": " + we.getMessage());
            }
        }
    }

    private void autoSubmitPageAfterModification(PageModification pm, WorkflowSession wfSession, String modifierUID) {
        ReplicationStatus repStatus;
        Resource res = this.jcrResourceResolverFactory.getResourceResolver(wfSession.getSession()).getResource(pm.getPath());
        Page page = (Page)res.adaptTo(Page.class);
        if (page != null && !this.isInWorkflow(pm.getPath()) && (repStatus = (ReplicationStatus)res.adaptTo(ReplicationStatus.class)) != null && repStatus.isActivated()) {
            Calendar lastModified = page.getLastModified();
            Calendar lastActivated = repStatus.getLastPublished();
            if (lastModified != null && lastActivated != null && lastModified.getTimeInMillis() > lastActivated.getTimeInMillis()) {
                this.autoAssignWorkflow(page, wfSession, modifierUID);
            }
        }
    }

    private WorkflowSession getWorkflowSession(String userId) {
        try {
            if (null == userId) {
                return this.workflowService.getWorkflowSession(this.repository.loginService("wcm-workflow-service", null));
            }
            SimpleCredentials credentials = new SimpleCredentials(userId, new char[0]);
            Session userSession = this.repository.impersonateFromService("wcm-workflow-service", (Credentials)credentials, null);
            return this.workflowService.getWorkflowSession(userSession);
        }
        catch (RepositoryException re) {
            log.error("Cannot login into repository", (Throwable)re);
            return null;
        }
    }

    private WorkflowModel getRequestForReplicationWorkflowModel(WorkflowSession wfSession, ReplicationActionType replicationActionType) {
        String type = replicationActionType.toString().toLowerCase();
        String modelId = (String)this.config.get("cq.wcm.workflow.req." + type);
        try {
            return wfSession.getModel(modelId);
        }
        catch (WorkflowException we) {
            log.warn("Cannot load workflow model " + modelId + "specified in " + "cq.wcm.workflow.req." + type, (Throwable)we);
            return null;
        }
    }

    protected void bindThreadPoolManager(ThreadPoolManager threadPoolManager) {
        this.threadPoolManager = threadPoolManager;
    }

    protected void unbindThreadPoolManager(ThreadPoolManager threadPoolManager) {
        if (this.threadPoolManager == threadPoolManager) {
            this.threadPoolManager = null;
        }
    }

    protected void bindWorkflowService(WorkflowService workflowService) {
        this.workflowService = workflowService;
    }

    protected void unbindWorkflowService(WorkflowService workflowService) {
        if (this.workflowService == workflowService) {
            this.workflowService = null;
        }
    }

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

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

    protected void bindPayloadMap(PayloadMap payloadMap) {
        this.payloadMap = payloadMap;
    }

    protected void unbindPayloadMap(PayloadMap payloadMap) {
        if (this.payloadMap == payloadMap) {
            this.payloadMap = null;
        }
    }

    protected void bindJcrResourceResolverFactory(JcrResourceResolverFactory jcrResourceResolverFactory) {
        this.jcrResourceResolverFactory = jcrResourceResolverFactory;
    }

    protected void unbindJcrResourceResolverFactory(JcrResourceResolverFactory jcrResourceResolverFactory) {
        if (this.jcrResourceResolverFactory == jcrResourceResolverFactory) {
            this.jcrResourceResolverFactory = null;
        }
    }

}