@Nullable
  private static FetchResult fetchData(
      final Project project, final String dtdUrl, final ProgressIndicator indicator)
      throws IOException {
    try {
      return HttpRequests.request(dtdUrl)
          .accept("text/xml,application/xml,text/html,*/*")
          .connect(
              new HttpRequests.RequestProcessor<FetchResult>() {
                @Override
                public FetchResult process(@NotNull HttpRequests.Request request)
                    throws IOException {
                  FetchResult result = new FetchResult();
                  result.bytes = request.readBytes(indicator);
                  result.contentType = request.getConnection().getContentType();
                  return result;
                }
              });
    } catch (MalformedURLException e) {
      if (!ApplicationManager.getApplication().isUnitTestMode()) {
        ApplicationManager.getApplication()
            .invokeLater(
                () ->
                    Messages.showMessageDialog(
                        project,
                        XmlBundle.message("invalid.url.message", dtdUrl),
                        XmlBundle.message("invalid.url.title"),
                        Messages.getErrorIcon()),
                indicator.getModalityState());
      }
    }

    return null;
  }
  public static void deleteFile(Project project, final VirtualFile file) throws ExecutionException {
    final Ref<IOException> error = new Ref<IOException>();

    final Runnable runnable =
        new Runnable() {
          public void run() {
            ApplicationManager.getApplication()
                .runWriteAction(
                    new Runnable() {
                      public void run() {
                        try {
                          if (file.isValid()) {
                            file.delete(this);
                          }
                        } catch (IOException e) {
                          error.set(e);
                        }
                      }
                    });
          }
        };

    if (ApplicationManager.getApplication().isDispatchThread()) {
      runnable.run();
    } else {
      ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
      ApplicationManager.getApplication()
          .invokeAndWait(runnable, pi != null ? pi.getModalityState() : ModalityState.NON_MODAL);
    }
    if (!error.isNull()) {
      //noinspection ThrowableResultOfMethodCallIgnored
      throw new ExecutionException(error.get().getMessage());
    }
  }
 protected boolean resultIsValid(
     final Project project,
     ProgressIndicator indicator,
     final String resourceUrl,
     FetchResult result) {
   if (myForceResultIsValid) {
     return true;
   }
   if (!ApplicationManager.getApplication().isUnitTestMode()
       && result.contentType != null
       && result.contentType.contains(HTML_MIME)
       && new String(result.bytes).contains("<html")) {
     ApplicationManager.getApplication()
         .invokeLater(
             () ->
                 Messages.showMessageDialog(
                     project,
                     XmlBundle.message("invalid.url.no.xml.file.at.location", resourceUrl),
                     XmlBundle.message("invalid.url.title"),
                     Messages.getErrorIcon()),
             indicator.getModalityState());
     return false;
   }
   return true;
 }
Ejemplo n.º 4
0
 @NotNull
 public ModalityState getDefaultModalityState() {
   if (EventQueue.isDispatchThread()) {
     return getCurrentModalityState();
   } else {
     ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
     return progress == null ? getNoneModalityState() : progress.getModalityState();
   }
 }
  public static VirtualFile createFile(
      Project project, final VirtualFile directory, final String fileName, final String fileText)
      throws ExecutionException {
    LOG.assertTrue(directory != null);
    final Ref<IOException> error = new Ref<IOException>();
    final Ref<VirtualFile> launcherFile = new Ref<VirtualFile>();

    final Runnable runnable =
        new Runnable() {
          public void run() {
            ApplicationManager.getApplication()
                .runWriteAction(
                    new Runnable() {
                      public void run() {
                        try {
                          VirtualFile file = directory.findChild(fileName);
                          if (file == null) {
                            file =
                                directory.createChildData(CfmlUnitRunConfiguration.class, fileName);
                          }
                          CfmlScriptNodeSuppressor.suppress(file);
                          VfsUtil.saveText(file, fileText);
                          launcherFile.set(file);
                        } catch (IOException e) {
                          error.set(e);
                        }
                      }
                    });
          }
        };
    if (ApplicationManager.getApplication().isDispatchThread()) {
      runnable.run();
    } else {
      ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
      ApplicationManager.getApplication()
          .invokeAndWait(runnable, pi != null ? pi.getModalityState() : ModalityState.NON_MODAL);
    }

    if (!error.isNull()) {
      //noinspection ThrowableResultOfMethodCallIgnored
      throw new ExecutionException(error.get().getMessage());
    }
    return launcherFile.get();
  }
 private static VirtualFile findFileByPath(
     final String resPath, @Nullable final String dtdUrl, ProgressIndicator indicator) {
   final Ref<VirtualFile> ref = new Ref<>();
   ApplicationManager.getApplication()
       .invokeAndWait(
           () ->
               ApplicationManager.getApplication()
                   .runWriteAction(
                       () -> {
                         ref.set(
                             LocalFileSystem.getInstance()
                                 .refreshAndFindFileByPath(
                                     resPath.replace(File.separatorChar, '/')));
                         if (dtdUrl != null) {
                           ExternalResourceManager.getInstance().addResource(dtdUrl, resPath);
                         }
                       }),
           indicator.getModalityState());
   return ref.get();
 }
 @Override
 @NotNull
 public ModalityState getModalityState() {
   return myIndicator.getModalityState();
 }
  private void fetchDtd(
      final Project project,
      final String dtdUrl,
      final String url,
      final ProgressIndicator indicator)
      throws IOException {
    final String extResourcesPath = getExternalResourcesPath();
    final File extResources = new File(extResourcesPath);
    LOG.assertTrue(extResources.mkdirs() || extResources.exists(), extResources);

    final PsiManager psiManager = PsiManager.getInstance(project);
    ApplicationManager.getApplication()
        .invokeAndWait(
            () -> {
              @SuppressWarnings("deprecation")
              final AccessToken token =
                  ApplicationManager.getApplication()
                      .acquireWriteActionLock(FetchExtResourceAction.class);
              try {
                final String path =
                    FileUtil.toSystemIndependentName(extResources.getAbsolutePath());
                final VirtualFile vFile =
                    LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
                LOG.assertTrue(vFile != null, path);
              } finally {
                token.finish();
              }
            },
            indicator.getModalityState());

    final List<String> downloadedResources = new LinkedList<>();
    final List<String> resourceUrls = new LinkedList<>();
    final IOException[] nestedException = new IOException[1];

    try {
      final String resPath = fetchOneFile(indicator, url, project, extResourcesPath, null);
      if (resPath == null) return;
      resourceUrls.add(dtdUrl);
      downloadedResources.add(resPath);

      VirtualFile virtualFile = findFileByPath(resPath, dtdUrl, indicator);

      Set<String> linksToProcess = new HashSet<>();
      Set<String> processedLinks = new HashSet<>();
      Map<String, String> baseUrls = new HashMap<>();
      VirtualFile contextFile = virtualFile;
      linksToProcess.addAll(extractEmbeddedFileReferences(virtualFile, null, psiManager, url));

      while (!linksToProcess.isEmpty()) {
        String s = linksToProcess.iterator().next();
        linksToProcess.remove(s);
        processedLinks.add(s);

        final boolean absoluteUrl = s.startsWith(HTTP_PROTOCOL);
        String resourceUrl;
        if (absoluteUrl) {
          resourceUrl = s;
        } else {
          String baseUrl = baseUrls.get(s);
          if (baseUrl == null) baseUrl = url;

          resourceUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/') + 1) + s;
        }

        String resourcePath;

        String refname = s.substring(s.lastIndexOf('/') + 1);
        if (absoluteUrl) refname = Integer.toHexString(s.hashCode()) + "_" + refname;
        try {
          resourcePath = fetchOneFile(indicator, resourceUrl, project, extResourcesPath, refname);
        } catch (IOException e) {
          nestedException[0] = new FetchingResourceIOException(e, resourceUrl);
          break;
        }

        if (resourcePath == null) break;

        virtualFile = findFileByPath(resourcePath, absoluteUrl ? s : null, indicator);
        downloadedResources.add(resourcePath);

        if (absoluteUrl) {
          resourceUrls.add(s);
        }

        final Set<String> newLinks =
            extractEmbeddedFileReferences(virtualFile, contextFile, psiManager, resourceUrl);
        for (String u : newLinks) {
          baseUrls.put(u, resourceUrl);
          if (!processedLinks.contains(u)) linksToProcess.add(u);
        }
      }
    } catch (IOException ex) {
      nestedException[0] = ex;
    }
    if (nestedException[0] != null) {
      cleanup(resourceUrls, downloadedResources);
      throw nestedException[0];
    }
  }
  private static boolean performFirstCommitIfRequired(
      @NotNull final Project project,
      @NotNull VirtualFile root,
      @NotNull GitRepository repository,
      @NotNull ProgressIndicator indicator,
      @NotNull String name,
      @NotNull String url) {
    // check if there is no commits
    if (!repository.isFresh()) {
      return true;
    }

    LOG.info("Trying to commit");
    try {
      LOG.info("Adding files for commit");
      indicator.setText("Adding files to git...");

      // ask for files to add
      final List<VirtualFile> trackedFiles =
          ChangeListManager.getInstance(project).getAffectedFiles();
      final Collection<VirtualFile> untrackedFiles =
          filterOutIgnored(project, repository.getUntrackedFilesHolder().retrieveUntrackedFiles());
      trackedFiles.removeAll(untrackedFiles); // fix IDEA-119855

      final List<VirtualFile> allFiles = new ArrayList<VirtualFile>();
      allFiles.addAll(trackedFiles);
      allFiles.addAll(untrackedFiles);

      final Ref<GithubUntrackedFilesDialog> dialogRef = new Ref<GithubUntrackedFilesDialog>();
      ApplicationManager.getApplication()
          .invokeAndWait(
              new Runnable() {
                @Override
                public void run() {
                  GithubUntrackedFilesDialog dialog =
                      new GithubUntrackedFilesDialog(project, allFiles);
                  if (!trackedFiles.isEmpty()) {
                    dialog.setSelectedFiles(trackedFiles);
                  }
                  DialogManager.show(dialog);
                  dialogRef.set(dialog);
                }
              },
              indicator.getModalityState());
      final GithubUntrackedFilesDialog dialog = dialogRef.get();

      final Collection<VirtualFile> files2commit = dialog.getSelectedFiles();
      if (!dialog.isOK() || files2commit.isEmpty()) {
        GithubNotifications.showInfoURL(
            project, "Successfully created empty repository on GitHub", name, url);
        return false;
      }

      Collection<VirtualFile> files2add = ContainerUtil.intersection(untrackedFiles, files2commit);
      Collection<VirtualFile> files2rm = ContainerUtil.subtract(trackedFiles, files2commit);
      Collection<VirtualFile> modified = new HashSet<VirtualFile>(trackedFiles);
      modified.addAll(files2commit);

      GitFileUtils.addFiles(project, root, files2add);
      GitFileUtils.deleteFilesFromCache(project, root, files2rm);

      // commit
      LOG.info("Performing commit");
      indicator.setText("Performing commit...");
      GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT);
      handler.addParameters("-m", dialog.getCommitMessage());
      handler.endOptions();
      handler.run();

      VcsFileUtil.refreshFiles(project, modified);
    } catch (VcsException e) {
      LOG.warn(e);
      GithubNotifications.showErrorURL(
          project,
          "Can't finish GitHub sharing process",
          "Successfully created project ",
          "'" + name + "'",
          " on GitHub, but initial commit failed:<br/>" + GithubUtil.getErrorTextFromException(e),
          url);
      return false;
    }
    LOG.info("Successfully created initial commit");
    return true;
  }
Ejemplo n.º 10
0
 @Override
 public final void run(@NotNull ProgressIndicator indicator) {
   myHandler.setModalityState(indicator.getModalityState());
   myDelegate.run(indicator);
 }