Java Code Examples for com.intellij.openapi.roots.libraries.Library

The following examples show how to use com.intellij.openapi.roots.libraries.Library. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private Library createLibraryFromRoots(ModifiableModuleRootLayer layer, List<OrderRoot> roots, @Nullable final LibraryType libraryType) {
  final LibraryTable.ModifiableModel moduleLibraryModel = layer.getModuleLibraryTable().getModifiableModel();

  final PersistentLibraryKind kind = libraryType == null ? null : libraryType.getKind();
  final Library library = ((LibraryTableBase.ModifiableModelEx)moduleLibraryModel).createLibrary(null, kind);
  final LibraryEx.ModifiableModelEx libModel = (LibraryEx.ModifiableModelEx)library.getModifiableModel();

  for (OrderRoot root : roots) {
    if (root.isJarDirectory()) {
      libModel.addJarDirectory(root.getFile(), false, root.getType());
    }
    else {
      libModel.addRoot(root.getFile(), root.getType());
    }
  }
  libModel.commit();
  return library;
}
 
Example 2
Source Project: consulo   Source File: ArtifactEditorContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void selectLibrary(@Nonnull Library library) {
  final LibraryTable table = library.getTable();
  if (table != null) {
    ProjectStructureConfigurable.getInstance(getProject()).selectProjectOrGlobalLibrary(library, true);
  }
  else {
    final Module module = ((LibraryImpl)library).getModule();
    if (module != null) {
      final ModuleRootModel rootModel = myParent.getModulesProvider().getRootModel(module);
      final String libraryName = library.getName();
      for (OrderEntry entry : rootModel.getOrderEntries()) {
        if (entry instanceof ModuleLibraryOrderEntryImpl) {
          final ModuleLibraryOrderEntryImpl libraryEntry = (ModuleLibraryOrderEntryImpl)entry;
          if (libraryName != null && libraryName.equals(libraryEntry.getLibraryName())
             || libraryName == null && library.equals(libraryEntry.getLibrary())) {
            ProjectStructureConfigurable.getInstance(getProject()).selectOrderEntry(module, libraryEntry);
            return;
          }
        }
      }
    }
  }
}
 
Example 3
protected void updateLibraryContent(@NotNull Set<String> contentUrls) {
  if (!FlutterModuleUtils.declaresFlutter(project)) {
    // If we have a Flutter library, remove it.
    final LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project);
    final Library existingLibrary = getLibraryByName(getLibraryName());
    if (existingLibrary != null) {
      WriteAction.compute(() -> {
        final LibraryTable.ModifiableModel libraryTableModel = libraryTable.getModifiableModel();
        libraryTableModel.removeLibrary(existingLibrary);
        libraryTableModel.commit();
        return null;
      });
    }
    return;
  }
  updateLibraryContent(getLibraryName(), contentUrls, null);
}
 
Example 4
Source Project: camel-idea-plugin   Source File: IdeaUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a URLClassLoader for a given library or libraries
 *
 * @param libraries the library or libraries
 * @return the classloader
 */
public @Nullable URLClassLoader newURLClassLoaderForLibrary(Library... libraries) throws MalformedURLException {
    List<URL> urls = new ArrayList<>();
    for (Library library : libraries) {
        if (library != null) {
            VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);
            if (files.length == 1) {
                VirtualFile vf = files[0];
                if (vf.getName().toLowerCase().endsWith(".jar")) {
                    String path = vf.getPath();
                    if (path.endsWith("!/")) {
                        path = path.substring(0, path.length() - 2);
                    }
                    URL url = new URL("file:" + path);
                    urls.add(url);
                }
            }
        }
    }
    if (urls.isEmpty()) {
        return null;
    }

    URL[] array = urls.toArray(new URL[urls.size()]);
    return new URLClassLoader(array);
}
 
Example 5
Source Project: consulo   Source File: BaseLibrariesConfigurable.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(final AnActionEvent e) {
  final Object o = getSelectedObject();
  if (o instanceof LibraryEx) {
    final LibraryEx selected = (LibraryEx)o;
    final String newName = Messages.showInputDialog("Enter library name:", "Copy Library", null, selected.getName() + "2", new NonEmptyInputValidator());
    if (newName == null) return;

    BaseLibrariesConfigurable configurable = BaseLibrariesConfigurable.this;
    final LibraryEx library = (LibraryEx)myContext.getLibrary(selected.getName(), myLevel);
    LOG.assertTrue(library != null);

    final LibrariesModifiableModel libsModel = configurable.getModelProvider().getModifiableModel();
    final Library lib = libsModel.createLibrary(newName, library.getKind());
    final LibraryEx.ModifiableModelEx model = (LibraryEx.ModifiableModelEx)libsModel.getLibraryEditor(lib).getModel();
    LibraryEditingUtil.copyLibrary(library, Collections.<String, String>emptyMap(), model);
  }
}
 
Example 6
Source Project: consulo   Source File: ModuleStructureConfigurable.java    License: Apache License 2.0 6 votes vote down vote up
public void addLibraryOrderEntry(final Module module, final Library library) {
  Component parent = TargetAWT.to(WindowManager.getInstance().suggestParentWindow(module.getProject()));

  final ModuleEditor moduleEditor = myContext.myModulesConfigurator.getModuleEditor(module);
  LOG.assertTrue(moduleEditor != null, "Current module editor was not initialized");
  final ModifiableRootModel modelProxy = moduleEditor.getModifiableRootModelProxy();
  final OrderEntry[] entries = modelProxy.getOrderEntries();
  for (OrderEntry entry : entries) {
    if (entry instanceof LibraryOrderEntry && Comparing.strEqual(entry.getPresentableName(), library.getName())) {
      if (Messages.showYesNoDialog(parent,
                                   ProjectBundle.message("project.roots.replace.library.entry.message", entry.getPresentableName()),
                                   ProjectBundle.message("project.roots.replace.library.entry.title"),
                                   Messages.getInformationIcon()) == Messages.YES) {
        modelProxy.removeOrderEntry(entry);
        break;
      }
    }
  }
  modelProxy.addLibraryEntry(library);
  myContext.getDaemonAnalyzer().queueUpdate(new ModuleProjectStructureElement(myContext, module));
  myTree.repaint();
}
 
Example 7
Source Project: intellij   Source File: DescribeLibraryAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void actionPerformedInBlazeProject(Project project, AnActionEvent e) {
  BlazeProjectData blazeProjectData =
      BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
  if (blazeProjectData == null) {
    return;
  }
  Library library = LibraryActionHelper.findLibraryForAction(e);
  if (library == null) {
    return;
  }
  BlazeJarLibrary blazeLibrary =
      LibraryActionHelper.findLibraryFromIntellijLibrary(project, blazeProjectData, library);
  if (blazeLibrary == null) {
    Messages.showErrorDialog(
        project, "Could not find this library in the project.", CommonBundle.getErrorTitle());
    return;
  }
  showLibraryDescription(project, blazeLibrary);
}
 
Example 8
Source Project: consulo   Source File: ProjectLibraryTabContext.java    License: Apache License 2.0 6 votes vote down vote up
public ProjectLibraryTabContext(final ClasspathPanel classpathPanel, StructureConfigurableContext context) {
  super(classpathPanel, context);

  StructureLibraryTableModifiableModelProvider projectLibrariesProvider = context.getProjectLibrariesProvider();
  Library[] libraries = projectLibrariesProvider.getModifiableModel().getLibraries();
  final Condition<Library> condition = LibraryEditingUtil.getNotAddedLibrariesCondition(myClasspathPanel.getRootModel());

  myItems = ContainerUtil.filter(libraries, condition);
  ContainerUtil.sort(myItems, new Comparator<Library>() {
    @Override
    public int compare(Library o1, Library o2) {
      return StringUtil.compare(o1.getName(), o2.getName(), false);
    }
  });

  myLibraryList = new JBList(myItems);
  myLibraryList.setCellRenderer(new ColoredListCellRendererWrapper<Library>() {
    @Override
    protected void doCustomize(JList list, Library value, int index, boolean selected, boolean hasFocus) {
      final CellAppearanceEx appearance = OrderEntryAppearanceService.getInstance().forLibrary(classpathPanel.getProject(), value, false);

      appearance.customize(this);
    }
  });
  new ListSpeedSearch(myLibraryList);
}
 
Example 9
Source Project: consulo   Source File: LibraryUsageCollector.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public Set<UsageDescriptor> getProjectUsages(@Nonnull Project project) {
  final Set<LibraryKind> usedKinds = new HashSet<LibraryKind>();
  final Processor<Library> processor = new Processor<Library>() {
    @Override
    public boolean process(Library library) {
      usedKinds.addAll(LibraryPresentationManagerImpl.getLibraryKinds(library, null));
      return true;
    }
  };
  for (Module module : ModuleManager.getInstance(project).getModules()) {
    ModuleRootManager.getInstance(module).orderEntries().librariesOnly().forEachLibrary(processor);
  }

  final HashSet<UsageDescriptor> usageDescriptors = new HashSet<UsageDescriptor>();
  for (LibraryKind kind : usedKinds) {
    usageDescriptors.add(new UsageDescriptor(kind.getKindId(), 1));
  }
  return usageDescriptors;
}
 
Example 10
Source Project: consulo   Source File: ProjectLibraryTabContext.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private static DependencyScope getDefaultScope(Library item) {
  for (LibraryDependencyScopeSuggester suggester : LibraryDependencyScopeSuggester.EP_NAME.getExtensions()) {
    DependencyScope scope = suggester.getDefaultDependencyScope(item);
    if (scope != null) {
      return scope;
    }
  }
  return null;
}
 
Example 11
Source Project: consulo   Source File: ChooseLibrariesDialogBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object getParentElement(Object element) {
  if (element instanceof Application) return null;
  if (element instanceof Project) return ApplicationManager.getApplication();
  if (element instanceof Module) return ((Module)element).getProject();
  if (element instanceof LibraryTable) return myParentsMap.get(element);
  if (element instanceof Library) return myParentsMap.get(element);
  throw new AssertionError();
}
 
Example 12
Source Project: consulo   Source File: LibraryDataService.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("MethodMayBeStatic")
public void registerPaths(@Nonnull final Map<OrderRootType, Collection<File>> libraryFiles, @Nonnull Library.ModifiableModel model, @Nonnull String libraryName) {
  for (Map.Entry<OrderRootType, Collection<File>> entry : libraryFiles.entrySet()) {
    for (File file : entry.getValue()) {
      VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
      if (virtualFile == null) {
        if (ExternalSystemConstants.VERBOSE_PROCESSING && entry.getKey() == BinariesOrderRootType.getInstance()) {
          LOG.warn(String.format("Can't find %s of the library '%s' at path '%s'", entry.getKey(), libraryName, file.getAbsolutePath()));
        }
        String url = VfsUtil.getUrlForLibraryRoot(file);
        model.addRoot(url, entry.getKey());
        continue;
      }
      if (virtualFile.isDirectory()) {
        model.addRoot(virtualFile, entry.getKey());
      }
      else {
        VirtualFile archiveRoot = ArchiveVfsUtil.getArchiveRootForLocalFile(virtualFile);
        if (archiveRoot == null) {
          LOG.warn(String.format("Can't parse contents of the jar file at path '%s' for the library '%s''", file.getAbsolutePath(), libraryName));
          continue;
        }
        model.addRoot(archiveRoot, entry.getKey());
      }
    }
  }
}
 
Example 13
public static boolean isQuarkusExtensionWithDeploymentArtifact(Library library) {
    boolean result = false;
    VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);

    for(int i=0; !result && i < files.length;++i) {
        if (files[i].isDirectory()) {
            result = ToolDelegate.getDeploymentJarId(VfsUtilCore.virtualToIoFile(files[i])) != null;
        }
    }
    return result;
}
 
Example 14
Source Project: intellij-haxe   Source File: HaxelibProjectUpdater.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Find an IDEA library matching a HaxeLibraryReference.
 *
 * @param iter the table iterator.
 * @param ref the library to look for.
 * @return the Library, if found; null, otherwise.
 */
@Nullable
private Library lookupLibrary(@NotNull Iterator<Library> iter, @NotNull HaxeLibraryReference ref) {
  Library found = null;
  while (null == found && iter.hasNext()) {
    Library toTest = iter.next();
    if (ref.matchesIdeaLib(toTest)) {
      found = toTest;
    }
  }
  return found;
}
 
Example 15
private void handleLibraryUpdate(Library library) {
  if (library.getTable() instanceof LibraryTableBase) {
    long modif = ((LibraryTableBase)library.getTable()).getStateModificationCount();
    if (modif > lastModification) {
      sendPropertiesChangeEvent(MicroProfilePropertiesScope.dependencies, QuarkusModuleUtil.getModulesURIs(getProject()));
      lastModification = modif;
    }
  }
}
 
Example 16
Source Project: consulo   Source File: ArtifactsStructureConfigurable.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isResolvedToLibrary(LibraryPackagingElement element, Library library, String name) {
  if (!element.getLibraryName().equals(name)) {
    return false;
  }

  final LibraryTable table = library.getTable();
  if (table != null) {
    return table.getTableLevel().equals(element.getLevel());
  }
  return element.getLevel().equals(LibraryTableImplUtil.MODULE_LEVEL);
}
 
Example 17
Source Project: consulo   Source File: ModuleLibraryTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Library[] getLibraries() {
  final ArrayList<Library> result = new ArrayList<Library>();
  final Iterator<Library> libraryIterator = getLibraryIterator();
  ContainerUtil.addAll(result, libraryIterator);
  return result.toArray(new Library[result.size()]);
}
 
Example 18
@Override
protected void updateModuleLibraryDependencies(@NotNull Library library) {
  for (final Module module : ModuleManager.getInstance(getProject()).getModules()) {
    // The logic is inverted wrt superclass.
    if (!FlutterModuleUtils.declaresFlutter(module)) {
      addFlutterLibraryDependency(module, library);
    }
    else {
      removeFlutterLibraryDependency(module, library);
    }
  }
}
 
Example 19
Source Project: consulo   Source File: ProjectRootManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterLibraryAdded(final Library newLibrary) {
  incModificationCount();
  mergeRootsChangesDuring(new Runnable() {
    @Override
    public void run() {
      for (LibraryTable.Listener listener : myListeners) {
        listener.afterLibraryAdded(newLibrary);
      }
    }
  });
}
 
Example 20
protected void updateModuleLibraryDependencies(@NotNull Library library) {
  for (final Module module : ModuleManager.getInstance(project).getModules()) {
    if (FlutterModuleUtils.declaresFlutter(module)) {
      addFlutterLibraryDependency(module, library);
    }
    else {
      removeFlutterLibraryDependency(module, library);
    }
  }
}
 
Example 21
Source Project: consulo   Source File: StructureConfigurableContext.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public Library getLibraryModel(@Nonnull Library library) {
  final LibraryTable libraryTable = library.getTable();
  if (libraryTable != null) {
    return findLibraryModel(library, myLevel2Providers.get(libraryTable.getTableLevel()));
  }
  return library;
}
 
Example 22
@Nullable
private static Library getDartSdkLibrary(@NotNull Project project) {
  final LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project);
  for (Library lib : libraryTable.getLibraries()) {
    if ("Dart SDK".equals(lib.getName())) {
      return lib;
    }
  }
  return null;
}
 
Example 23
@Nullable
private static FlutterSdk getFlutterFromDartSdkLibrary(Library lib) {
  final String[] urls = lib.getUrls(OrderRootType.CLASSES);
  for (String url : urls) {
    if (url.endsWith(DART_CORE_SUFFIX)) {
      final String flutterUrl = url.substring(0, url.length() - DART_CORE_SUFFIX.length());
      final VirtualFile home = VirtualFileManager.getInstance().findFileByUrl(flutterUrl);
      return home == null ? null : new FlutterSdk(home, FlutterSdkVersion.readFromSdk(home));
    }
  }
  return null;
}
 
Example 24
public static void configureFlutterSdk(@NotNull final Module module, @NotNull final Disposable disposable, final boolean realSdk) {
  final String sdkHome;
  if (realSdk) {
    sdkHome = System.getProperty("flutter.sdk");
    if (sdkHome == null) {
      Assert.fail("To run tests that use the flutter tools you need to add '-Dflutter.sdk=[real SDK home]' to the VM Options field of " +
                  "the corresponding JUnit run configuration (Run | Edit Configurations)");
    }
    if (!FlutterSdkUtil.isFlutterSdkHome(sdkHome)) {
      Assert.fail("Incorrect path to the Flutter SDK (" + sdkHome + ") is set as '-Dflutter.sdk' VM option of " +
                  "the corresponding JUnit run configuration (Run | Edit Configurations)");
    }
    VfsRootAccess.allowRootAccess(disposable, sdkHome);
  }
  else {
    sdkHome = SDK_HOME_PATH;
  }

  ApplicationManager.getApplication().runWriteAction(() -> {
    FlutterSdkUtil.setFlutterSdkPath(module.getProject(), sdkHome);
    DartPlugin.enableDartSdk(module);
  });

  Disposer.register(disposable, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    if (!module.isDisposed()) {
      DartPlugin.disableDartSdk(Collections.singletonList(module));
    }

    final ApplicationLibraryTable libraryTable = ApplicationLibraryTable.getApplicationTable();
    final Library library = libraryTable.getLibraryByName(FlutterSdk.FLUTTER_SDK_GLOBAL_LIB_NAME);
    if (library != null) {
      libraryTable.removeLibrary(library);
    }
  }));
}
 
Example 25
protected void updateModuleLibraryDependencies(@NotNull Library library) {
  for (final Module module : ModuleManager.getInstance(project).getModules()) {
    if (FlutterModuleUtils.declaresFlutter(module)) {
      addFlutterLibraryDependency(module, library);
    }
    else {
      removeFlutterLibraryDependency(module, library);
    }
  }
}
 
Example 26
Source Project: consulo   Source File: LibraryTableBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Library createLibrary(String name, @javax.annotation.Nullable PersistentLibraryKind kind) {
  assertWritable();
  final LibraryImpl library = new LibraryImpl(name, kind, LibraryTableBase.this, null);
  myLibraries.add(library);
  return library;
}
 
Example 27
Source Project: consulo   Source File: LibrariesContainerFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ExistingLibraryEditor getLibraryEditor(@Nonnull Library library) {
  final LibraryTable table = library.getTable();
  if (table == null) return null;

  final LibraryTable.ModifiableModel model = myContext.getModifiableLibraryTable(table);
  if (model instanceof LibrariesModifiableModel) {
    return ((LibrariesModifiableModel)model).getLibraryEditor(library);
  }
  return null;
}
 
Example 28
Source Project: consulo   Source File: CreateNewLibraryAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  Library library =
    createLibrary(myType, myLibrariesConfigurable.getTree(), myProject, myLibrariesConfigurable.getModelProvider().getModifiableModel());
  if (library == null) return;

  final BaseLibrariesConfigurable rootConfigurable = ProjectStructureConfigurable.getInstance(myProject).getConfigurableFor(library);
  final DefaultMutableTreeNode libraryNode =
    MasterDetailsComponent.findNodeByObject((TreeNode)rootConfigurable.getTree().getModel().getRoot(), library);
  rootConfigurable.selectNodeInTree(libraryNode);
  LibraryEditingUtil.showDialogAndAddLibraryToDependencies(library, myProject, true);
}
 
Example 29
/**
 * Returns the Flutter SDK for a project that has a possibly broken "Dart SDK" project library.
 * <p>
 * (This can happen for a newly-cloned Flutter SDK where the Dart SDK is not cached yet.)
 */
@Nullable
public static FlutterSdk getIncomplete(@NotNull final Project project) {
  if (project.isDisposed()) {
    return null;
  }
  final Library lib = getDartSdkLibrary(project);
  if (lib == null) {
    return null;
  }
  return getFlutterFromDartSdkLibrary(lib);
}
 
Example 30
@Override
public void addSupport(@NotNull Module module, @NotNull ModifiableRootModel modifiableRootModel, @Nullable Library library) {
    final FacetManager facetManager = FacetManager.getInstance(module);
    ModifiableFacetModel facetModel = facetManager.createModifiableModel();
    DWSettingsProvider dwSettingsProvider = ModuleServiceManager.getService(module, DWSettingsProvider.class);
    dwSettingsProvider.setPasswordKey(UUID.randomUUID().toString());
    dwSettingsProvider.setHostname(dwFrameworkSupportConfigurablePanel.getHostname());
    dwSettingsProvider.setUsername(dwFrameworkSupportConfigurablePanel.getUsername());
    dwSettingsProvider.setPassword(dwFrameworkSupportConfigurablePanel.getPassword());
    dwSettingsProvider.setVersion(dwFrameworkSupportConfigurablePanel.getVersion());
    dwSettingsProvider.setAutoUploadEnabled(dwFrameworkSupportConfigurablePanel.getAutoUploadEnabled());
    Facet facet = FacetManager.getInstance(modifiableRootModel.getModule()).addFacet(DWFacetType.INSTANCE, "Demandware", null);
    facetModel.addFacet(facet);
    facetModel.commit();
}