Java Code Examples for com.intellij.openapi.util.io.FileUtil#ensureExists()

The following examples show how to use com.intellij.openapi.util.io.FileUtil#ensureExists() . 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: ExternalSystemTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@NotNull
protected VirtualFile createProjectJarSubFile(String relativePath, Pair<ByteArraySequence, String>... contentEntries) throws IOException {
  assertTrue("Use 'jar' extension for JAR files: '" + relativePath + "'", FileUtilRt.extensionEquals(relativePath, "jar"));
  File f = new File(getProjectPath(), relativePath);
  FileUtil.ensureExists(f.getParentFile());
  FileUtil.ensureCanCreateFile(f);
  final boolean created = f.createNewFile();
  if (!created) {
    throw new AssertionError("Unable to create the project sub file: " + f.getAbsolutePath());
  }

  Manifest manifest = new Manifest();
  manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
  JarOutputStream target = new JarOutputStream(new FileOutputStream(f), manifest);
  for (Pair<ByteArraySequence, String> contentEntry : contentEntries) {
    addJarEntry(contentEntry.first.getBytes(), contentEntry.second, target);
  }
  target.close();

  final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f);
  assertNotNull(virtualFile);
  final VirtualFile jarFile = JarFileSystem.getInstance().getJarRootForLocalFile(virtualFile);
  assertNotNull(jarFile);
  return jarFile;
}
 
Example 2
Source File: ExternalSystemTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
  super.setUp();
  ensureTempDirCreated();

  myTestDir = new File(ourTempDir, getTestName(false));
  FileUtil.ensureExists(myTestDir);

  setUpFixtures();
  myProject = myTestFixture.getProject();

  EdtTestUtil.runInEdtAndWait(() -> ApplicationManager.getApplication().runWriteAction(() -> {
    try {
      setUpInWriteAction();
    }
    catch (Throwable e) {
      try {
        tearDown();
      }
      catch (Exception e1) {
        e1.printStackTrace();
      }
      throw new RuntimeException(e);
    }
  }));

  List<String> allowedRoots = new ArrayList<>();
  collectAllowedRoots(allowedRoots);
  if (!allowedRoots.isEmpty()) {
    VfsRootAccess.allowRootAccess(myTestFixture.getTestRootDisposable(), ArrayUtil.toStringArray(allowedRoots));
  }
}
 
Example 3
Source File: ExternalSystemTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
protected VirtualFile createProjectSubFile(String relativePath) throws IOException {
  File f = new File(getProjectPath(), relativePath);
  FileUtil.ensureExists(f.getParentFile());
  FileUtil.ensureCanCreateFile(f);
  final boolean created = f.createNewFile();
  if (!created && !f.exists()) {
    throw new AssertionError("Unable to create the project sub file: " + f.getAbsolutePath());
  }
  return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f);
}
 
Example 4
Source File: MavenTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();

  ensureTempDirCreated();

  myDir = new File(ourTempDir, getTestName(false));
  FileUtil.ensureExists(myDir);

  setUpFixtures();

  myProject = myTestFixture.getProject();

  MavenWorkspaceSettingsComponent.getInstance(myProject).loadState(new MavenWorkspaceSettings());

  String home = getTestMavenHome();
  if (home != null) {
    getMavenGeneralSettings().setMavenHome(home);
  }

  EdtTestUtil.runInEdtAndWait(() -> {
    restoreSettingsFile();

    ApplicationManager.getApplication().runWriteAction(() -> {
      try {
        setUpInWriteAction();
      }
      catch (Throwable e) {
        try {
          tearDown();
        }
        catch (Exception e1) {
          e1.printStackTrace();
        }
        throw new RuntimeException(e);
      }
    });
  });
}
 
Example 5
Source File: VMOptions.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void writeGeneralOption(@Nonnull Pattern pattern, @Nonnull String value) {
  File file = getWriteFile();
  if (file == null) {
    LOG.warn("VM options file not configured");
    return;
  }

  try {
    String content = file.exists() ? FileUtil.loadFile(file) : read();

    if (!StringUtil.isEmptyOrSpaces(content)) {
      Matcher m = pattern.matcher(content);
      if (m.find()) {
        StringBuffer b = new StringBuffer();
        m.appendReplacement(b, Matcher.quoteReplacement(value));
        m.appendTail(b);
        content = b.toString();
      }
      else {
        content = StringUtil.trimTrailing(content) + SystemProperties.getLineSeparator() + value;
      }
    }
    else {
      content = value;
    }

    if (file.exists()) {
      FileUtil.setReadOnlyAttribute(file.getPath(), false);
    }
    else {
      FileUtil.ensureExists(file.getParentFile());
    }

    FileUtil.writeToFile(file, content);
  }
  catch (IOException e) {
    LOG.warn(e);
  }
}
 
Example 6
Source File: NewOrImportModuleUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@RequiredUIAccess
public static <T extends ModuleImportContext> AsyncResult<Project> importProject(@Nonnull T context, @Nonnull ModuleImportProvider<T> importProvider) {
  final ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
  final String projectFilePath = context.getPath();
  String projectName = context.getName();

  try {
    File projectDir = new File(projectFilePath);
    FileUtil.ensureExists(projectDir);
    File projectConfigDir = new File(projectDir, Project.DIRECTORY_STORE_FOLDER);
    FileUtil.ensureExists(projectConfigDir);

    final Project newProject = projectManager.createProject(projectName, projectFilePath);

    if (newProject == null) return AsyncResult.rejected();

    newProject.save();

    ModifiableModuleModel modifiableModel = ModuleManager.getInstance(newProject).getModifiableModel();

    importProvider.process(context, newProject, modifiableModel, module -> {
    });

    WriteAction.runAndWait(modifiableModel::commit);

    newProject.save();

    context.dispose();

    return AsyncResult.resolved(newProject);
  }
  catch (Exception e) {
    context.dispose();

    return AsyncResult.<Project>undefined().rejectWithThrowable(e);
  }
}
 
Example 7
Source File: ExternalSystemTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
protected void setUpInWriteAction() throws Exception {
  File projectDir = new File(myTestDir, "project");
  FileUtil.ensureExists(projectDir);
  myProjectRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectDir);
}
 
Example 8
Source File: ExternalSystemTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
protected VirtualFile createProjectSubDir(String relativePath) throws IOException {
  File f = new File(getProjectPath(), relativePath);
  FileUtil.ensureExists(f);
  return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f);
}
 
Example 9
Source File: AbstractModelBuilderTest.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  assumeThat(gradleVersion, versionMatcherRule.getMatcher());

  ensureTempDirCreated();

  String methodName = name.getMethodName();
  Matcher m = TEST_METHOD_NAME_PATTERN.matcher(methodName);
  if (m.matches()) {
    methodName = m.group(1);
  }

  testDir = new File(ourTempDir, methodName);
  FileUtil.ensureExists(testDir);

  final InputStream buildScriptStream = getClass().getResourceAsStream("/" + methodName + "/" + GradleConstants.DEFAULT_SCRIPT_NAME);
  try {
    FileUtil.writeToFile(
      new File(testDir, GradleConstants.DEFAULT_SCRIPT_NAME),
      FileUtil.loadTextAndClose(buildScriptStream)
    );
  }
  finally {
    StreamUtil.closeStream(buildScriptStream);
  }

  final InputStream settingsStream = getClass().getResourceAsStream("/" + methodName + "/" + GradleConstants.SETTINGS_FILE_NAME);
  try {
    if(settingsStream != null) {
      FileUtil.writeToFile(
        new File(testDir, GradleConstants.SETTINGS_FILE_NAME),
        FileUtil.loadTextAndClose(settingsStream)
      );
    }
  } finally {
    StreamUtil.closeStream(settingsStream);
  }

  GradleConnector connector = GradleConnector.newConnector();

  GradleVersion _gradleVersion = GradleVersion.version(gradleVersion);
  final URI distributionUri = new DistributionLocator().getDistributionFor(_gradleVersion);
  connector.useDistribution(distributionUri);
  connector.forProjectDirectory(testDir);
  int daemonMaxIdleTime = 10;
  try {
    daemonMaxIdleTime = Integer.parseInt(System.getProperty("gradleDaemonMaxIdleTime", "10"));
  }
  catch (NumberFormatException ignore) {}

  ((DefaultGradleConnector)connector).daemonMaxIdleTime(daemonMaxIdleTime, TimeUnit.SECONDS);
  ProjectConnection connection = connector.connect();

  try {
    boolean isGradleProjectDirSupported = _gradleVersion.compareTo(GradleVersion.version("2.4")) >= 0;
    boolean isCompositeBuildsSupported = isGradleProjectDirSupported && _gradleVersion.compareTo(GradleVersion.version("3.1")) >= 0;
    final ProjectImportAction projectImportAction = new ProjectImportAction(false, isGradleProjectDirSupported,
                                                                            isCompositeBuildsSupported);
    projectImportAction.addProjectImportExtraModelProvider(new ClassSetProjectImportExtraModelProvider(getModels()));
    BuildActionExecuter<ProjectImportAction.AllModels> buildActionExecutor = connection.action(projectImportAction);
    File initScript = GradleExecutionHelper.generateInitScript(false, getToolingExtensionClasses());
    assertNotNull(initScript);
    String jdkHome = IdeaTestUtil.requireRealJdkHome();
    buildActionExecutor.setJavaHome(new File(jdkHome));
    buildActionExecutor.setJvmArguments("-Xmx128m", "-XX:MaxPermSize=64m");
    buildActionExecutor.withArguments("--info", GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath());
    allModels = buildActionExecutor.run();
    assertNotNull(allModels);
  } finally {
    connection.close();
  }
}
 
Example 10
Source File: BlazeProjectCreator.java    From intellij with Apache License 2.0 4 votes vote down vote up
private void doCreate() throws IOException {
  String projectFilePath = wizardContext.getProjectFileDirectory();

  File projectDir = new File(projectFilePath).getParentFile();
  logger.assertTrue(
      projectDir != null,
      "Cannot create project in '" + projectFilePath + "': no parent file exists");
  FileUtil.ensureExists(projectDir);
  if (wizardContext.getProjectStorageFormat() == StorageScheme.DIRECTORY_BASED) {
    final File ideaDir = new File(projectFilePath, Project.DIRECTORY_STORE_FOLDER);
    FileUtil.ensureExists(ideaDir);
  }

  String name = wizardContext.getProjectName();
  Project newProject = projectBuilder.createProject(name, projectFilePath);
  if (newProject == null) {
    return;
  }

  if (!ApplicationManager.getApplication().isUnitTestMode()) {
    newProject.save();
  }

  if (!projectBuilder.validate(null, newProject)) {
    return;
  }

  projectBuilder.commit(newProject, null, ModulesProvider.EMPTY_MODULES_PROVIDER);

  StartupManager.getInstance(newProject)
      .registerPostStartupActivity(
          () -> {
            // ensure the dialog is shown after all startup activities are done
            //noinspection SSBasedInspection
            SwingUtilities.invokeLater(
                () -> {
                  if (newProject.isDisposed()
                      || ApplicationManager.getApplication().isUnitTestMode()) {
                    return;
                  }
                  ApplicationManager.getApplication()
                      .invokeLater(
                          () -> {
                            if (newProject.isDisposed()) {
                              return;
                            }
                            final ToolWindow toolWindow =
                                ToolWindowManager.getInstance(newProject)
                                    .getToolWindow(ToolWindowId.PROJECT_VIEW);
                            if (toolWindow != null) {
                              toolWindow.activate(null);
                            }
                          },
                          ModalityState.NON_MODAL);
                });
          });

  ProjectUtil.updateLastProjectLocation(projectFilePath);

  if (WindowManager.getInstance().isFullScreenSupportedInCurrentOS()) {
    IdeFocusManager instance = IdeFocusManager.findInstance();
    IdeFrame lastFocusedFrame = instance.getLastFocusedFrame();
    if (lastFocusedFrame instanceof IdeFrameEx) {
      boolean fullScreen = ((IdeFrameEx) lastFocusedFrame).isInFullScreen();
      if (fullScreen) {
        newProject.putUserData(IdeFrameImpl.SHOULD_OPEN_IN_FULL_SCREEN, Boolean.TRUE);
      }
    }
  }

  BaseSdkCompat.openProject(newProject, Paths.get(projectFilePath));

  if (!ApplicationManager.getApplication().isUnitTestMode()) {
    SaveAndSyncHandler.getInstance().scheduleProjectSave(newProject);
  }
}