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

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#getInputStream() . These examples are extracted from open source projects. 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
/**
 * Returns the loaded config and null otherwise.
 * 
 * @return the loaded config and null otherwise
 */
private T getConfig() {
	VirtualFile configFile = getConfigFile();
	if (configFile == null) {
		reset();
		return null;
	}
	try {
		long currentLastModified = configFile.getModificationStamp();
		if (currentLastModified != lastModified) {
			reset();
			try (InputStream input = configFile.getInputStream()) {
				config = loadConfig(input);
				lastModified = configFile.getModificationStamp();
			} catch (IOException e) {
				reset();
				LOGGER.error("Error while loading properties from '" + configFile + "'.", e);
			}
		}
	} catch (RuntimeException e1) {
		LOGGER.error("Error while getting last modified time for '" + configFile + "'.", e1);
	}
	return config;
}
 
Example 2
protected void doTestVariantsInner(String fileName) throws Throwable {
  final VirtualFile virtualFile = myFixture.copyFileToProject(fileName);
  final Scanner in = new Scanner(virtualFile.getInputStream());

  final CompletionType type = CompletionType.valueOf(in.next());
  final int count = in.nextInt();
  final CheckType checkType = CheckType.valueOf(in.next());

  final List<String> variants = new ArrayList<>();
  while (in.hasNext()) {
    final String variant = StringUtil.strip(in.next(), CharFilter.NOT_WHITESPACE_FILTER);
    if (variant.length() > 0) {
      variants.add(variant);
    }
  }

  myFixture.complete(type, count);
  checkCompletion(checkType, variants);
}
 
Example 3
protected void doTestVariantsInner(String fileName) throws Throwable {
  final VirtualFile virtualFile = myFixture.copyFileToProject(fileName);
  final Scanner in = new Scanner(virtualFile.getInputStream());

  final CompletionType type = CompletionType.valueOf(in.next());
  final int count = in.nextInt();
  final CheckType checkType = CheckType.valueOf(in.next());

  final List<String> variants = new ArrayList<String>();
  while (in.hasNext()) {
    final String variant = StringUtil.strip(in.next(), CharFilter.WHITESPACE_FILTER);
    if (variant.length() > 0) {
      variants.add(variant);
    }
  }

  myFixture.complete(type, count);
  checkCompletion(checkType, variants);
}
 
Example 4
protected void doTestVariantsInner(String fileName) throws Throwable {
  final VirtualFile virtualFile = myFixture.copyFileToProject(fileName);
  final Scanner in = new Scanner(virtualFile.getInputStream());

  final CompletionType type = CompletionType.valueOf(in.next());
  final int count = in.nextInt();
  final CheckType checkType = CheckType.valueOf(in.next());

  final List<String> variants = new ArrayList<String>();
  while (in.hasNext()) {
    final String variant = StringUtil.strip(in.next(), CharFilter.NOT_WHITESPACE_FILTER);
    if (variant.length() > 0) {
      variants.add(variant);
    }
  }

  myFixture.complete(type, count);
  checkCompletion(checkType, variants);
}
 
Example 5
Source Project: camel-idea-plugin   File: CamelService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Scans for third party maven repositories in the root pom.xml file of the module.
 *
 * @param module the module
 * @return a map with repo id and url for each found repository. The map may be empty if no third party repository is defined in the pom.xml file
 */
private @NotNull Map<String, String> scanThirdPartyMavenRepositories(@NotNull Module module) {
    Map<String, String> answer = new LinkedHashMap<>();

    VirtualFile vf = module.getProject().getBaseDir().findFileByRelativePath("pom.xml");
    if (vf != null) {
        try {
            InputStream is = vf.getInputStream();
            Document dom = loadDocument(is, false);
            NodeList list = dom.getElementsByTagName("repositories");
            if (list != null && list.getLength() == 1) {
                Node repos = list.item(0);
                if (repos instanceof Element) {
                    Element element = (Element) repos;
                    list = element.getElementsByTagName("repository");
                    if (list != null && list.getLength() > 0) {
                        for (int i = 0; i < list.getLength(); i++) {
                            Node node = list.item(i);
                            // grab id and url
                            Node id = getChildNodeByTagName(node, "id");
                            Node url = getChildNodeByTagName(node, "url");
                            if (id != null && url != null) {
                                LOG.info("Found third party Maven repository id: " + id.getTextContent() + " url:" + url.getTextContent());
                                answer.put(id.getTextContent(), url.getTextContent());
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            LOG.warn("Error parsing Maven pon.xml file", e);
        }
    }

    return answer;
}
 
Example 6
@Override
public void runActivity(@NotNull Project project) {
    final GraphQLSettings settings = GraphQLSettings.getSettings(project);
    if (settings.isEnableRelayModernFrameworkSupport()) {
        // already enabled Relay Modern
        return;
    }
    try {
        final GlobalSearchScope scope = GlobalSearchScope.projectScope(project);
        for (VirtualFile virtualFile : FilenameIndex.getVirtualFilesByName(project, "package.json", scope)) {
            if (!virtualFile.isDirectory() && virtualFile.isInLocalFileSystem()) {
                try (InputStream inputStream = virtualFile.getInputStream()) {
                    final String packageJson = IOUtils.toString(inputStream, virtualFile.getCharset());
                    if (packageJson.contains("\"react-relay\"") || packageJson.contains("\"relay-compiler\"")) {
                        final Notification enableRelayModern = new Notification("GraphQL", "Relay Modern project detected", "<a href=\"enable\">Enable Relay Modern</a> GraphQL tooling", NotificationType.INFORMATION, (notification, event) -> {
                            settings.setEnableRelayModernFrameworkSupport(true);
                            ApplicationManager.getApplication().saveSettings();
                            notification.expire();
                            DaemonCodeAnalyzer.getInstance(project).restart();
                            EditorNotifications.getInstance(project).updateAllNotifications();
                        });
                        enableRelayModern.setImportant(true);
                        Notifications.Bus.notify(enableRelayModern);
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Unable to detect Relay Modern", e);
    }
}
 
Example 7
Source Project: p4ic4idea   File: FileConfigPart.java    License: Apache License 2.0 5 votes vote down vote up
private static Properties loadProps(@Nullable VirtualFile filePath) throws IOException {
    Properties props = new Properties();
    if (filePath != null) {
        try (InputStreamReader reader = new InputStreamReader(filePath.getInputStream(), filePath.getCharset())) {
            // The Perforce config file is NOT the same as a Java
            // config file.  Java config files will read the "\" as
            // an escape character, whereas the Perforce config file
            // will keep it.

            try (BufferedReader inp = new BufferedReader(reader)) {
                String line;
                while ((line = inp.readLine()) != null) {
                    int pos = line.indexOf('=');
                    if (pos > 0) {
                        final String key = line.substring(0, pos).trim();
                        final String value = line.substring(pos + 1).trim();
                        // NOTE: an empty value is a set value!
                        if (key.length() > 0) {
                            props.setProperty(key, value);
                        }
                    }
                }
            }
        }
    }
    LOG.debug("Loaded property file " + filePath + " keys " + props.keySet());
    return props;
}
 
Example 8
private InputStream getContents(Project project, Editor editor, VirtualFile file) throws IOException {
    editor = getEditor(project, editor, file);
    if (editor != null) {
        return new ByteArrayInputStream(getText(editor).getBytes());
    } else {
        return file.getInputStream();
    }
}
 
Example 9
/**
 * Check whether all the class path entries in the manifest are valid.
 *
 * @param project current project.
 * @return true iff the manifest jar is valid.
 */
private static boolean isManifestJarValid(@NotNull Project project) {
  Optional<VirtualFile> manifestJar = PantsUtil.findProjectManifestJar(project);
  if (!manifestJar.isPresent()) {
    return false;
  }
  VirtualFile file = manifestJar.get();
  if (!new File(file.getPath()).exists()) {
    return false;
  }
  try {
    VirtualFile manifestInJar =
      VirtualFileManager.getInstance().refreshAndFindFileByUrl("jar://" + file.getPath() + "!/META-INF/MANIFEST.MF");
    if (manifestInJar == null) {
      return false;
    }
    Manifest manifest = new Manifest(manifestInJar.getInputStream());
    List<String> relPaths = PantsUtil.parseCmdParameters(manifest.getMainAttributes().getValue("Class-Path"));
    for (String path : relPaths) {
      // All rel paths in META-INF/MANIFEST.MF is relative to the jar directory
      if (!new File(file.getParent().getPath(), path).exists()) {
        return false;
      }
    }
    return true;
  }
  catch (IOException e) {
    e.printStackTrace();
    return false;
  }
}
 
Example 10
Source Project: saros   File: IntellijFile.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
@NotNull
public InputStream getContents() throws IOException {
  VirtualFile virtualFile = getVirtualFile();

  if (!existsInternal(virtualFile)) {
    throw new FileNotFoundException(
        "Could not obtain contents for " + this + " as it does not exist or is not valid");
  }

  return virtualFile.getInputStream();
}
 
Example 11
Source Project: consulo   File: VirtualFileImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public InputStream getInputStream() throws IOException {
  if (myFileInfo != null) {
    VirtualFile localFile = myFileInfo.getLocalFile();
    if (localFile != null) {
      return localFile.getInputStream();
    }
  }
  throw new UnsupportedOperationException();
}
 
Example 12
Source Project: consulo   File: LocalAttachHost.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public InputStream getFileContent(@Nonnull String filePath) throws IOException {
  VirtualFile file = LocalFileSystem.getInstance().findFileByPath(filePath);
  if (file == null) {
    return null;
  }

  return file.getInputStream();
}
 
Example 13
Source Project: p4ic4idea   File: IgnoreFileSet.java    License: Apache License 2.0 4 votes vote down vote up
static IgnoreFileSet create(@NotNull VirtualFile ignoreFile)
        throws IOException {
    try (InputStreamReader reader = new InputStreamReader(ignoreFile.getInputStream(), ignoreFile.getCharset())) {
        return new IgnoreFileSet(ignoreFile, IgnoreFilePattern.parseFile(reader));
    }
}
 
Example 14
Source Project: consulo   File: JdkUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @return the specified attribute of the JDK (examines rt.jar) or null if cannot determine the value
 */
@javax.annotation.Nullable
public static String getJdkMainAttribute(@Nonnull Sdk jdk, Attributes.Name attributeName) {
  final VirtualFile homeDirectory = jdk.getHomeDirectory();
  if (homeDirectory == null) {
    return null;
  }
  VirtualFile rtJar = homeDirectory.findFileByRelativePath("jre/lib/rt.jar");
  if (rtJar == null) {
    rtJar = homeDirectory.findFileByRelativePath("lib/rt.jar");
  }
  if (rtJar == null) {
    rtJar = homeDirectory.findFileByRelativePath("jre/lib/vm.jar"); // for IBM jdk
  }
  if (rtJar == null) {
    rtJar = homeDirectory.findFileByRelativePath("../Classes/classes.jar"); // for mac
  }
  if (rtJar == null) {
    String versionString = jdk.getVersionString();
    if (versionString != null) {
      final int start = versionString.indexOf("\"");
      final int end = versionString.lastIndexOf("\"");
      versionString = start >= 0 && (end > start)? versionString.substring(start + 1, end) : null;
    }
    return versionString;
  }

  VirtualFile archiveRootForLocalFile = ArchiveVfsUtil.getArchiveRootForLocalFile(rtJar);
  if(archiveRootForLocalFile == null) {
    return null;
  }
  try {
    VirtualFile manifestArchiveFile = archiveRootForLocalFile.findFileByRelativePath(JarFile.MANIFEST_NAME);
    if (manifestArchiveFile == null) {
      return null;
    }
    InputStream is = manifestArchiveFile.getInputStream();
    Manifest manifest = new Manifest(is);
    is.close();
    Attributes attributes = manifest.getMainAttributes();
    return attributes.getValue(attributeName);
  }
  catch (IOException e) {
    // nothing
  }
  return null;
}
 
Example 15
Source Project: consulo   File: NanoXmlUtil.java    License: Apache License 2.0 4 votes vote down vote up
@Nonnull
public static XmlFileHeader parseHeaderWithException(final VirtualFile file) throws IOException {
  try (InputStream stream = file.getInputStream()) {
    return parseHeader(new MyXMLReader(stream));
  }
}