<commit_before>/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2014 Adobe
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

package com.adobe.acs.commons.packaging.impl;

import com.adobe.acs.commons.packaging.PackageHelper;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.jcr.vault.fs.api.FilterSet;
import com.day.jcr.vault.fs.api.PathFilterSet;
import com.day.jcr.vault.fs.config.DefaultWorkspaceFilter;
import com.day.jcr.vault.packaging.JcrPackage;
import com.day.jcr.vault.packaging.JcrPackageDefinition;
import com.day.jcr.vault.packaging.JcrPackageManager;
import com.day.jcr.vault.packaging.PackageId;
import com.day.jcr.vault.packaging.Packaging;
import com.day.jcr.vault.packaging.Version;
import org.apache.commons.lang.StringUtils;
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.JcrConstants;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component(
        label = "ACS AEM Commons - Package Helper",
        description = "Helper utility for creating CRX Packages and using the ACS AEM Commons packager. "
)
@Service
public class PackageHelperImpl implements PackageHelper {
    private static final Logger log = LoggerFactory.getLogger(ACLPackagerServletImpl.class);

    private static final String NN_THUMBNAIL = "thumbnail.png";

    private static final String JSON_EXCEPTION_MSG =
            "{\"status\": \"error\", \"msg\": \"Error creating JSON response.\"}";

    @Reference
    private Packaging packaging;

    @Reference
    private ResourceResolverFactory resourceResolverFactory;

    /**
     * {@inheritDoc}
     */
    public final void addThumbnail(final JcrPackage jcrPackage, Resource thumbnailResource) {
        ResourceResolver resourceResolver = null;

        if (jcrPackage == null) {
            log.error("JCR Package is null; no package thumbnail needed for null packages!");
            return;
        }

        boolean useDefault = thumbnailResource == null || !thumbnailResource.isResourceType(JcrConstants.NT_FILE);

        try {
            if (useDefault) {
                log.debug("Using default ACS AEM Commons packager package icon.");
                resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
                thumbnailResource = resourceResolver.getResource(DEFAULT_PACKAGE_THUMBNAIL_RESOURCE_PATH);
            }

            if (thumbnailResource == null || !thumbnailResource.isResourceType(JcrConstants.NT_FILE)) {
                log.warn("Cannot find a specific OR a default package icon; no package icon will be used.");
            } else {
                final Node srcNode = thumbnailResource.adaptTo(Node.class);
                final Node dstParentNode = jcrPackage.getDefinition().getNode();

                JcrUtil.copy(srcNode, dstParentNode, NN_THUMBNAIL);
                dstParentNode.getSession().save();
            }
        } catch (RepositoryException e) {
            log.error("Could not add package thumbnail: {}", e.getMessage());
        } catch (LoginException e) {
            log.error("Could not add a default package thumbnail: {}", e.getMessage());
        } finally {
            if (resourceResolver != null) {
                resourceResolver.close();
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public final Version getNextVersion(final JcrPackageManager jcrPackageManager,
                                        final String groupName, final String name,
                                        final String version) throws RepositoryException {
        final Node packageRoot = jcrPackageManager.getPackageRoot(false);
        final Version configVersion = Version.create(version);

        if (!packageRoot.hasNode(groupName)) {
            return configVersion;
        }

        final Node packageGroupNode = packageRoot.getNode(groupName);

        if (packageGroupNode == null) {
            return configVersion;
        } else {
            final NodeIterator children = packageGroupNode.getNodes();
            Version latestVersion = configVersion;
            boolean configVersionEligible = true;

            while (children.hasNext()) {
                final Node child = children.nextNode();

                final JcrPackage jcrPackage = jcrPackageManager.open(child, true);
                if (!StringUtils.equals(name, jcrPackage.getDefinition().getId().getName())) {
                    // Name mismatch - so just skip
                    continue;
                }

                final Version packageVersion = jcrPackage.getDefinition().getId().getVersion();

                log.debug(packageVersion.toString() + " compareTo " + latestVersion.toString()
                        + " = " + packageVersion.compareTo(latestVersion));

                if (packageVersion.compareTo(latestVersion) >= 1) {
                    latestVersion = packageVersion;
                    log.debug("Found a new latest version: {}", latestVersion.toString());
                } else if (packageVersion.compareTo(configVersion) == 0) {
                    configVersionEligible = false;
                    log.debug("Found a package with the same version as the config version");
                }
            }

            log.debug("Current latest version: {}", latestVersion.toString());
            if (configVersionEligible && latestVersion.equals(configVersion)) {
                // If the config-specified version is newer than any existing package, jump to the config version
                return configVersion;<commit_msg>bug - Unexpected (non-package) nodes under /etc/packages break IncrementVersion<commit_after>/*
 * #%L
 * ACS AEM Commons Bundle
 * %%
 * Copyright (C) 2014 Adobe
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

package com.adobe.acs.commons.packaging.impl;

import com.adobe.acs.commons.packaging.PackageHelper;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.jcr.vault.fs.api.FilterSet;
import com.day.jcr.vault.fs.api.PathFilterSet;
import com.day.jcr.vault.fs.config.DefaultWorkspaceFilter;
import com.day.jcr.vault.packaging.JcrPackage;
import com.day.jcr.vault.packaging.JcrPackageDefinition;
import com.day.jcr.vault.packaging.JcrPackageManager;
import com.day.jcr.vault.packaging.PackageId;
import com.day.jcr.vault.packaging.Packaging;
import com.day.jcr.vault.packaging.Version;
import org.apache.commons.lang.StringUtils;
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.JcrConstants;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component(
        label = "ACS AEM Commons - Package Helper",
        description = "Helper utility for creating CRX Packages and using the ACS AEM Commons packager. "
)
@Service
public class PackageHelperImpl implements PackageHelper {
    private static final Logger log = LoggerFactory.getLogger(ACLPackagerServletImpl.class);

    private static final String NN_THUMBNAIL = "thumbnail.png";

    private static final String JSON_EXCEPTION_MSG =
            "{\"status\": \"error\", \"msg\": \"Error creating JSON response.\"}";

    @Reference
    private Packaging packaging;

    @Reference
    private ResourceResolverFactory resourceResolverFactory;

    /**
     * {@inheritDoc}
     */
    public final void addThumbnail(final JcrPackage jcrPackage, Resource thumbnailResource) {
        ResourceResolver resourceResolver = null;

        if (jcrPackage == null) {
            log.error("JCR Package is null; no package thumbnail needed for null packages!");
            return;
        }

        boolean useDefault = thumbnailResource == null || !thumbnailResource.isResourceType(JcrConstants.NT_FILE);

        try {
            if (useDefault) {
                log.debug("Using default ACS AEM Commons packager package icon.");
                resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
                thumbnailResource = resourceResolver.getResource(DEFAULT_PACKAGE_THUMBNAIL_RESOURCE_PATH);
            }

            if (thumbnailResource == null || !thumbnailResource.isResourceType(JcrConstants.NT_FILE)) {
                log.warn("Cannot find a specific OR a default package icon; no package icon will be used.");
            } else {
                final Node srcNode = thumbnailResource.adaptTo(Node.class);
                final Node dstParentNode = jcrPackage.getDefinition().getNode();

                JcrUtil.copy(srcNode, dstParentNode, NN_THUMBNAIL);
                dstParentNode.getSession().save();
            }
        } catch (RepositoryException e) {
            log.error("Could not add package thumbnail: {}", e.getMessage());
        } catch (LoginException e) {
            log.error("Could not add a default package thumbnail: {}", e.getMessage());
        } finally {
            if (resourceResolver != null) {
                resourceResolver.close();
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public final Version getNextVersion(final JcrPackageManager jcrPackageManager,
                                        final String groupName, final String name,
                                        final String version) throws RepositoryException {
        final Node packageRoot = jcrPackageManager.getPackageRoot(false);
        final Version configVersion = Version.create(version);

        if (!packageRoot.hasNode(groupName)) {
            return configVersion;
        }

        final Node packageGroupNode = packageRoot.getNode(groupName);

        if (packageGroupNode == null) {
            return configVersion;
        } else {
            final NodeIterator children = packageGroupNode.getNodes();
            Version latestVersion = configVersion;
            boolean configVersionEligible = true;

            while (children.hasNext()) {
                final Node child = children.nextNode();

                final JcrPackage jcrPackage = jcrPackageManager.open(child, true);
                if (jcrPackage == null
                        || jcrPackage.getDefinition() == null
                        || jcrPackage.getDefinition().getId() == null) {

                    log.warn("Could not covert node [ {} ] into a proper JCR Package, moving to next node", child.getPath());
                    continue;

                } else if (!StringUtils.equals(name, jcrPackage.getDefinition().getId().getName())) {
                    // Name mismatch - so just skip
                    continue;
                }

                final Version packageVersion = jcrPackage.getDefinition().getId().getVersion();

                log.debug(packageVersion.toString() + " compareTo " + latestVersion.toString()
                        + " = " + packageVersion.compareTo(latestVersion));

                if (packageVersion.compareTo(latestVersion) >= 1) {
                    latestVersion = packageVersion;
                    log.debug("Found a new latest version: {}", latestVersion.toString());
                } else if (packageVersion.compareTo(configVersion) == 0) {
                    configVersionEligible = false;
                    log.debug("Found a package with the same version as the config version");
                }
            }

            log.debug("Current latest version: {}", latestVersion.toString());
            if (configVersionEligible && latestVersion.equals(configVersion)) {
                // If the config-specified version is newer than any existing package, jump to the config version
                return configVersion;
{'fraction_non_alphanumeric': 0.0954119247011667, 'fraction_numerical': 0.0017178441056474125, 'mean_word_length': 2.631920977384975, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3754220', 'n_tokens_mistral': 3668, 'n_tokens_neox': 3541, 'n_words': 929}