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

The following examples show how to use com.intellij.openapi.util.io.FileUtil#loadFile() . 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: VMOptions.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static String read() {
  try {
    File newFile = getWriteFile();
    if (newFile != null && newFile.exists()) {
      return FileUtil.loadFile(newFile);
    }

    String vmOptionsFile = System.getProperty("jb.vmOptionsFile");
    if (vmOptionsFile != null) {
      return FileUtil.loadFile(new File(vmOptionsFile));
    }
  }
  catch (IOException e) {
    LOG.info(e);
  }

  return null;
}
 
Example 2
Source File: TestFileSystemItem.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void assertFileEqual(File file, String relativePath) {
  try {
    Assert.assertEquals("in " + relativePath, myName, file.getName());
    if (myArchive) {
      final File dirForExtracted = FileUtil.createTempDirectory("extracted_archive", null,false);
      ZipUtil.extract(file, dirForExtracted, null);
      assertDirectoryEqual(dirForExtracted, relativePath);
      FileUtil.delete(dirForExtracted);
    }
    else if (myDirectory) {
      Assert.assertTrue(relativePath + file.getName() + " is not a directory", file.isDirectory());
      assertDirectoryEqual(file, relativePath);
    }
    else if (myContent != null) {
      final String content = FileUtil.loadFile(file);
      Assert.assertEquals("content mismatch for " + relativePath, myContent, content);
    }
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 3
Source File: FormatterTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected String loadFile(String name, String resultNumber) throws Exception {
  String fullName = getTestDataPath() + File.separatorChar + getBasePath() + File.separatorChar + name;
  String text = FileUtil.loadFile(new File(fullName));
  text = StringUtil.convertLineSeparators(text);
  if (resultNumber == null) {
    return prepareText(text);
  }
  else {
    String beginLine = "<<<" + resultNumber + ">>>";
    String endLine = "<<</" + resultNumber + ">>>";
    int beginPos = text.indexOf(beginLine);
    assertTrue(beginPos >= 0);
    int endPos = text.indexOf(endLine);
    assertTrue(endPos >= 0);

    return prepareText(text.substring(beginPos + beginLine.length(), endPos).trim());

  }
}
 
Example 4
Source File: RoutesManager.java    From railways with MIT License 6 votes vote down vote up
/**
 * Returns cached output if cache file exists and actual. Cache file is
 * considered to be actual if its modification time is the same as for
 * routes.rb file of current project.
 *
 * @return String that contains cached output or null if no valid cache
 * date is found.
 */
@Nullable
private String getCachedOutput() {
    try {
        String fileName = getCacheFileName();
        if (fileName == null)
            return null;

        File f = new File(fileName);

        // Check if cached file still contains actual data. Cached file and routes.rb file should have the same
        // modification time.
        long routesMTime = getRoutesFilesMTime();
        if (routesMTime != f.lastModified())
            return null;

        return FileUtil.loadFile(f);
    } catch (Exception e) {
        return null;
    }
}
 
Example 5
Source File: BuckDeps.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * In the given {@code buckFile}, modify the given {@code target} to include {@code dependency} in
 * its deps.
 *
 * @param buckFile Home for the given {@code target}.
 * @param target The fully qualified target to be modified.
 * @param dependency The fully qualified dependency required by the target.
 */
static boolean modifyTargetToAddDependency(
    VirtualFile buckFile, String target, String dependency) {
  try {
    File file = new File(buckFile.getPath());
    String oldContents = FileUtil.loadFile(file);
    String newContents = tryToAddDepsToTarget(oldContents, dependency, target);
    if (oldContents.equals(newContents)) {
      return false;
    }
    LOG.info("Updating " + file.getPath());
    FileUtil.writeToFile(file, newContents);
    buckFile.refresh(false, false);
    return true;
  } catch (IOException e) {
    LOG.error(
        "Failed to update "
            + buckFile.getPath()
            + " target "
            + target
            + " to include "
            + dependency,
        e);
    return false;
  }
}
 
Example 6
Source File: BuckDeps.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * In the given {@code buckFile}, modify the given {@code target} to make it visible to the given
 * {@code dependency}.
 *
 * @param buckFile Home for the given {@code target}.
 * @param target The fully qualified target to be modified.
 * @param dependent The fully qualified dependent that needs visibility to the target.
 */
static void addVisibilityToTargetForUsage(VirtualFile buckFile, String target, String dependent) {
  try {
    File file = new File(buckFile.getPath());
    String oldContents = FileUtil.loadFile(file);
    String newContents = maybeAddVisibilityToTarget(oldContents, dependent, target);
    if (!oldContents.equals(newContents)) {
      LOG.info("Updating " + file.getPath());
      FileUtil.writeToFile(file, newContents);
      buckFile.refresh(false, false);
    }
  } catch (IOException e) {
    LOG.error(
        "Failed to update "
            + buckFile.getPath()
            + " target "
            + target
            + " to be visible to "
            + dependent,
        e);
  }
}
 
Example 7
Source File: FileTypeManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ConstantConditions")
private static Object streamInfo(@Nonnull InputStream stream) throws IOException {
  if (stream instanceof BufferedInputStream) {
    InputStream in = ReflectionUtil.getField(stream.getClass(), stream, InputStream.class, "in");
    byte[] buf = ReflectionUtil.getField(stream.getClass(), stream, byte[].class, "buf");
    int count = ReflectionUtil.getField(stream.getClass(), stream, int.class, "count");
    int pos = ReflectionUtil.getField(stream.getClass(), stream, int.class, "pos");
    return "BufferedInputStream(buf=" + (buf == null ? null : Arrays.toString(Arrays.copyOf(buf, count))) + ", count=" + count + ", pos=" + pos + ", in=" + streamInfo(in) + ")";
  }
  if (stream instanceof FileInputStream) {
    String path = ReflectionUtil.getField(stream.getClass(), stream, String.class, "path");
    FileChannel channel = ReflectionUtil.getField(stream.getClass(), stream, FileChannel.class, "channel");
    boolean closed = ReflectionUtil.getField(stream.getClass(), stream, boolean.class, "closed");
    int available = stream.available();
    File file = new File(path);
    return "FileInputStream(path=" + path + ", available=" + available + ", closed=" + closed +
           ", channel=" + channel + ", channel.size=" + (channel == null ? null : channel.size()) +
           ", file.exists=" + file.exists() + ", file.content='" + FileUtil.loadFile(file) + "')";
  }
  return stream;
}
 
Example 8
Source File: AssertEx.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void assertSameLinesWithFile(String filePath, String actualText) {
  String fileText;
  try {
    if (OVERWRITE_TESTDATA) {
      FileUtil.writeToFile(new File(filePath), actualText);
      System.out.println("File " + filePath + " created.");
    }
    fileText = FileUtil.loadFile(new File(filePath));
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
  String expected = StringUtil.convertLineSeparators(fileText.trim());
  String actual = StringUtil.convertLineSeparators(actualText.trim());
  if (!Comparing.equal(expected, actual)) {
    throw new FileComparisonFailure(null, expected, actual, filePath);
  }
}
 
Example 9
Source File: FoldingTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void runTestInternal() throws Throwable {
  String filePath = myFullDataPath + "/" + getTestName(false) + "." + myExtension;
  File file = new File(filePath);

  String expectedContent;
  try {
    expectedContent = FileUtil.loadFile(file);
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
  Assert.assertNotNull(expectedContent);

  expectedContent = StringUtil.replace(expectedContent, "\r", "");
  final String cleanContent = expectedContent.replaceAll(START_FOLD, "").replaceAll(END_FOLD, "");
  final String actual = getFoldingDescription(cleanContent, file.getName(), myDoCheckCollapseStatus);

  Assert.assertEquals(expectedContent, actual);
}
 
Example 10
Source File: GeneralToSMTRunnerEventsConvertorTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testPreserveFullOutputAfterImport() throws Exception {

    mySuite.addChild(mySimpleTest);
    for (int i = 0; i < 550; i++) {
      String message = "line" + i + "\n";
      mySimpleTest.addLast(printer -> printer.print(message, ConsoleViewContentType.NORMAL_OUTPUT));
    }
    mySimpleTest.setFinished();
    mySuite.setFinished();

    SAXTransformerFactory transformerFactory = (SAXTransformerFactory)TransformerFactory.newInstance();
    TransformerHandler handler = transformerFactory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    handler.getTransformer().setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    File output = FileUtil.createTempFile("output", "");
    try {
      FileUtilRt.createParentDirs(output);
      handler.setResult(new StreamResult(new FileWriter(output)));
      MockRuntimeConfiguration configuration = new MockRuntimeConfiguration(getProject());
      TestResultsXmlFormatter.execute(mySuite, configuration, new SMTRunnerConsoleProperties(configuration, "framework", new DefaultRunExecutor()), handler);

      String savedText = FileUtil.loadFile(output);
      assertTrue(savedText.split("\n").length > 550);

      myEventsProcessor.onStartTesting();
      ImportedToGeneralTestEventsConverter.parseTestResults(() -> new StringReader(savedText), myEventsProcessor);
      myEventsProcessor.onFinishTesting();

      List<? extends SMTestProxy> children = myResultsViewer.getTestsRootNode().getChildren();
      assertSize(1, children);
      SMTestProxy testProxy = children.get(0);
      MockPrinter mockPrinter = new MockPrinter();
      testProxy.printOn(mockPrinter);
      assertSize(550, mockPrinter.getAllOut().split("\n"));
    }
    finally {
      FileUtil.delete(output);
    }
  }
 
Example 11
Source File: EncodingAwareProperties.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void load(File file, String encoding) throws IOException{
  String propText = FileUtil.loadFile(file, encoding);
  propText = StringUtil.convertLineSeparators(propText);
  StringTokenizer stringTokenizer = new StringTokenizer(propText, "\n");
  while (stringTokenizer.hasMoreElements()){
    String line = stringTokenizer.nextElement();
    int i = line.indexOf('=');
    String propName = i == -1 ? line : line.substring(0,i);
    String propValue = i == -1 ? "" : line.substring(i+1);
    setProperty(propName, propValue);
  }
}
 
Example 12
Source File: LightPlatformCodeInsightTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Configure test from data file. Data file is usual java, xml or whatever file that needs to be tested except it
 * has &lt;caret&gt; marker where caret should be placed when file is loaded in editor and &lt;selection&gt;&lt;/selection&gt;
 * denoting selection bounds.
 * @param filePath - relative path from %IDEA_INSTALLATION_HOME%/testData/
 * @throws Exception
 */
protected void configureByFile(@TestDataFile @NonNls @Nonnull String filePath) {
  try {
    String fullPath = getTestDataPath() + filePath;

    final File ioFile = new File(fullPath);
    String fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8);
    fileText = StringUtil.convertLineSeparators(fileText);

    configureFromFileText(ioFile.getName(), fileText);
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 13
Source File: LexerTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void doFileTest(@NonNls String fileExt) {
  String fileName = ContainerPathManager.get().getHomePath() + "/" + getDirPath() + "/" + TestUtil.getTestName(this, true) + "." + fileExt;
  String text = "";
  try {
    String fileText = FileUtil.loadFile(new File(fileName));
    text = StringUtil.convertLineSeparators(shouldTrim() ? fileText.trim() : fileText);
  }
  catch (IOException e) {
    fail("can't load file " + fileName + ": " + e.getMessage());
  }
  doTest(text);
}
 
Example 14
Source File: ProjectStoreImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String readProjectName(@Nonnull File file) {
  if (file.isDirectory()) {
    final File nameFile = new File(new File(file, Project.DIRECTORY_STORE_FOLDER), ProjectImpl.NAME_FILE);
    if (nameFile.exists()) {
      try {
        return FileUtil.loadFile(nameFile, true);
      }
      catch (IOException ignored) {
      }
    }
  }
  return file.getName();
}
 
Example 15
Source File: TestFailedEvent.java    From consulo with Apache License 2.0 5 votes vote down vote up
public TestFailedEvent(@javax.annotation.Nullable String testName,
                       @javax.annotation.Nullable String id,
                       @Nonnull String localizedFailureMessage,
                       @Nullable String stackTrace,
                       boolean testError,
                       @Nullable String comparisonFailureActualText,
                       @Nullable String comparisonFailureExpectedText,
                       @javax.annotation.Nullable String expectedFilePath,
                       @javax.annotation.Nullable String actualFilePath,
                       boolean expectedFileTemp,
                       boolean actualFileTemp,
                       long durationMillis) {
  super(testName, id);
  myLocalizedFailureMessage = localizedFailureMessage;
  myStacktrace = stackTrace;
  myTestError = testError;
  myExpectedFilePath = expectedFilePath;
  if (comparisonFailureExpectedText == null && expectedFilePath != null) {
    try {
      comparisonFailureExpectedText = FileUtil.loadFile(new File(expectedFilePath));
    }
    catch (IOException ignore) {}
  }
  myComparisonFailureActualText = comparisonFailureActualText;

  myActualFilePath = actualFilePath;
  myComparisonFailureExpectedText = comparisonFailureExpectedText;
  myDurationMillis = durationMillis;
  myExpectedFileTemp = expectedFileTemp;
  myActualFileTemp = actualFileTemp;
}
 
Example 16
Source File: LightGLSLTestCase.java    From glsl4idea with GNU Lesser General Public License v3.0 5 votes vote down vote up
public GLSLFile parseFile(String filePath){
    final String testFileContent;
    try {
        testFileContent = FileUtil.loadFile(getTestFile(filePath), "UTF-8", true);
        assertNotNull(testFileContent);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return ((GLSLFile) PsiFileFactory.getInstance(getProject()).createFileFromText("dummy.glsl", GLSLSupportLoader.GLSL, testFileContent));
}
 
Example 17
Source File: HaskellResolveTestCase.java    From intellij-haskforce with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    for (File file : getTestDataFiles()) {
        if (file.isDirectory()) continue;
        String text = FileUtil.loadFile(file, CharsetToolkit.UTF8);
        text = StringUtil.convertLineSeparators(text);
        int referencedOffset = text.indexOf("<ref>");
        text = text.replace("<ref>", "");
        int resolvedOffset = text.indexOf("<resolved>");
        text = text.replace("<resolved>", "");
        String relativePath = file.getCanonicalPath().substring(
          file.getCanonicalPath().indexOf(getTestDataPath()) + getTestDataPath().length() + 1
        );
        VirtualFile vFile = myFixture.getTempDirFixture().createFile(relativePath, text);
        PsiFile psiFile = myFixture.configureFromTempProjectFile(relativePath);
        if (referencedOffset != -1) {
            referencedElement = psiFile.findReferenceAt(referencedOffset);
            if (referencedElement == null) fail("Reference was null in " + file.getName());
        }
        if (resolvedOffset != -1) {
            final PsiReference ref = psiFile.findReferenceAt(resolvedOffset);
            if (ref == null) { fail("Reference was null in " + file.getName()); }
            resolvedElement = ref.getElement();
            if (resolvedElement == null) { fail("Reference returned null element in " + file.getName()); }
        }
    }
}
 
Example 18
Source File: LocatorTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void test() throws Exception {
  File locatorFile = new File(ContainerPathManager.get().getSystemPath() + "/" + ApplicationEx.LOCATOR_FILE_NAME);
  assertTrue(locatorFile.getPath(), locatorFile.canRead());

  String home = FileUtil.loadFile(locatorFile, "UTF-8");
  assertTrue(home, StringUtil.isNotEmpty(home));

  assertEquals(home, ContainerPathManager.get().getHomePath());
}
 
Example 19
Source File: DownloadUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Downloads content of {@code url} to {@code outputFile} atomically.<br/>
 * {@code outputFile} isn't modified if an I/O error occurs or {@code contentChecker} is provided and returns false on the downloaded content.
 * More formally, the steps are:
 * <ol>
 *   <li>Download {@code url} to {@code tempFile}. Stop in case of any I/O errors.</li>
 *   <li>Stop if {@code contentChecker} is provided, and it returns false on the downloaded content.</li>
 *   <li>Move {@code tempFile} to {@code outputFile}. On most OS this operation is done atomically.</li>
 * </ol>
 *
 * Motivation: some web filtering products return pure HTML with HTTP 200 OK status instead of
 * the asked content.
 *
 * @param indicator   progress indicator
 * @param url         url to download
 * @param outputFile  output file
 * @param tempFile    temporary file to download to. This file is deleted on method exit.
 * @param contentChecker checks whether the downloaded content is OK or not
 * @returns true if no {@code contentChecker} is provided or the provided one returned true
 * @throws IOException if an I/O error occurs
 */
public static boolean downloadAtomically(@Nullable ProgressIndicator indicator,
                                         @Nonnull String url,
                                         @Nonnull File outputFile,
                                         @Nonnull File tempFile,
                                         @Nullable Predicate<String> contentChecker) throws IOException
{
  try {
    downloadContentToFile(indicator, url, tempFile);
    if (contentChecker != null) {
      String content = FileUtil.loadFile(tempFile);
      if (!contentChecker.test(content)) {
        return false;
      }
    }
    FileUtil.rename(tempFile, outputFile);
    return true;
  } finally {
    FileUtil.delete(tempFile);
  }
}
 
Example 20
Source File: OSSPantsIdeaPluginGoalIntegrationTest.java    From intellij-pants-plugin with Apache License 2.0 4 votes vote down vote up
public void testPantsIdeaPluginGoal() throws Throwable {
  assertEmpty(ModuleManager.getInstance(myProject).getModules());

  /**
   * Check whether Pants supports `idea-plugin` goal.
   */
  final GeneralCommandLine commandLinePantsGoals = PantsUtil.defaultCommandLine(getProjectFolder().getPath());
  commandLinePantsGoals.addParameter("goals");
  final ProcessOutput cmdOutputGoals = PantsUtil.getCmdOutput(commandLinePantsGoals.withWorkDirectory(getProjectFolder()), null);
  assertEquals(commandLinePantsGoals.toString() + " failed", 0, cmdOutputGoals.getExitCode());
  if (!cmdOutputGoals.getStdout().contains("idea-plugin")) {
    return;
  }

  /**
   * Generate idea project via `idea-plugin` goal.
   */
  final GeneralCommandLine commandLine = PantsUtil.defaultCommandLine(getProjectFolder().getPath());
  final File outputFile = FileUtil.createTempFile("project_dir_location", ".out");
  String targetToImport = "testprojects/tests/java/org/pantsbuild/testproject/matcher:matcher";
  commandLine.addParameters(
    "idea-plugin",
    "--no-open",
    "--output-file=" + outputFile.getPath(),
    targetToImport
  );
  final ProcessOutput cmdOutput = PantsUtil.getCmdOutput(commandLine.withWorkDirectory(getProjectFolder()), null);
  assertEquals(commandLine.toString() + " failed", 0, cmdOutput.getExitCode());
  // `outputFile` contains the path to the project directory.
  String projectDir = FileUtil.loadFile(outputFile);

  // Search the directory for ipr file.
  File[] files = new File(projectDir).listFiles();
  assertNotNull(files);
  Optional<String> iprFile = Arrays.stream(files)
    .map(File::getPath)
    .filter(s -> s.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION))
    .findFirst();
  assertTrue(iprFile.isPresent());

  myProject = ProjectUtil.openProject(iprFile.get(), myProject, false);
  // Invoke post startup activities.
  UIUtil.dispatchAllInvocationEvents();
  /**
   * Under unit test mode, {@link com.intellij.ide.impl.ProjectUtil#openProject} will force open a project in a new window,
   * so Project SDK has to be reset. In practice, this is not needed.
   */
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      final JavaSdk javaSdk = JavaSdk.getInstance();
      ProjectRootManager.getInstance(myProject).setProjectSdk(ProjectJdkTable.getInstance().getSdksOfType(javaSdk).iterator().next());
    }
  });

  assertSuccessfulTest(PantsUtil.getCanonicalModuleName(targetToImport), "org.pantsbuild.testproject.matcher.MatcherTest");
  assertTrue(ProjectUtil.closeAndDispose(myProject));
}