Java Code Examples for org.eclipse.core.resources.IFile#getContents()

The following examples show how to use org.eclipse.core.resources.IFile#getContents() . 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: ConversionTests.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/** Verify that appengine-web.xml has no <runtime>java8</runtime>. */
private void assertNoJava8Runtime(IFacetedProject project)
    throws IOException, SAXException, CoreException, AppEngineException {
  IFile appengineWebXml =
      AppEngineConfigurationUtil.findConfigurationFile(
          project.getProject(), new Path("appengine-web.xml"));
  assertNotNull("appengine-web.xml is missing", appengineWebXml);
  assertTrue("appengine-web.xml does not exist", appengineWebXml.exists());
  try (InputStream contents = appengineWebXml.getContents()) {
    String appEngineWebContent =
        CharStreams.toString(new InputStreamReader(contents, StandardCharsets.UTF_8));
    if (originalAppEngineWebContent != null) {
      assertEquals("appengine-web.xml was changed", originalAppEngineWebContent,
          appEngineWebContent);
    }
    AppEngineDescriptor descriptor = AppEngineDescriptor
        .parse(new ByteArrayInputStream(appEngineWebContent.getBytes(StandardCharsets.UTF_8)));
    assertFalse("should not have <runtime>java8</runtime>", descriptor.isJava8());
    assertEquals("should report runtime=java7", "java7", descriptor.getRuntime());
  }
}
 
Example 2
Source File: AbstractRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void migrate(final IProgressMonitor monitor) throws CoreException, MigrationException {
    List<IFile> filesToMigrate = getChildren().stream()
            .filter(fs -> !fs.isReadOnly())
            .filter(IRepositoryFileStore::canBeShared)
            .map(IRepositoryFileStore::getResource)
            .filter(IFile.class::isInstance)
            .map(IFile.class::cast)
            .filter(IFile::exists)
            .collect(Collectors.toList());

    for (IFile file : filesToMigrate) {
        monitor.subTask(file.getName());
        InputStream newIs;
        try (final InputStream is = file.getContents()) {
            newIs = handlePreImport(file.getName(), is);
            if (!is.equals(newIs)) {
                file.setContents(newIs, IResource.FORCE, monitor);
                file.refreshLocal(IResource.DEPTH_ONE, monitor);
            }
        } catch (final IOException e) {
            throw new MigrationException("Cannot migrate resource " + file.getName() + " (not a valid file)", e);
        }
    }
}
 
Example 3
Source File: FindbugsPlugin.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Read UserPreferences for project from the file in the project directory.
 * Returns null if the preferences have not been saved to a file, or if
 * there is an error reading the preferences file.
 *
 * @param project
 *            the project to get the UserPreferences for
 * @return the UserPreferences, or null if the UserPreferences file could
 *         not be read
 * @throws CoreException
 */
private static UserPreferences readUserPreferences(IProject project) throws CoreException {
    IFile userPrefsFile = getUserPreferencesFile(project);
    if (!userPrefsFile.exists()) {
        return null;
    }
    try {
        // force is preventing us for out-of-sync exception if file was
        // changed externally
        InputStream in = userPrefsFile.getContents(true);
        UserPreferences userPrefs = FindBugsPreferenceInitializer.createDefaultUserPreferences();
        userPrefs.read(in);
        return userPrefs;
    } catch (IOException e) {
        FindbugsPlugin.getDefault().logException(e, "Could not read user preferences for project");
        return null;
    }
}
 
Example 4
Source File: EncodingUtils.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * In the case resource is IFile, its encoding is guessed from its first bytes (see {@link TextEncoding#readFileAndCodepage(java.io.InputStream, StringBuilder, CodepageId[])}) 
 * @param r
 * @param monitor
 * @throws IOException 
 * @throws FileNotFoundException 
 * @throws CoreException 
 */
public static void determineAndSetEncoding(IFile f, IProgressMonitor monitor) throws IOException, CoreException {
	if (!f.exists()) {
		return;
	}
	CodepageId cpId[] = {null};
	try(InputStream stream = f.getContents()){
		TextEncoding.readFileAndCodepage(stream, null, cpId);
		if (cpId[0] == null) {
			cpId[0] = null;
		}
		if(cpId[0] != null && !cpId[0].charsetName.equalsIgnoreCase(f.getCharset(true))) {
			f.setCharset(cpId[0].charsetName, monitor);
		}
	}
}
 
Example 5
Source File: BusinessObjectModelFileStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public BusinessObjectModel getContent() {
    final IFile resource = getResource();
    if (!resource.exists()) {
        cachedBusinessObjectModel.clear();
        return null;
    }
    final long modificationStamp = resource.getModificationStamp();
    if (cachedBusinessObjectModel.containsKey(modificationStamp)) {
        return cachedBusinessObjectModel.get(modificationStamp);
    }
    try (InputStream contents = resource.getContents()) {
        final BusinessObjectModel bom = getConverter().unmarshall(ByteStreams.toByteArray(contents));
        cachedBusinessObjectModel.clear();
        cachedBusinessObjectModel.put(modificationStamp, bom);
        return bom;
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
    return null;
}
 
Example 6
Source File: AppEngineStandardJre8ProjectFacetDetector.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static IProjectFacetVersion getWebFacetVersionToInstall(IProject project) {
  IFile webXml = WebProjectUtil.findInWebInf(project, new Path("web.xml"));
  if (webXml == null) {
    return WebFacetUtils.WEB_31;
  }

  try (InputStream in = webXml.getContents()) {
    String servletVersion = buildDomDocument(in).getDocumentElement().getAttribute("version");
    if ("2.5".equals(servletVersion)) {
      return WebFacetUtils.WEB_25;
    }
  } catch (IOException | CoreException | ParserConfigurationException | SAXException ex) {
    // give up and install Servlet 3.1 facet
  }
  return WebFacetUtils.WEB_31;
}
 
Example 7
Source File: AbstractNewModelWizard.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings ("resource")
private InputStream getInputStream(final IContainer folder, final String template, final String title,
		final String author, final String desc) {
	InputStream result;
	final IFile file = folder.getProject().getFile(new Path(template));
	if (file.exists()) {
		try {
			result = file.getContents();
		} catch (final CoreException e) {
			return null;
		}
	} else {
		result = getClass().getResourceAsStream(template);
	}
	return replacePlaceHolders(folder, result, title, author, desc);
}
 
Example 8
Source File: TexProjectParser.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Reads a file from the project.
 * 
 * @param file the file to be read.
 * @return The contents of the file as a String.
 * @throws IOException
 */
private String readFile(IFile file) throws IOException {
    StringBuilder inputContent = new StringBuilder("");
    try {
        BufferedReader buf = new BufferedReader(
                new InputStreamReader(file.getContents()));
        
        final int length = 10000;
        int read = length;
        char[] fileData = new char[length];
        while (read == length) {
            read = buf.read(fileData, 0, length);
            if (read > 0) {
                inputContent.append(fileData, 0, read);
            }
        }
        buf.close();
    } catch (CoreException e) {
        // This should be very rare...
        throw new IOException(e.getMessage());
    }
    // TODO
    //return this.rmTrailingWhitespace(inputContent);
    return inputContent.toString();
}
 
Example 9
Source File: ProjectConfigurationFactory.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Load the audit configurations from the persistent state storage.
 */
private static IProjectConfiguration loadFromPersistence(IProject project)
        throws CheckstylePluginException {
  IProjectConfiguration configuration = null;

  //
  // Make sure the files exists, it might not.
  //
  IFile file = project.getFile(PROJECT_CONFIGURATION_FILE);
  boolean exists = file.exists();
  if (!exists) {
    return createDefaultProjectConfiguration(project);
  }

  try (InputStream inStream = file.getContents(true)) {
    configuration = getProjectConfiguration(inStream, project);
  } catch (DocumentException | CoreException | IOException e) {
    CheckstylePluginException.rethrow(e);
  }

  return configuration;
}
 
Example 10
Source File: DebugUtil.java    From corrosion with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the default workspace path to the executable produced for the given
 * project. This location is a guess based on the default rust/cargo project
 * layout and the operating system running eclipse.
 *
 * @param project Rust project for which the executable workspace path is
 *                computed.
 * @return default workspace path to the executable created for the given Rust
 *         {@code project}.
 */
static String getDefaultExecutablePath(IProject project) {
	if (project == null) {
		return ""; //$NON-NLS-1$
	}
	IFile cargoFile = project.getFile("Cargo.toml"); //$NON-NLS-1$
	if (!cargoFile.exists()) {
		return ""; //$NON-NLS-1$
	}
	StringBuilder builder = new StringBuilder(project.getName());
	builder.append("/target/debug/"); //$NON-NLS-1$
	try (InputStream file = cargoFile.getContents()) {
		Properties properties = new Properties();
		properties.load(file);
		String name = properties.getProperty("name"); //$NON-NLS-1$
		if (!name.isEmpty()) {
			name = name.substring(name.indexOf('"') + 1, name.lastIndexOf('"'));
		}
		builder.append(name);
	} catch (Exception e) {
		CorrosionPlugin.logError(e);
	}
	if (IS_WINDOWS) {
		builder.append(".exe"); //$NON-NLS-1$
	}
	return builder.toString();
}
 
Example 11
Source File: ContentTypeHelper.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the content of the given buffer.
 * 
 * @param buffer
 * @return the content of the given buffer.
 * @throws CoreException
 */
private static InputStream getContents(ITextFileBuffer buffer) throws CoreException {
	IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
	IFile file = workspaceRoot.getFile(buffer.getLocation());
	if (file.exists() && buffer.isSynchronized()) {
		return file.getContents();
	}
	return buffer.getFileStore().openInputStream(EFS.NONE, null);
}
 
Example 12
Source File: MenuLevelValidator.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected ApplicationNodeContainer toApplicationContainer(IFile resource) {
    try (InputStream is = resource.getContents()) {
        return converter.unmarshallFromXML(ByteStreams.toByteArray(is));
    } catch (IOException | CoreException | JAXBException | SAXException e) {
        return null;
    }
}
 
Example 13
Source File: WorkbenchTestHelper.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the content of the given file.
 *
 * @param file the name of the file.
 * @return the content of the file.
 * @throws Exception
 */
public String getContents(IFile file) throws Exception {
	try (InputStream inputStream = file.getContents()) {
		byte[] buffer = new byte[2048];
		int bytesRead = 0;
		StringBuffer b = new StringBuffer();
		do {
			bytesRead = inputStream.read(buffer);
			if (bytesRead != -1)
				b.append(new String(buffer, 0, bytesRead));
		} while (bytesRead != -1);
		return b.toString();
	}
}
 
Example 14
Source File: ResourceUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static String getContent(IFile file) throws CoreException {
	if (file == null) {
		return null;
	}
	String content;
	try {
		try (final Reader reader = new InputStreamReader(file.getContents())) {
			content = CharStreams.toString(reader);
		}
	} catch (IOException e) {
		throw new CoreException(StatusFactory.newErrorStatus("Can not get " + file.getRawLocation() + " content", e));
	}
	return content;
}
 
Example 15
Source File: StandardFacetInstallDelegateTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateConfigFiles_appengineWebXml()
    throws CoreException, IOException, SAXException, AppEngineException {
  delegate.createConfigFiles(project, AppEngineStandardFacet.JRE7, monitor);

  IFile appengineWebXml = project.getFile("src/main/webapp/WEB-INF/appengine-web.xml");
  Assert.assertTrue(appengineWebXml.exists());

  try (InputStream in = appengineWebXml.getContents(true)) {
    AppEngineDescriptor descriptor = AppEngineDescriptor.parse(in);
    // AppEngineDescriptor treats an empty runtime as java7 as of 0.6.
    assertEquals("java7", descriptor.getRuntime());
  }
}
 
Example 16
Source File: StandardFacetInstallDelegateTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private void assertNoOverwriting(String fileInWebInf) throws CoreException, IOException {
  IFolder webInfDir = project.getFolder("src/main/webapp/WEB-INF");
  ResourceUtils.createFolders(webInfDir, monitor);
  IFile file = webInfDir.getFile(fileInWebInf);
  file.create(new ByteArrayInputStream(new byte[0]), true, monitor);

  Assert.assertTrue(file.exists());

  delegate.createConfigFiles(project, AppEngineStandardFacet.JRE7, monitor);

  // Make sure createConfigFiles did not overwrite the file in WEB-INF
  try (InputStream in = file.getContents(true)) {
    Assert.assertEquals(fileInWebInf + " is not empty", -1, in.read());
  }
}
 
Example 17
Source File: AppEngineConfigurationUtilTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateConfigurationFile_byteContent() throws CoreException, IOException {
  IFile file =
      AppEngineConfigurationUtil.createConfigurationFile(
          projectCreator.getProject(),
          new Path("example.txt"),
          new ByteArrayInputStream(new byte[] {0, 1, 2, 3}),
          true,
          null);
  try (InputStream input = file.getContents()) {
    byte[] contents = ByteStreams.toByteArray(input);
    assertArrayEquals(new byte[] {0, 1, 2, 3}, contents);
  }
}
 
Example 18
Source File: AppEngineConfigurationUtilTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateConfigurationFile_charContent() throws CoreException, IOException {
  String original = "\u1f64c this is a test \u00b5";
  IFile file =
      AppEngineConfigurationUtil.createConfigurationFile(
          projectCreator.getProject(), new Path("example.txt"), original, true, null);
  try (InputStream input = file.getContents()) {
    String contents = new String(ByteStreams.toByteArray(input), StandardCharsets.UTF_8);
    assertEquals(original, contents);
  }
}
 
Example 19
Source File: StandardFacetInstallationTest.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
private static void assertEmptyFile(IFile file) throws IOException, CoreException {
  try (InputStream in = file.getContents()) {
    assertEquals(-1, in.read());  // Verify it is an empty file.
  }
}
 
Example 20
Source File: AppEngineStandardJre8ProjectFacetDetector.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
@Override
public void detect(IFacetedProjectWorkingCopy workingCopy, IProgressMonitor monitor)
    throws CoreException {
  String projectName = workingCopy.getProjectName();
  SubMonitor progress = SubMonitor.convert(monitor, 5);

  if (workingCopy.hasProjectFacet(AppEngineStandardFacet.FACET)) {
    return;
  }

  // Check if there are some fundamental conflicts with AESv8 other than Java and DWP versions
  if (FacetUtil.conflictsWith(workingCopy,
      AppEngineStandardFacetChangeListener.APP_ENGINE_STANDARD_JRE8,
      Arrays.asList(JavaFacet.FACET, WebFacetUtils.WEB_FACET))) {
    logger.warning(
        "skipping " + projectName + ": project conflicts with AES Java 8 runtime");
    return;
  }

  IFile appEngineWebXml =
      AppEngineConfigurationUtil.findConfigurationFile(
          workingCopy.getProject(), new Path("appengine-web.xml"));
  if (appEngineWebXml == null || !appEngineWebXml.exists()) {
    return;
  }
  progress.worked(1);
  try (InputStream content = appEngineWebXml.getContents()) {
    AppEngineDescriptor descriptor = AppEngineDescriptor.parse(content);
    progress.worked(1);
    if (!descriptor.isJava8()) {
      return;
    }
    
    workingCopy.addProjectFacet(AppEngineStandardFacetChangeListener.APP_ENGINE_STANDARD_JRE8);
    progress.worked(1);

    // Always change to the Java 8 facet
    if (!workingCopy.hasProjectFacet(JavaFacet.VERSION_1_8)) {
      if (workingCopy.hasProjectFacet(JavaFacet.FACET)) {
        workingCopy.changeProjectFacetVersion(JavaFacet.VERSION_1_8);
      } else {
        Object javaModel = FacetUtil.createJavaDataModel(workingCopy.getProject());
        workingCopy.addProjectFacet(JavaFacet.VERSION_1_8);
        workingCopy.setProjectFacetActionConfig(JavaFacet.FACET, javaModel);
      }
      progress.worked(1);
    }

    // But we don't touch the Dynamic Web facet unless required
    if (!workingCopy.hasProjectFacet(WebFacetUtils.WEB_FACET)) {
      Object webModel =
          FacetUtil.createWebFacetDataModel(appEngineWebXml.getParent().getParent());
      workingCopy.addProjectFacet(getWebFacetVersionToInstall(workingCopy.getProject()));
      workingCopy.setProjectFacetActionConfig(WebFacetUtils.WEB_FACET, webModel);
      progress.worked(1);
    }
    AppEngineStandardFacet.installAllAppEngineRuntimes(workingCopy, progress.newChild(1));
  } catch (SAXException | IOException | AppEngineException ex) {
    throw new CoreException(StatusUtil.error(this, "Unable to retrieve appengine-web.xml", ex));
  }
}