@Nullable private static IProperty getResolvedProperty(@NotNull final XmlAttributeValue codeValue) { return CachedValuesManager.getCachedValue(codeValue, KEY, () -> { List<IProperty> allProperties = new SmartList<>(); for (PsiReference nextRef : codeValue.getReferences()) { if (nextRef instanceof PsiPolyVariantReference) { Arrays.stream(((PsiPolyVariantReference) nextRef).multiResolve(false)) .filter(ResolveResult::isValidResult) .map(ResolveResult::getElement) .map(o -> ObjectUtils.tryCast(o, IProperty.class)) .filter(Objects::nonNull) .forEach(allProperties::add); } else { Optional.ofNullable(nextRef.resolve()) .map(o -> ObjectUtils.tryCast(o, IProperty.class)) .ifPresent(allProperties::add); } } IProperty theChosenOne = chooseForLocale(allProperties); return new CachedValueProvider.Result<>(theChosenOne, PsiModificationTracker.MODIFICATION_COUNT); }); }
public static <T extends DomElement, V> GenericAttributeValue<V> expectDomAttributeValue( @NotNull final PsiElement element, @NotNull final Class<? extends T> domTagClass, @NotNull final Function<T, GenericAttributeValue<V>> domGetter ) { final DomManager domManager = DomManager.getDomManager(element.getProject()); if (!(element instanceof XmlElement)) { return null; } final XmlAttribute xmlAttribute = PsiTreeUtil.getParentOfType(element, XmlAttribute.class, false); if (xmlAttribute == null) { return null; } final XmlTag xmlParentTag = PsiTreeUtil.getParentOfType(element, XmlTag.class, false); DomElement domParentTag = domManager.getDomElement(xmlParentTag); return Optional.ofNullable(domParentTag) .map(o -> ObjectUtils.tryCast(o, domTagClass)) .map(domGetter) .filter(val -> val == domManager.getDomElement(xmlAttribute)) .orElse(null); }
public static YAMLKeyValue getKeyValue(YAMLFile yamlFile, List<String> key) { YAMLDocument document = (YAMLDocument) yamlFile.getDocuments().get(0); YAMLMapping mapping = (YAMLMapping) ObjectUtils.tryCast(document.getTopLevelValue(), YAMLMapping.class); for (int i = 0; i < key.size(); ++i) { if (mapping == null) { return null; } YAMLKeyValue keyValue = null; for (YAMLKeyValue each : mapping.getKeyValues()) { if (each.getKeyText().equals(key.get(i))) { keyValue = each; break; } } if (keyValue == null || i + 1 == key.size()) { return keyValue; } mapping = ObjectUtils.tryCast(keyValue.getValue(), YAMLMapping.class); } throw new IllegalStateException("Should have returned from the loop"); }
private void setupSshAuthenticator() throws IOException { GitXmlRpcSshService ssh = ServiceManager.getService(GitXmlRpcSshService.class); myEnv.put(GitSSHHandler.GIT_SSH_ENV, ssh.getScriptPath().getPath()); mySshHandler = ssh.registerHandler(new GitSSHGUIHandler(myProject)); myEnvironmentCleanedUp = false; myEnv.put(GitSSHHandler.SSH_HANDLER_ENV, Integer.toString(mySshHandler)); int port = ssh.getXmlRcpPort(); myEnv.put(GitSSHHandler.SSH_PORT_ENV, Integer.toString(port)); LOG.debug(String.format("handler=%s, port=%s", mySshHandler, port)); final HttpConfigurable httpConfigurable = HttpConfigurable.getInstance(); boolean useHttpProxy = httpConfigurable.USE_HTTP_PROXY && !isSshUrlExcluded(httpConfigurable, ObjectUtils.assertNotNull(myUrls)); myEnv.put(GitSSHHandler.SSH_USE_PROXY_ENV, String.valueOf(useHttpProxy)); if (useHttpProxy) { myEnv.put(GitSSHHandler.SSH_PROXY_HOST_ENV, StringUtil.notNullize(httpConfigurable.PROXY_HOST)); myEnv.put(GitSSHHandler.SSH_PROXY_PORT_ENV, String.valueOf(httpConfigurable.PROXY_PORT)); boolean proxyAuthentication = httpConfigurable.PROXY_AUTHENTICATION; myEnv.put(GitSSHHandler.SSH_PROXY_AUTHENTICATION_ENV, String.valueOf(proxyAuthentication)); if (proxyAuthentication) { myEnv.put(GitSSHHandler.SSH_PROXY_USER_ENV, StringUtil.notNullize(httpConfigurable.PROXY_LOGIN)); myEnv.put(GitSSHHandler.SSH_PROXY_PASSWORD_ENV, StringUtil.notNullize(httpConfigurable.getPlainProxyPassword())); } } }
@Override public void actionPerformed(@NotNull 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 = ObjectUtils.notNull(e.getRequiredData(VcsDataKeys.HISTORY_PROVIDER).getHistoryDiffHandler(), new StandardDiffFromHistoryHandler()); diffHandler.showDiffForTwo(project, filePath, selectedRevision, new CurrentRevision(filePath.getVirtualFile(), currentRevisionNumber)); } }
@Override public Type visitClassType(PsiClassType type) { PsiClassType.ClassResolveResult resolveResult = type.resolveGenerics(); PsiClass aClass = resolveResult.getElement(); if (aClass instanceof PsiAnonymousClass) { return visitClassType(((PsiAnonymousClass)aClass).getBaseClassType()); } else if (aClass == null) { return new UnresolvedType(type); } else { Map<String, Type> substitutionMap = ContainerUtil.newHashMap(); PsiSubstitutor substitutor = resolveResult.getSubstitutor(); for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(aClass)) { PsiType substitute = substitutor.substitute(typeParameter); substitutionMap.put(typeParameter.getName(), substitute != null ? substitute.accept(this) : null); } String qualifiedName = ObjectUtils.notNull(aClass.getQualifiedName(), aClass.getName()); return new ClassType(type, qualifiedName, substitutionMap); } }
@Nullable @Override public LookupElement createLookupElement(ActionOrGroup actionOrGroup) { if (actionOrGroup instanceof Action) { Action action = (Action)actionOrGroup; final PsiElement element = getPsiElement(actionOrGroup); if (element == null) { throw new IllegalStateException(action.getId().getStringValue() + " in " + DomUtil.getFile(action) + " " + action.isValid() + " "); } LookupElementBuilder builder = LookupElementBuilder.create(ObjectUtils.assertNotNull(element), ObjectUtils.assertNotNull(getName(action))); final String text = action.getText().getStringValue(); if (StringUtil.isNotEmpty(text)) { String withoutMnemonic = StringUtil.replace(text, "_", ""); builder = builder.withTailText(" \"" + withoutMnemonic + "\"", true); } return builder; } return super.createLookupElement(actionOrGroup); }
@Override @Nullable public Document getDocument() { if (myDocument == null) { if (isBinary()) return null; String text = null; try { Charset charset = ObjectUtils.notNull(myCharset, EncodingProjectManager.getInstance(myProject).getDefaultCharset()); text = CharsetToolkit.bytesToString(myBytes, charset); } catch (IllegalCharsetNameException ignored) { } // 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; }
@Messages.YesNoCancelResult public int show() { String yesText = ObjectUtils.chooseNotNull(myYesText, Messages.YES_BUTTON); String noText = ObjectUtils.chooseNotNull(myNoText, Messages.NO_BUTTON); String cancelText = ObjectUtils.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; }
private void paintOnComponentUnderViewport(Component component, Graphics g) { JBViewport viewport = ObjectUtils.tryCast(myOwner, JBViewport.class); if (viewport == null || viewport.getView() != component || viewport.isPaintingNow()) return; // We're painting a component which has a viewport as it's ancestor. // As the viewport paints status text, we'll erase it, so we need to schedule a repaint for the viewport with status text's bounds. // But it causes flicker, so we paint status text over the component first and then schedule the viewport repaint. Rectangle textBoundsInViewport = getTextComponentBound(); int xInOwner = textBoundsInViewport.x - component.getX(); int yInOwner = textBoundsInViewport.y - component.getY(); Rectangle textBoundsInOwner = new Rectangle(xInOwner, yInOwner, textBoundsInViewport.width, textBoundsInViewport.height); doPaintStatusText(g, textBoundsInOwner); viewport.repaint(textBoundsInViewport); }
private AnAction replaceAction(@NotNull String actionId, @NotNull AnAction newAction, @Nullable PluginId pluginId) { AnAction oldAction = getActionOrStub(actionId); if (oldAction != null) { boolean isGroup = oldAction instanceof ActionGroup; if (isGroup != newAction instanceof ActionGroup) { throw new IllegalStateException("cannot replace a group with an action and vice versa: " + actionId); } unregisterAction(actionId); if (isGroup) { myId2GroupId.values().remove(actionId); } } registerAction(actionId, newAction, pluginId); for (String groupId : myId2GroupId.get(actionId)) { DefaultActionGroup group = ObjectUtils.assertNotNull((DefaultActionGroup)getActionOrStub(groupId)); group.replaceAction(oldAction, newAction); } return oldAction; }
private static void generateDocstring(@Nullable PyNamedParameter param, @NotNull PyFunction pyFunction) { if (!DocStringUtil.ensureNotPlainDocstringFormat(pyFunction)) { return; } final PyDocstringGenerator docstringGenerator = PyDocstringGenerator.forDocStringOwner(pyFunction); String type = "object"; if (param != null) { final String paramName = StringUtil.notNullize(param.getName()); final PySignature signature = PySignatureCacheManager.getInstance(pyFunction.getProject()).findSignature(pyFunction); if (signature != null) { type = ObjectUtils.chooseNotNull(signature.getArgTypeQualifiedName(paramName), type); } docstringGenerator.withParamTypedByName(param, type); } else { docstringGenerator.withReturnValue(type); } docstringGenerator.addFirstEmptyLine().buildAndInsert(); docstringGenerator.startTemplate(); }
private Object calculateRoot(DataContext dataContext) { // Narrow down the root element to the first interesting one Object root = LangDataKeys.MODULE.getData(dataContext); if (root != null) return root; Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) return null; Object projectChild; Object projectGrandChild = null; CommonProcessors.FindFirstAndOnlyProcessor<Object> processor = new CommonProcessors.FindFirstAndOnlyProcessor<Object>(); processChildren(project, processor); projectChild = processor.reset(); if (projectChild != null) { processChildren(projectChild, processor); projectGrandChild = processor.reset(); } return ObjectUtils.chooseNotNull(projectGrandChild, ObjectUtils.chooseNotNull(projectChild, project)); }
void fillTable() { Class<?> clazz0 = myComponent.getClass(); Class<?> clazz = clazz0.isAnonymousClass() ? clazz0.getSuperclass() : clazz0; myProperties.add(new PropertyBean("class", clazz.getName())); for (String name: PROPERTIES) { String propertyName = ObjectUtils.notNull(StringUtil.getPropertyName(name), name); Object propertyValue; try { try { //noinspection ConstantConditions propertyValue = ReflectionUtil.findMethod(Arrays.asList(clazz.getMethods()), name).invoke(myComponent); } catch (Exception e) { propertyValue = ReflectionUtil.findField(clazz, null, name).get(myComponent); } myProperties.add(new PropertyBean(propertyName, propertyValue)); } catch (Exception ignored) { } } Object addedAt = myComponent instanceof JComponent ? ((JComponent)myComponent).getClientProperty("uiInspector.addedAt") : null; myProperties.add(new PropertyBean("added-at", addedAt)); }
public void testUnsavedDocument_DoNotGC() throws Exception { final VirtualFile file = createFile(); Document document = myDocumentManager.getDocument(file); int idCode = System.identityHashCode(document); assertNotNull(file.toString(), document); WriteCommandAction.runWriteCommandAction(myProject, new Runnable() { @Override public void run() { ObjectUtils.assertNotNull(myDocumentManager.getDocument(file)).insertString(0, "xxx"); } }); //noinspection UnusedAssignment document = null; System.gc(); System.gc(); document = myDocumentManager.getDocument(file); assertEquals(idCode, System.identityHashCode(document)); }
public static boolean isPath(@Nullable String s) { if (!StringUtil.isEmpty(s)) { s = ObjectUtils.assertNotNull(s); s = FileUtil.toSystemIndependentName(s); final List<String> components = StringUtil.split(s, "/"); for (String name : components) { if (name == components.get(0) && SystemInfo.isWindows && name.endsWith(":")) { continue; } if (!PathUtil.isValidFileName(name)) { return false; } } return true; } return false; }
@NotNull public static GitCommandResult merge(@Nullable GitCommandResult first, @NotNull GitCommandResult second) { if (first == null) return second; int mergedExitCode; if (first.myExitCode == 0) { mergedExitCode = second.myExitCode; } else if (second.myExitCode == 0) { mergedExitCode = first.myExitCode; } else { mergedExitCode = second.myExitCode; // take exit code of the latest command } return new GitCommandResult(first.success() && second.success(), mergedExitCode, ContainerUtil.concat(first.myErrorOutput, second.myErrorOutput), ContainerUtil.concat(first.myOutput, second.myOutput), ObjectUtils.chooseNotNull(second.myException, first.myException)); }
@Override public void revert(@NotNull Collection<File> paths, @Nullable Depth depth, @Nullable ProgressTracker handler) throws VcsException { if (!ContainerUtil.isEmpty(paths)) { Command command = newCommand(SvnCommandName.revert); command.put(depth); command.setTargets(paths); // TODO: handler should be called in parallel with command execution, but this will be in other thread // TODO: check if that is ok for current handler implementation // TODO: add possibility to invoke "handler.checkCancelled" - process should be killed SvnTarget target = SvnTarget.fromFile(ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(paths))); CommandExecutor executor = execute(myVcs, target, CommandUtil.getHomeDirectory(), command, null); FileStatusResultParser parser = new FileStatusResultParser(CHANGED_PATH, handler, new RevertStatusConvertor()); parser.parse(executor.getOutput()); } }
private static SelectInContext doCreateEditorContext(Project project, FileEditor editor, @Nullable DataContext dataContext) { if (project == null || editor == null) { return null; } VirtualFile file = FileEditorManagerEx.getInstanceEx(project).getFile(editor); if (file == null) { file = dataContext == null ? null : CommonDataKeys.VIRTUAL_FILE.getData(dataContext); if (file == null) { return null; } } final PsiFile psiFile = PsiManager.getInstance(project).findFile(file); if (psiFile == null) { return null; } if (editor instanceof TextEditor) { return new TextEditorContext((TextEditor)editor, psiFile); } else { StructureViewBuilder builder = editor.getStructureViewBuilder(); StructureView structureView = builder != null ? builder.createStructureView(editor, project) : null; Object selectorInFile = structureView != null ? structureView.getTreeModel().getCurrentEditorElement() : null; if (structureView != null) Disposer.dispose(structureView); return new SimpleSelectInContext(psiFile, ObjectUtils.chooseNotNull(selectorInFile, psiFile)); } }
public void performCopy(@NotNull DataContext dataContext) { List<TreePath> paths = ContainerUtil.sorted(Arrays.asList(ObjectUtils.assertNotNull(myTree.getSelectionPaths())), TreeUtil.getDisplayOrderComparator(myTree)); CopyPasteManager.getInstance().setContents(new StringSelection(StringUtil.join(paths, new Function<TreePath, String>() { @Override public String fun(TreePath path) { Object node = path.getLastPathComponent(); if (node instanceof ChangesBrowserNode) { return ((ChangesBrowserNode)node).getTextPresentation(); } else { return node.toString(); } } }, "\n"))); }
@NotNull public static HybrisWritingAccessProvider getInstance(@NotNull final Project project) { return Arrays.stream(Extensions.getExtensions(EP_NAME, project)) .map(o -> ObjectUtils.tryCast(o, HybrisWritingAccessProvider.class)) .filter(Objects::nonNull) .findAny() .orElseThrow(IllegalStateException::new); }
public static PsiField resolveToPsiField(@NotNull final Property property, @Nullable final String name) { if (StringUtil.isEmptyOrSpaces(name)) { return null; } if (!(property.getParent() instanceof Bean)) { return null; } final Bean bean = (Bean) property.getParent(); final GenericAttributeValue<String> clazz = bean.getClazz(); if (!clazz.exists()) { return null; } final XmlAttributeValue xmlValue = clazz.getXmlAttributeValue(); if (xmlValue == null) { return null; } return Arrays.stream(xmlValue.getReferences()) .map(PsiReference::resolve) .map(o -> ObjectUtils.tryCast(o, PsiClass.class)) .filter(Objects::nonNull) .map(nextClass -> nextClass.findFieldByName(name, false)) .filter(Objects::nonNull) .findAny() .orElse(null); }
@Nullable private static ImpexFullHeaderParameter getLinkedHeaderParameter(final @NotNull PsiElement psi) { return Optional.ofNullable(ImpexPsiUtils.getClosestSelectedValueGroupFromTheSameLine(psi)) .map(ImpexPsiUtils::getHeaderForValueGroup) .map(o -> ObjectUtils.tryCast(o, ImpexFullHeaderParameter.class)) .orElse(null); }
@NotNull private XValuePresentation getPresentation() { final String stringValue = myValueAsString; if (isNumber()) return new XNumericValuePresentation(stringValue); if (isString()) return new XStringValuePresentation(stringValue); if (isBool()) { return new XValuePresentation() { @Override public void renderValue(@NotNull XValueTextRenderer renderer) { renderer.renderValue(stringValue); } }; } return new XRegularValuePresentation(ObjectUtils.notNull(ObjectUtils.coalesce(Arrays.asList(stringValue, identityValue, ""))), myTypeName); }
@NotNull @Override public GitPushSource getSource(@NotNull GitRepository repository) { GitLocalBranch currentBranch = repository.getCurrentBranch(); return currentBranch != null ? GitPushSource.create(currentBranch) : GitPushSource.create(ObjectUtils.assertNotNull(repository.getCurrentRevision())); // fresh repository is on branch }
@Nullable protected JSFile findMainJsFile(@NotNull JsonFile packageJsonFile) { final JsonStringLiteralImpl value = ObjectUtils.tryCast(JsonPsiUtil.findPropertyValue( packageJsonFile.getTopLevelValue(), "main"), JsonStringLiteralImpl.class); if (value == null) return null; VirtualFile mainJsVFile = packageJsonFile.getVirtualFile().getParent().findFileByRelativePath(value.getValue()); if (mainJsVFile == null) return null; return ObjectUtils.tryCast(PsiManager.getInstance(project).findFile(mainJsVFile), JSFile.class); }
@NotNull protected JsonFile[] findConfigFiles() { VirtualFile configDir = project.getBaseDir().findChild("config"); if(configDir == null) return new JsonFile[0]; List<JsonFile> files = new LinkedList<JsonFile>(); PsiManager psiManager = PsiManager.getInstance(project); for(VirtualFile file : configDir.getChildren()) { JsonFile jsonFile = ObjectUtils.tryCast(psiManager.findFile(file), JsonFile.class); if(jsonFile != null) files.add(jsonFile); } return files.toArray(new JsonFile[files.size()]); }
private void fireTemplateFinished(boolean brokenOff) { if (myFinished) return; myFinished = true; for (TemplateEditingListener listener : myListeners) { listener.templateFinished(ObjectUtils.chooseNotNull(myTemplate, myPrevTemplate), brokenOff); } }
@NotNull @Override public PsiElement getDelimiter() { PsiElement in = findChildByType(GroovyTokenTypes.kIN); if (in != null) return in; PsiElement colon = findChildByType(GroovyTokenTypes.mCOLON); return ObjectUtils.assertNotNull(colon); }
/** * Tests that merge commit after resolving a conflict works fine if there is a file with spaces in its path. * IDEA-50318 */ @Test public void testMergeCommitWithSpacesInPath() throws IOException { final String PATH = "dir with spaces/file with spaces.txt"; GitTestUtil.createFileStructure(myProjectRoot, PATH); addCommit("created some file structure"); git("branch feature"); File file = new File(myProjectPath, PATH); assertTrue("File doesn't exist!", file.exists()); overwrite(file, "my content"); addCommit("modified in master"); checkout("feature"); overwrite(file, "brother content"); addCommit("modified in feature"); checkout("master"); git("merge feature", true); // ignoring non-zero exit-code reporting about conflicts overwrite(file, "merged content"); // manually resolving conflict git("add ."); final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); updateChangeListManager(); final LocalChangeList changeList = changeListManager.getDefaultChangeList(); changeList.setComment("Commit message"); List<Change> changes = ContainerUtil.newArrayList(changeListManager.getChangesIn(myProjectRoot)); assertTrue(!changes.isEmpty()); CheckinEnvironment checkingEnv = ObjectUtils.assertNotNull(myVcs.getCheckinEnvironment()); List<VcsException> exceptions = checkingEnv.commit(changes, "comment"); assertNoExceptions(exceptions); updateChangeListManager(); assertTrue(changeListManager.getChangesIn(myProjectRoot).isEmpty()); }
private String getOptionalLambdaType(PsiAnonymousClass anonymousClass, PsiNewExpression expression) { if (shouldShowExplicitLambdaType(anonymousClass, expression)) { final String baseClassName = ObjectUtils.assertNotNull(anonymousClass.getBaseClassType().resolve()).getName(); if (baseClassName != null) { return "(" + baseClassName + ") "; } } return ""; }
@NotNull public static List<Object> collectOperands(@NotNull final String prefix, final String suffix, final Ref<Boolean> unparsable, final PsiElement[] operands) { final ArrayList<Object> result = new ArrayList<Object>(); final ContextComputationProcessor processor = new ContextComputationProcessor(operands[0].getProject()); addStringFragment(prefix, result); PsiElement topParent = ObjectUtils.assertNotNull(PsiTreeUtil.findCommonParent(operands)); processor.collectOperands(getTopLevelInjectionTarget(topParent), result, unparsable); addStringFragment(suffix, result); return result; }
@Override @NotNull public PsiAnnotationMemberValue createChild(@NotNull PsiAnnotation psiAnnotation) throws IncorrectOperationException { final PsiExpression nullValue = JavaPsiFacade.getElementFactory(psiAnnotation.getProject()).createExpressionFromText(PsiKeyword.NULL, null); psiAnnotation.setDeclaredAttributeValue(myAttributeName, nullValue); return ObjectUtils.assertNotNull(psiAnnotation.findDeclaredAttributeValue(myAttributeName)); }
public AddAnnotationPsiFix(@NotNull String fqn, @NotNull PsiModifierListOwner modifierListOwner, @NotNull PsiNameValuePair[] values, @NotNull String... annotationsToRemove) { super(modifierListOwner); myAnnotation = fqn; ObjectUtils.assertAllElementsNotNull(values); myPairs = values; ObjectUtils.assertAllElementsNotNull(annotationsToRemove); myAnnotationsToRemove = annotationsToRemove; myText = calcText(modifierListOwner, myAnnotation); }
public void setFileText(final PsiFile file, final String text) throws IOException { new WriteAction() { @Override protected void run(@NotNull Result result) throws Throwable { final VirtualFile virtualFile = file.getVirtualFile(); VfsUtil.saveText(ObjectUtils.assertNotNull(virtualFile), text); } }.execute().throwException(); touch(file.getVirtualFile()); }
@Override public void actionPerformed(final AnActionEvent e) { String command; if (myNext) { command = getModel().getHistoryNext(); if (!myMultiline && command == null) return; } else { command = ObjectUtils.chooseNotNull(getModel().getHistoryPrev(), myMultiline ? "" : StringUtil.notNullize(myHelper.getContent())); } setConsoleText(command, myNext && !getModel().hasHistory(false), true); }
@NotNull public static GitRemoteBranch findOrCreateRemoteBranch(@NotNull GitRepository repository, @NotNull GitRemote remote, @NotNull String branchName) { GitRemoteBranch remoteBranch = findRemoteBranch(repository, remote, branchName); return ObjectUtils.notNull(remoteBranch, new GitStandardRemoteBranch(remote, branchName, GitBranch.DUMMY_HASH)); }
@Override public PsiElement handleElementRename(final String newElementName) throws IncorrectOperationException { CheckUtil.checkWritable(this); final PsiElement firstChildNode = ObjectUtils.assertNotNull(getFirstChild()); final PsiElement firstInIdentifier = getClass().isInstance(firstChildNode) ? ObjectUtils.assertNotNull(firstChildNode.getNextSibling()).getNextSibling() : firstChildNode; getNode().removeRange(firstInIdentifier.getNode(), null); final PsiElement referenceName = ObjectUtils.assertNotNull(parseReference(newElementName).getReferenceNameElement()); getNode().addChild(referenceName.getNode()); return this; }
@NotNull private static GitCommandResult runAll(@NotNull List<Computable<GitCommandResult>> commands) { if (commands.isEmpty()) { LOG.error("List of commands should not be empty", new Exception()); return GitCommandResult.error("Internal error"); } GitCommandResult compoundResult = null; for (Computable<GitCommandResult> command : commands) { compoundResult = GitCommandResult.merge(compoundResult, command.compute()); } return ObjectUtils.assertNotNull(compoundResult); }
private static void performForLocal(boolean searchForSuper, boolean removeLocalVariable, boolean replaceAllOccurrences, boolean declareFinal, final boolean removeUnusedParameters) { final int offset = myEditor.getCaretModel().getOffset(); final PsiElement element = ObjectUtils.assertNotNull(myFile.findElementAt(offset)).getParent(); assertTrue(element instanceof PsiLocalVariable); PsiMethod method = Util.getContainingMethod(element); final PsiMethod methodToSearchFor; if (searchForSuper) { PsiMethod[] deepestSuperMethods = method.findDeepestSuperMethods(); methodToSearchFor = deepestSuperMethods.length > 0 ? deepestSuperMethods[0] : method; } else { methodToSearchFor = method; } assertNotNull(method); assertNotNull(methodToSearchFor); final PsiLocalVariable localVariable = (PsiLocalVariable)element; final PsiExpression parameterInitializer = localVariable.getInitializer(); assertNotNull(parameterInitializer); TIntArrayList parametersToRemove = removeUnusedParameters ? Util.findParametersToRemove(method, parameterInitializer, null) : new TIntArrayList(); new IntroduceParameterProcessor( getProject(), method, methodToSearchFor, parameterInitializer, null, localVariable, removeLocalVariable, localVariable.getName(), replaceAllOccurrences, IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE, declareFinal, false, null, parametersToRemove ).run(); }