private static Collection<? extends PackagingSourceItem> createClasspathItems( ArtifactEditorContext editorContext, Artifact artifact, @NotNull Module module) { final List<PackagingSourceItem> items = new ArrayList<PackagingSourceItem>(); final ModuleRootModel rootModel = editorContext.getModulesProvider().getRootModel(module); List<Library> libraries = new ArrayList<Library>(); for (OrderEntry orderEntry : rootModel.getOrderEntries()) { if (orderEntry instanceof LibraryOrderEntry) { final LibraryOrderEntry libraryEntry = (LibraryOrderEntry) orderEntry; final Library library = libraryEntry.getLibrary(); final DependencyScope scope = libraryEntry.getScope(); if (library != null && scope.isForProductionRuntime()) { libraries.add(library); } } } for (Module toAdd : getNotAddedModules(editorContext, artifact, module)) { items.add(new ModuleOutputSourceItem(toAdd)); } for (Library library : getNotAddedLibraries(editorContext, artifact, libraries)) { items.add(new LibrarySourceItem(library)); } return items; }
public void unConfigureModule(@NotNull ModifiableRootModel model) { for (OrderEntry orderEntry : model.getOrderEntries()) { if (orderEntry instanceof LibraryOrderEntry) { LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry) orderEntry; Library library = libraryOrderEntry.getLibrary(); if (library != null) { String libraryName = library.getName(); if (libraryName != null && libraryName.equals(this.libraryName)) { // Dispose attached roots Library.ModifiableModel modifiableModel = library.getModifiableModel(); for (String rootUrl : library.getRootProvider().getUrls(OrderRootType.CLASSES)) { modifiableModel.removeRoot(rootUrl, OrderRootType.CLASSES); } modifiableModel.commit(); model.getModuleLibraryTable().removeLibrary(library); break; } } } } }
private void attachLibraries( @NotNull Collection<VirtualFile> libraryRoots, Set<VirtualFile> exclusions) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!libraryRoots.isEmpty()) { ApplicationManager.getApplication() .runWriteAction( () -> { ModuleRootManager model = ModuleRootManager.getInstance(myModule); LibraryOrderEntry goLibraryEntry = OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName()); if (goLibraryEntry != null && goLibraryEntry.isValid()) { Library library = goLibraryEntry.getLibrary(); if (library != null && !((LibraryEx) library).isDisposed()) { fillLibrary(library, libraryRoots, exclusions); } } else { LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(myModule.getProject()); Library library = libraryTable.createLibrary(getLibraryName()); fillLibrary(library, libraryRoots, exclusions); ModuleRootModificationUtil.addDependency(myModule, library); } }); showNotification(myModule.getProject()); } else { removeLibraryIfNeeded(); } }
@Override @NotNull public Collection<AbstractTreeNode> getChildren() { Module module = getValue().getModule(); final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>(); final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries(); for (final OrderEntry orderEntry : orderEntries) { if (orderEntry instanceof LibraryOrderEntry) { final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry) orderEntry; final Library library = libraryOrderEntry.getLibrary(); if (library == null) { continue; } final String libraryName = library.getName(); if (libraryName == null || libraryName.length() == 0) { addLibraryChildren(libraryOrderEntry, children, getProject(), this); } else { children.add( new NamedLibraryElementNode( getProject(), new NamedLibraryElement(module, libraryOrderEntry), getSettings())); } } else if (orderEntry instanceof SdkOrderEntry) { final SdkOrderEntry sdkOrderEntry = (SdkOrderEntry) orderEntry; final Sdk jdk = sdkOrderEntry.getSdk(); if (jdk != null) { children.add( new NamedLibraryElementNode( getProject(), new NamedLibraryElement(module, sdkOrderEntry), getSettings())); } } } return children; }
@Override @Nullable protected ClasspathTableItem<?> createTableItem(final Library item) { // clear invalid order entry corresponding to added library if any final ModifiableRootModel rootModel = myClasspathPanel.getRootModel(); final OrderEntry[] orderEntries = rootModel.getOrderEntries(); for (OrderEntry orderEntry : orderEntries) { if (orderEntry instanceof LibraryOrderEntry) { final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry) orderEntry; if (item.equals(libraryOrderEntry.getLibrary())) { return ClasspathTableItem.createItem(libraryOrderEntry, myContext); } String name = item.getName(); if (name != null && name.equals(libraryOrderEntry.getLibraryName())) { if (orderEntry.isValid()) { Messages.showErrorDialog( ProjectBundle.message("classpath.message.library.already.added", item.getName()), ProjectBundle.message("classpath.title.adding.dependency")); return null; } else { rootModel.removeOrderEntry(orderEntry); } } } } final LibraryOrderEntry orderEntry = rootModel.addLibraryEntry(item); DependencyScope defaultScope = getDefaultScope(item); if (defaultScope != null) { orderEntry.setScope(defaultScope); } return ClasspathTableItem.createItem(orderEntry, myContext); }
public void addLibraryDependency( MavenArtifact artifact, DependencyScope scope, MavenModifiableModelsProvider provider, MavenProject project) { String libraryName = artifact.getLibraryName(); Library library = provider.getLibraryByName(libraryName); if (library == null) { library = provider.createLibrary(libraryName); } Library.ModifiableModel libraryModel = provider.getLibraryModel(library); updateUrl(libraryModel, OrderRootType.CLASSES, artifact, null, null, true); if (!MavenConstants.SCOPE_SYSTEM.equals(artifact.getScope())) { updateUrl( libraryModel, OrderRootType.SOURCES, artifact, MavenExtraArtifactType.SOURCES, project, false); updateUrl( libraryModel, JavadocOrderRootType.getInstance(), artifact, MavenExtraArtifactType.DOCS, project, false); } LibraryOrderEntry e = myRootModel.addLibraryEntry(library); e.setScope(scope); }
private void removeLibraryIfNeeded() { ApplicationManager.getApplication().assertIsDispatchThread(); ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance(); ModifiableRootModel model = modelsProvider.getModuleModifiableModel(myModule); LibraryOrderEntry goLibraryEntry = OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName()); if (goLibraryEntry != null) { ApplicationManager.getApplication() .runWriteAction( () -> { Library library = goLibraryEntry.getLibrary(); if (library != null) { LibraryTable table = library.getTable(); if (table != null) { table.removeLibrary(library); model.removeOrderEntry(goLibraryEntry); modelsProvider.commitModuleModifiableModel(model); } } else { modelsProvider.disposeModuleModifiableModel(model); } }); } else { ApplicationManager.getApplication() .runWriteAction(() -> modelsProvider.disposeModuleModifiableModel(model)); } }
private static void assertModuleLibDepPath( LibraryOrderEntry lib, OrderRootType type, List<String> paths) { if (paths == null) return; assertUnorderedPathsAreEqual(Arrays.asList(lib.getRootUrls(type)), paths); // also check the library because it may contain slight different set of urls (e.g. with // duplicates) assertUnorderedPathsAreEqual(Arrays.asList(lib.getLibrary().getUrls(type)), paths); }
private void syncExistingAndRemoveObsolete( @NotNull IdeModifiableModelsProvider modelsProvider, @NotNull Map<Set<String>, LibraryDependencyData> moduleLibrariesToImport, @NotNull Map<String, LibraryDependencyData> projectLibrariesToImport, @NotNull Set<LibraryDependencyData> toImport, @NotNull Map<OrderEntry, OrderAware> orderEntryDataMap, @NotNull ModifiableRootModel moduleRootModel, boolean hasUnresolvedLibraries) { for (OrderEntry entry : moduleRootModel.getOrderEntries()) { if (entry instanceof ModuleLibraryOrderEntryImpl) { ModuleLibraryOrderEntryImpl moduleLibraryOrderEntry = (ModuleLibraryOrderEntryImpl) entry; Library library = moduleLibraryOrderEntry.getLibrary(); if (library == null) { LOG.warn( "Skipping module-level library entry because it doesn't have backing Library object. Entry: " + entry); continue; } final VirtualFile[] libraryFiles = library.getFiles(OrderRootType.CLASSES); final Set<String> moduleLibraryKey = ContainerUtilRt.newHashSet(libraryFiles.length); for (VirtualFile file : libraryFiles) { moduleLibraryKey.add( ExternalSystemApiUtil.getLocalFileSystemPath(file) + moduleLibraryOrderEntry.getScope().name()); } LibraryDependencyData existing = moduleLibrariesToImport.remove(moduleLibraryKey); if (existing == null || !StringUtil.equals(existing.getInternalName(), library.getName())) { moduleRootModel.removeOrderEntry(entry); } else { orderEntryDataMap.put(entry, existing); syncExistingLibraryDependency( modelsProvider, existing, library, moduleRootModel, moduleLibraryOrderEntry.getOwnerModule()); toImport.remove(existing); } } else if (entry instanceof LibraryOrderEntry) { LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry) entry; String libraryName = libraryOrderEntry.getLibraryName(); LibraryDependencyData existing = projectLibrariesToImport.remove(libraryName + libraryOrderEntry.getScope().name()); if (existing != null) { toImport.remove(existing); orderEntryDataMap.put(entry, existing); } else if (!hasUnresolvedLibraries) { // There is a possible case that a project has been successfully imported from external // model and after // that network/repo goes down. We don't want to drop existing binary mappings then. moduleRootModel.removeOrderEntry(entry); } } } }
private void addAttachArtifactDependency( @NotNull Element buildHelperCfg, @NotNull DependencyScope scope, @NotNull MavenProject mavenProject, @NotNull MavenArtifact artifact) { Library.ModifiableModel libraryModel = null; for (Element artifactsElement : (List<Element>) buildHelperCfg.getChildren("artifacts")) { for (Element artifactElement : (List<Element>) artifactsElement.getChildren("artifact")) { String typeString = artifactElement.getChildTextTrim("type"); if (typeString != null && !typeString.equals("jar")) continue; OrderRootType rootType = OrderRootType.CLASSES; String classifier = artifactElement.getChildTextTrim("classifier"); if ("sources".equals(classifier)) { rootType = OrderRootType.SOURCES; } else if ("javadoc".equals(classifier)) { rootType = JavadocOrderRootType.getInstance(); } String filePath = artifactElement.getChildTextTrim("file"); if (StringUtil.isEmpty(filePath)) continue; VirtualFile file = VfsUtil.findRelativeFile(filePath, mavenProject.getDirectoryFile()); if (file == null) continue; file = JarFileSystem.getInstance().getJarRootForLocalFile(file); if (file == null) continue; if (libraryModel == null) { String libraryName = artifact.getLibraryName(); assert libraryName.startsWith(MavenArtifact.MAVEN_LIB_PREFIX); libraryName = MavenArtifact.MAVEN_LIB_PREFIX + "ATTACHED-JAR: " + libraryName.substring(MavenArtifact.MAVEN_LIB_PREFIX.length()); Library library = myModifiableModelsProvider.getLibraryByName(libraryName); if (library == null) { library = myModifiableModelsProvider.createLibrary(libraryName); } libraryModel = myModifiableModelsProvider.getLibraryModel(library); LibraryOrderEntry entry = myRootModelAdapter.getRootModel().addLibraryEntry(library); entry.setScope(scope); } libraryModel.addRoot(file, rootType); } } }
private static void setLibraryScope( @NotNull LibraryOrderEntry orderEntry, @NotNull Library lib, @NotNull Module module, @NotNull LibraryDependencyData dependencyData) { orderEntry.setExported(dependencyData.isExported()); orderEntry.setScope(dependencyData.getScope()); LOG.debug( String.format( "Configuring library '%s' of module '%s' to be%s exported and have scope %s", lib, module.getName(), dependencyData.isExported() ? " not" : "", dependencyData.getScope())); }
private void importMissing( @NotNull Set<LibraryDependencyData> toImport, @NotNull ModifiableRootModel moduleRootModel, @NotNull LibraryTable moduleLibraryTable, @NotNull LibraryTable libraryTable, @NotNull Module module) { for (LibraryDependencyData dependencyData : toImport) { LibraryData libraryData = dependencyData.getTarget(); if (libraryData.isUnresolved()) { continue; } switch (dependencyData.getLevel()) { case MODULE: @SuppressWarnings("ConstantConditions") Library moduleLib = moduleLibraryTable.createLibrary(dependencyData.getName()); Library.ModifiableModel libModel = moduleLib.getModifiableModel(); try { Map<OrderRootType, Collection<File>> files = myLibraryManager.prepareLibraryFiles(libraryData); myLibraryManager.registerPaths(files, libModel, dependencyData.getName()); } finally { libModel.commit(); } break; case PROJECT: final Library projectLib = libraryTable.getLibraryByName(dependencyData.getName()); if (projectLib == null) { assert false; continue; } LibraryOrderEntry orderEntry = moduleRootModel.addLibraryEntry(projectLib); LOG.info( String.format( "Adding library dependency '%s' to module '%s'", projectLib.getName(), module.getName())); orderEntry.setExported(dependencyData.isExported()); orderEntry.setScope(dependencyData.getScope()); LOG.info( String.format( "Configuring library dependency '%s' of module '%s' to be%s exported and have scope %s", projectLib.getName(), module.getName(), dependencyData.isExported() ? " not" : "", dependencyData.getScope())); } } }
private static void setLibraryEntryExported( ModifiableRootModel rootModel, boolean exported, Library library) { for (OrderEntry orderEntry : rootModel.getOrderEntries()) { if (orderEntry instanceof LibraryOrderEntry && ((LibraryOrderEntry) orderEntry).isModuleLevel() && Comparing.equal(((LibraryOrderEntry) orderEntry).getLibrary(), library)) { ((LibraryOrderEntry) orderEntry).setExported(exported); break; } } }
@Nullable private static LibraryOrderEntry findLibraryOrderEntry( @NotNull ModifiableRootModel moduleRootModel, @NotNull Library library, @NotNull DependencyScope scope) { LibraryOrderEntry candidate = null; for (OrderEntry orderEntry : moduleRootModel.getOrderEntries()) { if (orderEntry instanceof LibraryOrderEntry) { final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry) orderEntry; if (library == libraryOrderEntry.getLibrary()) { return libraryOrderEntry; } if (library.equals(libraryOrderEntry.getLibrary())) { if (libraryOrderEntry.getScope() == scope) { return libraryOrderEntry; } else { candidate = libraryOrderEntry; } } } } return candidate; }
@NotNull static VirtualFile[] getLibraryRoots(@NotNull LibraryOrderEntry orderEntry) { Library library = orderEntry.getLibrary(); if (library == null) return VirtualFile.EMPTY_ARRAY; OrderRootType[] rootTypes = LibraryType.DEFAULT_EXTERNAL_ROOT_TYPES; if (library instanceof LibraryEx) { if (((LibraryEx) library).isDisposed()) return VirtualFile.EMPTY_ARRAY; PersistentLibraryKind<?> libKind = ((LibraryEx) library).getKind(); if (libKind != null) { rootTypes = LibraryType.findByKind(libKind).getExternalRootTypes(); } } final ArrayList<VirtualFile> files = new ArrayList<VirtualFile>(); for (OrderRootType rootType : rootTypes) { files.addAll(Arrays.asList(library.getFiles(rootType))); } return VfsUtilCore.toVirtualFileArray(files); }
protected void assertModuleLibDepScope(String moduleName, String depName, DependencyScope scope) { LibraryOrderEntry dep = getModuleLibDep(moduleName, depName); assertEquals(scope, dep.getScope()); }
public LibraryRuntimeClasspathScope(Project project, LibraryOrderEntry entry) { super(project); myIndex = ProjectRootManager.getInstance(project).getFileIndex(); Collections.addAll(myEntries, entry.getFiles(BinariesOrderRootType.getInstance())); }
private void configSurefirePlugin() { List<String> urls = new ArrayList<String>(); AccessToken accessToken = ReadAction.start(); try { MavenDomProjectModel domModel = null; Element config = myMavenProject.getPluginConfiguration( "org.apache.maven.plugins", "maven-surefire-plugin"); for (String each : MavenJDOMUtil.findChildrenValuesByPath( config, "additionalClasspathElements", "additionalClasspathElement")) { String url = VfsUtil.pathToUrl(each); if (domModel == null) { domModel = MavenDomUtil.getMavenDomProjectModel(myModule.getProject(), myMavenProject.getFile()); } if (domModel != null) { url = MavenPropertyResolver.resolve(url, domModel); } urls.add(url); } } finally { accessToken.finish(); } LibraryTable moduleLibraryTable = myRootModelAdapter.getRootModel().getModuleLibraryTable(); Library library = moduleLibraryTable.getLibraryByName(SUREFIRE_PLUGIN_LIBRARY_NAME); if (library == null) { if (urls.isEmpty()) { return; } library = moduleLibraryTable.createLibrary(SUREFIRE_PLUGIN_LIBRARY_NAME); LibraryOrderEntry orderEntry = myRootModelAdapter.getRootModel().findLibraryOrderEntry(library); orderEntry.setScope(DependencyScope.TEST); } else { if (urls.isEmpty()) { moduleLibraryTable.removeLibrary(library); return; } } String[] oldUrls = library.getUrls(OrderRootType.CLASSES); if (!urls.equals(Arrays.asList(oldUrls))) { Library.ModifiableModel modifiableModel = library.getModifiableModel(); for (String url : oldUrls) { modifiableModel.removeRoot(url, OrderRootType.CLASSES); } for (String url : urls) { modifiableModel.addRoot(url, OrderRootType.CLASSES); } modifiableModel.commit(); } }
@Nullable public static List<LocalQuickFix> registerFixes( @NotNull final QuickFixActionRegistrar registrar, @NotNull final PsiReference reference) { final PsiElement psiElement = reference.getElement(); @NonNls final String shortReferenceName = reference.getRangeInElement().substring(psiElement.getText()); Project project = psiElement.getProject(); PsiFile containingFile = psiElement.getContainingFile(); if (containingFile == null) return null; final VirtualFile classVFile = containingFile.getVirtualFile(); if (classVFile == null) return null; final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final Module currentModule = fileIndex.getModuleForFile(classVFile); if (currentModule == null) return null; final List<LocalQuickFix> providedFixes = findFixes( new Function<MissingDependencyFixProvider, List<LocalQuickFix>>() { @Override public List<LocalQuickFix> fun(MissingDependencyFixProvider provider) { return provider.registerFixes(registrar, reference); } }); if (providedFixes != null) { return providedFixes; } List<LocalQuickFix> result = new ArrayList<LocalQuickFix>(); JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); String fullReferenceText = reference.getCanonicalText(); for (ExternalLibraryResolver resolver : ExternalLibraryResolver.EP_NAME.getExtensions()) { final ExternalClassResolveResult resolveResult = resolver.resolveClass(shortReferenceName, isReferenceToAnnotation(psiElement)); OrderEntryFix fix = null; if (resolveResult != null && psiFacade.findClass( resolveResult.getQualifiedClassName(), currentModule.getModuleWithDependenciesAndLibrariesScope(true)) == null) { fix = new AddExternalLibraryToDependenciesQuickFix( currentModule, resolveResult.getLibrary(), reference, resolveResult.getQualifiedClassName()); } else if (!fullReferenceText.equals(shortReferenceName)) { ExternalLibraryDescriptor descriptor = resolver.resolvePackage(fullReferenceText); if (descriptor != null) { fix = new AddExternalLibraryToDependenciesQuickFix( currentModule, descriptor, reference, null); } } if (fix != null) { registrar.register(fix); result.add(fix); } } if (!result.isEmpty()) { return result; } Set<Object> librariesToAdd = new THashSet<Object>(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(psiElement.getProject()); PsiClass[] classes = PsiShortNamesCache.getInstance(project) .getClassesByName(shortReferenceName, GlobalSearchScope.allScope(project)); List<PsiClass> allowedDependencies = filterAllowedDependencies(psiElement, classes); if (allowedDependencies.isEmpty()) { return result; } classes = allowedDependencies.toArray(new PsiClass[allowedDependencies.size()]); OrderEntryFix moduleDependencyFix = new AddModuleDependencyFix(currentModule, classVFile, classes, reference); final PsiClass[] finalClasses = classes; final OrderEntryFix finalModuleDependencyFix = moduleDependencyFix; final OrderEntryFix providedModuleDependencyFix = provideFix( new Function<MissingDependencyFixProvider, OrderEntryFix>() { @Override public OrderEntryFix fun(MissingDependencyFixProvider provider) { return provider.getAddModuleDependencyFix( reference, finalModuleDependencyFix, currentModule, classVFile, finalClasses); } }); moduleDependencyFix = ObjectUtils.notNull(providedModuleDependencyFix, moduleDependencyFix); registrar.register(moduleDependencyFix); result.add(moduleDependencyFix); for (final PsiClass aClass : classes) { if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue; PsiFile psiFile = aClass.getContainingFile(); if (psiFile == null) continue; VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) continue; ModuleFileIndex moduleFileIndex = ModuleRootManager.getInstance(currentModule).getFileIndex(); for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) { if (orderEntry instanceof LibraryOrderEntry) { final LibraryOrderEntry libraryEntry = (LibraryOrderEntry) orderEntry; final Library library = libraryEntry.getLibrary(); if (library == null) continue; VirtualFile[] files = library.getFiles(OrderRootType.CLASSES); if (files.length == 0) continue; final VirtualFile jar = files[0]; if (jar == null || libraryEntry.isModuleLevel() && !librariesToAdd.add(jar) || !librariesToAdd.add(library)) continue; OrderEntry entryForFile = moduleFileIndex.getOrderEntryForFile(virtualFile); if (entryForFile != null && !(entryForFile instanceof ExportableOrderEntry && ((ExportableOrderEntry) entryForFile).getScope() == DependencyScope.TEST && !ModuleRootManager.getInstance(currentModule) .getFileIndex() .isInTestSourceContent(classVFile))) { continue; } final OrderEntryFix platformFix = new OrderEntryFix() { @Override @NotNull public String getText() { return QuickFixBundle.message( "orderEntry.fix.add.library.to.classpath", libraryEntry.getPresentableName()); } @Override @NotNull public String getFamilyName() { return QuickFixBundle.message("orderEntry.fix.family.add.library.to.classpath"); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { return !project.isDisposed() && !currentModule.isDisposed() && libraryEntry.isValid(); } @Override public void invoke( @NotNull final Project project, @Nullable final Editor editor, PsiFile file) { OrderEntryUtil.addLibraryToRoots(libraryEntry, currentModule); if (editor != null) { DumbService.getInstance(project) .withAlternativeResolveEnabled( new Runnable() { @Override public void run() { new AddImportAction(project, reference, editor, aClass).execute(); } }); } } }; final OrderEntryFix providedFix = provideFix( new Function<MissingDependencyFixProvider, OrderEntryFix>() { @Override public OrderEntryFix fun(MissingDependencyFixProvider provider) { return provider.getAddLibraryToClasspathFix( reference, platformFix, currentModule, libraryEntry, aClass); } }); final OrderEntryFix fix = ObjectUtils.notNull(providedFix, platformFix); registrar.register(fix); result.add(fix); } } } return result; }