001/*
002 * (C) Copyright 2016 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019package org.nuxeo.connect.update.task.guards;
020
021import org.nuxeo.connect.update.Package;
022import org.nuxeo.connect.update.PackageException;
023import org.nuxeo.connect.update.PackageState;
024import org.nuxeo.connect.update.PackageUpdateService;
025
026/**
027 * Helper to access the package update service from JEXL.
028 *
029 * @since 8.4
030 */
031public class PackagesHelper {
032
033    private final PackageUpdateService service;
034
035    public PackagesHelper(PackageUpdateService service) {
036        this.service = service;
037    }
038
039    public boolean contains(String name) {
040        try {
041            if (name.contains(":")) {
042                // exact version
043                name = name.replace(':', '-');
044                Package pkg = service.getPackage(name);
045                return pkg != null && isPackageInstalled(pkg);
046            } else {
047                // any version
048                for (Package pkg : service.getPackages()) {
049                    // multiple packages can have the same name (not id),
050                    // iterate until an installed one is found.
051                    if (pkg.getName().equals(name) && isPackageInstalled(pkg)) {
052                        return true;
053                    }
054                }
055                return false;
056            }
057        } catch (PackageException e) {
058            return false;
059        }
060    }
061
062    protected boolean isPackageInstalled(Package pkg) {
063        PackageState state = pkg.getPackageState();
064        switch (state) {
065        case INSTALLING:
066        case INSTALLED:
067        case STARTED:
068            return true;
069        default:
070            return false;
071        }
072    }
073
074}