com.intellij.openapi.command.WriteCommandAction Java Examples

The following examples show how to use com.intellij.openapi.command.WriteCommandAction. 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: CsvFormatterTest.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
/**
 * This function should be executed (remove the underscore) if the current results are correct (manual testing).
 *
 * @throws Exception
 */
public void _testResultGenerator() throws Exception {
    for (int binarySettings = 0; binarySettings < 128; ++binarySettings) {
        tearDown();
        setUp();

        myFixture.configureByFiles("/generated/TestData.csv");

        initCsvCodeStyleSettings(binarySettings);

        new WriteCommandAction.Simple(getProject()) {
            @Override
            protected void run() throws Throwable {
                CodeStyleManager.getInstance(getProject()).reformatText(myFixture.getFile(),
                        ContainerUtil.newArrayList(myFixture.getFile().getTextRange()));
            }
        }.execute();

        try (PrintWriter writer = new PrintWriter(getTestDataPath() + String.format("/generated/TestResult%08d.csv", binarySettings))
        ) {
            writer.print(myFixture.getFile().getText());
        }
    }
}
 
Example #2
Source File: CodeInsightTestUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void doIntentionTest(@Nonnull final CodeInsightTestFixture fixture, @NonNls final String action,
                                   @Nonnull final String before, @Nonnull final String after) {
  fixture.configureByFile(before);
  List<IntentionAction> availableIntentions = fixture.getAvailableIntentions();
  final IntentionAction intentionAction = findIntentionByText(availableIntentions, action);
  if (intentionAction == null) {
    Assert.fail("Action not found: " + action + " in place: " + fixture.getElementAtCaret() + " among " + availableIntentions);
  }
  new WriteCommandAction(fixture.getProject()) {
    @Override
    protected void run(Result result) throws Throwable {
      fixture.launchAction(intentionAction);
    }
  }.execute();
  fixture.checkResultByFile(after, false);
}
 
Example #3
Source File: FileDocumentManagerImplTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
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() {
      myDocumentManager.getDocument(file).insertString(0, "xxx");
    }
  });

  //noinspection UnusedAssignment
  document = null;

  System.gc();
  System.gc();

  document = myDocumentManager.getDocument(file);
  assertEquals(idCode, System.identityHashCode(document));
}
 
Example #4
Source File: OperatorCompletionAction.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    final Document document = editor.getDocument();
    CaretModel caretModel = editor.getCaretModel();
    final int offset = caretModel.getOffset();
    new PopupChooserBuilder(QUERY_OPERATOR_LIST)
            .setMovable(false)
            .setCancelKeyEnabled(true)
            .setItemChoosenCallback(new Runnable() {
                public void run() {
                    final String selectedQueryOperator = (String) QUERY_OPERATOR_LIST.getSelectedValue();
                    if (selectedQueryOperator == null) return;

                    new WriteCommandAction(project, MONGO_OPERATOR_COMPLETION) {
                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            document.insertString(offset, selectedQueryOperator);
                        }
                    }.execute();
                }
            })
            .createPopup()
            .showInBestPositionFor(editor);
}
 
Example #5
Source File: CommandCamelCaseInspection.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, PsiFile file, @Nullable Editor editor) {
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			SQFPsiCommand commandElement = commandPointer.getElement();
			if (commandElement == null) {
				return;
			}
			for (String command : SQFStatic.COMMANDS_SET) {
				if (command.equalsIgnoreCase(commandElement.getText())) {
					SQFPsiCommand c = PsiUtil.createElement(project, command, SQFFileType.INSTANCE, SQFPsiCommand.class);
					if (c == null) {
						return;
					}
					commandElement.replace(c);
					return;
				}
			}
			throw new IllegalStateException("command '" + commandElement.getText() + "' should have been matched");

		}
	};
	WriteCommandAction.runWriteCommandAction(project, runnable);
}
 
Example #6
Source File: EntityBase.java    From CleanArchitecturePlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Create package in the directory specific with a name
 *
 * @param parent      package when create a subpackage
 * @param packageName package name
 * @return
 */
public static PsiDirectory createDirectory(PsiDirectory parent, String packageName) {
    directoryCreated = null;

    // Search subpackage with the same name
    for (PsiDirectory dir : parent.getSubdirectories()) {
        if (dir.getName().equalsIgnoreCase(packageName)) {
            directoryCreated = dir;
            break;
        }
    }

    // When the search not found a package with the same name, create a subdirectory
    if (directoryCreated == null) {
        runnable = () -> directoryCreated = parent.createSubdirectory(packageName);
        WriteCommandAction.runWriteCommandAction(project, runnable);
    }
    return directoryCreated;
}
 
Example #7
Source File: PsiTestUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void addProjectLibrary(final Module module,
                                      final ModifiableRootModel model,
                                      final String libName,
                                      final VirtualFile... classesRoots) {
  new WriteCommandAction.Simple(module.getProject()) {
    @Override
    protected void run() throws Throwable {
      final LibraryTable libraryTable = ProjectLibraryTable.getInstance(module.getProject());
      final Library library = libraryTable.createLibrary(libName);
      final Library.ModifiableModel libraryModel = library.getModifiableModel();
      for (VirtualFile root : classesRoots) {
        libraryModel.addRoot(root, BinariesOrderRootType.getInstance());
      }
      libraryModel.commit();
      model.addLibraryEntry(library);
      final OrderEntry[] orderEntries = model.getOrderEntries();
      OrderEntry last = orderEntries[orderEntries.length - 1];
      System.arraycopy(orderEntries, 0, orderEntries, 1, orderEntries.length - 1);
      orderEntries[0] = last;
      model.rearrangeOrderEntries(orderEntries);
    }
  }.execute().throwException();
}
 
Example #8
Source File: Reverter.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void revert() throws IOException {
  try {
    new WriteCommandAction(myProject, getCommandName()) {
      @Override
      protected void run(Result objectResult) throws Throwable {
        myGateway.saveAllUnsavedDocuments();
        doRevert();
        myGateway.saveAllUnsavedDocuments();
      }
    }.execute();
  }
  catch (RuntimeException e) {
    Throwable cause = e.getCause();
    if (cause instanceof IOException) {
      throw (IOException)cause;
    }
    throw e;
  }
}
 
Example #9
Source File: ActionGenerator.java    From nopol with GNU General Public License v2.0 6 votes vote down vote up
private void buildModule() {
	try {
		copyFileFromResources("/toy-project/src/NopolExample.java", this.BASE_PATH_TOY_PROJECT + "/src/nopol_example/NopolExample.java");
		copyFileFromResources("/toy-project/test/NopolExampleTest.java", this.BASE_PATH_TOY_PROJECT + "/test/nopol_example/NopolExampleTest.java");
		copyFileFromResources("/toy-project/pom.xml", this.BASE_PATH_TOY_PROJECT + "/pom.xml");
	} catch (IOException e) {
		e.printStackTrace();
	}

	WriteCommandAction.runWriteCommandAction(project, () -> {
		try {
			ModuleManager.getInstance(project).loadModule(this.BASE_PATH_TOY_PROJECT + "/toy-project.iml");
			project.getBaseDir().refresh(false, true);
		} catch (Exception ignored) {
			ignored.printStackTrace();
		}
	});
}
 
Example #10
Source File: TypeStateCheckingTest.java    From IntelliJDeodorant with MIT License 6 votes vote down vote up
private void performMultipleRefactoringsTest(List<Integer> eliminationGroupSizes) {
    initTest();
    eliminationGroupSizes = new ArrayList<>(eliminationGroupSizes);
    Project project = myFixture.getProject();
    while (eliminationGroupSizes.size() != 0) {
        Set<TypeCheckEliminationGroup> eliminationGroups =
                JDeodorantFacade.getTypeCheckEliminationRefactoringOpportunities(
                        new ProjectInfo(new AnalysisScope(project), false),
                        fakeProgressIndicator
                );
        assertEquals(eliminationGroupSizes.size(), eliminationGroups.size());
        TypeCheckEliminationGroup eliminationGroup = eliminationGroups.iterator().next();
        assertEquals(eliminationGroupSizes.get(0).intValue(), eliminationGroup.getCandidates().size());
        WriteCommandAction.runWriteCommandAction(
                project,
                () -> createRefactoring(eliminationGroup.getCandidates().get(0), project).apply()
        );

        if (eliminationGroupSizes.get(0) == 1) {
            eliminationGroupSizes.remove(0);
        } else {
            eliminationGroupSizes.set(0, eliminationGroupSizes.get(0) - 1);
        }
    }
    checkTest();
}
 
Example #11
Source File: FlutterProjectCreator.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static boolean finalValidityCheckPassed(@NotNull String projectLocation) {
  // See AS NewProjectModel.ProjectTemplateRenderer.doDryRun() for why this is necessary.
  boolean couldEnsureLocationExists = WriteCommandAction.runWriteCommandAction(null, (Computable<Boolean>)() -> {
    try {
      if (VfsUtil.createDirectoryIfMissing(projectLocation) != null && FileOpUtils.create().canWrite(new File(projectLocation))) {
        return true;
      }
    }
    catch (Exception e) {
      LOG.warn(String.format("Exception thrown when creating target project location: %1$s", projectLocation), e);
    }
    return false;
  });
  if (!couldEnsureLocationExists) {
    String msg =
      "Could not ensure the target project location exists and is accessible:\n\n%1$s\n\nPlease try to specify another path.";
    Messages.showErrorDialog(String.format(msg, projectLocation), "Error Creating Project");
    return false;
  }
  return true;
}
 
Example #12
Source File: CrudUtils.java    From crud-intellij-plugin with Apache License 2.0 6 votes vote down vote up
public static void doOptimize(Project project) {
    DumbService.getInstance(project).runWhenSmart((DumbAwareRunnable) () -> new WriteCommandAction(project) {
        @Override
        protected void run(@NotNull Result result) {
            for (VirtualFile virtualFile : virtualFiles) {
                try {
                    PsiJavaFile javaFile = (PsiJavaFile) PsiManager.getInstance(project).findFile(virtualFile);
                    if (javaFile != null) {
                        CodeStyleManager.getInstance(project).reformat(javaFile);
                        JavaCodeStyleManager.getInstance(project).optimizeImports(javaFile);
                        JavaCodeStyleManager.getInstance(project).shortenClassReferences(javaFile);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            virtualFiles.clear();
        }
    }.execute());
}
 
Example #13
Source File: XLFFileTypeListener.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@Override
public void projectOpened(@NotNull Project project) {
    if (!(FileTypeManager.getInstance().getFileTypeByExtension("xlf") instanceof XmlFileType)) {
        WriteCommandAction.runWriteCommandAction(ProjectManager.getInstance().getOpenProjects()[0], () -> {
            FileTypeManager.getInstance().associateExtension(XmlFileType.INSTANCE, "xlf");

            ApplicationManager.getApplication().invokeLater(() -> {
                Notification notification = GROUP_DISPLAY_ID_INFO.createNotification(
                    "TYPO3 CMS Plugin",
                    "XLF File Type Association",
                    "The XLF File Type was re-assigned to XML to prevent errors with the XLIFF Plugin and allow autocompletion. Please re-index your projects.",
                    NotificationType.INFORMATION
                );
                Project[] projects = ProjectManager.getInstance().getOpenProjects();
                Notifications.Bus.notify(notification, projects[0]);
            });
        });
    }
}
 
Example #14
Source File: ORJsLibraryManager.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
private void runActivityLater(Project project) {
    LOG.info("run Js library manager");

    Optional<VirtualFile> bsConfigFileOptional = ORProjectManager.findFirstBsConfigurationFile(project);
    if (bsConfigFileOptional.isPresent()) {
        VirtualFile bsConfigFile = bsConfigFileOptional.get();
        LOG.debug("bucklescript config file", bsConfigFile);

        String baseDir = "file://" + bsConfigFile.getParent().getPath() + "/node_modules/";
        List<VirtualFile> sources = new ArrayList<>(readBsConfigDependencies(project, baseDir, bsConfigFile));

        JSLibraryManager jsLibraryManager = JSLibraryManager.getInstance(project);

        ScriptingLibraryModel bucklescriptModel = jsLibraryManager.getLibraryByName(LIB_NAME);
        if (bucklescriptModel == null) {
            LOG.debug("Creating js library", LIB_NAME);
            jsLibraryManager.createLibrary(LIB_NAME, sources.toArray(new VirtualFile[0]), EMPTY_ARRAY, EMPTY_STRING_ARRAY, PROJECT, true);
        } else {
            LOG.debug("Updating js library", LIB_NAME);
            jsLibraryManager.updateLibrary(LIB_NAME, LIB_NAME, sources.toArray(new VirtualFile[0]), EMPTY_ARRAY, EMPTY_STRING_ARRAY);
        }

        WriteCommandAction.runWriteCommandAction(project, (Runnable) jsLibraryManager::commitChanges);
    }
}
 
Example #15
Source File: JavaBuilder.java    From OkHttpParamsGet with Apache License 2.0 6 votes vote down vote up
@Override
public void build(PsiFile psiFile, Project project1, Editor editor) {
    if (psiFile == null) return;
    WriteCommandAction.runWriteCommandAction(project1, () -> {
        if (editor == null) return;
        Project project = editor.getProject();
        if (project == null) return;
        PsiElement mouse = psiFile.findElementAt(editor.getCaretModel().getOffset());
        PsiClass psiClass = PsiTreeUtil.getParentOfType(mouse, PsiClass.class);
        if (psiClass == null) return;

        if (psiClass.getNameIdentifier() == null) return;
        String className = psiClass.getNameIdentifier().getText();

        PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);

        build(editor, mouse, elementFactory, project, psiClass, psiFile, className);

        JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
        styleManager.optimizeImports(psiFile);
        styleManager.shortenClassReferences(psiClass);

    });
}
 
Example #16
Source File: CodeInsightTestFixtureImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected PsiFile addFileToProject(final String rootPath, final String relativePath, final String fileText) {
  return new WriteCommandAction<PsiFile>(getProject()) {
    @Override
    protected void run(Result<PsiFile> result) throws Throwable {
      try {
        if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) {
          final VirtualFile file = myTempDirFixture.createFile(relativePath, fileText);
          result.setResult(PsiManager.getInstance(getProject()).findFile(file));
        }
        else {
          result.setResult(((HeavyIdeaTestFixture)myProjectFixture).addFileToProject(rootPath, relativePath, fileText));
        }
      }
      catch (IOException e) {
        throw new RuntimeException(e);
      }
      finally {
        ((PsiModificationTrackerImpl)PsiManager.getInstance(getProject()).getModificationTracker()).incCounter();
      }
    }
  }.execute().getResultObject();
}
 
Example #17
Source File: OpenSampleAction.java    From mule-intellij-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    logger.debug("Loading sample!");

    final Project project = anActionEvent.getProject();
    final PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE);

    VirtualFile sample = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
            project, null);
    if (sample == null)
        return;

    try {
        final String text = new String(sample.contentsToByteArray(), sample.getCharset());

        new WriteCommandAction.Simple(project, psiFile) {
            @Override
            protected void run() throws Throwable {
                document.setText(text);
            }
        }.execute();
    } catch (Exception e) {
        logger.error(e);
    }

}
 
Example #18
Source File: HaxeLiveTemplatesTest.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
private void doTest(String... files) throws Exception {
  myFixture.configureByFiles(files);
  if (IdeaTarget.IS_VERSION_17_COMPATIBLE) {
    // The implementation of finishLookup in IDEA 2017 requires that it run OUTSIDE of a write command,
    // while previous versions require that is run inside of one.
    expandTemplate(myFixture.getEditor());
  }
  WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
    @Override
    public void run() {
      if (!IdeaTarget.IS_VERSION_17_COMPATIBLE) {
        expandTemplate(myFixture.getEditor());
      }
      CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
    }
  });
  myFixture.getEditor().getSelectionModel().removeSelection();
  myFixture.checkResultByFile(getTestName(false) + "_after.hx");
}
 
Example #19
Source File: ExceptionTest.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testError526() {
  //TODO disable assertions for the moment
  RecursionManager.disableMissedCacheAssertions(myFixture.getProjectDisposable());

  PsiFile psiFile = loadToPsiFile(getTestName(false) + ".java");
  assertNotNull(psiFile);

  PsiClass psiClass = PsiTreeUtil.getParentOfType(psiFile.findElementAt(myFixture.getCaretOffset()), PsiClass.class);
  assertNotNull(psiClass);

  // call augmentprovider first time
  final PsiMethod[] psiClassMethods = psiClass.getMethods();
  assertEquals(8, psiClassMethods.length);

  // change something to trigger cache drop
  WriteCommandAction.writeCommandAction(getProject(), psiFile).compute(() ->
    {
      psiClass.getModifierList().addAnnotation("java.lang.SuppressWarnings");
      return true;
    }
  );

  // call augment provider second time
  final PsiMethod[] psiClassMethods2 = psiClass.getMethods();
  assertArrayEquals(psiClassMethods, psiClassMethods2);
}
 
Example #20
Source File: MuleDomainMavenProjectBuilderHelper.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
private VirtualFile createMuleDeployPropertiesFile(final Project project, final MavenId projectId, final VirtualFile appDirectory)
{
    return new WriteCommandAction<VirtualFile>(project, "Create Mule Deploy Properties File", PsiFile.EMPTY_ARRAY)
    {
        @Override
        protected void run(@NotNull Result<VirtualFile> result) throws Throwable
        {

            try
            {
                VirtualFile configFile = appDirectory.findOrCreateChildData(this, "mule-deploy.properties");
                final Properties templateProps = new Properties();
                templateProps.setProperty("NAME", projectId.getArtifactId());
                final FileTemplateManager manager = FileTemplateManager.getInstance(project);
                final FileTemplate template = manager.getInternalTemplate(MuleFileTemplateDescriptorManager.MULE_DOMAIN_DEPLOY_PROPERTIES);
                final Properties defaultProperties = manager.getDefaultProperties();
                defaultProperties.putAll(templateProps);
                final String text = template.getText(defaultProperties);
                VfsUtil.saveText(configFile, text);
                result.setResult(configFile);
            }
            catch (IOException e)
            {
                showError(project, e);
            }
        }
    }.execute().getResultObject();
}
 
Example #21
Source File: VcsTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void moveFileInCommand(@Nonnull Project project, @Nonnull final VirtualFile file, @Nonnull final VirtualFile newParent) {
  new WriteCommandAction.Simple(project) {
    @Override
    protected void run() throws Throwable {
      try {
        file.move(this, newParent);
      }
      catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }.execute();
}
 
Example #22
Source File: DefaultProviderImpl.java    From CodeGen with MIT License 5 votes vote down vote up
@Override
public void create(CodeTemplate template, CodeContext context, Map<String, Object> extraMap){

    VelocityContext velocityContext = new VelocityContext(BuilderUtil.transBean2Map(context));
    velocityContext.put("serialVersionUID", BuilderUtil.computeDefaultSUID(context.getModel(), context.getFields()));
    // $!dateFormatUtils.format($!now,'yyyy-MM-dd')
    velocityContext.put("dateFormatUtils", new org.apache.commons.lang.time.DateFormatUtils());
    if (extraMap != null && extraMap.size() > 0) {
        for (Map.Entry<String, Object> entry: extraMap.entrySet()) {
            velocityContext.put(entry.getKey(), entry.getValue());
        }
    }

    String fileName = VelocityUtil.evaluate(velocityContext, template.getFilename());
    String subPath = VelocityUtil.evaluate(velocityContext, template.getSubPath());
    String temp = VelocityUtil.evaluate(velocityContext, template.getTemplate());

    WriteCommandAction.runWriteCommandAction(this.project, () -> {
        try {
            VirtualFile vFile = VfsUtil.createDirectoryIfMissing(outputPath);
            PsiDirectory psiDirectory = PsiDirectoryFactory.getInstance(this.project).createDirectory(vFile);
            PsiDirectory directory = subDirectory(psiDirectory, subPath, template.getResources());
            // TODO: 这里干啥用的, 没用的话是不是可以删除了
            if (JavaFileType.INSTANCE == this.languageFileType) {
                PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory);
                if (psiPackage != null && !StringUtils.isEmpty(psiPackage.getQualifiedName())) {
                    extraMap.put(fileName, new StringBuilder(psiPackage.getQualifiedName()).append(".").append(fileName));
                }
            }
            createFile(project, directory, fileName + "." + this.languageFileType.getDefaultExtension(), temp, this.languageFileType);
        } catch (Exception e) {
            LOGGER.error(StringUtils.getStackTraceAsString(e));
        }
    });
}
 
Example #23
Source File: HaxeFormatterTest.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private void doTest() throws Exception {
  myFixture.configureByFile(getTestName(false) + ".hx");
    /*CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        @Override
        public void run() {
            CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());

        }
    }, null, null);*/
  WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
    @Override
    public void run() {
      CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
    }
  });
  try {
    myFixture.checkResultByFile(getTestName(false) + ".txt");
  }
  catch (RuntimeException e) {
    if (!(e.getCause() instanceof FileNotFoundException)) {
      throw e;
    }
    final String path = getTestDataPath() + getTestName(false) + ".txt";
    FileWriter writer = new FileWriter(FileUtil.toSystemDependentName(path));
    try {
      writer.write(myFixture.getFile().getText().trim());
    }
    finally {
      writer.close();
    }
    fail("No output text found. File " + path + " created.");
  }
}
 
Example #24
Source File: SurroundWithHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  new WriteCommandAction(myProject) {
    @Override
    protected void run(@Nonnull Result result) throws Exception {
      doSurround(myProject, myEditor, mySurrounder, myElements);
    }
  }.execute();
}
 
Example #25
Source File: DecompileAndAttachAction.java    From decompile-and-attach with MIT License 5 votes vote down vote up
private void attach(final Project project, final VirtualFile sourceVF, File resultJar) {
    ApplicationManager.getApplication().invokeAndWait(() -> {
        VirtualFile resultJarVF = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(resultJar);
        checkNotNull(resultJarVF, "could not find Virtual File of %s", resultJar.getAbsolutePath());
        VirtualFile resultJarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(resultJarVF);
        VirtualFile[] roots = PathUIUtils.scanAndSelectDetectedJavaSourceRoots(null,
                new VirtualFile[] {resultJarRoot});
        new WriteCommandAction<Void>(project) {

            @Override
            protected void run(@NotNull Result<Void> result) throws Throwable {
                final Module currentModule = ProjectRootManager.getInstance(project).getFileIndex()
                        .getModuleForFile(sourceVF, false);

                checkNotNull(currentModule, "could not find current module");
                Optional<Library> moduleLib = findModuleDependency(currentModule, sourceVF);
                checkState(moduleLib.isPresent(), "could not find library in module dependencies");
                Library.ModifiableModel model = moduleLib.get().getModifiableModel();
                for (VirtualFile root : roots) {
                    model.addRoot(root, OrderRootType.SOURCES);
                }
                model.commit();

                new Notification("DecompileAndAttach", "Jar Sources Added", "decompiled sources " + resultJar.getName()
                        + " where added successfully to dependency of a module '" + currentModule.getName() + "'",
                        INFORMATION).notify(project);
            }
        }.execute();
    } , ModalityState.NON_MODAL);
}
 
Example #26
Source File: GenerateSqlXmlIntention.java    From NutzCodeInsight with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException {
    PsiDirectory psiDirectory = psiFile.getContainingDirectory();
    WriteCommandAction.runWriteCommandAction(project, () -> {
        try {
            Properties properties = new Properties();
            properties.setProperty("CLASSNAME", clazz);
            PsiElement element = TemplateFileUtil.createFromTemplate(SqlTplFileTemplateGroupFactory.NUTZ_SQL_TPL_XML, templateFileName, properties, psiDirectory);
            NavigationUtil.activateFileWithPsiElement(element, true);
        } catch (Exception e) {
            HintManager.getInstance().showErrorHint(editor, "Failed: " + e.getLocalizedMessage());
        }
    });
}
 
Example #27
Source File: CodeInsightTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void doSurroundWithTest(@Nonnull final CodeInsightTestFixture fixture, @Nonnull final Surrounder surrounder,
                                      @Nonnull final String before, @Nonnull final String after) {
  fixture.configureByFile(before);
  new WriteCommandAction.Simple(fixture.getProject()) {
    @Override
    protected void run() throws Throwable {
      SurroundWithHandler.invoke(fixture.getProject(), fixture.getEditor(), fixture.getFile(), surrounder);
    }
  }.execute();
  fixture.checkResultByFile(after, false);
}
 
Example #28
Source File: DecryptPropertyAction.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    final Project project = (Project) anActionEvent.getData(CommonDataKeys.PROJECT);

    PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE);

    IProperty selectedProperty = getSelectedProperty(anActionEvent.getDataContext());

    final EncryptDialog form = new EncryptDialog();
    form.setTitle("Decrypt Property: " + selectedProperty.getKey());
    form.show();
    boolean isOk = form.getExitCode() == DialogWrapper.OK_EXIT_CODE;

    logger.debug("**** ALGORITHM " + form.getAlgorithm().getSelectedItem());
    logger.debug("**** MODE " + form.getMode().getSelectedItem());

    if (isOk) {
        new WriteCommandAction.Simple(project, psiFile) {
            @Override
            protected void run() throws Throwable {
                EncryptionAlgorithm algorithm = (EncryptionAlgorithm) form.getAlgorithm().getSelectedItem();
                EncryptionMode mode = (EncryptionMode) form.getMode().getSelectedItem();

                try {
                    String originalValue = selectedProperty.getValue();
                    String encryptedProperty = originalValue.substring(2, originalValue.length() - 1);

                    byte[] decryptedBytes = algorithm.getBuilder().forKey(form.getEncryptionKey().getText()).using(mode)
                            .build().decrypt(Base64.decode(encryptedProperty));

                    selectedProperty.setValue(new String(decryptedBytes));
                } catch (Exception e) {
                    Notification notification = MuleUIUtils.MULE_NOTIFICATION_GROUP.createNotification("Unable to decrypt property",
                            "Property '" + selectedProperty.getKey() + "' cannot be decrypted : " + e, NotificationType.ERROR, null);
                    Notifications.Bus.notify(notification, project);
                }
            }
        }.execute();
    }
}
 
Example #29
Source File: ParcelablePleaseAction.java    From ParcelablePlease with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(AnActionEvent e) {

    final PsiClass psiClass = getPsiClassFromContext(e);

    // Generate Code
    new WriteCommandAction.Simple(psiClass.getProject(), psiClass.getContainingFile()) {
      @Override
      protected void run() throws Throwable {
        new CodeGenerator(psiClass).generate();
      }
    }.execute();
  }
 
Example #30
Source File: PsiTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void commitModel(final ModifiableRootModel model) {
  new WriteCommandAction.Simple(model.getProject()) {
    @Override
    protected void run() throws Throwable {
      model.commit();
    }
  }.execute().throwException();
}