com.intellij.util.ObjectUtil Java Examples

The following examples show how to use com.intellij.util.ObjectUtil. 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
Source File: BinaryContent.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings({"EmptyCatchBlock"})
@Nullable
public Document getDocument() {
  if (myDocument == null) {
    if (isBinary()) return null;

    String text = null;
    try {
      Charset charset = ObjectUtil
              .notNull(myCharset, EncodingProjectManager.getInstance(myProject).getDefaultCharset());
      text = CharsetToolkit.bytesToString(myBytes, charset);
    }
    catch (IllegalCharsetNameException e) {
    }

    //  Still NULL? only if not supported or an exception was thrown.
    //  Decode a string using the truly default encoding.
    if (text == null) text = new String(myBytes);
    text = LineTokenizer.correctLineSeparators(text);

    myDocument = EditorFactory.getInstance().createDocument(text);
    myDocument.setReadOnly(true);
  }
  return myDocument;
}
 
Example #2
Source File: ApplicationDefaultStoreCache.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public Element findDefaultStoreElement(@Nonnull Class<?> clazz, @Nonnull String path) {
  Object result = myUrlCache.computeIfAbsent(Pair.create(clazz.getClassLoader(), path), pair -> {
    URL resource = pair.getFirst().getResource(pair.getSecond());

    if(resource != null) {
      try {
        Document document = JDOMUtil.loadDocument(resource);
        Element rootElement = document.getRootElement();
        rootElement.detach();
        return rootElement;
      }
      catch (JDOMException | IOException e) {
        throw new RuntimeException(e);
      }
    }

    return ObjectUtil.NULL;
  });

  return result == ObjectUtil.NULL ? null : (Element)result;
}
 
Example #3
Source File: CS0708.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public HighlightInfoFactory checkImpl(@Nonnull CSharpLanguageVersion languageVersion, @Nonnull CSharpHighlightContext highlightContext, @Nonnull DotNetModifierListOwner element)
{
	PsiElement parent = element.getParent();
	if(parent instanceof DotNetTypeDeclaration && ((DotNetTypeDeclaration) parent).hasModifier(DotNetModifier.STATIC))
	{
		if(CSharpPsiUtilImpl.isTypeLikeElement(element))
		{
			return null;
		}
		if(!element.hasModifier(DotNetModifier.STATIC))
		{
			PsiElement nameIdentifier = ((PsiNameIdentifierOwner) element).getNameIdentifier();
			return newBuilder(ObjectUtil.notNull(nameIdentifier, element), formatElement(element)).addQuickFix(new AddModifierFix
					(DotNetModifier.STATIC, element));
		}
	}
	return null;
}
 
Example #4
Source File: CS1106.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public HighlightInfoFactory checkImpl(@Nonnull CSharpLanguageVersion languageVersion, @Nonnull CSharpHighlightContext highlightContext, @Nonnull CSharpMethodDeclaration element)
{
	DotNetParameter[] parameters = element.getParameters();
	if(parameters.length > 0 && parameters[0].hasModifier(CSharpModifier.THIS))
	{
		PsiElement parent = element.getParent();
		if(parent instanceof CSharpTypeDeclaration)
		{
			DotNetTypeDeclaration type = CSharpCompositeTypeDeclaration.selectCompositeOrSelfType((DotNetTypeDeclaration) parent);

			if(type.getGenericParametersCount() > 0 || !type.hasModifier(DotNetModifier.STATIC))
			{
				return newBuilder(ObjectUtil.notNull(element.getNameIdentifier(), element), formatElement(element));
			}
		}
	}
	return super.checkImpl(languageVersion, highlightContext, element);
}
 
Example #5
Source File: MessageDialogBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Messages.YesNoCancelResult
public int show() {
  String yesText = ObjectUtil.chooseNotNull(myYesText, Messages.YES_BUTTON);
  String noText = ObjectUtil.chooseNotNull(myNoText, Messages.NO_BUTTON);
  String cancelText = ObjectUtil.chooseNotNull(myCancelText, Messages.CANCEL_BUTTON);
  try {
    if (Messages.canShowMacSheetPanel() && !Messages.isApplicationInUnitTestOrHeadless()) {
      return MacMessages.getInstance().showYesNoCancelDialog(myTitle, myMessage, yesText, noText, cancelText, WindowManager.getInstance().suggestParentWindow(myProject), myDoNotAskOption);
    }
  }
  catch (Exception ignored) {}

  int buttonNumber = Messages.showDialog(myProject, myMessage, myTitle, new String[]{yesText, noText, cancelText}, 0, myIcon, myDoNotAskOption);
  return buttonNumber == 0 ? Messages.YES : buttonNumber == 1 ? Messages.NO : Messages.CANCEL;

}
 
Example #6
Source File: ActionGroupStub.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void initGroup(ActionGroup target, ActionManager actionManager) {
  ActionStub.copyTemplatePresentation(getTemplatePresentation(), target.getTemplatePresentation());
  target.setCanUseProjectAsDefault(isCanUseProjectAsDefault());
  target.setModuleExtensionIds(getModuleExtensionIds());

  target.setShortcutSet(getShortcutSet());

  AnAction[] children = getChildren(null, actionManager);
  if (children.length > 0) {
    DefaultActionGroup dTarget = ObjectUtil.tryCast(target, DefaultActionGroup.class);
    if(dTarget == null) {
      throw new PluginException("Action group class must extend DefaultActionGroup for the group to accept children:" + myActionClass, getPluginId());
    }

    for (AnAction action : children) {
      dTarget.addAction(action, Constraints.LAST, actionManager);
    }
  }

  if(myPopupDefinedInXml) {
    target.setPopup(isPopup());
  }
}
 
Example #7
Source File: TreeTable.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void processKeyEvent(KeyEvent e){
  if (!myProcessCursorKeys) {
    super.processKeyEvent(e);
    return;
  }

  int keyCode = e.getKeyCode();
  final int selColumn = columnModel.getSelectionModel().getAnchorSelectionIndex();
  boolean treeHasFocus = selColumn == -1 || selColumn >= 0 && isTreeColumn(selColumn);
  boolean oneRowSelected = getSelectedRowCount() == 1;
  if(treeHasFocus && oneRowSelected && ((keyCode == KeyEvent.VK_LEFT) || (keyCode == KeyEvent.VK_RIGHT))){
    myTree._processKeyEvent(e);
    int rowToSelect = ObjectUtil.notNull(myTree.getSelectionRows())[0];
    getSelectionModel().setSelectionInterval(rowToSelect, rowToSelect);
    TableUtil.scrollSelectionToVisible(this);
  }
  else{
    super.processKeyEvent(e);
  }
}
 
Example #8
Source File: LocalFileSystemImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public Set<WatchRequest> replaceWatchedRoots(@Nonnull Collection<WatchRequest> watchRequests,
                                             @Nullable Collection<String> recursiveRoots,
                                             @Nullable Collection<String> flatRoots) {
  recursiveRoots = ObjectUtil.notNull(recursiveRoots, Collections.emptyList());
  flatRoots = ObjectUtil.notNull(flatRoots, Collections.emptyList());

  Set<WatchRequest> result = new HashSet<>();
  synchronized (myLock) {
    boolean update = doAddRootsToWatch(recursiveRoots, flatRoots, result) |
                     doRemoveWatchedRoots(watchRequests);
    if (update) {
      myNormalizedTree = null;
      setUpFileWatcher();
    }
  }
  return result;
}
 
Example #9
Source File: BaseCSharpModuleExtension.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
@RequiredReadAction
public PsiElement[] getEntryPointElements()
{
	final List<DotNetTypeDeclaration> typeDeclarations = new ArrayList<DotNetTypeDeclaration>();
	Collection<DotNetLikeMethodDeclaration> methods = MethodIndex.getInstance().get("Main", getProject(), GlobalSearchScope.moduleScope(getModule()));
	for(DotNetLikeMethodDeclaration method : methods)
	{
		if(method instanceof CSharpMethodDeclaration && DotNetRunUtil.isEntryPoint((DotNetMethodDeclaration) method))
		{
			Module moduleForPsiElement = ModuleUtilCore.findModuleForPsiElement(method);
			// scope is broken?
			if(!getModule().equals(moduleForPsiElement))
			{
				continue;
			}
			ContainerUtil.addIfNotNull(typeDeclarations, ObjectUtil.tryCast(method.getParent(), DotNetTypeDeclaration.class));
		}
	}
	return ContainerUtil.toArray(typeDeclarations, DotNetTypeDeclaration.ARRAY_FACTORY);
}
 
Example #10
Source File: LoginAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void update(@Nonnull AnActionEvent e) {
  if (!EarlyAccessProgramManager.is(ServiceAuthEarlyAccessProgramDescriptor.class)) {
    e.getPresentation().setEnabledAndVisible(false);
    return;
  }

  ServiceAuthConfiguration configuration = ServiceAuthConfiguration.getInstance();

  Presentation presentation = e.getPresentation();

  String email = configuration.getEmail();
  if (email == null) {
    presentation.setText("Logged as anonymous");
    presentation.setIcon(AllIcons.Actions.LoginAvator);
  }
  else {
    presentation.setText("Logged as '" + email + "'");

    Image userIcon = configuration.getUserIcon();
    presentation.setIcon(ObjectUtil.notNull(userIcon, AllIcons.Actions.LoginAvator));
  }
}
 
Example #11
Source File: CSharpLambdaExpressionImplUtil.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nonnull
@RequiredReadAction
public static DotNetTypeRef resolveTypeForParameter(CSharpLambdaExpressionImpl target, int parameterIndex)
{
	CSharpLambdaResolveResult leftTypeRef = resolveLeftLambdaTypeRef(target);
	if(leftTypeRef == null)
	{
		return DotNetTypeRef.ERROR_TYPE;
	}

	if(leftTypeRef == CSharpUndefinedLambdaResolveResult.INSTANCE)
	{
		return DotNetTypeRef.UNKNOWN_TYPE;
	}
	DotNetTypeRef[] leftTypeParameters = leftTypeRef.getParameterTypeRefs();
	DotNetTypeRef typeRef = ArrayUtil2.safeGet(leftTypeParameters, parameterIndex);
	return ObjectUtil.notNull(typeRef, DotNetTypeRef.ERROR_TYPE);
}
 
Example #12
Source File: ModuleImportProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Will execute module importing. Will show popup for selecting import providers if more that one, and then show import wizard
 *
 * @param project - null mean its new project creation
 * @return
 */
@RequiredUIAccess
public static <C extends ModuleImportContext> AsyncResult<Pair<C, ModuleImportProvider<C>>> showFileChooser(@Nullable Project project, @Nullable FileChooserDescriptor chooserDescriptor) {
  boolean isModuleImport = project != null;

  FileChooserDescriptor descriptor = ObjectUtil.notNull(chooserDescriptor, createAllImportDescriptor(isModuleImport));

  VirtualFile toSelect = null;
  String lastLocation = PropertiesComponent.getInstance().getValue(LAST_IMPORTED_LOCATION);
  if (lastLocation != null) {
    toSelect = LocalFileSystem.getInstance().refreshAndFindFileByPath(lastLocation);
  }

  AsyncResult<Pair<C, ModuleImportProvider<C>>> result = AsyncResult.undefined();

  AsyncResult<VirtualFile> fileChooseAsync = FileChooser.chooseFile(descriptor, project, toSelect);
  fileChooseAsync.doWhenDone((f) -> {
    PropertiesComponent.getInstance().setValue(LAST_IMPORTED_LOCATION, f.getPath());

    showImportChooser(project, f, AsyncResult.undefined());
  });

  fileChooseAsync.doWhenRejected((Runnable)result::setRejected);

  return result;
}
 
Example #13
Source File: WizardSessionTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Test
public void testVisibleStep() {
  List<WizardStep<Object>> steps = new ArrayList<>();
  steps.add(new StepStub<>("first", true));
  steps.add(new StepStub<>("second", true));
  steps.add(new StepStub<>("third", false));
  steps.add(new StepStub<>("fourth", true));

  WizardSession<Object> session = new WizardSession<>(ObjectUtil.NULL, steps);

  assertTrue(session.hasNext());

  assertEquals(session.next().toString(), "first");
  assertEquals(session.next().toString(), "second");
  assertEquals(session.next().toString(), "fourth");


  WizardStep<Object> prev = session.prev();

  assertEquals(prev.toString(), "second");
}
 
Example #14
Source File: UIDecorator.java    From consulo with Apache License 2.0 6 votes vote down vote up
static <ARG, U extends UIDecorator> void apply(BiPredicate<U, ARG> predicate, ARG arg, Class<U> clazz) {
  for (UIDecorator decorator : UIDecorators.getDecorators()) {
    if (!decorator.isAvaliable()) {
      continue;
    }

    U u = ObjectUtil.tryCast(decorator, clazz);
    if (u == null) {
      continue;
    }

    if (predicate.test(u, arg)) {
      break;
    }
  }
}
 
Example #15
Source File: CSharpPreprocessorVisitor.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Override
public void visitElement(PsiElement element)
{
	if(element.getStartOffsetInParent() >= myStopOffset)
	{
		stopWalk(ObjectUtil.NULL);
		return;
	}

	if(element.getNode().getElementType() == CSharpPreprocessorElements.PREPROCESSOR_DIRECTIVE)
	{
		CSharpBuilderWrapper.processState(myState, () -> myVariables, it -> {
			myVariables.clear();
			myVariables.addAll(it);
		}, element.getNode().getChars());
	}

	super.visitElement(element);
}
 
Example #16
Source File: UIDecorator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
static <R, U extends UIDecorator> R get(Function<U, R> supplier, Class<U> clazz) {
  for (UIDecorator decorator : UIDecorators.getDecorators()) {
    if (!decorator.isAvaliable()) {
      continue;
    }

    U u = ObjectUtil.tryCast(decorator, clazz);
    if (u == null) {
      continue;
    }

    R fun = supplier.apply(u);
    if (fun != null) {
      return fun;
    }
  }
  throw new IllegalArgumentException("Null value");
}
 
Example #17
Source File: DesktopToolWindowManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private EditorsSplitters getSplittersToFocus() {
  WindowManagerEx windowManager = (WindowManagerEx)myWindowManager.get();

  Window activeWindow = TargetAWT.to(windowManager.getMostRecentFocusedWindow());

  if (activeWindow instanceof DesktopFloatingDecorator) {
    IdeFocusManager ideFocusManager = IdeFocusManager.findInstanceByComponent(activeWindow);
    IdeFrame lastFocusedFrame = ideFocusManager.getLastFocusedFrame();
    JComponent frameComponent = lastFocusedFrame != null ? lastFocusedFrame.getComponent() : null;
    Window lastFocusedWindow = frameComponent != null ? SwingUtilities.getWindowAncestor(frameComponent) : null;
    activeWindow = ObjectUtil.notNull(lastFocusedWindow, activeWindow);
  }

  FileEditorManagerEx fem = FileEditorManagerEx.getInstanceEx(myProject);
  EditorsSplitters splitters = activeWindow != null ? fem.getSplittersFor(activeWindow) : null;
  return splitters != null ? splitters : fem.getSplitters();
}
 
Example #18
Source File: UIDecorator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
static <R, U extends UIDecorator> R get(Function<U, R> supplier, Class<U> clazz, @Nonnull R defaultValue) {
  for (UIDecorator decorator : UIDecorators.getDecorators()) {
    if (!decorator.isAvaliable()) {
      continue;
    }

    U u = ObjectUtil.tryCast(decorator, clazz);
    if (u == null) {
      continue;
    }

    R fun = supplier.apply(u);
    if (fun != null) {
      return fun;
    }
  }
  return defaultValue;
}
 
Example #19
Source File: ShowDiffWithLocalAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  Project project = e.getRequiredData(CommonDataKeys.PROJECT);
  if (ChangeListManager.getInstance(project).isFreezedWithNotification(null)) return;

  VcsRevisionNumber currentRevisionNumber = e.getRequiredData(VcsDataKeys.HISTORY_SESSION).getCurrentRevisionNumber();
  VcsFileRevision selectedRevision = e.getRequiredData(VcsDataKeys.VCS_FILE_REVISIONS)[0];
  FilePath filePath = e.getRequiredData(VcsDataKeys.FILE_PATH);

  if (currentRevisionNumber != null && selectedRevision != null) {
    DiffFromHistoryHandler diffHandler =
            ObjectUtil.notNull(e.getRequiredData(VcsDataKeys.HISTORY_PROVIDER).getHistoryDiffHandler(), new StandardDiffFromHistoryHandler());
    diffHandler.showDiffForTwo(project, filePath, selectedRevision, new CurrentRevision(filePath.getVirtualFile(), currentRevisionNumber));
  }
}
 
Example #20
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static int hostToInjectedUnescaped(DocumentWindow window, int hostOffset) {
  Place shreds = ((DocumentWindowImpl)window).getShreds();
  Segment hostRangeMarker = shreds.get(0).getHostRangeMarker();
  if (hostRangeMarker == null || hostOffset < hostRangeMarker.getStartOffset()) {
    return shreds.get(0).getPrefix().length();
  }
  StringBuilder chars = new StringBuilder();
  int unescaped = 0;
  for (int i = 0; i < shreds.size(); i++, chars.setLength(0)) {
    PsiLanguageInjectionHost.Shred shred = shreds.get(i);
    int prefixLength = shred.getPrefix().length();
    int suffixLength = shred.getSuffix().length();
    PsiLanguageInjectionHost host = shred.getHost();
    TextRange rangeInsideHost = shred.getRangeInsideHost();
    LiteralTextEscaper<? extends PsiLanguageInjectionHost> escaper = host == null ? null : host.createLiteralTextEscaper();
    unescaped += prefixLength;
    Segment currentRange = shred.getHostRangeMarker();
    if (currentRange == null) continue;
    Segment nextRange = i == shreds.size() - 1 ? null : shreds.get(i + 1).getHostRangeMarker();
    if (nextRange == null || hostOffset < nextRange.getStartOffset()) {
      hostOffset = Math.min(hostOffset, currentRange.getEndOffset());
      int inHost = hostOffset - currentRange.getStartOffset();
      if (escaper != null && escaper.decode(rangeInsideHost, chars)) {
        int found = ObjectUtil.binarySearch(0, inHost, index -> Comparing.compare(escaper.getOffsetInHost(index, TextRange.create(0, host.getTextLength())), inHost));
        return unescaped + (found >= 0 ? found : -found - 1);
      }
      return unescaped + inHost;
    }
    if (escaper != null && escaper.decode(rangeInsideHost, chars)) {
      unescaped += chars.length();
    }
    else {
      unescaped += currentRange.getEndOffset() - currentRange.getStartOffset();
    }
    unescaped += suffixLength;
  }
  return unescaped - shreds.get(shreds.size() - 1).getSuffix().length();
}
 
Example #21
Source File: FileOrDirectoryDependencyTabContext.java    From consulo with Apache License 2.0 5 votes vote down vote up
public FileOrDirectoryDependencyTabContext(Disposable parent, ClasspathPanel panel, StructureConfigurableContext context) {
  super(panel, context);

  myLibraryTypes = new HashMap<LibraryRootsComponentDescriptor, LibraryType>();
  myDefaultDescriptor = new DefaultLibraryRootsComponentDescriptor();

  for (LibraryType<?> libraryType : LibraryEditingUtil.getSuitableTypes(myClasspathPanel)) {
    LibraryRootsComponentDescriptor descriptor = null;
    if (libraryType != null) {
      descriptor = libraryType.createLibraryRootsComponentDescriptor();
    }
    if (descriptor == null) {
      descriptor = myDefaultDescriptor;
    }
    if (!myLibraryTypes.containsKey(descriptor)) {
      myLibraryTypes.put(descriptor, libraryType);
    }
  }

  Module module = myClasspathPanel.getRootModel().getModule();

  myFileChooserDescriptor = createFileChooserDescriptor();
  myFileSystemTree = FileSystemTreeFactory.getInstance().createFileSystemTree(module.getProject(), myFileChooserDescriptor);
  Disposer.register(parent, myFileSystemTree);
  myFileSystemTree.showHiddens(true);
  final VirtualFile dirForSelect = ObjectUtil.chooseNotNull(module.getModuleDir(), module.getProject().getBaseDir());
  if(dirForSelect != null) {
    myFileSystemTree.select(dirForSelect, new Runnable() {
      @Override
      public void run() {
        myFileSystemTree.expand(dirForSelect, null);
      }
    });
  }
}
 
Example #22
Source File: TemplateCommentPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void initEditor() {
  if (myEditor == null) {
    myPreviewEditorPanel.removeAll();
    EditorFactory editorFactory = EditorFactory.getInstance();
    myDocument = editorFactory.createDocument("");

    myEditor = editorFactory.createEditor(myDocument, myProject, ObjectUtil.notNull(myFileType, PlainTextFileType.INSTANCE), true);
    CopyrightConfigurable.setupEditor(myEditor);

    myPreviewEditorPanel.add(myEditor.getComponent(), BorderLayout.CENTER);
  }
}
 
Example #23
Source File: XDebuggerTreeSpeedSearch.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected Object findElement(String s) {
  String string = s.trim();

  XDebuggerTreeNode node = ObjectUtil.tryCast(myComponent.getLastSelectedPathComponent(), XDebuggerTreeNode.class);
  if (node == null) {
    node = ObjectUtil.tryCast(myComponent.getModel().getRoot(), XDebuggerTreeNode.class);
    if (node == null) {
      return null;
    }
  }
  return findPath(string, node, true);
}
 
Example #24
Source File: IOExceptionDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
protected Action[] createLeftSideActions() {
  return new Action[] {
    new AbstractAction(CommonBundle.message("dialog.ioexception.proxy")) {
      @Override
      public void actionPerformed(@Nonnull ActionEvent e) {
        ShowSettingsUtil.getInstance().editConfigurable(ObjectUtil.tryCast(e.getSource(), JComponent.class), new HttpProxyConfigurable());
      }
    }
  };
}
 
Example #25
Source File: GotoDeclarationAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static Pair<PsiElement[], GotoDeclarationHandler> findAllTargetElementsInfo(Project project, Editor editor, int offset) {
  if (TargetElementUtil.inVirtualSpace(editor, offset)) {
    return Pair.create(PsiElement.EMPTY_ARRAY, null);
  }

  Pair<PsiElement[], GotoDeclarationHandler> pair = findTargetElementsNoVSWithHandler(project, editor, offset, true);
  return Pair.create(ObjectUtil.notNull(pair.getFirst(), PsiElement.EMPTY_ARRAY), pair.getSecond());
}
 
Example #26
Source File: BaseDataManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getData(@Nonnull Key<T> dataId) {
  if (ourSafeKeys.contains(dataId)) {
    Object answer = myCachedData.get(dataId);
    if (answer == null) {
      answer = doGetData(dataId);
      myCachedData.put(dataId, answer == null ? ObjectUtil.NULL : answer);
    }
    return answer != ObjectUtil.NULL ? (T)answer : null;
  }
  else {
    return doGetData(dataId);
  }
}
 
Example #27
Source File: LanguageSubstitutors.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void processLanguageSubstitution(@Nonnull final VirtualFile file,
                                                @Nonnull Language originalLang,
                                                @Nonnull final Language substitutedLang) {
  if (file instanceof VirtualFileWindow) {
    // Injected files are created with substituted language, no need to reparse:
    //   com.intellij.psi.impl.source.tree.injected.MultiHostRegistrarImpl#doneInjecting
    return;
  }
  Language prevSubstitutedLang = SUBSTITUTED_LANG_KEY.get(file);
  final Language prevLang = ObjectUtil.notNull(prevSubstitutedLang, originalLang);
  if (!prevLang.is(substitutedLang)) {
    if (file.replace(SUBSTITUTED_LANG_KEY, prevSubstitutedLang, substitutedLang)) {
      if (prevSubstitutedLang == null) {
        return; // no need to reparse for the first language substitution
      }
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        return;
      }
      file.putUserData(REPARSING_SCHEDULED, true);
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          if (file.replace(REPARSING_SCHEDULED, true, null)) {
            LOG.info("Reparsing " + file.getPath() + " because of language substitution " +
                     prevLang.getID() + "->" + substitutedLang.getID());
            FileContentUtilCore.reparseFiles(file);
          }
        }
      }, ModalityState.defaultModalityState());
    }
  }
}
 
Example #28
Source File: StubBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public T getPsi() {
  T psi = myPsi;
  if (psi != null) return psi;

  //noinspection unchecked
  psi = (T)getStubType().createPsi(this);
  return ourPsiUpdater.compareAndSet(this, null, psi) ? psi : ObjectUtil.assertNotNull(myPsi);
}
 
Example #29
Source File: Platform.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Deprecated
@DeprecationInfo("Use os().getEnvironmentVariables()")
@SuppressWarnings("deprecation")
default String getEnvironmentVariable(@Nonnull String key, @Nonnull String defaultValue) {
  return ObjectUtil.notNull(getEnvironmentVariable(key), defaultValue);
}
 
Example #30
Source File: Platform.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Deprecated
@DeprecationInfo("Use jvm().getRuntimeProperty()")
@SuppressWarnings("deprecation")
default String getRuntimeProperty(@Nonnull String key, @Nonnull String defaultValue) {
  return ObjectUtil.notNull(getRuntimeProperty(key), defaultValue);
}