com.intellij.util.io.URLUtil Java Examples

The following examples show how to use com.intellij.util.io.URLUtil. 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: VfsUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * @return correct URL, must be used only for external communication
 */
@Nonnull
public static URI toUri(@Nonnull VirtualFile file) {
  String path = file.getPath();
  try {
    String protocol = file.getFileSystem().getProtocol();
    if (file.isInLocalFileSystem()) {
      if (SystemInfo.isWindows && path.charAt(0) != '/') {
        path = '/' + path;
      }
      return new URI(protocol, "", path, null, null);
    }
    if (URLUtil.HTTP_PROTOCOL.equals(protocol)) {
      return new URI(URLUtil.HTTP_PROTOCOL + URLUtil.SCHEME_SEPARATOR + path);
    }
    return new URI(protocol, path, null);
  }
  catch (URISyntaxException e) {
    throw new IllegalArgumentException(e);
  }
}
 
Example #2
Source File: BlazeJavaScriptTestRunLineMarkerContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static Icon getClosureTestIcon(
    Project project, Collection<Label> labels, JSFile file, JSFunction function) {
  WorkspaceRoot root = WorkspaceRoot.fromProject(project);
  WorkspacePath path = root.workspacePathFor(file.getVirtualFile());
  String relativePath = root.directory().getName() + '/' + path.relativePath();
  if (relativePath.endsWith(".js")) {
    relativePath = relativePath.substring(0, relativePath.lastIndexOf(".js"));
  }
  String urlSuffix =
      relativePath
          + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
          + function.getName()
          + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
          + relativePath; // redundant class name
  return labels.stream()
      .map(
          label ->
              SmRunnerUtils.GENERIC_TEST_PROTOCOL
                  + URLUtil.SCHEME_SEPARATOR
                  + label
                  + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
                  + urlSuffix)
      .map(url -> getTestStateIcon(url, project, /* isClass = */ false))
      .max(Comparator.comparingInt(iconPriorities::get))
      .orElse(TestState.Run);
}
 
Example #3
Source File: BlazeScalaTestRunLineMarkerContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
private static String getSpecs2TestUrl(ScClass testClass, ScInfixExpr testCase) {
  String name = null;
  String protocol = null;
  if (TestNodeProvider.isSpecs2ScopeExpr(testCase)) {
    protocol = SmRunnerUtils.GENERIC_SUITE_PROTOCOL;
    name = Specs2Utils.getSpecs2ScopeName(testCase);
  } else if (TestNodeProvider.isSpecs2Expr(testCase)) {
    protocol = SmRunnerUtils.GENERIC_TEST_PROTOCOL;
    name = Specs2Utils.getSpecs2ScopedTestName(testCase);
  }
  if (name == null) {
    return null;
  }
  return protocol
      + URLUtil.SCHEME_SEPARATOR
      + testClass.getQualifiedName()
      + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
      + name;
}
 
Example #4
Source File: NewLibraryEditor.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void collectJarFiles(@Nonnull VirtualFile dir, @Nonnull List<? super VirtualFile> container, final boolean recursively) {
  VfsUtilCore.visitChildrenRecursively(dir, new VirtualFileVisitor(VirtualFileVisitor.SKIP_ROOT, recursively ? null : VirtualFileVisitor.ONE_LEVEL_DEEP) {
    @Override
    public boolean visitFile(@Nonnull VirtualFile file) {
      FileType type;
      if (!file.isDirectory() && (type = FileTypeRegistry.getInstance().getFileTypeByFileName(file.getNameSequence())) instanceof ArchiveFileType) {
        VirtualFile jarRoot = ((ArchiveFileType)type).getFileSystem().findFileByPath(file.getPath() + URLUtil.JAR_SEPARATOR);
        if (jarRoot != null) {
          container.add(jarRoot);
          return false;
        }
      }
      return true;
    }
  });
}
 
Example #5
Source File: UrlImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public String toDecodedForm() {
  StringBuilder builder = new StringBuilder();
  if (scheme != null) {
    builder.append(scheme);
    if (authority != null || isInLocalFileSystem()) {
      builder.append(URLUtil.SCHEME_SEPARATOR);
    }
    else {
      builder.append(':');
    }

    if (authority != null) {
      builder.append(authority);
    }
  }
  builder.append(getPath());
  if (parameters != null) {
    builder.append(parameters);
  }
  return builder.toString();
}
 
Example #6
Source File: BlazeJavaTestEventsHandler.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
public String testLocationUrl(
    Label label,
    @Nullable Kind kind,
    String parentSuite,
    String name,
    @Nullable String classname) {
  if (classname == null) {
    return null;
  }
  String classComponent = JavaTestLocator.TEST_PROTOCOL + URLUtil.SCHEME_SEPARATOR + classname;
  String parameterComponent = extractParameterComponent(name);
  if (parameterComponent != null) {
    return classComponent + TEST_CASE_SEPARATOR + parentSuite + parameterComponent;
  }
  return classComponent + TEST_CASE_SEPARATOR + name;
}
 
Example #7
Source File: PostfixTemplateMetaData.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected URL getDirURL() {
  if (urlDir != null) {
    return urlDir;
  }

  final URL pageURL = myLoader.getResource(DESCRIPTION_FOLDER + "/" + myDescriptionDirectoryName + "/" + DESCRIPTION_FILE_NAME);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Path:" + DESCRIPTION_FOLDER + "/" + myDescriptionDirectoryName);
    LOG.debug("URL:" + pageURL);
  }
  if (pageURL != null) {
    try {
      final String url = pageURL.toExternalForm();
      urlDir = URLUtil.internProtocol(new URL(url.substring(0, url.lastIndexOf('/'))));
      return urlDir;
    }
    catch (MalformedURLException e) {
      LOG.error(e);
    }
  }
  return null;
}
 
Example #8
Source File: IntentionActionMetaData.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static URL getIntentionDescriptionDirURL(ClassLoader aClassLoader, String intentionFolderName) {
  final URL pageURL = aClassLoader.getResource(INTENTION_DESCRIPTION_FOLDER + "/" + intentionFolderName+"/"+ DESCRIPTION_FILE_NAME);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Path:"+"intentionDescriptions/" + intentionFolderName);
    LOG.debug("URL:"+pageURL);
  }
  if (pageURL != null) {
    try {
      final String url = pageURL.toExternalForm();
      return URLUtil.internProtocol(new URL(url.substring(0, url.lastIndexOf('/'))));
    }
    catch (MalformedURLException e) {
      LOG.error(e);
    }
  }
  return null;
}
 
Example #9
Source File: BlazeWebTestEventsHandler.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
public String testLocationUrl(
    Label label,
    @Nullable Kind kind,
    String parentSuite,
    String name,
    @Nullable String className) {
  return WEB_TEST_PROTOCOL
      + URLUtil.SCHEME_SEPARATOR
      + label
      + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
      + parentSuite
      + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
      + name
      + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
      + Strings.nullToEmpty(className);
}
 
Example #10
Source File: HaxeClasspathEntry.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
public HaxeClasspathEntry(@Nullable String name, @NotNull String url) {
  myName = name;
  myUrl = url;

  // Try to fix the URL if it wasn't correct.
  if (!url.contains(URLUtil.SCHEME_SEPARATOR)) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Fixing malformed URL passed by " + HaxeDebugUtil.printCallers(5));
    }
    VirtualFileSystem vfs = VirtualFileManager.getInstance().getFileSystem(LocalFileSystem.PROTOCOL);
    VirtualFile file = vfs.findFileByPath(url);
    if (null != file) {
      myUrl = file.getUrl();
    }
  }

  if (null != myName) {
    if (HaxelibNameUtil.isManagedLibrary(myName)) {
      myName = HaxelibNameUtil.parseHaxelib(myName);
      myIsManagedEntry = true;
    }
  }
}
 
Example #11
Source File: OrderEntryAppearanceServiceImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public CellAppearanceEx forLibrary(Project project, @Nonnull final Library library, final boolean hasInvalidRoots) {
  final StructureConfigurableContext context = ProjectStructureConfigurable.getInstance(project).getContext();
  final Image icon = LibraryPresentationManager.getInstance().getCustomIcon(library, context);

  final String name = library.getName();
  if (name != null) {
    return normalOrRedWaved(name, (icon != null ? icon :  AllIcons.Nodes.PpLib), hasInvalidRoots);
  }

  final String[] files = library.getUrls(BinariesOrderRootType.getInstance());
  if (files.length == 0) {
    return SimpleTextCellAppearance.invalid(ProjectBundle.message("library.empty.library.item"),  AllIcons.Nodes.PpLib);
  }
  else if (files.length == 1) {
    return forVirtualFilePointer(new LightFilePointer(files[0]));
  }

  final String url = StringUtil.trimEnd(files[0], URLUtil.ARCHIVE_SEPARATOR);
  return SimpleTextCellAppearance.regular(PathUtil.getFileName(url),  AllIcons.Nodes.PpLib);
}
 
Example #12
Source File: OutputArtifactParser.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public OutputArtifact parse(
    BuildEventStreamProtos.File file,
    String configurationMnemonic,
    long syncStartTimeMillis) {
  String uri = file.getUri();
  if (uri == null || !uri.startsWith(URLUtil.FILE_PROTOCOL)) {
    return null;
  }
  try {
    File f = new File(new URI(uri));
    return new LocalFileOutputArtifact(
        f, getBlazeOutRelativePath(file, configurationMnemonic), configurationMnemonic);
  } catch (URISyntaxException | IllegalArgumentException e) {
    return null;
  }
}
 
Example #13
Source File: SchemesManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void loadBundledScheme(@Nonnull String resourceName, @Nonnull Object requestor, @Nonnull ThrowableConvertor<Element, T, Throwable> convertor) {
  try {
    URL url = requestor instanceof AbstractExtensionPointBean
              ? (((AbstractExtensionPointBean)requestor).getLoaderForClass().getResource(resourceName))
              : DecodeDefaultsUtil.getDefaults(requestor, resourceName);
    if (url == null) {
      // Error shouldn't occur during this operation thus we report error instead of info
      LOG.error("Cannot read scheme from " + resourceName);
      return;
    }
    addNewScheme(convertor.convert(JDOMUtil.load(URLUtil.openStream(url))), false);
  }
  catch (Throwable e) {
    LOG.error("Cannot read scheme from " + resourceName, e);
  }
}
 
Example #14
Source File: BlazeLibrary.java    From intellij with Apache License 2.0 6 votes vote down vote up
protected static String pathToUrl(File path) {
  String name = path.getName();
  boolean isJarFile =
      FileUtilRt.extensionEquals(name, "jar")
          || FileUtilRt.extensionEquals(name, "srcjar")
          || FileUtilRt.extensionEquals(name, "zip");
  // .jar files require an URL with "jar" protocol.
  String protocol =
      isJarFile
          ? StandardFileSystems.JAR_PROTOCOL
          : VirtualFileSystemProvider.getInstance().getSystem().getProtocol();
  String filePath = FileUtil.toSystemIndependentName(path.getPath());
  String url = VirtualFileManager.constructUrl(protocol, filePath);
  if (isJarFile) {
    url += URLUtil.JAR_SEPARATOR;
  }
  return url;
}
 
Example #15
Source File: ResourceUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static String loadText(@Nonnull URL url) throws IOException {
  InputStream inputStream = new BufferedInputStream(URLUtil.openStream(url));

  InputStreamReader reader = new InputStreamReader(inputStream, ENCODING_UTF_8);
  try {
    StringBuilder text = new StringBuilder();
    char[] buf = new char[5000];
    while (reader.ready()) {
      final int length = reader.read(buf);
      if (length == -1) break;
      text.append(buf, 0, length);
    }
    return text.toString();
  }
  finally {
    reader.close();
  }
}
 
Example #16
Source File: BlazeAndroidTestEventsHandler.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
public String testLocationUrl(
    Label label,
    @Nullable Kind kind,
    String parentSuite,
    String name,
    @Nullable String className) {
  // ignore initial value of className -- it's the test runner class.
  name = StringUtil.trimTrailing(name, '-');
  if (!name.contains("-")) {
    return SmRunnerUtils.GENERIC_SUITE_PROTOCOL + URLUtil.SCHEME_SEPARATOR + name;
  }
  int ix = name.lastIndexOf('-');
  className = name.substring(0, ix);
  String methodName = name.substring(ix + 1);
  return SmRunnerUtils.GENERIC_SUITE_PROTOCOL
      + URLUtil.SCHEME_SEPARATOR
      + className
      + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
      + methodName;
}
 
Example #17
Source File: UriUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Splits the url into 2 parts: the scheme ("http", for instance) and the rest of the URL. <br/>
 * Scheme separator is not included neither to the scheme part, nor to the url part. <br/>
 * The scheme can be absent, in which case empty string is written to the first item of the Pair.
 */
@Nonnull
public static Couple<String> splitScheme(@Nonnull String url) {
  ArrayList<String> list = Lists.newArrayList(Splitter.on(URLUtil.SCHEME_SEPARATOR).limit(2).split(url));
  if (list.size() == 1) {
    return Couple.of("", list.get(0));
  }
  return Couple.of(list.get(0), list.get(1));
}
 
Example #18
Source File: UrlImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String getPath() {
  if (decodedPath == null) {
    decodedPath = URLUtil.unescapePercentSequences(path);
  }
  return decodedPath;
}
 
Example #19
Source File: VfsUtilCore.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String convertFromUrl(@Nonnull URL url) {
  String protocol = url.getProtocol();
  String path = url.getPath();
  if (protocol.equals(URLUtil.JAR_PROTOCOL)) {
    if (StringUtil.startsWithConcatenation(path, URLUtil.FILE_PROTOCOL, PROTOCOL_DELIMITER)) {
      try {
        URL subURL = new URL(path);
        path = subURL.getPath();
      }
      catch (MalformedURLException e) {
        throw new RuntimeException(VfsBundle.message("url.parse.unhandled.exception"), e);
      }
    }
    else {
      throw new RuntimeException(new IOException(VfsBundle.message("url.parse.error", url.toExternalForm())));
    }
  }
  if (SystemInfo.isWindows || SystemInfo.isOS2) {
    while (!path.isEmpty() && path.charAt(0) == '/') {
      path = path.substring(1, path.length());
    }
  }

  path = URLUtil.unescapePercentSequences(path);
  return protocol + "://" + path;
}
 
Example #20
Source File: HaxelibClasspathUtils.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the first file on the classpath having the given name or relative path.
 * This is attempting to emulate what the compiler would do.
 *
 * @param module - Module from which to gather the classpath.
 * @param filePath - filePath name or relative path.
 * @return a VirtualFile if found, or null otherwise.
 */
@Nullable
public static VirtualFile findFileOnClasspath(@NotNull final Module module, @NotNull final String filePath) {
  if (filePath.isEmpty()) {
    return null;
  }

  return ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile>() {
    @Override
    public VirtualFile compute() {
      final String fixedPath = null == VirtualFileManager.extractProtocol(filePath)
                                ? VirtualFileManager.constructUrl(URLUtil.FILE_PROTOCOL, filePath)
                                : filePath;
      VirtualFile found = VirtualFileManager.getInstance().findFileByUrl(fixedPath);
      if (null == found) {
        found = findFileOnOneClasspath(getImplicitClassPath(module), filePath);
      }
      if (null == found) {
        found = findFileOnOneClasspath(getModuleClasspath(module), filePath);
      }
      if (null == found) {
        found = findFileOnOneClasspath(getProjectLibraryClasspath(module.getProject()), filePath);
      }
      if (null == found) {
        // This grabs either the module's SDK, or the inherited one, if any.
        found = findFileOnOneClasspath(getSdkClasspath(HaxelibSdkUtils.lookupSdk(module)), filePath);
      }
      return found;
    }
  });
}
 
Example #21
Source File: Urls.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static Url parse(@Nonnull String url, boolean asLocalIfNoScheme) {
  if (url.isEmpty()) {
    return null;
  }

  if (asLocalIfNoScheme && !URLUtil.containsScheme(url)) {
    // nodejs debug — files only in local filesystem
    return newLocalFileUrl(url);
  }
  return parseUrl(URLUtil.toIdeaUrl(url));
}
 
Example #22
Source File: CustomProtocolHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public List<String> getOpenArgs(URI uri) {
  final List<String> args = new ArrayList<String>();
  final String query = uri.getQuery();
  String file = null;
  String line = null;
  if (query != null) {
    for (String param : query.split("&")) {
      String[] pair = param.split("=");
      String key = URLUtil.unescapePercentSequences(pair[0]);
      if (pair.length > 1) {
        if ("file".equals(key)) {
          file = URLUtil.unescapePercentSequences(pair[1]);
        } else if ("line".equals(key)) {
          line = URLUtil.unescapePercentSequences(pair[1]);
        }
      }
    }
  }

  if (file != null) {
    if (line != null) {
      args.add(LINE_NUMBER_ARG_NAME);
      args.add(line);
    }
    args.add(file);
  }
  return args;
}
 
Example #23
Source File: ArchiveFileSystemBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public VirtualFile findLocalVirtualFileByPath(@Nonnull String path) {
  if (!path.contains(URLUtil.ARCHIVE_SEPARATOR)) {
    path += URLUtil.ARCHIVE_SEPARATOR;
  }
  return findFileByPath(path);
}
 
Example #24
Source File: DecodeDefaultsUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static InputStream getDefaultsInputStream(Object requestor, final String componentResourcePath) {
  try {
    final URL defaults = getDefaults(requestor, componentResourcePath);
    return defaults != null ? URLUtil.openStream(defaults) : null;
  }
  catch (IOException e) {
    LOG.error(e);
    return null;
  }
}
 
Example #25
Source File: LocalFileSystemImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static WatchRequestImpl watch(String rootPath, boolean recursively) {
  int index = rootPath.indexOf(URLUtil.ARCHIVE_SEPARATOR);
  if (index >= 0) rootPath = rootPath.substring(0, index);

  File rootFile = new File(FileUtil.toSystemDependentName(rootPath));
  if (!rootFile.isAbsolute()) {
    LOG.warn(new IllegalArgumentException("Invalid path: " + rootPath));
    return null;
  }

  return new WatchRequestImpl(rootFile.getAbsolutePath(), recursively);
}
 
Example #26
Source File: ArchiveFileSystemBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected String normalize(@Nonnull String path) {
  final int jarSeparatorIndex = path.indexOf(URLUtil.ARCHIVE_SEPARATOR);
  if (jarSeparatorIndex > 0) {
    final String root = path.substring(0, jarSeparatorIndex);
    return FileUtil.normalize(root) + path.substring(jarSeparatorIndex);
  }
  return super.normalize(path);
}
 
Example #27
Source File: ResourceModuleContentRootCustomizer.java    From intellij with Apache License 2.0 5 votes vote down vote up
@NotNull
private static String pathToUrl(@NotNull String filePath) {
  filePath = FileUtil.toSystemIndependentName(filePath);
  if (filePath.endsWith(".srcjar") || filePath.endsWith(".jar")) {
    return URLUtil.JAR_PROTOCOL + URLUtil.SCHEME_SEPARATOR + filePath + URLUtil.JAR_SEPARATOR;
  } else if (filePath.contains("src.jar!")) {
    return URLUtil.JAR_PROTOCOL + URLUtil.SCHEME_SEPARATOR + filePath;
  } else {
    return VfsUtilCore.pathToUrl(filePath);
  }
}
 
Example #28
Source File: ArchiveFileSystemBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void setNoCopyJarForPath(String pathInJar) {
  if (myNoCopyJarPaths == null || pathInJar == null) return;
  int index = pathInJar.indexOf(URLUtil.ARCHIVE_SEPARATOR);
  if (index < 0) return;
  String path = FileUtil.toSystemIndependentName(pathInJar.substring(0, index));
  myNoCopyJarPaths.add(path);
}
 
Example #29
Source File: CompilerConfigurationImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String getCompilerOutputUrl() {
  if (myOutputDirPointer == null) {
    return VirtualFileManager.constructUrl(URLUtil.FILE_PROTOCOL, FileUtil.toSystemIndependentName(myProject.getBasePath()) + "/" + DEFAULT_OUTPUT_URL);
  }
  return myOutputDirPointer.getUrl();
}
 
Example #30
Source File: PackagingElementFactoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public PackagingElement<?> createExtractedDirectory(@Nonnull VirtualFile jarEntry) {
  LOG.assertTrue(jarEntry.getFileSystem() instanceof ArchiveFileSystem, "Expected file from jar but file from " + jarEntry.getFileSystem() + " found");
  final String fullPath = jarEntry.getPath();
  final int jarEnd = fullPath.indexOf(URLUtil.ARCHIVE_SEPARATOR);
  return new ExtractedDirectoryPackagingElement(fullPath.substring(0, jarEnd), fullPath.substring(jarEnd + 1));
}