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;
020
021import javax.inject.Inject;
022import javax.inject.Named;
023import javax.inject.Singleton;
024
025import java.nio.file.Path;
026import java.util.ArrayList;
027import java.util.Collection;
028import java.util.Collections;
029import java.util.HashMap;
030import java.util.IdentityHashMap;
031import java.util.List;
032import java.util.ListIterator;
033import java.util.Map;
034
035import org.eclipse.aether.RepositoryEvent;
036import org.eclipse.aether.RepositoryEvent.EventType;
037import org.eclipse.aether.RepositorySystemSession;
038import org.eclipse.aether.RequestTrace;
039import org.eclipse.aether.SyncContext;
040import org.eclipse.aether.artifact.Artifact;
041import org.eclipse.aether.impl.Installer;
042import org.eclipse.aether.impl.MetadataGenerator;
043import org.eclipse.aether.impl.MetadataGeneratorFactory;
044import org.eclipse.aether.impl.RepositoryEventDispatcher;
045import org.eclipse.aether.installation.InstallRequest;
046import org.eclipse.aether.installation.InstallResult;
047import org.eclipse.aether.installation.InstallationException;
048import org.eclipse.aether.metadata.MergeableMetadata;
049import org.eclipse.aether.metadata.Metadata;
050import org.eclipse.aether.repository.LocalArtifactRegistration;
051import org.eclipse.aether.repository.LocalMetadataRegistration;
052import org.eclipse.aether.repository.LocalRepositoryManager;
053import org.eclipse.aether.spi.artifact.generator.ArtifactGenerator;
054import org.eclipse.aether.spi.artifact.generator.ArtifactGeneratorFactory;
055import org.eclipse.aether.spi.io.PathProcessor;
056import org.eclipse.aether.spi.synccontext.SyncContextFactory;
057import org.slf4j.Logger;
058import org.slf4j.LoggerFactory;
059
060import static java.util.Objects.requireNonNull;
061
062/**
063 */
064@Singleton
065@Named
066public class DefaultInstaller implements Installer {
067    private final Logger logger = LoggerFactory.getLogger(getClass());
068
069    private final PathProcessor pathProcessor;
070
071    private final RepositoryEventDispatcher repositoryEventDispatcher;
072
073    private final Map<String, ArtifactGeneratorFactory> artifactFactories;
074
075    private final Map<String, MetadataGeneratorFactory> metadataFactories;
076
077    private final SyncContextFactory syncContextFactory;
078
079    @Inject
080    public DefaultInstaller(
081            PathProcessor pathProcessor,
082            RepositoryEventDispatcher repositoryEventDispatcher,
083            Map<String, ArtifactGeneratorFactory> artifactFactories,
084            Map<String, MetadataGeneratorFactory> metadataFactories,
085            SyncContextFactory syncContextFactory) {
086        this.pathProcessor = requireNonNull(pathProcessor, "path processor cannot be null");
087        this.repositoryEventDispatcher =
088                requireNonNull(repositoryEventDispatcher, "repository event dispatcher cannot be null");
089        this.artifactFactories = Collections.unmodifiableMap(artifactFactories);
090        this.metadataFactories = Collections.unmodifiableMap(metadataFactories);
091        this.syncContextFactory = requireNonNull(syncContextFactory, "sync context factory cannot be null");
092    }
093
094    @Override
095    public InstallResult install(RepositorySystemSession session, InstallRequest request) throws InstallationException {
096        requireNonNull(session, "session cannot be null");
097        requireNonNull(request, "request cannot be null");
098        try (SyncContext syncContext = syncContextFactory.newInstance(session, false)) {
099            return install(syncContext, session, request);
100        }
101    }
102
103    private InstallResult install(SyncContext syncContext, RepositorySystemSession session, InstallRequest request)
104            throws InstallationException {
105        InstallResult result = new InstallResult(request);
106
107        RequestTrace trace = RequestTrace.newChild(request.getTrace(), request);
108
109        List<Artifact> artifacts = new ArrayList<>(request.getArtifacts());
110        List<? extends ArtifactGenerator> artifactGenerators =
111                Utils.getArtifactGenerators(session, artifactFactories, request);
112        try {
113            List<Artifact> generatedArtifacts = new ArrayList<>();
114            for (ArtifactGenerator artifactGenerator : artifactGenerators) {
115                Collection<? extends Artifact> generated = artifactGenerator.generate(generatedArtifacts);
116                for (Artifact generatedArtifact : generated) {
117                    Map<String, String> properties = new HashMap<>(generatedArtifact.getProperties());
118                    properties.put(
119                            ArtifactGeneratorFactory.ARTIFACT_GENERATOR_ID,
120                            requireNonNull(artifactGenerator.generatorId(), "generatorId"));
121                    Artifact ga = generatedArtifact.setProperties(properties);
122                    generatedArtifacts.add(ga);
123                }
124            }
125            artifacts.addAll(generatedArtifacts);
126
127            List<? extends MetadataGenerator> metadataGenerators =
128                    Utils.getMetadataGenerators(session, metadataFactories, request);
129
130            IdentityHashMap<Metadata, Object> processedMetadata = new IdentityHashMap<>();
131
132            List<Metadata> metadatas = Utils.prepareMetadata(metadataGenerators, artifacts);
133
134            syncContext.acquire(artifacts, Utils.combine(request.getMetadata(), metadatas));
135
136            for (Metadata metadata : metadatas) {
137                install(session, trace, metadata);
138                processedMetadata.put(metadata, null);
139                result.addMetadata(metadata);
140            }
141
142            for (ListIterator<Artifact> iterator = artifacts.listIterator(); iterator.hasNext(); ) {
143                Artifact artifact = iterator.next();
144
145                for (MetadataGenerator generator : metadataGenerators) {
146                    artifact = generator.transformArtifact(artifact);
147                }
148
149                iterator.set(artifact);
150
151                install(session, trace, artifact);
152                if (artifact.getProperty(ArtifactGeneratorFactory.ARTIFACT_GENERATOR_ID, null) == null) {
153                    result.addArtifact(artifact);
154                }
155            }
156
157            metadatas = Utils.finishMetadata(metadataGenerators, artifacts);
158
159            syncContext.acquire(null, metadatas);
160
161            for (Metadata metadata : metadatas) {
162                install(session, trace, metadata);
163                processedMetadata.put(metadata, null);
164                result.addMetadata(metadata);
165            }
166
167            for (Metadata metadata : request.getMetadata()) {
168                if (!processedMetadata.containsKey(metadata)) {
169                    install(session, trace, metadata);
170                    result.addMetadata(metadata);
171                }
172            }
173
174            return result;
175        } finally {
176            for (ArtifactGenerator artifactGenerator : artifactGenerators) {
177                try {
178                    artifactGenerator.close();
179                } catch (Exception e) {
180                    logger.warn("ArtifactGenerator close failure: {}", artifactGenerator.generatorId(), e);
181                }
182            }
183        }
184    }
185
186    private void install(RepositorySystemSession session, RequestTrace trace, Artifact artifact)
187            throws InstallationException {
188        final LocalRepositoryManager lrm = session.getLocalRepositoryManager();
189        final Path srcPath = artifact.getPath();
190        final Path dstPath = lrm.getRepository().getBasePath().resolve(lrm.getPathForLocalArtifact(artifact));
191
192        artifactInstalling(session, trace, artifact, dstPath);
193
194        Exception exception = null;
195        try {
196            if (dstPath.equals(srcPath)) {
197                throw new IllegalStateException("cannot install " + dstPath + " to same path");
198            }
199
200            pathProcessor.copyWithTimestamp(srcPath, dstPath);
201            lrm.add(session, new LocalArtifactRegistration(artifact));
202        } catch (Exception e) {
203            exception = e;
204            throw new InstallationException("Failed to install artifact " + artifact + ": " + e.getMessage(), e);
205        } finally {
206            artifactInstalled(session, trace, artifact, dstPath, exception);
207        }
208    }
209
210    private void install(RepositorySystemSession session, RequestTrace trace, Metadata metadata)
211            throws InstallationException {
212        LocalRepositoryManager lrm = session.getLocalRepositoryManager();
213
214        Path dstPath = lrm.getRepository().getBasePath().resolve(lrm.getPathForLocalMetadata(metadata));
215
216        metadataInstalling(session, trace, metadata, dstPath);
217
218        Exception exception = null;
219        try {
220            if (metadata instanceof MergeableMetadata) {
221                ((MergeableMetadata) metadata).merge(dstPath, dstPath);
222            } else {
223                if (dstPath.equals(metadata.getPath())) {
224                    throw new IllegalStateException("cannot install " + dstPath + " to same path");
225                }
226                pathProcessor.copy(metadata.getPath(), dstPath);
227            }
228
229            lrm.add(session, new LocalMetadataRegistration(metadata));
230        } catch (Exception e) {
231            exception = e;
232            throw new InstallationException("Failed to install metadata " + metadata + ": " + e.getMessage(), e);
233        } finally {
234            metadataInstalled(session, trace, metadata, dstPath, exception);
235        }
236    }
237
238    private void artifactInstalling(
239            RepositorySystemSession session, RequestTrace trace, Artifact artifact, Path dstPath) {
240        RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_INSTALLING);
241        event.setTrace(trace);
242        event.setArtifact(artifact);
243        event.setRepository(session.getLocalRepositoryManager().getRepository());
244        event.setPath(dstPath);
245
246        repositoryEventDispatcher.dispatch(event.build());
247    }
248
249    private void artifactInstalled(
250            RepositorySystemSession session, RequestTrace trace, Artifact artifact, Path dstPath, Exception exception) {
251        RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_INSTALLED);
252        event.setTrace(trace);
253        event.setArtifact(artifact);
254        event.setRepository(session.getLocalRepositoryManager().getRepository());
255        event.setPath(dstPath);
256        event.setException(exception);
257
258        repositoryEventDispatcher.dispatch(event.build());
259    }
260
261    private void metadataInstalling(
262            RepositorySystemSession session, RequestTrace trace, Metadata metadata, Path dstPath) {
263        RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INSTALLING);
264        event.setTrace(trace);
265        event.setMetadata(metadata);
266        event.setRepository(session.getLocalRepositoryManager().getRepository());
267        event.setPath(dstPath);
268
269        repositoryEventDispatcher.dispatch(event.build());
270    }
271
272    private void metadataInstalled(
273            RepositorySystemSession session, RequestTrace trace, Metadata metadata, Path dstPath, Exception exception) {
274        RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INSTALLED);
275        event.setTrace(trace);
276        event.setMetadata(metadata);
277        event.setRepository(session.getLocalRepositoryManager().getRepository());
278        event.setPath(dstPath);
279        event.setException(exception);
280
281        repositoryEventDispatcher.dispatch(event.build());
282    }
283}