TaskStorageProvider.java 36.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 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  aQute.bnd.annotation.ProviderType
 *  com.adobe.granite.taskmanagement.Filter
 *  com.adobe.granite.taskmanagement.Task
 *  com.adobe.granite.taskmanagement.TaskAction
 *  com.adobe.granite.taskmanagement.TaskManagerException
 *  com.adobe.granite.taskmanagement.TaskNotFoundException
 *  com.adobe.granite.taskmanagement.TaskProperty
 *  com.adobe.granite.workflow.exec.Status
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.Property
 *  javax.jcr.PropertyIterator
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.ValueFactory
 *  javax.jcr.ValueFormatException
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  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.jcr.api.SlingRepository
 *  org.osgi.service.event.Event
 *  org.osgi.service.event.EventAdmin
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.granite.taskmanagement.impl.jcr;

import aQute.bnd.annotation.ProviderType;
import com.adobe.granite.taskmanagement.Filter;
import com.adobe.granite.taskmanagement.Task;
import com.adobe.granite.taskmanagement.TaskAction;
import com.adobe.granite.taskmanagement.TaskManagerException;
import com.adobe.granite.taskmanagement.TaskNotFoundException;
import com.adobe.granite.taskmanagement.TaskProperty;
import com.adobe.granite.taskmanagement.impl.TaskActionImpl;
import com.adobe.granite.taskmanagement.impl.TaskImpl;
import com.adobe.granite.taskmanagement.impl.jcr.JcrQueryTaskFinder;
import com.adobe.granite.taskmanagement.impl.utils.ServiceLoginUtil;
import com.adobe.granite.taskmanagement.impl.utils.TaskEventHelper;
import com.adobe.granite.taskmanagement.impl.utils.TextUtil;
import com.adobe.granite.workflow.exec.Status;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
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.StringTokenizer;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.ValueFormatException;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * This class specifies class file version 49.0 but uses Java 6 signatures.  Assumed Java 6.
 */
@Component(metatype=1, label="Adobe Granite TaskManagement JCR Storage Implementation", description="Stores taskmanagement data in JCR Repository")
@Service(value={TaskStorageProvider.class})
@ProviderType
public class TaskStorageProvider {
    public static final long DATE_NODE_CHILD_SIZE = 1000;
    private static final Logger log = LoggerFactory.getLogger(TaskStorageProvider.class);
    public static final String PN_PARENT_ID = TaskProperty.PARENT_TASK_ID.getPropertyName();
    public static final String PN_DESCRIPTION = TaskProperty.DESCRIPTION.getPropertyName();
    public static final String PN_INSTRUCTIONS = TaskProperty.INSTRUCTIONS.getPropertyName();
    public static final String PN_NAME = TaskProperty.NAME.getPropertyName();
    public static final String PN_OWNER_ID = TaskProperty.OWNER_ID.getPropertyName();
    public static final String PN_TASK_TYPE_NAME = TaskProperty.TASK_TYPE_NAME.getPropertyName();
    public static final String PN_STATUS = TaskProperty.STATUS.getPropertyName();
    public static final String PN_CREATED = TaskProperty.CREATED_TIME.getPropertyName();
    public static final String PN_CREATED_BY = TaskProperty.CREATED_BY.getPropertyName();
    public static final String PN_LAST_MODIFIED = TaskProperty.MODIFIED_TIME.getPropertyName();
    public static final String PN_LAST_MODIFIED_BY = TaskProperty.MODIFIED_BY.getPropertyName();
    public static final String PN_COMPLETED = TaskProperty.COMPLETED_TIME.getPropertyName();
    public static final String PN_COMPLETED_BY = TaskProperty.COMPLETED_BY.getPropertyName();
    public static final String PN_ACTION_NAMES = TaskProperty.ACTION_NAMES.getPropertyName();
    public static final String PN_SELECTED_ACTION = TaskProperty.SELECTED_ACTION.getPropertyName();
    public static final String PN_CONTENT_PATH = TaskProperty.CONTENT_PATH.getPropertyName();
    public static final String PN_NAME_HIERARCHY = TaskProperty.NAME_HIERARCHY.getPropertyName();
    private static final Set<String> INTRINSIC_PROPS;
    public static final String TASK_NODE_TYPE = "granite:Task";
    private static final String SLING_FOLDER_TYPE = "sling:Folder";
    public static final String TASK_NODE_NAME_HINT = "_nodeNameHint";
    public static final String DEFAULT_TASK_NAME = "task";
    @Reference
    protected SlingRepository repository = null;
    @Reference
    protected EventAdmin eventAdminService = null;
    public static final String DEFAULT_ROOT_PATH = "/etc/taskmanagement/tasks";
    @org.apache.felix.scr.annotations.Property(value={"/etc/taskmanagement/tasks"}, label="Task Storage Root Path", description="Indicates where in the repository task data will be stored")
    public static final String OSGI_PROPERTY_ROOTPATH = "taskstorage.rootpath";
    public static final String HISTORICAL_TASKS_ROOTPATH = "/etc/taskmanagement/archivedtasks";
    @org.apache.felix.scr.annotations.Property(value={"/etc/taskmanagement/archivedtasks"}, label="Task History Storage Root Path", description="Indicates where in the repository task history data will be stored")
    public static final String OSGI_PROPERTY_HISTORY_ROOTPATH = "taskstorage.historyrootpath";
    protected String rootPath;
    protected String historyRootPath;
    private static final int MAX_RETRY_COUNT = 5;
    private final Session userSession;

    public TaskStorageProvider() {
        this.userSession = null;
        log.debug("**** TaskStorageProvider Created: {} ****", (Object)this);
    }

    public TaskStorageProvider(SlingRepository repository, EventAdmin eventAdminService, String rootPath, Session userSession) {
        this.repository = repository;
        this.eventAdminService = eventAdminService;
        this.rootPath = rootPath;
        this.userSession = userSession;
    }

    @Activate
    public void activate(Map<String, Object> props) {
        this.rootPath = (String)props.get("taskstorage.rootpath");
        this.historyRootPath = (String)props.get("taskstorage.historyrootpath");
    }

    private NodeIterator getNodeIteratorForParentTask(Session session, String parentTaskId) throws RepositoryException, TaskNotFoundException {
        if (parentTaskId == null) {
            if (session.nodeExists(this.rootPath)) {
                return session.getNode(this.rootPath).getNodes();
            }
            return null;
        }
        String path = this.getPath(parentTaskId);
        Node node = null;
        try {
            node = session.getNode(path);
        }
        catch (PathNotFoundException e) {
            throw new TaskNotFoundException(MessageFormat.format("Task with id {0} does not exist (path={1})", parentTaskId, path));
        }
        return node.getNodes();
    }

    public List<Task> findByFilter(Set<String> userIds, Filter aFilter, int startIndex, int maxNumberOfTasks) throws TaskManagerException {
        log.debug("**** TaskStorageProvider.findByFilter({}, {}) ", userIds, (Object)aFilter);
        Session session = null;
        try {
            session = this.getSession();
            JcrQueryTaskFinder taskFinder = new JcrQueryTaskFinder(this, session, this.rootPath);
            if (this.userSession != null) {
                userIds = null;
            }
            List<Task> list = taskFinder.findTasks(userIds, aFilter, startIndex, maxNumberOfTasks);
            return list;
        }
        catch (RepositoryException e) {
            throw new TaskManagerException("Error while reading filtered tasks.", (Throwable)e);
        }
        finally {
            this.discardSession(session);
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public Task create(String parentTaskId, Task newInstance) throws TaskNotFoundException, TaskManagerException {
        String nodeNameHint;
        log.debug("**** TaskStorageProvider.create({}) ****", (Object)newInstance.getName());
        String nodeNameBase = newInstance.getName();
        if (newInstance.getProperty("_nodeNameHint") instanceof String && (nodeNameHint = (String)newInstance.getProperty("_nodeNameHint")) != null && nodeNameHint.trim().length() > 0) {
            nodeNameBase = nodeNameHint.trim();
        }
        int retryCount = 5;
        while (retryCount > 0) {
            Session session = null;
            Node taskNode = null;
            try {
                String parentTaskPath;
                Node taskParentNode;
                session = this.getSession();
                this.checkRootNode();
                String idBase = nodeNameBase;
                if (!TextUtil.isEmpty(idBase)) {
                    idBase = idBase.replace("/", "");
                }
                idBase = TextUtil.isEmpty(idBase) ? "task" : TextUtil.createValidName(idBase);
                if (retryCount < 4) {
                    idBase = idBase + System.currentTimeMillis();
                }
                if (parentTaskId == null) {
                    taskParentNode = this.getDateNode(session);
                } else {
                    parentTaskPath = this.getPath(parentTaskId);
                    if (!session.nodeExists(parentTaskPath)) {
                        throw new TaskNotFoundException(MessageFormat.format("Parent Task Node not found {0}", parentTaskId));
                    }
                    taskParentNode = session.getNode(parentTaskPath);
                }
                taskNode = JcrUtils.getOrCreateUniqueByPath((Node)taskParentNode, (String)idBase, (String)"granite:Task");
                ((TaskImpl)newInstance).setId(this.constructId(parentTaskId, taskNode));
                ((TaskImpl)newInstance).setParentId(parentTaskId);
                this.update(taskNode, newInstance);
                session.save();
                log.debug("**** TaskStorageProvider.created {} ****", (Object)newInstance.getId());
                parentTaskPath = newInstance;
                return parentTaskPath;
            }
            catch (RepositoryException e) {
                if (--retryCount <= 0) {
                    log.debug("Error while creating task.", (Throwable)e);
                    throw new TaskManagerException("Error while creating task.", (Throwable)e);
                }
                try {
                    Thread.sleep(10);
                }
                catch (InterruptedException interruptedException) {
                    // empty catch block
                }
                continue;
            }
            finally {
                this.discardSession(session);
                continue;
            }
        }
        throw new TaskManagerException("Failed to create task.");
    }

    protected Node getDateNode(Session session) throws RepositoryException {
        Node rootNode = session.getNode(this.rootPath);
        return this.getDateNode(rootNode);
    }

    protected Node getDateNode(Node rootNode) throws RepositoryException {
        Date date = Calendar.getInstance().getTime();
        String dateName = new SimpleDateFormat("yyyy-MM-dd").format(date);
        Node dateNode = this.getDateNode(rootNode, dateName);
        int count = 0;
        while (dateNode.getNodes().getSize() >= 1000) {
            dateNode = this.getDateNode(rootNode, dateName + "_" + ++count);
        }
        return dateNode;
    }

    private Node getDateNode(Node rootNode, String dateName) throws RepositoryException {
        Node dateNode = rootNode.hasNode(dateName) ? rootNode.getNode(dateName) : rootNode.addNode(dateName, "sling:Folder");
        return dateNode;
    }

    private String constructId(String parentTaskId, Node taskNode) throws RepositoryException {
        if (this.userSession != null) {
            return taskNode.getPath();
        }
        if (taskNode.getPath().startsWith(this.rootPath)) {
            if (parentTaskId != null) {
                return this.constructId(parentTaskId, taskNode.getName());
            }
            return taskNode.getParent().getName() + "/" + taskNode.getName();
        }
        return taskNode.getPath();
    }

    private String constructId(String parentTaskId, String taskKey) {
        if (parentTaskId == null) {
            return taskKey;
        }
        return parentTaskId + "/" + taskKey;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void checkRootNode() throws RepositoryException {
        Session session = null;
        try {
            session = this.getSession();
            if (!session.nodeExists(this.rootPath)) {
                JcrUtils.getOrCreateByPath((String)this.rootPath, (String)"sling:Folder", (Session)session);
                session.save();
            }
        }
        finally {
            this.discardSession(session);
        }
    }

    public Task getTask(String id) throws TaskNotFoundException, TaskManagerException {
        log.debug("**** TaskStorageProvider.getTask({}) ****", (Object)id);
        Session session = null;
        try {
            session = this.getSession();
            String path = this.getPath(id);
            Node node = null;
            try {
                node = session.getNode(path);
            }
            catch (PathNotFoundException e2) {
                throw new TaskNotFoundException(MessageFormat.format("Task with id {0} does not exist (path={1})", id, path));
            }
            Task e2 = this.read(node, false);
            return e2;
        }
        catch (RepositoryException e) {
            throw new TaskManagerException("Error while reading task.", (Throwable)e);
        }
        finally {
            this.discardSession(session);
        }
    }

    public Task readRecursive(String taskId) throws TaskNotFoundException, TaskManagerException {
        log.debug("**** TaskStorageProvider.readRecursive({}) ****", (Object)taskId);
        Session session = null;
        try {
            session = this.getSession();
            String path = this.getPath(taskId);
            Node node = null;
            try {
                node = session.getNode(path);
            }
            catch (PathNotFoundException e2) {
                throw new TaskNotFoundException(MessageFormat.format("Task with id {0} does not exist (path={1})", taskId, path));
            }
            Task e2 = this.read(node, true);
            return e2;
        }
        catch (RepositoryException e) {
            throw new TaskManagerException("Error while reading task.", (Throwable)e);
        }
        finally {
            this.discardSession(session);
        }
    }

    private void addSubTasks(Task task, Node taskNode) throws RepositoryException, TaskManagerException {
        NodeIterator nodes = taskNode.getNodes();
        ArrayList<Task> subNodes = new ArrayList<Task>();
        if (nodes != null) {
            while (nodes.hasNext()) {
                Node subNode = nodes.nextNode();
                if (!this.isSubTaskNode(subNode)) continue;
                ((TaskImpl)task).setParentTask(true);
                Task subTask = this.read(subNode, true);
                subNodes.add(subTask);
            }
        }
        ((TaskImpl)task).setSubTasks(subNodes);
    }

    boolean isSubTaskNode(Node subNode) throws RepositoryException {
        return subNode != null && subNode.isNodeType("granite:Task");
    }

    Task read(Node node, boolean loadSubTasks) throws RepositoryException, TaskNotFoundException, TaskManagerException {
        if (!node.isNodeType("granite:Task")) {
            throw new TaskNotFoundException(MessageFormat.format("A valid Task was not found for path [{0}]", node.getPath()));
        }
        TaskImpl task = new TaskImpl();
        HashMap<String, Property> customPropertyValues = new HashMap<String, Property>();
        PropertyIterator iter = node.getProperties();
        while (iter.hasNext()) {
            Property p = iter.nextProperty();
            String name = p.getName();
            if (name.startsWith("jcr:")) continue;
            if (name.equals(PN_PARENT_ID)) {
                task.setParentId(p.getString());
                continue;
            }
            if (name.equals(PN_DESCRIPTION)) {
                task.setDescription(p.getString());
                continue;
            }
            if (name.equals(PN_INSTRUCTIONS)) {
                task.setInstructions(p.getString());
                continue;
            }
            if (name.equals(PN_CONTENT_PATH)) {
                task.setContentPath(p.getString());
                continue;
            }
            if (name.equals(PN_NAME)) {
                task.setName(p.getString());
                continue;
            }
            if (name.equals(PN_TASK_TYPE_NAME)) {
                task.setTaskTypeName(p.getString());
                continue;
            }
            if (name.equals(PN_OWNER_ID)) {
                task.setCurrentAssignee(p.getString());
                continue;
            }
            if (name.equals(PN_CREATED)) {
                task.setTimeStarted(TaskStorageProvider.toDate(p.getDate()));
                continue;
            }
            if (name.equals(PN_CREATED_BY)) {
                task.setCreatedBy(p.getString());
                continue;
            }
            if (name.equals(PN_LAST_MODIFIED)) {
                task.setLastModified(TaskStorageProvider.toDate(p.getDate()));
                continue;
            }
            if (name.equals(PN_LAST_MODIFIED_BY)) {
                task.setLastModifiedBy(p.getString());
                continue;
            }
            if (name.equals(PN_COMPLETED)) {
                task.setTimeEnded(TaskStorageProvider.toDate(p.getDate()));
                continue;
            }
            if (name.equals(PN_COMPLETED_BY)) {
                task.setCompletedBy(p.getString());
                continue;
            }
            if (name.equals(PN_NAME_HIERARCHY)) {
                task.setNameHierarchy(p.getString());
                continue;
            }
            if (name.equals(PN_ACTION_NAMES)) {
                Value[] vs = p.getValues();
                ArrayList<TaskAction> names = new ArrayList<TaskAction>(vs.length);
                for (Value v : vs) {
                    TaskActionImpl action = new TaskActionImpl(v.getString());
                    names.add(action);
                }
                task.setActions(names);
                continue;
            }
            if (name.equals(PN_SELECTED_ACTION)) {
                task.setSelectedAction(new TaskActionImpl(p.getString()));
                continue;
            }
            if (name.equals(PN_STATUS)) {
                task.setStatus(Status.valueOf((String)p.getString()));
                continue;
            }
            customPropertyValues.put(name, p);
        }
        task.setId(this.constructId(task.getParentId(), node));
        for (Property customProperty : customPropertyValues.values()) {
            String propertyName = customProperty.getName();
            Object propertyValue = null;
            switch (customProperty.getType()) {
                case 6: {
                    propertyValue = customProperty.getBoolean();
                    break;
                }
                case 1: {
                    propertyValue = customProperty.getString();
                    break;
                }
                case 3: {
                    propertyValue = customProperty.getLong();
                    break;
                }
                case 4: {
                    propertyValue = customProperty.getDouble();
                    break;
                }
                default: {
                    propertyValue = customProperty.getString();
                }
            }
            task.setProperty(propertyName, propertyValue);
        }
        if (loadSubTasks) {
            this.addSubTasks(task, node);
        } else {
            NodeIterator nodes = node.getNodes();
            if (nodes != null) {
                while (nodes.hasNext()) {
                    if (!this.isSubTaskNode(nodes.nextNode())) continue;
                    task.setParentTask(true);
                    break;
                }
            }
        }
        return task;
    }

    private String getStringPropSafe(Node node, String propertyName) {
        try {
            Property prop = node.getProperty(propertyName);
            return prop.getString();
        }
        catch (RepositoryException e) {
            return null;
        }
    }

    private Date getDatePropSafe(Node node, String propertyName) {
        try {
            Property prop = node.getProperty(propertyName);
            return TaskStorageProvider.toDate(prop.getDate());
        }
        catch (RepositoryException e) {
            return null;
        }
    }

    public boolean exists(String taskId) throws TaskManagerException {
        log.debug("**** TaskStorageProvider.exists({}) ****", (Object)taskId);
        Session session = null;
        try {
            session = this.getSession();
            String path = this.getPath(taskId);
            boolean bl = session.nodeExists(path);
            return bl;
        }
        catch (RepositoryException e) {
            throw new TaskManagerException("Error while reading task.", (Throwable)e);
        }
        finally {
            this.discardSession(session);
        }
    }

    public void update(Task transientObject) throws TaskNotFoundException, TaskManagerException {
        log.debug("**** TaskStorageProvider.update({}) ****", (Object)transientObject);
        Session session = null;
        try {
            session = this.getSession();
            String path = this.getPath(transientObject.getId());
            Node node = null;
            try {
                node = session.getNode(path);
            }
            catch (PathNotFoundException e) {
                throw new TaskNotFoundException(MessageFormat.format("Task with id {0} does not exist (path={1})", transientObject.getId(), path));
            }
            this.update(node, transientObject);
            session.save();
        }
        catch (RepositoryException e) {
            throw new TaskManagerException("Error while updating task.", (Throwable)e);
        }
        finally {
            this.discardSession(session);
        }
    }

    private void update(Node node, Task task) throws RepositoryException {
        List taskActions;
        node.setProperty(PN_PARENT_ID, task.getParentId());
        node.setProperty(PN_NAME, task.getName());
        node.setProperty(PN_CREATED, TaskStorageProvider.toCalendar(task.getTimeStarted()));
        node.setProperty(PN_DESCRIPTION, task.getDescription());
        node.setProperty(PN_INSTRUCTIONS, task.getInstructions());
        node.setProperty(PN_OWNER_ID, task.getCurrentAssignee());
        node.setProperty(PN_CONTENT_PATH, task.getContentPath());
        node.setProperty(PN_STATUS, task.getStatus().name());
        if (node.isNew()) {
            node.setProperty(PN_CREATED_BY, task.getCreatedBy());
        }
        node.setProperty(PN_TASK_TYPE_NAME, task.getTaskTypeName());
        node.setProperty(PN_LAST_MODIFIED, TaskStorageProvider.toCalendar(task.getLastModified()));
        node.setProperty(PN_LAST_MODIFIED_BY, task.getLastModifiedBy());
        node.setProperty(PN_COMPLETED, TaskStorageProvider.toCalendar(task.getTimeEnded()));
        node.setProperty(PN_COMPLETED_BY, task.getCompletedBy());
        TaskAction selectedAction = task.getSelectedAction();
        if (selectedAction != null) {
            node.setProperty(PN_SELECTED_ACTION, selectedAction.getActionID());
        }
        if ((taskActions = task.getActions()) != null && !taskActions.isEmpty()) {
            ArrayList<String> actionNameList = new ArrayList<String>();
            for (TaskAction action : taskActions) {
                if (action == null || action.getActionID() == null) continue;
                actionNameList.add(action.getActionID());
            }
            if (!actionNameList.isEmpty()) {
                node.setProperty(PN_ACTION_NAMES, actionNameList.toArray(new String[actionNameList.size()]));
            }
        }
        String nameHierarchy = task.getName();
        Node currentNode = node;
        while (currentNode.getParent() != null && currentNode.getParent().isNodeType("granite:Task")) {
            currentNode = currentNode.getParent();
            String name = this.getStringPropSafe(currentNode, PN_NAME);
            nameHierarchy = name + '/' + nameHierarchy;
        }
        ((TaskImpl)task).setNameHierarchy(nameHierarchy);
        node.setProperty(PN_NAME_HIERARCHY, nameHierarchy);
        ValueFactory fac = node.getSession().getValueFactory();
        HashSet<String> names = new HashSet<String>(INTRINSIC_PROPS);
        Iterator propertyNameIterator = task.getPropertyNames();
        if (propertyNameIterator != null) {
            while (propertyNameIterator.hasNext()) {
                String key = (String)propertyNameIterator.next();
                if (key == null || "_nodeNameHint".equals(key)) continue;
                Object value = task.getProperty(key);
                log.debug("**** adding property: {}={}", (Object)key, value);
                names.add(key);
                if (value instanceof Boolean) {
                    node.setProperty(key, TaskStorageProvider.toBoolean(value));
                    continue;
                }
                if (value instanceof Date) {
                    node.setProperty(key, TaskStorageProvider.toCalendar((Date)value));
                    continue;
                }
                if (TaskStorageProvider.isNumber(value)) {
                    node.setProperty(key, TaskStorageProvider.toNumberValue(fac, value));
                    continue;
                }
                if (value instanceof Double) {
                    node.setProperty(key, TaskStorageProvider.toDoubleValue(fac, value));
                    continue;
                }
                node.setProperty(key, value == null ? null : value.toString());
            }
        }
        PropertyIterator iter = node.getProperties();
        while (iter.hasNext()) {
            Property p = iter.nextProperty();
            String name = p.getName();
            if (name.startsWith("jcr:") || names.contains(name)) continue;
            p.remove();
        }
    }

    public void deleteTask(String taskId) throws TaskNotFoundException, TaskManagerException {
        log.debug("**** TaskStorageProvider.deleteTask({}) ****", (Object)taskId);
        Session session = null;
        try {
            session = this.getSession();
            String path = this.getPath(taskId);
            try {
                session.getNode(path).remove();
            }
            catch (PathNotFoundException e) {
                throw new TaskNotFoundException(MessageFormat.format("Task with id {0} does not exist (path={1})", taskId, path));
            }
            session.save();
        }
        catch (RepositoryException e) {
            throw new TaskManagerException("Error while deleting task.", (Throwable)e);
        }
        finally {
            this.discardSession(session);
        }
    }

    String getPath(String id) {
        if (this.userSession == null) {
            if (!id.startsWith("/")) {
                StringBuilder builder = new StringBuilder(this.rootPath).append('/').append(id);
                return builder.toString();
            }
            return id;
        }
        return id;
    }

    private Session getSession() throws RepositoryException {
        if (this.userSession != null) {
            return this.userSession;
        }
        return ServiceLoginUtil.createTaskmanagementSession(this.repository);
    }

    private void discardSession(Session session) {
        if (session != this.userSession && session != null) {
            session.logout();
        }
    }

    private static boolean toBoolean(Object value) {
        boolean result = false;
        if (value != null) {
            if (value instanceof Boolean) {
                result = (Boolean)value;
            } else if (value instanceof String) {
                result = Boolean.parseBoolean((String)value);
            } else {
                log.error("Unable to convert {} to a boolean.", value);
            }
        }
        return result;
    }

    private static Calendar toCalendar(Date time) {
        if (time == null) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(time);
        return c;
    }

    private static Date toDate(Calendar time) {
        if (time == null) {
            return null;
        }
        return time.getTime();
    }

    private static boolean isNumber(Object value) {
        return value != null && (value instanceof Integer || value instanceof Long || value instanceof Short || value instanceof Byte || value instanceof BigDecimal);
    }

    private static Value toNumberValue(ValueFactory fac, Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Integer) {
            return fac.createValue((long)((Integer)value).intValue());
        }
        if (value instanceof Long) {
            return fac.createValue(((Long)value).longValue());
        }
        if (value instanceof Short) {
            return fac.createValue((long)((Short)value).shortValue());
        }
        if (value instanceof Byte) {
            return fac.createValue((long)((Byte)value).byteValue());
        }
        if (value instanceof BigDecimal) {
            return fac.createValue((BigDecimal)value);
        }
        return TaskStorageProvider.createValueFromString(fac, value, 3, "number");
    }

    private static Value toDoubleValue(ValueFactory fac, Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Float || value instanceof Double) {
            return fac.createValue(((Double)value).doubleValue());
        }
        return TaskStorageProvider.createValueFromString(fac, value, 4, "double");
    }

    private static Value createValueFromString(ValueFactory fac, Object value, int valueType, String typeName) {
        try {
            String str = value.toString();
            if (str.length() == 0) {
                return null;
            }
            return fac.createValue(value.toString(), valueType);
        }
        catch (ValueFormatException e) {
            log.error("Unable to convert {} to a {}.", (Object)new Object[]{value, typeName}, (Object)e);
            return null;
        }
    }

    private static void ensurePathExists(Session session, String path) throws RepositoryException {
        if (!session.nodeExists(path)) {
            JcrUtils.getOrCreateByPath((String)path, (String)"sling:Folder", (Session)session);
        }
    }

    public long archiveOldTasks(Date archiveSinceCompleted) throws TaskManagerException {
        log.info("archiving TASKS SINCE COMPLETED {}", (Object)archiveSinceCompleted);
        Session session = null;
        boolean modificationsMade = false;
        try {
            session = this.getSession();
            ArrayList<Task> archivedTasks = new ArrayList<Task>();
            NodeIterator subNodesIterator = this.getNodeIteratorForParentTask(session, null);
            if (subNodesIterator != null) {
                while (subNodesIterator.hasNext()) {
                    Node inter = subNodesIterator.nextNode();
                    NodeIterator i2 = inter.getNodes();
                    while (i2.hasNext()) {
                        Calendar lastModified;
                        long lastModifiedMillis;
                        Node _taskNode = i2.nextNode();
                        if (!_taskNode.isNodeType("granite:Task")) continue;
                        Property lastModifiedProp = _taskNode.getProperty(PN_LAST_MODIFIED);
                        Property statusProp = _taskNode.getProperty(PN_STATUS);
                        if (!Status.COMPLETE.name().equals(statusProp.getString()) || (lastModifiedMillis = (lastModified = lastModifiedProp.getDate()).getTimeInMillis()) >= archiveSinceCompleted.getTime()) continue;
                        log.info("WE FOUND A TASK TO ARCHIVE {} ", (Object)(inter.getName() + _taskNode.getName()));
                        Task taskBeingDeleted = this.readRecursive(_taskNode.getName());
                        archivedTasks.add(taskBeingDeleted);
                        StringBuilder builder = new StringBuilder(this.historyRootPath).append('/').append(inter.getName());
                        String newPath = builder.toString();
                        TaskStorageProvider.ensurePathExists(session, newPath);
                        builder.append('/').append(_taskNode.getName());
                        newPath = builder.toString();
                        session.move(_taskNode.getPath(), newPath);
                        modificationsMade = true;
                    }
                }
            }
            if (modificationsMade) {
                session.save();
            }
            long deletedCount = 0;
            for (Task task : archivedTasks) {
                deletedCount += this.sendTaskDeletedDeep(task);
            }
            long i$ = deletedCount;
            return i$;
        }
        catch (RepositoryException e) {
            throw new TaskManagerException("Error while archiving old tasks.", (Throwable)e);
        }
        finally {
            this.discardSession(session);
        }
    }

    private long sendTaskDeletedDeep(Task task) {
        long tasksDeleted = 1;
        this.eventAdminService.sendEvent((Event)TaskEventHelper.newTaskArchivedEvent(task));
        if (task.getSubTasks() != null) {
            for (Task subTask : task.getSubTasks()) {
                tasksDeleted += this.sendTaskDeletedDeep(subTask);
            }
        }
        return tasksDeleted;
    }

    Set<String> cleanupUserIDs(Filter filter, Set<String> userIds) throws TaskManagerException {
        if (filter == null || filter.getParentTaskId() == null) {
            return userIds;
        }
        if (userIds != null) {
            StringTokenizer tokenizer = new StringTokenizer(filter.getParentTaskId(), "/");
            String parentTaskPath = "";
            if (tokenizer.hasMoreElements()) {
                parentTaskPath = tokenizer.nextToken();
            }
            while (tokenizer.hasMoreElements()) {
                Task parentTask;
                if (parentTaskPath.length() != 0) {
                    parentTaskPath = parentTaskPath + "/";
                }
                if (!userIds.contains((parentTask = this.getTask(parentTaskPath = parentTaskPath + tokenizer.nextToken())).getCurrentAssignee())) continue;
                return null;
            }
        }
        return userIds;
    }

    public void fixId(TaskImpl theTask) {
        String originalId = theTask.getId();
        if (null != originalId) {
            theTask.setId(TextUtil.createValidName(originalId));
        }
    }

    static {
        HashSet<String> ips = new HashSet<String>();
        ips.add(PN_PARENT_ID);
        ips.add(PN_DESCRIPTION);
        ips.add(PN_INSTRUCTIONS);
        ips.add(PN_NAME);
        ips.add(PN_OWNER_ID);
        ips.add(PN_TASK_TYPE_NAME);
        ips.add(PN_STATUS);
        ips.add(PN_CREATED);
        ips.add(PN_CREATED_BY);
        ips.add(PN_LAST_MODIFIED);
        ips.add(PN_LAST_MODIFIED_BY);
        ips.add(PN_COMPLETED);
        ips.add(PN_COMPLETED_BY);
        ips.add(PN_ACTION_NAMES);
        ips.add(PN_SELECTED_ACTION);
        ips.add(PN_CONTENT_PATH);
        ips.add(PN_NAME_HIERARCHY);
        INTRINSIC_PROPS = Collections.unmodifiableSet(ips);
    }

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

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

    protected void bindEventAdminService(EventAdmin eventAdmin) {
        this.eventAdminService = eventAdmin;
    }

    protected void unbindEventAdminService(EventAdmin eventAdmin) {
        if (this.eventAdminService == eventAdmin) {
            this.eventAdminService = null;
        }
    }
}