public static String canonicalizePath(@NotNull String url, @NotNull Url baseUrl, boolean baseUrlIsFile) { String path = url; if (url.charAt(0) != '/') { String basePath = baseUrl.getPath(); if (baseUrlIsFile) { int lastSlashIndex = basePath.lastIndexOf('/'); StringBuilder pathBuilder = new StringBuilder(); if (lastSlashIndex == -1) { pathBuilder.append('/'); } else { pathBuilder.append(basePath, 0, lastSlashIndex + 1); } path = pathBuilder.append(url).toString(); } else { path = basePath + '/' + url; } } path = FileUtil.toCanonicalPath(path, '/'); return path; }
@Nullable public MappingList findMappings(@NotNull List<Url> sourceUrls, @NotNull SourceMap sourceMap, @Nullable VirtualFile sourceFile) { for (Url sourceUrl : sourceUrls) { int index = canonicalizedSourcesMap.get(sourceUrl); if (index != -1) { return sourceMap.sourceIndexToMappings[index]; } } if (sourceFile != null) { MappingList mappings = findByFile(sourceMap, sourceFile); if (mappings != null) { return mappings; } } return null; }
@NotNull public static List<Url> getUrls(@NotNull VirtualFile file, @NotNull Project project, @Nullable String currentAuthority) { if (currentAuthority != null && !compareAuthority(currentAuthority)) { return Collections.emptyList(); } String path = WebServerPathToFileManager.getInstance(project).getPath(file); if (path == null) { return Collections.emptyList(); } int effectiveBuiltInServerPort = BuiltInServerOptions.getInstance().getEffectiveBuiltInServerPort(); Url url = Urls.newHttpUrl(currentAuthority == null ? "localhost:" + effectiveBuiltInServerPort : currentAuthority, '/' + project.getName() + '/' + path); int defaultPort = BuiltInServerManager.getInstance().getPort(); if (currentAuthority != null || defaultPort == effectiveBuiltInServerPort) { return Collections.singletonList(url); } return Arrays.asList(url, Urls.newHttpUrl("localhost:" + defaultPort, '/' + project.getName() + '/' + path)); }
public synchronized HttpVirtualFileImpl getOrCreateFile(@Nullable HttpVirtualFileImpl parent, @NotNull Url url, @NotNull String path, final boolean directory) { Map<Url, HttpVirtualFileImpl> cache = directory ? remoteDirectories : remoteFiles; HttpVirtualFileImpl file = cache.get(url); if (file == null) { if (directory) { file = new HttpVirtualFileImpl(getHttpFileSystem(url), parent, path, null); } else { RemoteFileInfoImpl fileInfo = new RemoteFileInfoImpl(url, this); file = new HttpVirtualFileImpl(getHttpFileSystem(url), parent, path, fileInfo); fileInfo.addDownloadingListener(new MyDownloadingListener(file)); } cache.put(url, file); } return file; }
public static void setupUrlField(@NotNull TextFieldWithBrowseButton field, @NotNull final Project project) { FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false, false) { @Override public boolean isFileSelectable(VirtualFile file) { return HtmlUtil.isHtmlFile(file) || virtualFileToUrl(file, project) != null; } }; descriptor.setTitle(XmlBundle.message("javascript.debugger.settings.choose.file.title")); descriptor.setDescription(XmlBundle.message("javascript.debugger.settings.choose.file.subtitle")); descriptor.setRoots(ProjectRootManager.getInstance(project).getContentRoots()); field.addBrowseFolderListener(new TextBrowseFolderListener(descriptor, project) { @NotNull @Override protected String chosenFileToResultingText(@NotNull VirtualFile chosenFile) { if (chosenFile.isDirectory()) { return chosenFile.getPath(); } Url url = virtualFileToUrl(chosenFile, project); return url == null ? chosenFile.getUrl() : url.toDecodedForm(); } }); }
@NotNull @Override public Collection<Url> getUrlsToOpen(@NotNull OpenInBrowserRequest request, boolean preferLocalUrl) throws WebBrowserUrlProvider.BrowserException { boolean isHtmlOrXml = isHtmlOrXmlFile(request.getFile().getViewProvider().getBaseLanguage()); if (!preferLocalUrl || !isHtmlOrXml) { DumbService dumbService = DumbService.getInstance(request.getProject()); for (WebBrowserUrlProvider urlProvider : WebBrowserUrlProvider.EP_NAME.getExtensions()) { if ((!dumbService.isDumb() || DumbService.isDumbAware(urlProvider)) && urlProvider.canHandleElement(request)) { Collection<Url> urls = getUrls(urlProvider, request); if (!urls.isEmpty()) { return urls; } } } if (!isHtmlOrXml) { return Collections.emptyList(); } } VirtualFile file = request.getVirtualFile(); return file instanceof LightVirtualFile || !request.getFile().getViewProvider().isPhysical() ? Collections.<Url>emptyList() : Collections.singletonList(Urls.newFromVirtualFile(file)); }
@NotNull private static Collection<Url> getUrls(@Nullable WebBrowserUrlProvider provider, @NotNull OpenInBrowserRequest request) throws WebBrowserUrlProvider.BrowserException { if (provider != null) { if (request.getResult() != null) { return request.getResult(); } try { return provider.getUrls(request); } catch (WebBrowserUrlProvider.BrowserException e) { if (!HtmlUtil.isHtmlFile(request.getFile())) { throw e; } } } return Collections.emptyList(); }
@Nullable private Url previewUrl(OpenInBrowserRequest request, VirtualFile virtualFile, GaugeSettingsModel settings) throws IOException, InterruptedException { ProcessBuilder builder = new ProcessBuilder(settings.getGaugePath(), Constants.DOCS, Spectacle.NAME, virtualFile.getPath()); String projectName = request.getProject().getName(); builder.environment().put("spectacle_out_dir", createOrGetTempDirectory(projectName).getPath() + "/docs"); builder.directory(GaugeUtil.moduleDir(GaugeUtil.moduleForPsiElement(request.getFile()))); GaugeUtil.setGaugeEnvironmentsTo(builder, settings); Process docsProcess = builder.start(); int exitCode = docsProcess.waitFor(); if (exitCode != 0) { String docsOutput = String.format("<pre>%s</pre>", GaugeUtil.getOutput(docsProcess.getInputStream(), " ").replace("<", "<").replace(">", ">")); Notifications.Bus.notify(new Notification("Specification Preview", "Error: Specification Preview", docsOutput, NotificationType.ERROR)); return null; } return new UrlImpl(FileUtil.join(createOrGetTempDirectory(projectName).getPath(), "docs/html/specs/" + virtualFile.getNameWithoutExtension() + ".html")); }
public static boolean parseAndCheckIsLocalHost(String uri, boolean onlyAnyOrLoopback, boolean hostsOnly) { if (uri == null || uri.equals("about:blank")) { return true; } try { Url parsedUri = Urls.parse(uri, false); if (parsedUri == null) { return false; } String host = getHost(parsedUri); return host != null && (isTrustedChromeExtension(parsedUri) || isLocalHost(host, onlyAnyOrLoopback, hostsOnly)); } catch (Exception ignored) { } return false; }
@Override public Image get(Object key) { if (myManager == null || key == null) return null; PsiElement element = getElement(); if (element == null) return null; URL url = (URL)key; Image inMemory = myManager.getElementImage(element, url.toExternalForm()); if (inMemory != null) { return inMemory; } Url parsedUrl = Urls.parseEncoded(url.toExternalForm()); BuiltInServerManager builtInServerManager = BuiltInServerManager.getInstance(); if (parsedUrl != null && builtInServerManager.isOnBuiltInWebServer(parsedUrl)) { try { url = new URL(builtInServerManager.addAuthToken(parsedUrl).toExternalForm()); } catch (MalformedURLException e) { LOG.warn(e); } } return Toolkit.getDefaultToolkit().createImage(url); }
public boolean canHandleElement(@NotNull OpenInBrowserRequest request) { try { Collection<Url> urls = getUrls(request); if(!urls.isEmpty()) { request.setResult(urls); return true; } } catch(BrowserException ignored) { } return false; }
@Nullable public static Url getUrlForContext(@NotNull PsiElement sourceElement) { Url url; try { Collection<Url> urls = WebBrowserService.getInstance().getUrlsToOpen(sourceElement, false); url = ContainerUtil.getFirstItem(urls); if(url == null) { return null; } } catch(WebBrowserUrlProvider.BrowserException ignored) { return null; } VirtualFile virtualFile = sourceElement.getContainingFile().getVirtualFile(); if(virtualFile == null) { return null; } return !url.isInLocalFileSystem() || HtmlUtil.isHtmlFile(virtualFile) ? url : null; }
@Nullable @Override protected Url getUrl(@NotNull OpenInBrowserRequest request, @NotNull VirtualFile file) throws BrowserException { SwaggerFileService swaggerFileService = ServiceManager.getService(SwaggerFileService.class); Optional<Path> swaggerHTMLFolder = swaggerFileService.convertSwaggerToHtml(request.getFile()); return swaggerHTMLFolder .map(SwaggerFilesUtils::convertSwaggerLocationToUrl) .orElse(null); }
@Test public void test() throws IOException { Path path = Files.createTempDirectory(""); Url url = SwaggerFilesUtils.convertSwaggerLocationToUrl(path); Assert.assertEquals(url.getPath(), path.toString() + File.separator + "index.html"); }
protected ScriptBase(@NotNull Type type, @NotNull Url url, int line, int column, int endLine) { this.type = type; this.url = url; this.line = line; this.column = column; this.endLine = endLine; }
@Nullable public MappingList findMappingList(@NotNull List<Url> sourceUrls, @Nullable VirtualFile sourceFile, @Nullable NullableLazyValue<SourceResolver.Resolver> resolver) { MappingList mappings = sourceResolver.findMappings(sourceUrls, this, sourceFile); if (mappings == null && resolver != null) { SourceResolver.Resolver resolverValue = resolver.getValue(); if (resolverValue != null) { mappings = sourceResolver.findMappings(sourceFile, this, resolverValue); } } return mappings; }
public boolean processMappingsInLine(@NotNull List<Url> sourceUrls, int sourceLine, @NotNull MappingList.MappingsProcessorInLine mappingProcessor, @Nullable VirtualFile sourceFile, @Nullable NullableLazyValue<SourceResolver.Resolver> resolver) { MappingList mappings = findMappingList(sourceUrls, sourceFile, resolver); return mappings != null && mappings.processMappingsInLine(sourceLine, mappingProcessor); }
public SourceResolver(@NotNull List<String> sourceUrls, boolean trimFileScheme, @Nullable Url baseFileUrl, boolean baseUrlIsFile, @Nullable List<String> sourceContents) { rawSources = sourceUrls; this.sourceContents = sourceContents; canonicalizedSources = new Url[sourceUrls.size()]; canonicalizedSourcesMap = SystemInfo.isFileSystemCaseSensitive ? new ObjectIntHashMap<Url>(canonicalizedSources.length) : new ObjectIntHashMap<Url>(canonicalizedSources.length, Urls.getCaseInsensitiveUrlHashingStrategy()); for (int i = 0; i < sourceUrls.size(); i++) { String rawSource = sourceUrls.get(i); Url url = canonicalizeUrl(rawSource, baseFileUrl, trimFileScheme, i, baseUrlIsFile); canonicalizedSources[i] = url; canonicalizedSourcesMap.put(url, i); } }
protected Url canonicalizeUrl(@NotNull String url, @Nullable Url baseUrl, boolean trimFileScheme, int sourceIndex, boolean baseUrlIsFile) { if (trimFileScheme && url.startsWith(StandardFileSystems.FILE_PROTOCOL_PREFIX)) { return Urls.newLocalFileUrl(FileUtil.toCanonicalPath(VfsUtilCore.toIdeaUrl(url, true).substring(StandardFileSystems.FILE_PROTOCOL_PREFIX.length()), '/')); } else if (baseUrl == null || url.contains(URLUtil.SCHEME_SEPARATOR) || url.startsWith("data:") || url.startsWith("blob:") || url.startsWith("javascript:")) { return Urls.parseEncoded(url); } String path = canonicalizePath(url, baseUrl, baseUrlIsFile); if (baseUrl.getScheme() == null && baseUrl.isInLocalFileSystem()) { return Urls.newLocalFileUrl(path); } // browserify produces absolute path in the local filesystem if (isAbsolute(path)) { VirtualFile file = LocalFileFinder.findFile(path); if (file != null) { if (absoluteLocalPathToSourceIndex == null) { // must be linked, on iterate original path must be first absoluteLocalPathToSourceIndex = createStringIntMap(rawSources.size()); sourceIndexToAbsoluteLocalPath = new String[rawSources.size()]; } absoluteLocalPathToSourceIndex.put(path, sourceIndex); sourceIndexToAbsoluteLocalPath[sourceIndex] = path; String canonicalPath = file.getCanonicalPath(); if (canonicalPath != null && !canonicalPath.equals(path)) { absoluteLocalPathToSourceIndex.put(canonicalPath, sourceIndex); } return Urls.newLocalFileUrl(path); } } return new UrlImpl(baseUrl.getScheme(), baseUrl.getAuthority(), path, null); }
@Nullable private MappingList findByFile(@NotNull SourceMap sourceMap, @NotNull VirtualFile sourceFile) { MappingList mappings = null; if (absoluteLocalPathToSourceIndex != null && sourceFile.isInLocalFileSystem()) { mappings = getMappingsBySource(sourceMap, absoluteLocalPathToSourceIndex.get(sourceFile.getPath())); if (mappings == null) { String sourceFileCanonicalPath = sourceFile.getCanonicalPath(); if (sourceFileCanonicalPath != null) { mappings = getMappingsBySource(sourceMap, absoluteLocalPathToSourceIndex.get(sourceFileCanonicalPath)); } } } if (mappings == null) { int index = canonicalizedSourcesMap.get(Urls.newFromVirtualFile(sourceFile).trimParameters()); if (index != -1) { return sourceMap.sourceIndexToMappings[index]; } for (int i = 0; i < canonicalizedSources.length; i++) { Url url = canonicalizedSources[i]; if (Urls.equalsIgnoreParameters(url, sourceFile)) { return sourceMap.sourceIndexToMappings[i]; } VirtualFile canonicalFile = sourceFile.getCanonicalFile(); if (canonicalFile != null && !canonicalFile.equals(sourceFile) && Urls.equalsIgnoreParameters(url, canonicalFile)) { return sourceMap.sourceIndexToMappings[i]; } } } return mappings; }
@Nullable @Override public final Script findScriptByUrl(@NotNull Url url) { for (SCRIPT script : idToScript.values()) { if (url.equalsIgnoreParameters(script.getUrl())) { return script; } } return null; }
@Nullable @Override protected Url getUrl(@NotNull OpenInBrowserRequest request, @NotNull VirtualFile file) throws BrowserException { if (file instanceof HttpVirtualFile) { return Urls.newFromVirtualFile(file); } else { return ContainerUtil.getFirstItem(getUrls(file, request.getProject(), null)); } }
@NotNull public RemoteContentProvider findContentProvider(final @NotNull Url url) { for (RemoteContentProvider provider : myProviders) { if (provider.canProvideContent(url)) { return provider; } } return myDefaultRemoteContentProvider; }
@Override public void saveContent(@NotNull final Url url, @NotNull final File file, @NotNull final DownloadingCallback callback) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { downloadContent(url, file, callback); } }); }
public File createLocalFile(@NotNull Url url) throws IOException { String baseName = PathUtilRt.getFileName(url.getPath()); int index = baseName.lastIndexOf('.'); String prefix = index == -1 ? baseName : baseName.substring(0, index); String suffix = index == -1 ? "" : baseName.substring(index+1); prefix = PathUtilRt.suggestFileName(prefix); suffix = PathUtilRt.suggestFileName(suffix); File file = FileUtil.findSequentNonexistentFile(myStorageIODirectory, prefix, suffix); FileUtilRt.createIfNotExists(file); return file; }
private static Collection<VirtualFile> findLocalFiles(Project project, Url url, String fileName) { for (LocalFileFinder finder : LocalFileFinder.EP_NAME.getExtensions()) { final VirtualFile file = finder.findLocalFile(url, project); if (file != null) { return Collections.singletonList(file); } } return FilenameIndex.getVirtualFilesByName(project, fileName, GlobalSearchScope.allScope(project)); }
public boolean canHandleElement(@NotNull OpenInBrowserRequest request) { try { Collection<Url> urls = getUrls(request); if (!urls.isEmpty()) { request.setResult(urls); return true; } } catch (BrowserException ignored) { } return false; }
@Nullable private static Url virtualFileToUrl(@NotNull VirtualFile file, @NotNull Project project) { PsiFile psiFile; AccessToken token = ReadAction.start(); try { psiFile = PsiManager.getInstance(project).findFile(file); } finally { token.finish(); } return WebBrowserServiceImpl.getDebuggableUrl(psiFile); }
@NotNull public static Collection<Url> getDebuggableUrls(@Nullable PsiElement context) { try { OpenInBrowserRequest request = context == null ? null : OpenInBrowserRequest.create(context); return request == null || request.getFile().getViewProvider().getBaseLanguage() == XMLLanguage.INSTANCE ? Collections.<Url>emptyList() : getUrls(getProvider(request), request); } catch (WebBrowserUrlProvider.BrowserException ignored) { return Collections.emptyList(); } }
@Nullable @Override protected Url getUrl(OpenInBrowserRequest request, VirtualFile virtualFile) throws BrowserException { try { GaugeSettingsModel settings = getGaugeSettings(); Spectacle spectacle = new Spectacle(request.getProject(), settings); if (spectacle.isInstalled()) return previewUrl(request, virtualFile, settings); spectacle.notifyToInstall(); } catch (Exception e) { Messages.showWarningDialog(String.format("Unable to create html file for %s", virtualFile.getName()), "Error"); } return null; }
@Override public VirtualFile findSourceFile(@NotNull final J2EEServerInstance serverInstance, @NotNull final CommonModel commonModel, @NotNull Url url) { String baseUrl = ApplicationServerUrlMapping.createUrl(commonModel, null, null); String urlString = url.trimParameters().toDecodedForm(); if (!urlString.startsWith(baseUrl)) { return null; } String relative = StringUtil.trimStart(urlString.substring(baseUrl.length()), "/"); return WebUtil.findSourceFile(relative, commonModel, model -> { TomcatModuleDeploymentModel tomcatModel = (TomcatModuleDeploymentModel)model; return tomcatModel.isEEArtifact() ? null : tomcatModel.CONTEXT_PATH; }); }
@Override public Url addAuthToken(@Nonnull Url url) { if (url.getParameters() != null) { // built-in server url contains query only if token specified return url; } return new UrlImpl(url.getScheme(), url.getAuthority(), url.getPath(), "?" + BuiltInWebServerKt.TOKEN_PARAM_NAME + "=" + BuiltInWebServerKt.acquireToken()); }
private static String getHost(Url uri) { String authority = uri.getAuthority(); if (authority != null) { int portIndex = authority.indexOf(':'); if (portIndex > 0) { return authority.substring(0, portIndex); } else { return authority; } } return null; }
private static boolean isTrustedChromeExtension(Url url) { /* FIXME [VISTALL] this is only jetbrains plugins return Comparing.equal(url.getScheme(), "chrome-extension") && (Comparing.equal(url.getAuthority(), "hmhgeddbohgjknpmjagkdomcpobmllji") || Comparing .equal(url.getAuthority(), "offnedcbhjldheanlbojaefbfbllddna")); */ return false; }
@NotNull @Override public Collection<Url> getUrlsToOpen(@NotNull OpenInBrowserRequest request, boolean preferLocalUrl) throws WebBrowserUrlProvider.BrowserException { VirtualFile virtualFile = request.getVirtualFile(); if(virtualFile instanceof HttpVirtualFile) { return Collections.singleton(Urls.newFromVirtualFile(virtualFile)); } if(!preferLocalUrl || !HtmlUtil.isHtmlFile(request.getFile())) { WebBrowserUrlProvider provider = getProvider(request); if(provider != null) { if(request.getResult() != null) { return request.getResult(); } try { Collection<Url> urls = provider.getUrls(request); if(!urls.isEmpty()) { return urls; } } catch(WebBrowserUrlProvider.BrowserException e) { if(!HtmlUtil.isHtmlFile(request.getFile())) { throw e; } } } } return virtualFile instanceof LightVirtualFile || !request.getFile().getViewProvider().isPhysical() ? Collections.<Url>emptySet() : Collections.singleton(Urls.newFromVirtualFile(virtualFile)); }
public static Url convertSwaggerLocationToUrl(@NotNull final Path swaggerHtmlDirectory) { return new LocalFileUrl(swaggerHtmlDirectory.toString() + File.separator + "index.html"); }
@Override public void swaggerHTMLFilesChanged(Url indexUrl) { Platform.runLater(() -> webEngine.load("file://" + indexUrl.toExternalForm())); }
@Nullable public static List<String> findUrlForVirtualFile(@NotNull Project project, @NotNull VirtualFile virtualFile, @NotNull String relPath) { final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); Module module = fileIndex.getModuleForFile(virtualFile); if (module == null) { final VirtualFileSystem fs = virtualFile.getFileSystem(); if (fs instanceof JarFileSystem) { final VirtualFile jar = ((JarFileSystem)fs).getVirtualFileForJar(virtualFile); if (jar != null) { module = fileIndex.getModuleForFile(jar); } } } if (module != null) { String[] javadocPaths = JavaModuleExternalPaths.getInstance(module).getJavadocUrls(); final List<String> httpRoots = PlatformDocumentationUtil.getHttpRoots(javadocPaths, relPath); // if found nothing and the file is from library classes, fall back to order entries if (httpRoots != null || !fileIndex.isInLibraryClasses(virtualFile)) { return httpRoots; } } for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) { for (VirtualFile root : orderEntry.getFiles(JavadocOrderRootType.getInstance())) { if (root.getFileSystem() == JarFileSystem.getInstance()) { VirtualFile file = root.findFileByRelativePath(relPath); List<Url> urls = file == null ? null : BuiltInWebBrowserUrlProvider.getUrls(file, project, null); if (!ContainerUtil.isEmpty(urls)) { List<String> result = new SmartList<String>(); for (Url url : urls) { result.add(url.toExternalForm()); } return result; } } } List<String> httpRoot = PlatformDocumentationUtil.getHttpRoots(JavadocOrderRootType.getUrls(orderEntry), relPath); if (httpRoot != null) { return httpRoot; } } return null; }
public Location(@NotNull Url url, int line, int column) { this.url = url; this.line = line; this.column = column; this.script = null; }
public Location(@NotNull Url url, int line) { this(url, line, -1); }