001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.internal.impl.synccontext.named;
020
021import java.util.Collection;
022import java.util.stream.Collectors;
023
024import org.eclipse.aether.RepositorySystemSession;
025import org.eclipse.aether.artifact.Artifact;
026import org.eclipse.aether.metadata.Metadata;
027import org.eclipse.aether.named.NamedLockKey;
028import org.eclipse.aether.util.ConfigUtils;
029import org.eclipse.aether.util.StringDigestUtil;
030
031import static java.util.Objects.requireNonNull;
032
033/**
034 * Wrapping {@link NameMapper}, that wraps another {@link NameMapper} and hashes resulting strings. It makes use of
035 * fact that (proper) Hash will create unique fixed length string for each different input string (so injection still
036 * stands). This mapper produces file system friendly names. Supports different "depths" (0-4 inclusive) where the
037 * name will contain 0 to 4 level deep directories.
038 * <p>
039 * This mapper is usable in any scenario, but intent was to produce more "compact" name mapper for file locking.
040 *
041 * @since 1.9.0
042 */
043public class HashingNameMapper implements NameMapper {
044    /**
045     * The depth how many levels should adapter create. Acceptable values are 0-4 (inclusive).
046     *
047     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
048     * @configurationType {@link java.lang.Integer}
049     * @configurationDefaultValue {@link #DEFAULT_DEPTH}
050     */
051    public static final String CONFIG_PROP_DEPTH = NamedLockFactoryAdapter.CONFIG_PROPS_PREFIX + "hashing.depth";
052
053    public static final int DEFAULT_DEPTH = 2;
054
055    private final NameMapper delegate;
056
057    public HashingNameMapper(final NameMapper delegate) {
058        this.delegate = requireNonNull(delegate);
059    }
060
061    @Override
062    public boolean isFileSystemFriendly() {
063        return true; // hashes delegated strings, so whatever it wrapped, it does not come through
064    }
065
066    @Override
067    public Collection<NamedLockKey> nameLocks(
068            RepositorySystemSession session,
069            Collection<? extends Artifact> artifacts,
070            Collection<? extends Metadata> metadatas) {
071        final int depth = ConfigUtils.getInteger(session, DEFAULT_DEPTH, CONFIG_PROP_DEPTH);
072        if (depth < 0 || depth > 4) {
073            throw new IllegalArgumentException("allowed depth value is between 0 and 4 (inclusive)");
074        }
075        return delegate.nameLocks(session, artifacts, metadatas).stream()
076                .map(k -> NamedLockKey.of(hashName(k.name(), depth), k.resources()))
077                .collect(Collectors.toList());
078    }
079
080    private String hashName(final String name, final int depth) {
081        String hashedName = StringDigestUtil.sha1(name);
082        if (depth == 0) {
083            return hashedName;
084        }
085        StringBuilder prefix = new StringBuilder();
086        int i = 0;
087        while (i < hashedName.length() && i / 2 < depth) {
088            prefix.append(hashedName, i, i + 2).append("/");
089            i += 2;
090        }
091        return prefix.append(hashedName).toString();
092    }
093}