Search in sources :

Example 36 with Library

use of com.intellij.openapi.roots.libraries.Library in project intellij-community by JetBrains.

the class InternetAttachSourceProvider method getActions.

@NotNull
@Override
public Collection<AttachSourcesAction> getActions(List<LibraryOrderEntry> orderEntries, @Nullable PsiFile psiFile) {
    final VirtualFile jar = getJarByPsiFile(psiFile);
    if (jar == null)
        return Collections.emptyList();
    final String jarName = jar.getNameWithoutExtension();
    int index = jarName.lastIndexOf('-');
    if (index == -1)
        return Collections.emptyList();
    final String version = jarName.substring(index + 1);
    final String artifactId = jarName.substring(0, index);
    if (!ARTIFACT_IDENTIFIER.matcher(version).matches() || !ARTIFACT_IDENTIFIER.matcher(artifactId).matches()) {
        return Collections.emptyList();
    }
    final Set<Library> libraries = new HashSet<>();
    for (LibraryOrderEntry orderEntry : orderEntries) {
        ContainerUtil.addIfNotNull(libraries, orderEntry.getLibrary());
    }
    if (libraries.isEmpty())
        return Collections.emptyList();
    final String sourceFileName = jarName + "-sources.jar";
    for (Library library : libraries) {
        for (VirtualFile file : library.getFiles(OrderRootType.SOURCES)) {
            if (file.getPath().contains(sourceFileName)) {
                if (isRootInExistingFile(file)) {
                    // Sources already attached, but source-jar doesn't contain current class.
                    return Collections.emptyList();
                }
            }
        }
    }
    final File libSourceDir = getLibrarySourceDir();
    final File sourceFile = new File(libSourceDir, sourceFileName);
    if (sourceFile.exists()) {
        return Collections.singleton(new LightAttachSourcesAction() {

            @Override
            public String getName() {
                return "Attach downloaded source";
            }

            @Override
            public String getBusyText() {
                return getName();
            }

            @Override
            public ActionCallback perform(List<LibraryOrderEntry> orderEntriesContainingFile) {
                attachSourceJar(sourceFile, libraries);
                return ActionCallback.DONE;
            }
        });
    }
    return Collections.singleton(new LightAttachSourcesAction() {

        @Override
        public String getName() {
            return "Download...";
        }

        @Override
        public String getBusyText() {
            return "Searching...";
        }

        @Override
        public ActionCallback perform(List<LibraryOrderEntry> orderEntriesContainingFile) {
            final Task task = new Task.Modal(psiFile.getProject(), "Searching source...", true) {

                @Override
                public void run(@NotNull final ProgressIndicator indicator) {
                    String artifactUrl = null;
                    SourceSearcher[] searchers = { new MavenCentralSourceSearcher(), new SonatypeSourceSearcher() };
                    for (SourceSearcher searcher : searchers) {
                        try {
                            artifactUrl = searcher.findSourceJar(indicator, artifactId, version, jar);
                        } catch (SourceSearchException e) {
                            LOG.warn(e);
                            showMessage("Downloading failed", e.getMessage(), NotificationType.ERROR);
                            continue;
                        }
                        if (artifactUrl != null)
                            break;
                    }
                    if (artifactUrl == null) {
                        showMessage("Sources not found", "Sources for '" + jarName + ".jar' not found", NotificationType.WARNING);
                        return;
                    }
                    if (!(libSourceDir.isDirectory() || libSourceDir.mkdirs())) {
                        showMessage("Downloading failed", "Failed to create directory to store sources: " + libSourceDir, NotificationType.ERROR);
                        return;
                    }
                    try {
                        File tmpDownload = FileUtil.createTempFile(libSourceDir, "download.", ".tmp", false, false);
                        HttpRequests.request(artifactUrl).saveToFile(tmpDownload, indicator);
                        if (!sourceFile.exists() && !tmpDownload.renameTo(sourceFile)) {
                            LOG.warn("Failed to rename file " + tmpDownload + " to " + sourceFileName);
                        }
                    } catch (IOException e) {
                        LOG.warn(e);
                        showMessage("Downloading failed", "Connection problem. See log for more details.", NotificationType.ERROR);
                    }
                }

                @Override
                public void onSuccess() {
                    attachSourceJar(sourceFile, libraries);
                }

                private void showMessage(String title, String message, NotificationType notificationType) {
                    new Notification("Source searcher", title, message, notificationType).notify(getProject());
                }
            };
            task.queue();
            return ActionCallback.DONE;
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Task(com.intellij.openapi.progress.Task) ActionCallback(com.intellij.openapi.util.ActionCallback) LibraryOrderEntry(com.intellij.openapi.roots.LibraryOrderEntry) IOException(java.io.IOException) Notification(com.intellij.notification.Notification) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) NotificationType(com.intellij.notification.NotificationType) Library(com.intellij.openapi.roots.libraries.Library) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) NotNull(org.jetbrains.annotations.NotNull)

Example 37 with Library

use of com.intellij.openapi.roots.libraries.Library in project intellij-community by JetBrains.

the class InternetAttachSourceProvider method doAttachSourceJars.

private static void doAttachSourceJars(@NotNull Collection<Library> libraries, VirtualFile[] roots) {
    WriteAction.run(() -> {
        for (Library library : libraries) {
            Library.ModifiableModel model = library.getModifiableModel();
            Set<VirtualFile> alreadyExistingFiles = ContainerUtil.newHashSet(model.getFiles(OrderRootType.SOURCES));
            for (VirtualFile root : roots) {
                if (!alreadyExistingFiles.contains(root)) {
                    model.addRoot(root, OrderRootType.SOURCES);
                }
            }
            model.commit();
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Library(com.intellij.openapi.roots.libraries.Library)

Example 38 with Library

use of com.intellij.openapi.roots.libraries.Library in project intellij-community by JetBrains.

the class IvyAttachSourceProvider method getActions.

@NotNull
@Override
public Collection<AttachSourcesAction> getActions(List<LibraryOrderEntry> orderEntries, PsiFile psiFile) {
    VirtualFile jar = getJarByPsiFile(psiFile);
    if (jar == null)
        return Collections.emptyList();
    VirtualFile jarsDir = jar.getParent();
    if (jarsDir == null || !jarsDir.getName().equals("jars"))
        return Collections.emptyList();
    VirtualFile artifactDir = jarsDir.getParent();
    if (artifactDir == null)
        return Collections.emptyList();
    String jarNameWithoutExt = jar.getNameWithoutExtension();
    String artifactName = artifactDir.getName();
    if (!jarNameWithoutExt.startsWith(artifactName) || !jarNameWithoutExt.substring(artifactName.length()).startsWith("-")) {
        return Collections.emptyList();
    }
    String version = jarNameWithoutExt.substring(artifactName.length() + 1);
    //noinspection SpellCheckingInspection
    VirtualFile propertiesFile = artifactDir.findChild("ivydata-" + version + ".properties");
    if (propertiesFile == null)
        return Collections.emptyList();
    Library library = getLibraryFromOrderEntriesList(orderEntries);
    if (library == null)
        return Collections.emptyList();
    String sourceFileName = artifactName + '-' + version + "-sources.jar";
    VirtualFile sources = artifactDir.findChild("sources");
    if (sources != null) {
        VirtualFile srcFile = sources.findChild(sourceFileName);
        if (srcFile != null) {
            // File already downloaded.
            VirtualFile jarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(srcFile);
            if (jarRoot == null || ArrayUtil.contains(jarRoot, (Object[]) library.getFiles(OrderRootType.SOURCES))) {
                // Sources already attached.
                return Collections.emptyList();
            }
            return Collections.singleton(new AttachExistingSourceAction(jarRoot, library, "Attache sources from Ivy repository"));
        }
    }
    String url = extractUrl(propertiesFile, artifactName);
    if (StringUtil.isEmptyOrSpaces(url))
        return Collections.emptyList();
    return Collections.singleton(new DownloadSourcesAction(psiFile.getProject(), "Downloading Ivy Sources", url) {

        @Override
        protected void storeFile(byte[] content) {
            try {
                VirtualFile existingSourcesFolder = sources;
                if (existingSourcesFolder == null) {
                    existingSourcesFolder = artifactDir.createChildDirectory(this, "sources");
                }
                VirtualFile srcFile = existingSourcesFolder.createChildData(this, sourceFileName);
                srcFile.setBinaryContent(content);
                addSourceFile(JarFileSystem.getInstance().getJarRootForLocalFile(srcFile), library);
            } catch (IOException e) {
                String message = "Failed to save " + artifactDir.getPath() + "/sources/" + sourceFileName;
                new Notification(myMessageGroupId, "IO Error", message, NotificationType.ERROR).notify(myProject);
                LOG.warn(e);
            }
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Library(com.intellij.openapi.roots.libraries.Library) IOException(java.io.IOException) Notification(com.intellij.notification.Notification) NotNull(org.jetbrains.annotations.NotNull)

Example 39 with Library

use of com.intellij.openapi.roots.libraries.Library in project intellij-community by JetBrains.

the class OrderEntryAppearanceServiceImpl method forOrderEntry.

@NotNull
@Override
public CellAppearanceEx forOrderEntry(Project project, @NotNull final OrderEntry orderEntry, final boolean selected) {
    if (orderEntry instanceof JdkOrderEntry) {
        JdkOrderEntry jdkLibraryEntry = (JdkOrderEntry) orderEntry;
        Sdk jdk = jdkLibraryEntry.getJdk();
        if (!orderEntry.isValid()) {
            final String oldJdkName = jdkLibraryEntry.getJdkName();
            return FileAppearanceService.getInstance().forInvalidUrl(oldJdkName != null ? oldJdkName : NO_JDK);
        }
        return forJdk(jdk, false, selected, true);
    } else if (!orderEntry.isValid()) {
        return FileAppearanceService.getInstance().forInvalidUrl(orderEntry.getPresentableName());
    } else if (orderEntry instanceof LibraryOrderEntry) {
        LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry) orderEntry;
        if (!libraryOrderEntry.isValid()) {
            //library can be removed
            return FileAppearanceService.getInstance().forInvalidUrl(orderEntry.getPresentableName());
        }
        Library library = libraryOrderEntry.getLibrary();
        assert library != null : libraryOrderEntry;
        return forLibrary(project, library, !((LibraryEx) library).getInvalidRootUrls(OrderRootType.CLASSES).isEmpty());
    } else if (orderEntry.isSynthetic()) {
        String presentableName = orderEntry.getPresentableName();
        Icon icon = orderEntry instanceof ModuleSourceOrderEntry ? sourceFolderIcon(false) : null;
        return new SimpleTextCellAppearance(presentableName, icon, SimpleTextAttributes.SYNTHETIC_ATTRIBUTES);
    } else if (orderEntry instanceof ModuleOrderEntry) {
        final Icon icon = ModuleType.get(((ModuleOrderEntry) orderEntry).getModule()).getIcon();
        return SimpleTextCellAppearance.regular(orderEntry.getPresentableName(), icon);
    } else {
        return CompositeAppearance.single(orderEntry.getPresentableName());
    }
}
Also used : SimpleTextCellAppearance(com.intellij.openapi.roots.ui.util.SimpleTextCellAppearance) Sdk(com.intellij.openapi.projectRoots.Sdk) Library(com.intellij.openapi.roots.libraries.Library) NotNull(org.jetbrains.annotations.NotNull)

Example 40 with Library

use of com.intellij.openapi.roots.libraries.Library in project intellij-community by JetBrains.

the class UsageInArtifact method replaceElement.

@Override
public void replaceElement(final ProjectStructureElement newElement) {
    Library library = ((LibraryProjectStructureElement) newElement).getLibrary();
    PackagingElement<?> newLibraryElement = PackagingElementFactory.getInstance().createLibraryFiles(library.getName(), library.getTable().getTableLevel(), null);
    replaceElement(newLibraryElement);
}
Also used : Library(com.intellij.openapi.roots.libraries.Library) LibraryProjectStructureElement(com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.LibraryProjectStructureElement)

Aggregations

Library (com.intellij.openapi.roots.libraries.Library)266 LibraryTable (com.intellij.openapi.roots.libraries.LibraryTable)69 VirtualFile (com.intellij.openapi.vfs.VirtualFile)65 Module (com.intellij.openapi.module.Module)43 NotNull (org.jetbrains.annotations.NotNull)32 File (java.io.File)31 LibraryOrderEntry (com.intellij.openapi.roots.LibraryOrderEntry)28 LibraryEx (com.intellij.openapi.roots.impl.libraries.LibraryEx)27 Project (com.intellij.openapi.project.Project)25 ProjectLibraryTable (com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable)25 Nullable (org.jetbrains.annotations.Nullable)25 ModifiableRootModel (com.intellij.openapi.roots.ModifiableRootModel)19 ArrayList (java.util.ArrayList)15 Sdk (com.intellij.openapi.projectRoots.Sdk)13 OrderEntry (com.intellij.openapi.roots.OrderEntry)12 THashSet (gnu.trove.THashSet)9 Element (org.jdom.Element)9 OrderRoot (com.intellij.openapi.roots.libraries.ui.OrderRoot)8 Result (com.intellij.openapi.application.Result)7 Logger (com.intellij.openapi.diagnostic.Logger)7