Search in sources :

Example 21 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project assembly64fx by freabemania.

the class InstallationService method unpackDynamic.

private void unpackDynamic(File content, LocationAndInstallationStatus location, Artifact entry, ArtifactDelta delta) throws Exception {
    CancelableTask cancelTask = CancelableTask.of();
    LocalStorageUtil.createDir(pathService.getTmpDynFolder());
    unzipService.extractZip(content, pathService.getTmpDynFolder(), entry);
    if (cancelTask.isCancelled()) {
        return;
    }
    File[] files = LocalStorageUtil.getSubdirOrFile(pathService.getTmpDynFolder(), entry.getFolder()).listFiles();
    File base = LocalStorageUtil.getSubdirOrFile(location.getLocation(), entry.getPrefix() + "/" + entry.getFolder());
    Optional<File> releaseLogFile = Arrays.stream(files).filter(item -> item.getName().equals("releaselog.json")).findFirst();
    List<ReleaseInfo> releaseInfoList = null;
    List<ReleaseInfo> matchedReleaseInfoList = new ArrayList<>();
    if (releaseLogFile.isPresent()) {
        releaseInfoList = Support.readList(ReleaseInfo.class, releaseLogFile.get()).stream().collect(Collectors.toList());
        for (ReleaseInfo item : releaseInfoList) {
            String p = item.getPath();
            int start = p.indexOf("/", p.indexOf("/") + 1);
            item.setPath(entry.getPrefix() + "/" + entry.getFolder() + "/" + p.substring(start + 1));
            item.setStrippedPath(entry.getFolder() + "/" + p.substring(start + 1));
        }
    }
    for (File f : files) {
        if (f.isDirectory()) {
            String dirname = f.getName().toUpperCase();
            char firstChar = dirname.charAt(0);
            boolean isDigit = Character.isDigit(firstChar);
            boolean isAlpha = Character.isAlphabetic(firstChar);
            String target = findDestination(firstChar, dirname, base);
            if (target != null) {
                File t = null;
                if (isDigit) {
                    t = new File(base.getAbsolutePath() + "/0-9/" + target + "/" + f.getName());
                } else if (isAlpha) {
                    t = new File(base.getAbsolutePath() + "/" + String.valueOf(firstChar) + "/" + target + "/" + f.getName());
                } else {
                    t = new File(base.getAbsolutePath() + "/___MISC___/" + target + "/" + f.getName());
                }
                FileUtils.forceMkdir(t);
                FileUtils.copyDirectory(f, t);
                if (releaseInfoList != null) {
                    ReleaseInfo matchedReleaseInfo = null;
                    for (ReleaseInfo item : releaseInfoList) {
                        File[] subdirs = f.listFiles(File::isDirectory);
                        for (File dir : subdirs) {
                            if (dir.getPath().contains(item.getStrippedPath())) {
                                matchedReleaseInfo = item;
                                break;
                            }
                        }
                    }
                    if (matchedReleaseInfo != null) {
                        matchedReleaseInfo.setPath(t.getAbsolutePath().substring(base.getAbsolutePath().length() + 1));
                        matchedReleaseInfoList.add(matchedReleaseInfo);
                    }
                }
                ProgressControlWrapper.getInstance().setProgressLabel("Moved " + f.getName() + " to " + t.getAbsolutePath());
                if (cancelTask.isCancelled()) {
                    break;
                }
            } else {
                LOGGER.info("Unable to install " + dirname);
            }
        }
    }
    ProgressControlWrapper.getInstance().increaseProgress();
    if (releaseLogFile.isPresent()) {
        File t = new File(base.getAbsolutePath() + "/releaselog.json");
        LOGGER.info("Flushing rebuildt releaselog.json to " + t.getAbsolutePath());
        Support.flush(matchedReleaseInfoList, t);
    }
}
Also used : ArtifactDelta(se.light.assembly64.model.ArtifactDelta) ReturningTask(se.light.assembly64.model.ReturningTask) Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Support.isRemoteArtifact(se.light.assembly64.Support.isRemoteArtifact) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LatestInstalledItemInfo(se.light.assembly64.model.LatestInstalledItemInfo) Support.getVersionAsInteger(se.light.assembly64.Support.getVersionAsInteger) ArtifactType(se.light.assembly64.model.ArtifactType) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ProgressDBController(se.light.assembly64.fx.ProgressDBController) GuiUtils(se.light.assembly64.util.GuiUtils) Map(java.util.Map) Support(se.light.assembly64.Support) Support.flush(se.light.assembly64.Support.flush) CancelableTask(se.light.assembly64.model.CancelableTask) TrueFileFilter(org.apache.commons.io.filefilter.TrueFileFilter) Support.getObjectMapper(se.light.assembly64.Support.getObjectMapper) ContentEntry(se.light.assembly64.model.ContentEntry) GenericMessageDialogController(se.light.assembly64.fx.GenericMessageDialogController) Analytics(se.light.assembly64.Analytics) Logger(org.slf4j.Logger) ExecutorUtil(se.light.assembly64.util.ExecutorUtil) Set(java.util.Set) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) Artifact(se.light.assembly64.model.Artifact) Collectors(java.util.stream.Collectors) LocalStorageUtil(se.light.assembly64.util.LocalStorageUtil) File(java.io.File) ReleaseInfo(se.light.assembly64.model.ReleaseInfo) Platform(javafx.application.Platform) ProgressControlWrapper(se.light.assembly64.fx.ProgressControlWrapper) List(java.util.List) ChronoUnit(java.time.temporal.ChronoUnit) SearchResultItem(se.light.assembly64.model.SearchResultItem) NullWindowOwner(se.light.assembly64.fx.NullWindowOwner) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) Optional(java.util.Optional) DOWNLOAD_STATUS(se.light.assembly64.service.FTPService.DOWNLOAD_STATUS) ProgressMessageBox(se.light.assembly64.ProgressMessageBox) FILE_ACTION(se.light.assembly64.Support.FILE_ACTION) Support.getTodayDateAsBasicIsoString(se.light.assembly64.Support.getTodayDateAsBasicIsoString) LocationAndInstallationStatus(se.light.assembly64.model.LocationAndInstallationStatus) ArrayList(java.util.ArrayList) ReleaseInfo(se.light.assembly64.model.ReleaseInfo) Support.getTodayDateAsBasicIsoString(se.light.assembly64.Support.getTodayDateAsBasicIsoString) File(java.io.File) CancelableTask(se.light.assembly64.model.CancelableTask)

Example 22 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project assembly64fx by freabemania.

the class Main method refreshTree.

public static void refreshTree() {
    Platform.runLater(new Runnable() {

        @Override
        public void run() {
            try {
                ProgressbarEnhanced progressBar = (ProgressbarEnhanced) GlobalRepoService.getInstance().get("pbar");
                if (progressBar != null) {
                    topContainer.getChildren().remove(progressBar);
                }
                rootItemBase.getChildren().clear();
                for (WorkLocation location : userService.getLocations()) {
                    List<Artifact> artifactsDb = artifactsService.getArtifactsDb();
                    Set<LatestInstalledItemInfo> lastestAdditions = null;
                    if (location.exists()) {
                        lastestAdditions = InstallationService.getInstance().resolveLatestInstalledByLocation(location.toLocationAndInstallation());
                    } else {
                        lastestAdditions = lastestAdditionsNotFound;
                    }
                    ImageView icon = new ImageView();
                    icon.setFitWidth(20);
                    icon.setFitHeight(20);
                    if (location.exists()) {
                        if (userService.isInstallationPrimary(location.getId())) {
                            icon.setImage(ImageResolveService.getInstance().getImage("image-root-primary.png"));
                        } else {
                            icon.setImage(ImageResolveService.getInstance().getImage("image-root.png"));
                        }
                        TreeItem<GuiLocation> rootItem = new TreeItem<GuiLocation>(GuiLocation.builder().id(location.getId()).type(TYPE.INSTALLATION_ROOT).name(Support.removeEndingSlash(location.getPath())).build(), icon);
                        rootItem.setExpanded(localDbService.getBooleanLocalDBSetting(resolveInstallationExpandedKey(location.getId()), false));
                        rootItemBase.getChildren().add(rootItem);
                        TreeItem<GuiLocation> leaf = rootItem;
                        for (Artifact entry : artifactsDb) {
                            String node = entry.getPrefix();
                            if (node != null) {
                                String[] path = node.split("/");
                                String leafKey = "";
                                for (String pathItem : path) {
                                    leafKey += pathItem + "/";
                                    ImageView testIcon = new ImageView();
                                    testIcon.setFitWidth(20);
                                    testIcon.setFitHeight(20);
                                    if (checkIfFolderNeedsUpdate(leafKey, location) && userService.isPremium()) {
                                        testIcon.setImage(ImageResolveService.getInstance().getImage("image-folder-updateneeded.png"));
                                    } else {
                                        testIcon.setImage(ImageResolveService.getInstance().getImage("image-folder.png"));
                                    }
                                    Optional<TreeItem<GuiLocation>> categoryItem = leaf.getChildren().stream().filter(item -> item.getValue().getName() != null && item.getValue().getName().equals(pathItem)).findFirst();
                                    if (!categoryItem.isPresent()) {
                                        TreeItem<GuiLocation> depNode = new TreeItem<GuiLocation>(GuiLocation.builder().id(location.getId()).type(TYPE.LEAF).name(pathItem).leafKey(leafKey).build(), testIcon);
                                        leaf.getChildren().add(depNode);
                                        leaf = depNode;
                                    } else {
                                        leaf = categoryItem.get();
                                    }
                                    leaf.setExpanded(localDbService.getBooleanLocalDBSetting(resolveLeafInInstallationExpandedKey(leaf.getValue()), false));
                                }
                                // we're at thre position in the list now with the correct leaf
                                if (!localDbService.hasLocalDBSetting("exclude_" + location.getId() + "_" + entry.getName())) {
                                    ImageView itemIcon = new ImageView();
                                    itemIcon.setFitWidth(16);
                                    itemIcon.setFitHeight(16);
                                    if (entry.getCurrentInstallingId() != null && entry.getCurrentInstallingId().equals(location.getId())) {
                                        if (entry.isMarkedForUpdate() && !entry.isUpdating()) {
                                            itemIcon.setImage(ImageResolveService.getInstance().getImage("image-waiting.png"));
                                        } else if (entry.isUpdating()) {
                                            itemIcon.setImage(ImageResolveService.getInstance().getImage("image-install2.png"));
                                        }
                                    } else {
                                        if (entry.getHero() && userService.isFreemium()) {
                                            itemIcon.setImage(ImageResolveService.getInstance().getImage("image-notavailable.png"));
                                        } else if (entry.getType() == ArtifactType.LOCAL && !artifactsService.isPrivateDirAvailable()) {
                                            itemIcon.setImage(ImageResolveService.getInstance().getImage("image-notavailable.png"));
                                        } else if (!artifactsService.isInstalled(location.toLocationAndInstallation(), entry)) {
                                            itemIcon.setImage(ImageResolveService.getInstance().getImage("image-notinstalled2bw.png"));
                                        } else if (artifactsService.needsUpdate(location.toLocationAndInstallation(), entry)) {
                                            itemIcon.setImage(ImageResolveService.getInstance().getImage("image-needsupdatebw.png"));
                                        } else {
                                            Optional<LatestInstalledItemInfo> findFirst = lastestAdditions.stream().filter(item -> item.getId().equals(entry.getName())).findFirst();
                                            if (findFirst.isPresent() && userService.isPremium()) {
                                                itemIcon.setImage(ImageResolveService.getInstance().getImage("image-updated-new.png"));
                                            } else {
                                                itemIcon.setImage(ImageResolveService.getInstance().getImage("image-updated2.png"));
                                            }
                                        }
                                    }
                                    TreeItem<GuiLocation> depNode = new TreeItem<GuiLocation>(GuiLocation.builder().id(location.getId()).type(TYPE.INSTALLATION).artifact(entry).build(), itemIcon);
                                    leaf.getChildren().add(depNode);
                                }
                                // reset
                                leaf = rootItem;
                            }
                        }
                    } else {
                        icon.setImage(ImageResolveService.getInstance().getImage("image-root-invalid.png"));
                        TreeItem<GuiLocation> rootItem = new TreeItem<GuiLocation>(GuiLocation.builder().id(location.getId()).type(TYPE.INSTALLATION_ROOT).name(Support.removeEndingSlash(location.getPath())).build(), icon);
                        rootItemBase.getChildren().add(rootItem);
                    }
                }
                if (Scheduler.getInstance() != null && Scheduler.getInstance().isWorking() && ProgressControlWrapper.getInstance().isClosed()) {
                    int height = 25;
                    progressBar = new ProgressbarEnhanced();
                    progressBar.setMinWidth(300);
                    progressBar.setMinHeight(height);
                    progressBar.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent event) -> handleMouseClicked2(event));
                    topContainer.getChildren().add(1, progressBar);
                    GlobalRepoService.getInstance().put("pbar", progressBar);
                    tree.setMinHeight(topContainer.getHeight() - menuBar.getHeight() - height);
                } else {
                    tree.setMinHeight(topContainer.getHeight() - menuBar.getHeight());
                }
            } catch (Exception e) {
                LOGGER.error("Unable to refresh view", e);
                GenericMessageDialogController.withErrorProps("Ooops", "Unable to refresh view").showAndWait();
            }
        }
    });
}
Also used : EventHandler(javafx.event.EventHandler) StageStyle(javafx.stage.StageStyle) RandomAccessFile(java.io.RandomAccessFile) Scheduler(se.light.assembly64.Scheduler) TYPE(se.light.assembly64.model.GuiLocation.TYPE) LoggerFactory(org.slf4j.LoggerFactory) PathService(se.light.assembly64.service.PathService) VBox(javafx.scene.layout.VBox) StringUtils(org.apache.commons.lang3.StringUtils) FileLock(java.nio.channels.FileLock) Application(javafx.application.Application) ArtifactType(se.light.assembly64.model.ArtifactType) LogConfig(se.light.assembly64.LogConfig) ContextMenu(javafx.scene.control.ContextMenu) Type(se.light.assembly64.Support.Type) WindowEvent(javafx.stage.WindowEvent) WorkLocation(se.light.assembly64.model.WorkLocation) Pane(javafx.scene.layout.Pane) Rectangle2D(javafx.geometry.Rectangle2D) MenuItem(javafx.scene.control.MenuItem) ButtonType(se.light.assembly64.fx.GenericMessageDialogController.ButtonType) Set(java.util.Set) Screen(javafx.stage.Screen) Artifact(se.light.assembly64.model.Artifact) LocalStorageUtil(se.light.assembly64.util.LocalStorageUtil) Collectors(java.util.stream.Collectors) TreeView(javafx.scene.control.TreeView) UserService(se.light.assembly64.service.UserService) Platform(javafx.application.Platform) Duration(javafx.util.Duration) List(java.util.List) PlatformInfoService(se.light.assembly64.service.PlatformInfoService) Optional(java.util.Optional) InstallationService(se.light.assembly64.service.InstallationService) Autoupgrade(se.light.assembly64.Autoupgrade) ReturningTask(se.light.assembly64.model.ReturningTask) Scene(javafx.scene.Scene) MouseButton(javafx.scene.input.MouseButton) TreeItem(javafx.scene.control.TreeItem) GuiLocation(se.light.assembly64.model.GuiLocation) MouseEvent(javafx.scene.input.MouseEvent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GlobalRepoService(se.light.assembly64.service.GlobalRepoService) GenericMessageDialogController.heroesOnlyFeatureDialog(se.light.assembly64.fx.GenericMessageDialogController.heroesOnlyFeatureDialog) ArrayList(java.util.ArrayList) LatestInstalledItemInfo(se.light.assembly64.model.LatestInstalledItemInfo) ViceService(se.light.assembly64.service.ViceService) UpgradeOptions(se.light.assembly64.Support.UpgradeOptions) FadeTransition(javafx.animation.FadeTransition) GuiUtils(se.light.assembly64.util.GuiUtils) Support(se.light.assembly64.Support) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Support.resolveInstallationExpandedKey(se.light.assembly64.Support.resolveInstallationExpandedKey) DirectoryChooser(javafx.stage.DirectoryChooser) Color(javafx.scene.paint.Color) Analytics(se.light.assembly64.Analytics) Logger(org.slf4j.Logger) MenuBar(javafx.scene.control.MenuBar) ExecutorUtil(se.light.assembly64.util.ExecutorUtil) FileUtils(org.apache.commons.io.FileUtils) ArtifactsService(se.light.assembly64.service.ArtifactsService) File(java.io.File) Menu(javafx.scene.control.Menu) Consumer(java.util.function.Consumer) FileChooser(javafx.stage.FileChooser) ActionEvent(javafx.event.ActionEvent) SelectionMode(javafx.scene.control.SelectionMode) Stage(javafx.stage.Stage) PlatformInfo(se.light.assembly64.model.PlatformInfo) ImageView(javafx.scene.image.ImageView) LocalDBService(se.light.assembly64.service.LocalDBService) ObservableValue(javafx.beans.value.ObservableValue) ChangeListener(javafx.beans.value.ChangeListener) Support.resolveLeafInInstallationExpandedKey(se.light.assembly64.Support.resolveLeafInInstallationExpandedKey) Image(javafx.scene.image.Image) FileChannel(java.nio.channels.FileChannel) Collections(java.util.Collections) LocationAndInstallationStatus(se.light.assembly64.model.LocationAndInstallationStatus) Set(java.util.Set) MouseEvent(javafx.scene.input.MouseEvent) Optional(java.util.Optional) TreeItem(javafx.scene.control.TreeItem) WorkLocation(se.light.assembly64.model.WorkLocation) GuiLocation(se.light.assembly64.model.GuiLocation) Artifact(se.light.assembly64.model.Artifact) LatestInstalledItemInfo(se.light.assembly64.model.LatestInstalledItemInfo) List(java.util.List) ArrayList(java.util.ArrayList) ImageView(javafx.scene.image.ImageView)

Example 23 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project assembly64fx by freabemania.

the class Scheduler method cancel.

@Override
public void cancel() {
    try {
        workQueue.clear();
        for (Artifact entry : artifactsService.getArtifactsDb()) {
            entry.setMarkedForUpdate(false);
            entry.setUpdating(false);
        }
        Support.refreshTree();
    } catch (Exception e) {
        LOGGER.error("Exception when cancelling", e);
    }
}
Also used : Artifact(se.light.assembly64.model.Artifact)

Example 24 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project archiva by apache.

the class DownloadMergedIndexTest method downloadMergedIndex.

@Test
public void downloadMergedIndex() throws Exception {
    Path tmpIndexDir = Paths.get(System.getProperty("java.io.tmpdir"), "tmpIndex");
    if (Files.exists(tmpIndexDir)) {
        FileUtils.deleteDirectory(tmpIndexDir.toFile());
    }
    String id = Long.toString(System.currentTimeMillis());
    ManagedRepository managedRepository = new ManagedRepository(Locale.getDefault());
    managedRepository.setId(id);
    managedRepository.setName("name of " + id);
    managedRepository.setLocation(System.getProperty("basedir") + "/src/test/repositories/test-repo");
    managedRepository.setIndexDirectory(System.getProperty("java.io.tmpdir") + "/tmpIndex/" + id);
    ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();
    if (managedRepositoriesService.getManagedRepository(id) != null) {
        managedRepositoriesService.deleteManagedRepository(id, false);
    }
    getManagedRepositoriesService().addManagedRepository(managedRepository);
    RepositoriesService repositoriesService = getRepositoriesService();
    repositoriesService.scanRepositoryNow(id, true);
    // wait a bit to ensure index is finished
    int timeout = 20000;
    while (timeout > 0 && repositoriesService.alreadyScanning(id)) {
        Thread.sleep(500);
        timeout -= 500;
    }
    RepositoryGroupService repositoryGroupService = getRepositoryGroupService();
    String repoGroupId = "test-group";
    if (repositoryGroupService.getRepositoryGroup(repoGroupId) != null) {
        repositoryGroupService.deleteRepositoryGroup(repoGroupId);
    }
    RepositoryGroup repositoryGroup = new RepositoryGroup();
    repositoryGroup.setId(repoGroupId);
    repositoryGroup.setRepositories(Arrays.asList(id));
    repositoryGroupService.addRepositoryGroup(repositoryGroup);
    // create a repo with a remote on the one with index
    id = Long.toString(System.currentTimeMillis());
    managedRepository = new ManagedRepository(Locale.getDefault());
    managedRepository.setId(id);
    managedRepository.setName("name of " + id);
    managedRepository.setLocation(System.getProperty("basedir") + "/src/test/repositories/test-repo");
    managedRepository.setIndexDirectory(System.getProperty("java.io.tmpdir") + "/tmpIndex/" + id);
    if (managedRepositoriesService.getManagedRepository(id) != null) {
        managedRepositoriesService.deleteManagedRepository(id, false);
    }
    getManagedRepositoriesService().addManagedRepository(managedRepository);
    RemoteRepository remoteRepository = new RemoteRepository(Locale.getDefault());
    remoteRepository.setId("all-merged");
    remoteRepository.setName("all-merged");
    remoteRepository.setDownloadRemoteIndex(true);
    remoteRepository.setUrl("http://localhost:" + port + "/repository/test-group");
    remoteRepository.setRemoteIndexUrl("http://localhost:" + port + "/repository/test-group/.index");
    remoteRepository.setUserName(RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME);
    remoteRepository.setPassword(FakeCreateAdminService.ADMIN_TEST_PWD);
    if (getRemoteRepositoriesService().getRemoteRepository(remoteRepository.getId()) != null) {
        getRemoteRepositoriesService().deleteRemoteRepository(remoteRepository.getId());
    }
    getRemoteRepositoriesService().addRemoteRepository(remoteRepository);
    ProxyConnectorService proxyConnectorService = getProxyConnectorService();
    ProxyConnector proxyConnector = new ProxyConnector();
    proxyConnector.setProxyId("foo-bar1");
    proxyConnector.setSourceRepoId(id);
    proxyConnector.setTargetRepoId("all-merged");
    proxyConnectorService.addProxyConnector(proxyConnector);
    repositoriesService.scheduleDownloadRemoteIndex("all-merged", true, true);
    // wait a bit
    timeout = 20000;
    while (timeout > 0) {
        Thread.sleep(500);
        timeout -= 500;
    }
    SearchService searchService = getSearchService();
    SearchRequest request = new SearchRequest();
    request.setRepositories(Arrays.asList(id));
    request.setGroupId("org.apache.felix");
    List<Artifact> artifacts = searchService.searchArtifacts(request);
    assertThat(artifacts).isNotNull().isNotEmpty().hasSize(1);
}
Also used : Path(java.nio.file.Path) SearchRequest(org.apache.archiva.rest.api.model.SearchRequest) ManagedRepository(org.apache.archiva.admin.model.beans.ManagedRepository) ProxyConnectorService(org.apache.archiva.rest.api.services.ProxyConnectorService) RemoteRepository(org.apache.archiva.admin.model.beans.RemoteRepository) Artifact(org.apache.archiva.maven2.model.Artifact) ManagedRepositoriesService(org.apache.archiva.rest.api.services.ManagedRepositoriesService) RepositoryGroup(org.apache.archiva.admin.model.beans.RepositoryGroup) RepositoriesService(org.apache.archiva.rest.api.services.RepositoriesService) ManagedRepositoriesService(org.apache.archiva.rest.api.services.ManagedRepositoriesService) SearchService(org.apache.archiva.rest.api.services.SearchService) RepositoryGroupService(org.apache.archiva.rest.api.services.RepositoryGroupService) ProxyConnector(org.apache.archiva.admin.model.beans.ProxyConnector) Test(org.junit.Test)

Example 25 with Artifact

use of org.apache.archiva.maven2.model.Artifact in project archiva by apache.

the class DefaultRepositoriesService method removeProjectVersion.

@Override
public Boolean removeProjectVersion(String repositoryId, String namespace, String projectId, String version) throws ArchivaRestServiceException {
    // if not a generic we can use the standard way to delete artifact
    if (!VersionUtil.isGenericSnapshot(version)) {
        Artifact artifact = new Artifact(namespace, projectId, version);
        artifact.setRepositoryId(repositoryId);
        artifact.setContext(repositoryId);
        return deleteArtifact(artifact);
    }
    if (StringUtils.isEmpty(repositoryId)) {
        throw new ArchivaRestServiceException("repositoryId cannot be null", 400, null);
    }
    if (!isAuthorizedToDeleteArtifacts(repositoryId)) {
        throw new ArchivaRestServiceException("not authorized to delete artifacts", 403, null);
    }
    if (StringUtils.isEmpty(namespace)) {
        throw new ArchivaRestServiceException("groupId cannot be null", 400, null);
    }
    if (StringUtils.isEmpty(projectId)) {
        throw new ArchivaRestServiceException("artifactId cannot be null", 400, null);
    }
    if (StringUtils.isEmpty(version)) {
        throw new ArchivaRestServiceException("version cannot be null", 400, null);
    }
    RepositorySession repositorySession = repositorySessionFactory.createSession();
    try {
        ManagedRepositoryContent repository = getManagedRepositoryContent(repositoryId);
        VersionedReference ref = new VersionedReference();
        ref.setArtifactId(projectId);
        ref.setGroupId(namespace);
        ref.setVersion(version);
        repository.deleteVersion(ref);
        /*
            ProjectReference projectReference = new ProjectReference();
            projectReference.setGroupId( namespace );
            projectReference.setArtifactId( projectId );

            repository.getVersions(  )
            */
        ArtifactReference artifactReference = new ArtifactReference();
        artifactReference.setGroupId(namespace);
        artifactReference.setArtifactId(projectId);
        artifactReference.setVersion(version);
        MetadataRepository metadataRepository = repositorySession.getRepository();
        Set<ArtifactReference> related = repository.getRelatedArtifacts(artifactReference);
        log.debug("related: {}", related);
        for (ArtifactReference artifactRef : related) {
            repository.deleteArtifact(artifactRef);
        }
        Collection<ArtifactMetadata> artifacts = metadataRepository.getArtifacts(repositoryId, namespace, projectId, version);
        for (ArtifactMetadata artifactMetadata : artifacts) {
            metadataRepository.removeArtifact(artifactMetadata, version);
        }
        metadataRepository.removeProjectVersion(repositoryId, namespace, projectId, version);
    } catch (MetadataRepositoryException e) {
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } catch (MetadataResolutionException e) {
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } catch (RepositoryException e) {
        throw new ArchivaRestServiceException("Repository exception: " + e.getMessage(), 500, e);
    } finally {
        repositorySession.save();
        repositorySession.close();
    }
    return Boolean.TRUE;
}
Also used : MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) RepositoryException(org.apache.archiva.repository.RepositoryException) MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) RepositorySession(org.apache.archiva.metadata.repository.RepositorySession) Artifact(org.apache.archiva.maven2.model.Artifact) MetadataResolutionException(org.apache.archiva.metadata.repository.MetadataResolutionException) MetadataRepository(org.apache.archiva.metadata.repository.MetadataRepository) VersionedReference(org.apache.archiva.model.VersionedReference) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) ArtifactReference(org.apache.archiva.model.ArtifactReference) ArtifactMetadata(org.apache.archiva.metadata.model.ArtifactMetadata)

Aggregations

Artifact (org.apache.archiva.maven2.model.Artifact)37 Test (org.junit.Test)29 ArrayList (java.util.ArrayList)14 SearchService (org.apache.archiva.rest.api.services.SearchService)14 BrowseService (org.apache.archiva.rest.api.services.BrowseService)11 Path (java.nio.file.Path)10 SearchRequest (org.apache.archiva.rest.api.model.SearchRequest)9 Artifact (se.light.assembly64.model.Artifact)9 List (java.util.List)8 ManagedRepositoriesService (org.apache.archiva.rest.api.services.ManagedRepositoriesService)8 RepositoriesService (org.apache.archiva.rest.api.services.RepositoriesService)8 File (java.io.File)7 IOException (java.io.IOException)7 Logger (org.slf4j.Logger)7 LoggerFactory (org.slf4j.LoggerFactory)7 HashMap (java.util.HashMap)6 Map (java.util.Map)6 ArchivaRestServiceException (org.apache.archiva.rest.api.services.ArchivaRestServiceException)6 Arrays (java.util.Arrays)5 HashSet (java.util.HashSet)5