Search in sources :

Example 11 with Consumer

use of com.intellij.util.Consumer in project intellij-community by JetBrains.

the class TemplateModuleBuilder method unzip.

private void unzip(@Nullable final String projectName, String path, final boolean moduleMode, @Nullable ProgressIndicator pI, boolean reportFailuresWithDialog) {
    final WizardInputField basePackage = getBasePackageField();
    try {
        final File dir = new File(path);
        class ExceptionConsumer implements Consumer<VelocityException> {

            private String myPath;

            private String myText;

            private SmartList<Trinity<String, String, VelocityException>> myFailures = new SmartList<>();

            @Override
            public void consume(VelocityException e) {
                myFailures.add(Trinity.create(myPath, myText, e));
            }

            private void setCurrentFile(String path, String text) {
                myPath = path;
                myText = text;
            }

            private void reportFailures() {
                if (myFailures.isEmpty()) {
                    return;
                }
                if (reportFailuresWithDialog) {
                    String dialogMessage;
                    if (myFailures.size() == 1) {
                        dialogMessage = "Failed to decode file \'" + myFailures.get(0).getFirst() + "\'";
                    } else {
                        StringBuilder dialogMessageBuilder = new StringBuilder();
                        dialogMessageBuilder.append("Failed to decode files: \n");
                        for (Trinity<String, String, VelocityException> failure : myFailures) {
                            dialogMessageBuilder.append(failure.getFirst()).append("\n");
                        }
                        dialogMessage = dialogMessageBuilder.toString();
                    }
                    Messages.showErrorDialog(dialogMessage, "Decoding Template");
                }
                StringBuilder reportBuilder = new StringBuilder();
                for (Trinity<String, String, VelocityException> failure : myFailures) {
                    reportBuilder.append("File: ").append(failure.getFirst()).append("\n");
                    reportBuilder.append("Exception:\n").append(ExceptionUtil.getThrowableText(failure.getThird())).append("\n");
                    reportBuilder.append("File content:\n\'").append(failure.getSecond()).append("\'\n");
                    reportBuilder.append("\n===========================================\n");
                }
                LOG.error(LogMessageEx.createEvent("Cannot decode files in template", "", new Attachment("Files in template", reportBuilder.toString())));
            }
        }
        ExceptionConsumer consumer = new ExceptionConsumer();
        List<File> filesToRefresh = new ArrayList<>();
        myTemplate.processStream(new ArchivedProjectTemplate.StreamProcessor<Void>() {

            @Override
            public Void consume(@NotNull ZipInputStream stream) throws IOException {
                ZipUtil.unzip(ProgressManager.getInstance().getProgressIndicator(), dir, stream, path1 -> {
                    if (moduleMode && path1.contains(Project.DIRECTORY_STORE_FOLDER)) {
                        return null;
                    }
                    if (basePackage != null) {
                        return path1.replace(getPathFragment(basePackage.getDefaultValue()), getPathFragment(basePackage.getValue()));
                    }
                    return path1;
                }, new ZipUtil.ContentProcessor() {

                    @Override
                    public byte[] processContent(byte[] content, File file) throws IOException {
                        if (pI != null) {
                            pI.checkCanceled();
                        }
                        FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(FileUtilRt.getExtension(file.getName()));
                        String text = new String(content, CharsetToolkit.UTF8_CHARSET);
                        consumer.setCurrentFile(file.getName(), text);
                        return fileType.isBinary() ? content : processTemplates(projectName, text, file, consumer);
                    }
                }, true);
                myTemplate.handleUnzippedDirectories(dir, filesToRefresh);
                return null;
            }
        });
        if (pI != null) {
            pI.setText("Refreshing...");
        }
        String iml = ContainerUtil.find(dir.list(), s -> s.endsWith(".iml"));
        if (moduleMode) {
            File from = new File(path, iml);
            File to = new File(getModuleFilePath());
            if (!from.renameTo(to)) {
                throw new IOException("Can't rename " + from + " to " + to);
            }
        }
        RefreshQueue refreshQueue = RefreshQueue.getInstance();
        LOG.assertTrue(!filesToRefresh.isEmpty());
        for (File file : filesToRefresh) {
            VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
            if (virtualFile == null) {
                throw new IOException("Can't find " + file);
            }
            refreshQueue.refresh(false, true, null, virtualFile);
        }
        consumer.reportFailures();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : FileUtilRt(com.intellij.openapi.util.io.FileUtilRt) Trinity(com.intellij.openapi.util.Trinity) com.intellij.openapi.module(com.intellij.openapi.module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Task(com.intellij.openapi.progress.Task) JDOMException(org.jdom.JDOMException) SmartList(com.intellij.util.SmartList) ModifiableRootModel(com.intellij.openapi.roots.ModifiableRootModel) CodeStyleFacade(com.intellij.codeStyle.CodeStyleFacade) Messages(com.intellij.openapi.ui.Messages) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) VelocityException(org.apache.velocity.exception.VelocityException) ProgressManager(com.intellij.openapi.progress.ProgressManager) FileTypeManager(com.intellij.openapi.fileTypes.FileTypeManager) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) PathMacroUtil(org.jetbrains.jps.model.serialization.PathMacroUtil) com.intellij.ide.util.projectWizard(com.intellij.ide.util.projectWizard) Nullable(org.jetbrains.annotations.Nullable) LogMessageEx(com.intellij.diagnostic.LogMessageEx) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager) ApplicationManager(com.intellij.openapi.application.ApplicationManager) ModulesProvider(com.intellij.openapi.roots.ui.configuration.ModulesProvider) ConfigurationException(com.intellij.openapi.options.ConfigurationException) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) RunConfiguration(com.intellij.execution.configurations.RunConfiguration) WriteAction(com.intellij.openapi.application.WriteAction) ZipInputStream(java.util.zip.ZipInputStream) CharsetToolkit(com.intellij.openapi.vfs.CharsetToolkit) Computable(com.intellij.openapi.util.Computable) InvalidDataException(com.intellij.openapi.util.InvalidDataException) ContainerUtil(com.intellij.util.containers.ContainerUtil) ModuleBasedConfiguration(com.intellij.execution.configurations.ModuleBasedConfiguration) ArrayList(java.util.ArrayList) RefreshQueue(com.intellij.openapi.vfs.newvfs.RefreshQueue) StartupManager(com.intellij.openapi.startup.StartupManager) RunManager(com.intellij.execution.RunManager) Project(com.intellij.openapi.project.Project) Properties(java.util.Properties) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) ProjectManagerEx(com.intellij.openapi.project.ex.ProjectManagerEx) ZipUtil(com.intellij.platform.templates.github.ZipUtil) IOException(java.io.IOException) FileType(com.intellij.openapi.fileTypes.FileType) File(java.io.File) StringUtilRt(com.intellij.openapi.util.text.StringUtilRt) ExceptionUtil(com.intellij.util.ExceptionUtil) FileTemplateUtil(com.intellij.ide.fileTemplates.FileTemplateUtil) Attachment(com.intellij.openapi.diagnostic.Attachment) javax.swing(javax.swing) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ArrayList(java.util.ArrayList) Attachment(com.intellij.openapi.diagnostic.Attachment) RefreshQueue(com.intellij.openapi.vfs.newvfs.RefreshQueue) Consumer(com.intellij.util.Consumer) VelocityException(org.apache.velocity.exception.VelocityException) IOException(java.io.IOException) ZipInputStream(java.util.zip.ZipInputStream) FileType(com.intellij.openapi.fileTypes.FileType) SmartList(com.intellij.util.SmartList) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 12 with Consumer

use of com.intellij.util.Consumer in project intellij-community by JetBrains.

the class TargetElementUtil method getNamedElement.

@Override
@Nullable
public PsiElement getNamedElement(@Nullable final PsiElement element, final int offsetInElement) {
    if (element == null)
        return null;
    final List<PomTarget> targets = ContainerUtil.newArrayList();
    final Consumer<PomTarget> consumer = target -> {
        if (target instanceof PsiDeclaredTarget) {
            final PsiDeclaredTarget declaredTarget = (PsiDeclaredTarget) target;
            final PsiElement navigationElement = declaredTarget.getNavigationElement();
            final TextRange range = declaredTarget.getNameIdentifierRange();
            if (range != null && !range.shiftRight(navigationElement.getTextRange().getStartOffset()).contains(element.getTextRange().getStartOffset() + offsetInElement)) {
                return;
            }
        }
        targets.add(target);
    };
    PsiElement parent = element;
    int offset = offsetInElement;
    while (parent != null) {
        for (PomDeclarationSearcher searcher : PomDeclarationSearcher.EP_NAME.getExtensions()) {
            searcher.findDeclarationsAt(parent, offset, consumer);
            if (!targets.isEmpty()) {
                final PomTarget target = targets.get(0);
                return target == null ? null : PomService.convertToPsi(element.getProject(), target);
            }
        }
        offset += parent.getStartOffsetInParent();
        parent = parent.getParent();
    }
    return getNamedElement(element);
}
Also used : PomTarget(com.intellij.pom.PomTarget) Language(com.intellij.lang.Language) InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) NavigationItem(com.intellij.navigation.NavigationItem) Lookup(com.intellij.codeInsight.lookup.Lookup) Document(com.intellij.openapi.editor.Document) EditorUtil(com.intellij.openapi.editor.ex.util.EditorUtil) DaemonCodeAnalyzer(com.intellij.codeInsight.daemon.DaemonCodeAnalyzer) SearchScope(com.intellij.psi.search.SearchScope) ContainerUtil(com.intellij.util.containers.ContainerUtil) ArrayList(java.util.ArrayList) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) PomService(com.intellij.pom.references.PomService) Project(com.intellij.openapi.project.Project) EditorEx(com.intellij.openapi.editor.ex.EditorEx) PomTarget(com.intellij.pom.PomTarget) CompletionUtil(com.intellij.codeInsight.completion.CompletionUtil) Extensions(com.intellij.openapi.extensions.Extensions) PsiSearchHelper(com.intellij.psi.search.PsiSearchHelper) PsiDeclaredTarget(com.intellij.pom.PsiDeclaredTarget) ThreeState(com.intellij.util.ThreeState) LookupElement(com.intellij.codeInsight.lookup.LookupElement) Collection(java.util.Collection) LookupManager(com.intellij.codeInsight.lookup.LookupManager) LanguageExtension(com.intellij.lang.LanguageExtension) TextRange(com.intellij.openapi.util.TextRange) Editor(com.intellij.openapi.editor.Editor) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) ServiceManager(com.intellij.openapi.components.ServiceManager) PomDeclarationSearcher(com.intellij.pom.PomDeclarationSearcher) EditSourceUtil(com.intellij.ide.util.EditSourceUtil) BitUtil(com.intellij.util.BitUtil) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Navigatable(com.intellij.pom.Navigatable) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) Consumer(com.intellij.util.Consumer) TextRange(com.intellij.openapi.util.TextRange) PsiDeclaredTarget(com.intellij.pom.PsiDeclaredTarget) PomDeclarationSearcher(com.intellij.pom.PomDeclarationSearcher) Nullable(org.jetbrains.annotations.Nullable)

Example 13 with Consumer

use of com.intellij.util.Consumer in project intellij-community by JetBrains.

the class ChangeSignatureDialogBase method createOptionsPanel.

protected JComponent createOptionsPanel() {
    final JPanel panel = new JPanel(new BorderLayout());
    if (myAllowDelegation) {
        myDelegationPanel = createDelegationPanel();
        panel.add(myDelegationPanel, BorderLayout.WEST);
    }
    myPropagateParamChangesButton = new AnActionButton(RefactoringBundle.message("changeSignature.propagate.parameters.title"), null, AllIcons.Hierarchy.Caller) {

        @Override
        public void actionPerformed(AnActionEvent e) {
            final Ref<CallerChooserBase<Method>> chooser = new Ref<>();
            Consumer<Set<Method>> callback = callers -> {
                myMethodsToPropagateParameters = callers;
                myParameterPropagationTreeToReuse = chooser.get().getTree();
            };
            try {
                String message = RefactoringBundle.message("changeSignature.parameter.caller.chooser");
                chooser.set(createCallerChooser(message, myParameterPropagationTreeToReuse, callback));
            } catch (ProcessCanceledException ex) {
                // user cancelled initial callers search, don't show dialog
                return;
            }
            chooser.get().show();
        }
    };
    final JPanel result = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP));
    result.add(panel);
    return result;
}
Also used : Ref(com.intellij.openapi.util.Ref) Consumer(com.intellij.util.Consumer) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) VerticalFlowLayout(com.intellij.openapi.ui.VerticalFlowLayout)

Example 14 with Consumer

use of com.intellij.util.Consumer in project intellij-community by JetBrains.

the class RefactoringQuickFix method doFix.

default default void doFix(@NotNull PsiElement element) {
    final PsiElement elementToRefactor = getElementToRefactor(element);
    if (elementToRefactor == null) {
        return;
    }
    final Consumer<DataContext> consumer = dataContext -> {
        dataContext = enhanceDataContext(dataContext);
        final RefactoringActionHandler handler = getHandler();
        handler.invoke(element.getProject(), new PsiElement[] { elementToRefactor }, dataContext);
    };
    DataManager.getInstance().getDataContextFromFocus().doWhenDone(consumer);
}
Also used : DataContext(com.intellij.openapi.actionSystem.DataContext) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) RefactoringActionHandler(com.intellij.refactoring.RefactoringActionHandler) NonNls(org.jetbrains.annotations.NonNls) PsiNamedElement(com.intellij.psi.PsiNamedElement) NotNull(org.jetbrains.annotations.NotNull) DataManager(com.intellij.ide.DataManager) Consumer(com.intellij.util.Consumer) DataContext(com.intellij.openapi.actionSystem.DataContext) RefactoringActionHandler(com.intellij.refactoring.RefactoringActionHandler) PsiElement(com.intellij.psi.PsiElement)

Example 15 with Consumer

use of com.intellij.util.Consumer in project intellij-community by JetBrains.

the class PostfixTemplatesCheckboxTree method setState.

public void setState(@NotNull final Map<String, Set<String>> langToDisabledTemplates) {
    final TreeState treeState = TreeState.createOn(this, myRoot);
    Consumer<PostfixTemplateCheckedTreeNode> consumer = template -> {
        Set<String> disabledTemplates = langToDisabledTemplates.get(template.getLang());
        String key = template.getTemplate().getKey();
        if (disabledTemplates != null && disabledTemplates.contains(key)) {
            template.setChecked(false);
            return;
        }
        template.setChecked(true);
    };
    visit(consumer);
    myModel.nodeStructureChanged(myRoot);
    treeState.applyTo(this);
    TreeUtil.expandAll(this);
}
Also used : Language(com.intellij.lang.Language) UIUtil(com.intellij.util.ui.UIUtil) TreeUtil(com.intellij.util.ui.tree.TreeUtil) PostfixTemplate(com.intellij.codeInsight.template.postfix.templates.PostfixTemplate) TreePath(javax.swing.tree.TreePath) Enumeration(java.util.Enumeration) StringUtil(com.intellij.openapi.util.text.StringUtil) Collection(java.util.Collection) TreeState(com.intellij.ide.util.treeView.TreeState) Set(java.util.Set) ContainerUtil(com.intellij.util.containers.ContainerUtil) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent) java.awt(java.awt) TreeSelectionListener(javax.swing.event.TreeSelectionListener) Map(java.util.Map) SimpleTextAttributes(com.intellij.ui.SimpleTextAttributes) NotNull(org.jetbrains.annotations.NotNull) MultiMap(com.intellij.util.containers.MultiMap) CheckboxTree(com.intellij.ui.CheckboxTree) CheckedTreeNode(com.intellij.ui.CheckedTreeNode) JBColor(com.intellij.ui.JBColor) Consumer(com.intellij.util.Consumer) javax.swing(javax.swing) DefaultTreeModel(javax.swing.tree.DefaultTreeModel) TreeState(com.intellij.ide.util.treeView.TreeState) Set(java.util.Set)

Aggregations

Consumer (com.intellij.util.Consumer)59 NotNull (org.jetbrains.annotations.NotNull)41 Project (com.intellij.openapi.project.Project)37 Nullable (org.jetbrains.annotations.Nullable)33 VirtualFile (com.intellij.openapi.vfs.VirtualFile)26 List (java.util.List)22 ApplicationManager (com.intellij.openapi.application.ApplicationManager)17 StringUtil (com.intellij.openapi.util.text.StringUtil)17 javax.swing (javax.swing)16 ContainerUtil (com.intellij.util.containers.ContainerUtil)15 Logger (com.intellij.openapi.diagnostic.Logger)14 Module (com.intellij.openapi.module.Module)12 java.awt (java.awt)12 Pair (com.intellij.openapi.util.Pair)11 java.util (java.util)11 File (java.io.File)10 Collection (java.util.Collection)10 PsiElement (com.intellij.psi.PsiElement)9 PsiFile (com.intellij.psi.PsiFile)9 DataContext (com.intellij.openapi.actionSystem.DataContext)8