Java Code Examples for com.intellij.openapi.vfs.VirtualFile#setBinaryContent()

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#setBinaryContent() . 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: ApplyBinaryShelvedFilePatch.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected Result applyChange(Project project, final VirtualFile fileToPatch, FilePath pathBeforeRename, Getter<CharSequence> baseContents)
        throws IOException {
  try {
    ContentRevision contentRevision = myPatch.getShelvedBinaryFile().createChange(project).getAfterRevision();
    if (contentRevision != null) {
      assert (contentRevision instanceof ShelvedBinaryContentRevision);
      byte[] binaryContent = ((ShelvedBinaryContentRevision)contentRevision).getBinaryContent();
      //it may be new empty binary file
      fileToPatch.setBinaryContent(binaryContent != null ? binaryContent : ArrayUtil.EMPTY_BYTE_ARRAY);
    }
  }
  catch (VcsException e) {
    LOG.error("Couldn't apply shelved binary patch", e);
    return new Result(ApplyPatchStatus.FAILURE) {

      @Override
      public ApplyPatchForBaseRevisionTexts getMergeData() {
        return null;
      }
    };
  }
  return SUCCESS;
}
 
Example 2
Source File: DifferenceReverterTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testParentAndChildRename() throws Exception {
  VirtualFile dir = myRoot.createChildDirectory(this, "dir");
  VirtualFile f = dir.createChildData(this, "foo.txt");
  f.setBinaryContent(new byte[]{123}, -1, 4000);

  getVcs().beginChangeSet();
  dir.rename(this, "dir2");
  f.rename(this, "bar.txt");
  getVcs().endChangeSet(null);

  revertLastChange();

  assertNull(myRoot.findChild("dir2"));
  dir = myRoot.findChild("dir");

  assertNull(dir.findChild("bar.txt"));
  f = dir.findChild("foo.txt");
  assertNotNull(f);
  assertEquals(123, f.contentsToByteArray()[0]);
  assertEquals(4000, f.getTimeStamp());
}
 
Example 3
Source File: PsiFileUtils.java    From crud-intellij-plugin with Apache License 2.0 6 votes vote down vote up
private static void createDao(Project project, VirtualFile packageDir, Dao dao) {
	try {
		VirtualFile virtualFile = packageDir.createChildData(project, dao.getSimpleName() + ".java");
		StringWriter sw = new StringWriter();
		String templateName;
		if (dao.getOrmType() == SelectionContext.MYBATIS) {
			templateName = "dao_mybatis.ftl";
		} else {
			templateName = "dao_jpa.ftl";
		}
		Template template = freemarker.getTemplate(templateName);
		template.process(dao, sw);
		virtualFile.setBinaryContent(sw.toString().getBytes(CrudUtils.DEFAULT_CHARSET));

		CrudUtils.addWaitOptimizeFile(virtualFile);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 4
Source File: FileDocumentManagerImplTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testContentChanged_DoNotReloadChangedDocument() throws Exception {
  final VirtualFile file = createFile();
  final Document document = myDocumentManager.getDocument(file);
  assertNotNull(file.toString(), document);
  WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
    @Override
    public void run() {
      document.insertString(0, "old ");
    }
  });

  myReloadFromDisk = Boolean.FALSE;
  long oldDocumentStamp = document.getModificationStamp();

  file.setBinaryContent("xxx".getBytes(CharsetToolkit.UTF8_CHARSET));

  assertEquals("old test", document.getText());
  assertEquals(oldDocumentStamp, document.getModificationStamp());
}
 
Example 5
Source File: DifferenceReverterTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testRevertingContentChangeFromOldRevisionsWhenDirDoesNotExists() throws Exception {
  VirtualFile dir = myRoot.createChildDirectory(this, "dir");
  VirtualFile f = dir.createChildData(this, "foo.txt");

  f.setBinaryContent(new byte[]{1}, -1, 1000);
  f.setBinaryContent(new byte[]{2}, -1, 2000);

  dir.delete(this);

  revertChange(1);

  dir = myRoot.findChild("dir");
  assertNotNull(dir);
  f = dir.findChild("foo.txt");
  assertNotNull(f);
  assertEquals(1, f.contentsToByteArray()[0]);
  assertEquals(1000, f.getTimeStamp());
}
 
Example 6
Source File: DifferenceReverterTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testContentChangeWhenDirectoryExists() throws Exception {
  VirtualFile f = myRoot.createChildData(this, "foo.txt");
  f.setBinaryContent(new byte[]{1}, -1, 1000);

  getVcs().beginChangeSet();
  f.rename(this, "bar.txt");
  f.setBinaryContent(new byte[]{2}, -1, 2000);
  getVcs().endChangeSet(null);

  myRoot.createChildDirectory(this, "foo.txt");

  revertChange(1, 0, 1);

  assertNull(myRoot.findChild("bar.txt"));
  f = myRoot.findChild("foo.txt");
  assertNotNull(f);
  assertFalse(f.isDirectory());
  assertEquals(1, f.contentsToByteArray()[0]);
  assertEquals(1000, f.getTimeStamp());
}
 
Example 7
Source File: WebpackTemplate.java    From vue-for-idea with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Collection<VirtualFile> generateProject(@NotNull VueProjectWizardData data, @NotNull Module module, @NotNull VirtualFile baseDir) throws IOException {
    VirtualFile packagejson = baseDir.findChild("package.json");
    if(packagejson!=null){
        JsonParser jsonParser = new JsonParser();
        JsonElement je= jsonParser.parse(new FileReader(packagejson.getName()));
        try {
            JSONObject json = new JSONObject(je.toString());
            json.put("name",module.getName());
            json.put("private",false);
            je= jsonParser.parse(json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        packagejson.setBinaryContent(new GsonBuilder().setPrettyPrinting().create().toJson(je).getBytes());;
    }
    return Collections.EMPTY_LIST;
}
 
Example 8
Source File: CreateFileAction.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        VirtualFileManager manager = VirtualFileManager.getInstance();
        VirtualFile virtualFile = manager
                .refreshAndFindFileByUrl(VfsUtil.pathToUrl(outputFile));

        if (virtualFile != null && virtualFile.exists()) {
            virtualFile.setBinaryContent(content.getBytes(fileEncoding));
        } else {
            File file = new File(outputFile);
            FileUtils.writeStringToFile(file, content, fileEncoding);
            virtualFile = manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(outputFile));
        }
        VirtualFile finalVirtualFile = virtualFile;
        Project project = DataKeys.PROJECT.getData(dataContext);
        if (finalVirtualFile == null || project == null) {
            LOGGER.error(this);
            return;
        }
        ApplicationManager.getApplication()
                .invokeLater(
                        () -> FileEditorManager.getInstance(project).openFile(finalVirtualFile, true,
                                true));

    } catch (UnsupportedCharsetException ex) {
        ApplicationManager.getApplication().invokeLater(() -> Messages.showMessageDialog("Unknown Charset: " + fileEncoding + ", please use the correct charset", "Generate Failed", null));
    } catch (Exception e) {
        LOGGER.error("Create file failed", e);
    }

}
 
Example 9
Source File: LoadTextUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Overwrites file with text and sets modification stamp and time stamp to the specified values.
 * <p/>
 * Normally you should not use this method.
 *
 * @param requestor            any object to control who called this method. Note that
 *                             it is considered to be an external change if {@code requestor} is {@code null}.
 *                             See {@link VirtualFileEvent#getRequestor}
 * @param newModificationStamp new modification stamp or -1 if no special value should be set @return {@code Writer}
 * @throws IOException if an I/O error occurs
 * @see VirtualFile#getModificationStamp()
 */
public static void write(@Nullable Project project, @Nonnull VirtualFile virtualFile, @Nonnull Object requestor, @Nonnull String text, long newModificationStamp) throws IOException {
  Charset existing = virtualFile.getCharset();
  Pair.NonNull<Charset, byte[]> chosen = charsetForWriting(project, virtualFile, text, existing);
  Charset charset = chosen.first;
  byte[] buffer = chosen.second;
  if (!charset.equals(existing)) {
    virtualFile.setCharset(charset);
  }
  setDetectedFromBytesFlagBack(virtualFile, buffer);

  virtualFile.setBinaryContent(buffer, newModificationStamp, -1, requestor);
}
 
Example 10
Source File: FileHistoryDialogTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testContent() throws IOException {
  VirtualFile f = myRoot.createChildData(null, "f.txt");
  f.setBinaryContent("old".getBytes());
  f.setBinaryContent("new".getBytes());
  f.setBinaryContent("current".getBytes());

  FileHistoryDialogModel m = createFileModelAndSelectRevisions(f, 0, 1);

  assertDiffContents("old", "new", m);
}
 
Example 11
Source File: DifferenceReverterTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testRename() throws Exception {
  VirtualFile f = myRoot.createChildData(this, "foo.txt");
  f.setBinaryContent(new byte[]{123}, -1, 4000);
  f.rename(this, "bar.txt");

  revertLastChange();

  assertNull(myRoot.findChild("bar.txt"));
  f = myRoot.findChild("foo.txt");
  assertNotNull(f);
  assertEquals(123, f.contentsToByteArray()[0]);
  assertEquals(4000, f.getTimeStamp());
}
 
Example 12
Source File: FileDocumentManagerImplTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testContentChanged_ignoreEventsFromSelf() throws Exception {
  final VirtualFile file = createFile("test.txt", "test\rtest");
  Document document = myDocumentManager.getDocument(file);
  file.setBinaryContent("xxx".getBytes(CharsetToolkit.UTF8_CHARSET), -1, -1, myDocumentManager);
  assertNotNull(file.toString(), document);
  assertEquals("test\ntest", document.getText());
}
 
Example 13
Source File: PsiFileUtils.java    From crud-intellij-plugin with Apache License 2.0 5 votes vote down vote up
public static void createPOMXML(Project project, VirtualFile root, Selection selection) {
	try {
		VirtualFile virtualFile = root.createChildData(project, "pom.xml");
		StringWriter sw = new StringWriter();
		Template template = freemarker.getTemplate("pom.ftl");
		template.process(selection, sw);
		virtualFile.setBinaryContent(sw.toString().getBytes(CrudUtils.DEFAULT_CHARSET));
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 14
Source File: FileHistoryDialogTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testContentForCurrentRevision() throws IOException {
  VirtualFile f = myRoot.createChildData(null, "f.txt");
  f.setBinaryContent("old".getBytes());
  f.setBinaryContent("current".getBytes());

  FileHistoryDialogModel m = createFileModelAndSelectRevisions(f, 0, 0);

  assertDiffContents("old", "current", m);
  assertTrue(getRightDiffContent(m) instanceof DocumentContent);
}
 
Example 15
Source File: PsiFileUtils.java    From crud-intellij-plugin with Apache License 2.0 5 votes vote down vote up
private static void createMapper(Project project, VirtualFile packageDir, Dao dao) {
	try {
		VirtualFile virtualFile = packageDir.createChildData(project, dao.getModel().getSimpleName() + "Mapper.xml");
		StringWriter sw = new StringWriter();
		Template template = freemarker.getTemplate("mapper.ftl");
		template.process(dao, sw);
		virtualFile.setBinaryContent(sw.toString().getBytes(CrudUtils.DEFAULT_CHARSET));
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 16
Source File: PsiDirectoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PsiFile copyFileFrom(@Nonnull String newName, @Nonnull PsiFile originalFile) throws IncorrectOperationException {
  checkCreateFile(newName);

  final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(originalFile);
  if (document != null) {
    FileDocumentManager.getInstance().saveDocument(document);
  }

  final VirtualFile parent = getVirtualFile();
  try {
    final VirtualFile vFile = originalFile.getVirtualFile();
    if (vFile == null) throw new IncorrectOperationException("Cannot copy nonphysical file");
    VirtualFile copyVFile;
    if (parent.getFileSystem() == vFile.getFileSystem()) {
      copyVFile = vFile.copy(this, parent, newName);
    }
    else if (vFile instanceof LightVirtualFile) {
      copyVFile = parent.createChildData(this, newName);
      copyVFile.setBinaryContent(originalFile.getText().getBytes(copyVFile.getCharset()));
    }
    else {
      copyVFile = VfsUtilCore.copyFile(this, vFile, parent, newName);
    }
    LOG.assertTrue(copyVFile != null, "File was not copied: " + vFile);
    DumbService.getInstance(getProject()).completeJustSubmittedTasks();
    final PsiFile copyPsi = myManager.findFile(copyVFile);
    if (copyPsi == null) {
      LOG.error("Could not find file '" + copyVFile + "' after copying '" + vFile + "'");
    }
    updateAddedFile(copyPsi);
    return copyPsi;
  }
  catch (IOException e) {
    throw new IncorrectOperationException(e);
  }
}
 
Example 17
Source File: PsiFileUtils.java    From crud-intellij-plugin with Apache License 2.0 5 votes vote down vote up
public static void createApplicationJava(Project project, VirtualFile root, Selection selection) {
	try {
		VirtualFile virtualFile = root.createChildData(project, "Application.java");
		StringWriter sw = new StringWriter();
		Template template = freemarker.getTemplate("Application.java.ftl");
		template.process(selection, sw);
		virtualFile.setBinaryContent(sw.toString().getBytes(CrudUtils.DEFAULT_CHARSET));
		CrudUtils.addWaitOptimizeFile(virtualFile);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 18
Source File: DifferenceReverterTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testRevertContentChange() throws Exception {
  VirtualFile f = myRoot.createChildData(this, "foo.txt");
  f.setBinaryContent(new byte[]{1}, -1, 1000);
  f.setBinaryContent(new byte[]{2}, -1, 2000);

  revertLastChange();

  f = myRoot.findChild("foo.txt");
  assertNotNull(f);
  assertEquals(1, f.contentsToByteArray()[0]);
  assertEquals(1000, f.getTimeStamp());
}
 
Example 19
Source File: FileDocumentManagerImplTest.java    From consulo with Apache License 2.0 4 votes vote down vote up
void setContent(VirtualFile file, String content) throws IOException {
  file.setBinaryContent(content.getBytes(CharsetToolkit.UTF8_CHARSET));
}
 
Example 20
Source File: ApplyBinaryFilePatch.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected void applyCreate(Project project, final VirtualFile newFile, CommitContext commitContext) throws IOException {
  newFile.setBinaryContent(myPatch.getAfterContent());
}