Java 类com.intellij.openapi.util.ThrowableComputable 实例源码

项目:intellij-ce-playground    文件:VcsLogHashMapImpl.java   
public VcsLogHashMapImpl(@NotNull Project project, @NotNull Map<VirtualFile, VcsLogProvider> logProviders) throws IOException {
  cleanupOldNaming(project, logProviders);
  String logId = calcLogId(project, logProviders);
  final File mapFile = new File(LOG_CACHE_APP_DIR, logId + "." + VERSION);
  if (!mapFile.exists()) {
    IOUtil.deleteAllFilesStartingWith(new File(LOG_CACHE_APP_DIR, logId));
  }

  Disposer.register(project, this);
  myPersistentEnumerator = IOUtil.openCleanOrResetBroken(new ThrowableComputable<PersistentEnumerator<Hash>, IOException>() {
    @Override
    public PersistentEnumerator<Hash> compute() throws IOException {
      return new PersistentEnumerator<Hash>(mapFile, new MyHashKeyDescriptor(), Page.PAGE_SIZE);
    }
  }, mapFile);
}
项目:intellij-ce-playground    文件:EncodingRegistry.java   
public static <E extends Throwable> VirtualFile doActionAndRestoreEncoding(@NotNull VirtualFile fileBefore,
                                                                           @NotNull ThrowableComputable<VirtualFile, E> action) throws E {
  EncodingRegistry registry = getInstance();
  Charset charsetBefore = registry.getEncoding(fileBefore, true);
  VirtualFile fileAfter = null;
  try {
    fileAfter = action.compute();
    return fileAfter;
  }
  finally {
    if (fileAfter != null) {
      Charset actual = registry.getEncoding(fileAfter, true);
      if (!Comparing.equal(actual, charsetBefore)) {
        registry.setEncoding(fileAfter, charsetBefore);
      }
    }
  }
}
项目:intellij-ce-playground    文件:LightPlatformCodeInsightTestCase.java   
@Override
protected void runTest() throws Throwable {
  if (isRunInWriteAction()) {
    WriteCommandAction.runWriteCommandAction(getProject(), new ThrowableComputable<Void, Throwable>() {
      @Override
      public Void compute() throws Throwable {
        doRunTest();
        return null;
      }
    });
  }
  else {
    new WriteCommandAction.Simple(getProject()){
      @Override
      protected void run() throws Throwable {
        doRunTest();
      }
    }.performCommand();
  }
}
项目:intellij-ce-playground    文件:VirtualFileSystemEntry.java   
@Override
public VirtualFile copy(final Object requestor, @NotNull final VirtualFile newParent, @NotNull final String copyName) throws IOException {
  if (getFileSystem() != newParent.getFileSystem()) {
    throw new IOException(VfsBundle.message("file.copy.error", newParent.getPresentableUrl()));
  }

  if (!newParent.isDirectory()) {
    throw new IOException(VfsBundle.message("file.copy.target.must.be.directory"));
  }

  return EncodingRegistry.doActionAndRestoreEncoding(this, new ThrowableComputable<VirtualFile, IOException>() {
    @Override
    public VirtualFile compute() throws IOException {
      return ourPersistence.copyFile(requestor, VirtualFileSystemEntry.this, newParent, copyName);
    }
  });
}
项目:intellij-ce-playground    文件:ApplicationImplTest.java   
public void testProgressVsReadAction() throws Throwable {
  ProgressManager.getInstance().runProcessWithProgressSynchronously((ThrowableComputable<Void, Exception>)() -> {
    try {
      assertFalse(ApplicationManager.getApplication().isReadAccessAllowed());
      assertFalse(ApplicationManager.getApplication().isDispatchThread());
      for (int i=0; i<100;i++) {
        SwingUtilities.invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> {
          TimeoutUtil.sleep(20);
        }));
        ApplicationManager.getApplication().runReadAction(() -> {
          TimeoutUtil.sleep(20);
        });
      }
    }
    catch (Exception e) {
      exception = e;
    }
    return null;
  }, "cc", false, getProject());
  if (exception != null) throw exception;
}
项目:intellij-ce-playground    文件:ModuleBuilder.java   
@Nullable
public Module commitModule(@NotNull final Project project, @Nullable final ModifiableModuleModel model) {
  if (canCreateModule()) {
    if (myName == null) {
      myName = project.getName();
    }
    if (myModuleFilePath == null) {
      myModuleFilePath = project.getBaseDir().getPath() + File.separator + myName + ModuleFileType.DOT_DEFAULT_EXTENSION;
    }
    try {
      return ApplicationManager.getApplication().runWriteAction(new ThrowableComputable<Module, Exception>() {
        @Override
        public Module compute() throws Exception {
          return createAndCommitIfNeeded(project, model, true);
        }
      });
    }
    catch (Exception ex) {
      LOG.warn(ex);
      Messages.showErrorDialog(IdeBundle.message("error.adding.module.to.project", ex.getMessage()), IdeBundle.message("title.add.module"));
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:DvcsCommitAdditionalComponent.java   
private void loadMessagesInModalTask(@NotNull Project project) {
  try {
    myMessagesForRoots =
      ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<Map<VirtualFile,String>, VcsException>() {
        @Override
        public Map<VirtualFile, String> compute() throws VcsException {
          return getLastCommitMessages();
        }
      }, "Reading commit message...", false, project);
  }
  catch (VcsException e) {
    Messages.showErrorDialog(getComponent(), "Couldn't load commit message of the commit to amend.\n" + e.getMessage(),
                             "Commit Message not Loaded");
    log.info(e);
  }
}
项目:intellij-ce-playground    文件:CloneDvcsDialog.java   
private void test() {
  myTestURL = getCurrentUrlText();
  boolean testResult = ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<Boolean, RuntimeException>() {
    @Override
    public Boolean compute() {
      return test(myTestURL);
    }
  }, DvcsBundle.message("clone.testing", myTestURL), true, myProject);

  if (testResult) {
    Messages.showInfoMessage(myTestButton, DvcsBundle.message("clone.test.success.message", myTestURL),
                             DvcsBundle.getString("clone.test.connection.title"));
    myTestResult = Boolean.TRUE;
  }
  else {
    myTestResult = Boolean.FALSE;
  }
  updateButtons();
}
项目:intellij-ce-playground    文件:VcsBackgroundableComputable.java   
private VcsBackgroundableComputable(final Project project, final String title,
                                final String errorTitle,
                                final ThrowableComputable<T, VcsException> backgroundable,
                                final Consumer<T> awtSuccessContinuation,
                                final Runnable awtErrorContinuation,
                                final BackgroundableActionEnabledHandler handler,
                                final Object actionParameter) {
  super(project, title, true, BackgroundFromStartOption.getInstance());
  myErrorTitle = errorTitle;
  myBackgroundable = backgroundable;
  myAwtSuccessContinuation = awtSuccessContinuation;
  myAwtErrorContinuation = awtErrorContinuation;
  myProject = project;
  myHandler = handler;
  myActionParameter = actionParameter;
}
项目:intellij-ce-playground    文件:VcsBackgroundableComputable.java   
private static <T> void createAndRun(final Project project, @Nullable final VcsBackgroundableActions actionKey,
                               @Nullable final Object actionParameter,
                               final String title,
                               final String errorTitle,
                               final ThrowableComputable<T, VcsException> backgroundable,
                               @Nullable final Consumer<T> awtSuccessContinuation,
                               @Nullable final Runnable awtErrorContinuation, final boolean silent) {
  final ProjectLevelVcsManagerImpl vcsManager = (ProjectLevelVcsManagerImpl) ProjectLevelVcsManager.getInstance(project);
  final BackgroundableActionEnabledHandler handler;
  if (actionKey != null) {
    handler = vcsManager.getBackgroundableActionHandler(actionKey);
    // fo not start same action twice
    if (handler.isInProgress(actionParameter)) return;
  } else {
    handler = null;
  }

  final VcsBackgroundableComputable<T> backgroundableComputable =
    new VcsBackgroundableComputable<T>(project, title, errorTitle, backgroundable, awtSuccessContinuation, awtErrorContinuation,
                                handler, actionParameter);
  backgroundableComputable.setSilent(silent);
  if (handler != null) {
    handler.register(actionParameter);
  }
  ProgressManager.getInstance().run(backgroundableComputable);
}
项目:intellij-ce-playground    文件:VcsHistoryProviderBackgroundableProxy.java   
public VcsHistoryProviderBackgroundableProxy(final AbstractVcs vcs, final VcsHistoryProvider delegate, DiffProvider diffProvider) {
  myDelegate = delegate;
  myProject = vcs.getProject();
  myConfiguration = VcsConfiguration.getInstance(myProject);
  myCachesHistory = myDelegate instanceof VcsCacheableHistorySessionFactory;
  myDiffProvider = diffProvider;
  myVcsHistoryCache = ProjectLevelVcsManager.getInstance(myProject).getVcsHistoryCache();
  myType = vcs.getType();
  myHistoryComputerFactory = new HistoryComputerFactory() {
    @Override
    public ThrowableComputable<VcsHistorySession, VcsException> create(FilePath filePath,
                                                                       Consumer<VcsHistorySession> consumer,
                                                                       VcsKey vcsKey) {
      if (myCachesHistory) {
        return new CachingHistoryComputer(filePath, consumer, vcsKey);
      } else {
        return new SimpelHistoryComputer(filePath, consumer);
      }
    }
  };
}
项目:intellij-ce-playground    文件:VcsHistoryProviderBackgroundableProxy.java   
public void createSessionFor(final VcsKey vcsKey, final FilePath filePath, final Consumer<VcsHistorySession> continuation,
                             @Nullable VcsBackgroundableActions actionKey,
                             final boolean silent,
                             @Nullable final Consumer<VcsHistorySession> backgroundSpecialization) {
  final ThrowableComputable<VcsHistorySession, VcsException> throwableComputable =
    myHistoryComputerFactory.create(filePath, backgroundSpecialization, vcsKey);
  final VcsBackgroundableActions resultingActionKey = actionKey == null ? VcsBackgroundableActions.CREATE_HISTORY_SESSION : actionKey;
  final Object key = VcsBackgroundableActions.keyFrom(filePath);

  if (silent) {
    VcsBackgroundableComputable.createAndRunSilent(myProject, resultingActionKey, key, VcsBundle.message("loading.file.history.progress"),
                                                   throwableComputable, continuation);
  } else {
    VcsBackgroundableComputable.createAndRun(myProject, resultingActionKey, key, VcsBundle.message("loading.file.history.progress"),
                                             VcsBundle.message("message.title.could.not.load.file.history"), throwableComputable, continuation, null);
  }
}
项目:intellij-ce-playground    文件:RemoteProcessSupport.java   
private EntryPoint acquire(final RunningInfo port) throws Exception {
  EntryPoint result = RemoteUtil.executeWithClassLoader(new ThrowableComputable<EntryPoint, Exception>() {
    @Override
    public EntryPoint compute() throws Exception {
      Registry registry = LocateRegistry.getRegistry("localhost", port.port);
      Remote remote = ObjectUtils.assertNotNull(registry.lookup(port.name));

      if (Remote.class.isAssignableFrom(myValueClass)) {
        EntryPoint entryPoint = narrowImpl(remote, myValueClass);
        if (entryPoint == null) return null;
        return RemoteUtil.substituteClassLoader(entryPoint, myValueClass.getClassLoader());
      }
      else {
        return RemoteUtil.castToLocal(remote, myValueClass);
      }
    }
  }, getClass().getClassLoader()); // should be the loader of client plugin
  // init hard ref that will keep it from DGC and thus preventing from System.exit
  port.entryPointHardRef = result;
  return result;
}
项目:intellij-ce-playground    文件:TestStateStorage.java   
@NotNull
private static ThrowableComputable<PersistentHashMap<String, Record>, IOException> getComputable(final File file) {
  return new ThrowableComputable<PersistentHashMap<String, Record>, IOException>() {
    @Override
    public PersistentHashMap<String, Record> compute() throws IOException {
      return new PersistentHashMap<String, Record>(file, new EnumeratorStringDescriptor(), new DataExternalizer<Record>() {
        @Override
        public void save(@NotNull DataOutput out, Record value) throws IOException {
          out.writeInt(value.magnitude);
          out.writeLong(value.date.getTime());
        }

        @Override
        public Record read(@NotNull DataInput in) throws IOException {
          return new Record(in.readInt(), new Date(in.readLong()));
        }
      });
    }
  };
}
项目:intellij-ce-playground    文件:TemplateUtils.java   
/**
 * Creates a directory for the given file and returns the VirtualFile object.
 *
 * @return virtual file object for the given path. It can never be null.
 */
@NotNull
public static VirtualFile checkedCreateDirectoryIfMissing(final @NotNull File directory) throws IOException {
  return WriteCommandAction.runWriteCommandAction(null, new ThrowableComputable<VirtualFile, IOException>() {
    @Override
    public VirtualFile compute() throws IOException {
      VirtualFile dir = VfsUtil.createDirectoryIfMissing(directory.getAbsolutePath());
      if (dir == null) {
        throw new IOException("Unable to create " + directory.getAbsolutePath());
      }
      else {
        return dir;
      }
    }
  });
}
项目:intellij-ce-playground    文件:PropertyFixture.java   
/**
 * Reads the current value from the property
 */
@SuppressWarnings("unchecked")
@NotNull
public String getValue() throws Exception {
  /*
  TODO: Read via the UI property widget instead
  This should do the trick, but still needs some timing debugging:

  TableCell cell = findTableCell(true);
  assertNotNull(cell);

  JTableDriver tableDriver = new JTableDriver(myRobot);
  String value = tableDriver.value(getTable(), cell);
  return value == null ? "<null>" : value;
   */
  return ApplicationManager.getApplication().runReadAction(new ThrowableComputable<String,Exception>() {
    @Override
    public String compute() throws Exception {
      Object value = myProperty.getValue(myComponent.getComponent());
      return value == null ? "<null>" : value.toString();
    }
  });
}
项目:intellij-ce-playground    文件:MavenTemplateFileProcessor.java   
@Nullable
@Override
protected String encodeFileText(final String content, final VirtualFile file, final Project project) throws IOException {
  if ("pom.xml".equals(file.getName())) {
    return ApplicationManager.getApplication().runReadAction(new ThrowableComputable<String, IOException>() {
      @Override
      public String compute() throws IOException {
        PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("pom.xml", XmlFileType.INSTANCE, content);
        final MavenDomProjectModel model = MavenDomUtil.getMavenDomModel(psiFile, MavenDomProjectModel.class);
        if (model == null) return null;
        String text = psiFile.getText();
        XmlElement element = model.getName().getXmlElement();
        if (element instanceof XmlTag) {
          text = ((XmlTag)element).getValue().getTextRange().replace(text, wrap(ProjectTemplateParameterFactory.IJ_PROJECT_NAME));
        }
        element = model.getArtifactId().getXmlElement();
        if (element instanceof XmlTag) {
          text = ((XmlTag)element).getValue().getTextRange().replace(text, wrap(ProjectTemplateParameterFactory.IJ_PROJECT_NAME));
        }
        return text;
      }
    });
  }
  return null;
}
项目:intellij-ce-playground    文件:GitDefineRemoteDialog.java   
@Nullable
private String validateRemoteUnderModal(@NotNull String name, @NotNull final String url) throws ProcessCanceledException {
  if (url.isEmpty()) {
    return "URL can't be empty";
  }
  if (!GitRefNameValidator.getInstance().checkInput(name)) {
    return "Remote name contains illegal characters";
  }

  return ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<String, ProcessCanceledException>() {
    @Override
    public String compute() throws ProcessCanceledException {
      final GitCommandResult result = myGit.lsRemote(myRepository.getProject(), VfsUtilCore.virtualToIoFile(myRepository.getRoot()), url);
      return !result.success() ? "Remote URL test failed: " + result.getErrorOutputAsHtmlString() : null;
    }
  }, "Checking URL...", true, myRepository.getProject());
}
项目:intellij-ce-playground    文件:SshSharedConnection.java   
public SshSharedConnection(final String repository, final ConnectionSettings connectionSettings, final SshAuthentication authentication) {
  myValid = new AtomicBoolean(true);
  myRepository = repository;
  myConnectionSettings = connectionSettings;
  myLock = new Object();

  myConnectionFactory = new ThrowableComputable<Connection, AuthenticationException>() {
    public Connection compute() throws AuthenticationException {
      try {
        SshLogger.debug("connection factory called");
        return SshConnectionUtils.openConnection(connectionSettings, authentication);
      }
      catch (AuthenticationException e) {
        // todo +-
        myValid.set(false);
        throw e;
      } catch (IOException e) {
        // todo +-
        myValid.set(false);
        throw new AuthenticationException(e.getMessage(), e);
      }
    }
  };
  myQueue = new LinkedList<Cell>();
}
项目:intellij-ce-playground    文件:SvnAuthenticationManager.java   
public SVNAuthentication requestClientAuthentication(final String kind, final SVNURL url, final String realm, final SVNErrorMessage errorMessage,
                                                     final SVNAuthentication previousAuth, final boolean authMayBeStored) {
  try {
    return wrapNativeCall(new ThrowableComputable<SVNAuthentication, SVNException>() {
      @Override
      public SVNAuthentication compute() throws SVNException {
        final SVNAuthentication svnAuthentication =
          myDelegate.requestClientAuthentication(kind, url, realm, errorMessage, previousAuth, authMayBeStored);
        myListener.getMulticaster().requested(ProviderType.persistent, url, realm, kind, svnAuthentication == null);
        return svnAuthentication;
      }
    });
  }
  catch (SVNException e) {
    LOG.info(e);
    throw new RuntimeException(e);
  }
}
项目:intellij-ce-playground    文件:SvnAuthenticationManager.java   
public void saveAuthentication(final SVNAuthentication auth, final String kind, final String realm) throws SVNException {
  try {
    wrapNativeCall(new ThrowableComputable<Void, SVNException>() {
      @Override
      public Void compute() throws SVNException {
        final Boolean fromInteractive = ourJustEntered.get();
        ourJustEntered.set(null);
        if (! myArtificialSaving && ! Boolean.TRUE.equals(fromInteractive)) {
          // not what user entered
          return null;
        }
        myListener.getMulticaster().saveAttemptStarted(ProviderType.persistent, auth.getURL(), realm, auth.getKind());
        ((ISVNPersistentAuthenticationProvider) myDelegate).saveAuthentication(auth, kind, realm);
        myListener.getMulticaster().saveAttemptFinished(ProviderType.persistent, auth.getURL(), realm, auth.getKind());
        return null;
      }
    });
  }
  catch (SVNException e) {
    LOG.info(e);
    throw new RuntimeException(e);
  }
}
项目:intellij-ce-playground    文件:SvnAuthenticationManager.java   
@Override
public void saveFingerprints(final String realm, final byte[] fingerprints) {
  try {
    wrapNativeCall(new ThrowableComputable<Void, SVNException>() {
      @Override
      public Void compute() throws SVNException {
        ((ISVNPersistentAuthenticationProvider) myDelegate).saveFingerprints(realm, fingerprints);
        return null;
      }
    });
  }
  catch (SVNException e) {
    LOG.info(e);
    throw new RuntimeException(e);
  }
}
项目:intellij-ce-playground    文件:SvnAuthenticationManager.java   
private <T> T wrapNativeCall(final ThrowableComputable<T, SVNException> runnable) throws SVNException {
  try {
    NativeLogReader.startTracking();
    final T t = runnable.compute();
    final List<NativeLogReader.CallInfo> logged = NativeLogReader.getLogged();
    final StringBuilder sb = new StringBuilder();
    for (NativeLogReader.CallInfo info : logged) {
      final String message = SvnNativeCallsTranslator.getMessage(info);
      if (message != null) {
        if (sb.length() > 0) sb.append('\n');
        sb.append(message);
      }
    }
    if (sb.length() > 0) {
      VcsBalloonProblemNotifier.showOverChangesView(myProject, sb.toString(), MessageType.ERROR);
      LOG.info(sb.toString());
    }
    return t;
  } finally {
    NativeLogReader.clear();
    NativeLogReader.endTracking();
  }
}
项目:intellij    文件:DelegatingSwitchToHeaderOrSourceProvider.java   
/**
 * Runs the getter under a progress indicator that cancels itself after a certain timeout (assumes
 * that the getter will check for cancellation cooperatively).
 *
 * @param getter computes the GotoRelatedItems.
 * @return a list of items computed, or Optional.empty if timed out.
 */
private Optional<List<? extends GotoRelatedItem>> getItemsWithTimeout(
    ThrowableComputable<List<? extends GotoRelatedItem>, RuntimeException> getter) {
  try {
    ProgressIndicator indicator = new ProgressIndicatorBase();
    ProgressIndicator wrappedIndicator =
        new WatchdogIndicator(indicator, TIMEOUT_MS, TimeUnit.MILLISECONDS);
    // We don't use "runProcessWithProgressSynchronously" because that pops up a ProgressWindow,
    // and that will cause the event IDs to bump up and no longer match the event ID stored in
    // DataContexts which may be used in one of the GotoRelatedProvider#getItems overloads.
    return Optional.of(
        ProgressManager.getInstance()
            .runProcess(() -> ReadAction.compute(getter), wrappedIndicator));
  } catch (ProcessCanceledException e) {
    return Optional.empty();
  }
}
项目:vso-intellij    文件:TfsRequestManager.java   
private static <T> T executeRequestImpl(final URI serverUri,
                                        final Ref<Credentials> credentialsRef,
                                        final Request<T> request,
                                        final ProgressIndicator pi)
  throws Exception {
  return ClassLoaderUtil.runWithClassLoader(TfsRequestManager.class.getClassLoader(), new ThrowableComputable<T, Exception>() {
    @Override
    public T compute() throws Exception {
      Credentials credentials = credentialsRef.get();
      boolean needsAuthentication =
        credentials == null ||
        request.retrieveAuthorizedCredentials() && (credentials.getUserName().length() == 0 || credentials.getDomain().length() == 0);
      if (needsAuthentication) {
        TfsServerConnectionHelper.ServerDescriptor descriptor =
          TfsServerConnectionHelper.connect(serverUri, credentialsRef.get(), true, pi);
        credentialsRef.set(descriptor.authorizedCredentials);
      }
      return request.execute(credentialsRef.get(), serverUri, pi);
    }
  });
}
项目:vso-intellij    文件:MementoTest.java   
private static <T> T runWithPatchedClassloader(ThrowableComputable<T, Exception> computable) throws Exception {
  return ClassLoaderUtil.runWithClassLoader(new URLClassLoader(new URL[0], Thread.currentThread().getContextClassLoader()) {
    @Override
    public InputStream getResourceAsStream(String name) {
      if (XML_ENTITIES_URL.equals(name)) {
        String resource = XML_ENTITIES_CONTENT;
        try {
          return new ByteArrayInputStream(resource.getBytes("UTF-8"));
        }
        catch (UnsupportedEncodingException e) {
          // should not happen, fallback
        }
      }
      return super.getResourceAsStream(name);
    }
  }, computable);
}
项目:defrac-plugin-intellij    文件:DefracFacet.java   
@Nullable
public DefracConfigOracle getConfigOracle() {
  try {
    return ApplicationManager.getApplication().runReadAction(new ThrowableComputable<DefracConfigOracle, Throwable>() {
      @Override
      public DefracConfigOracle compute() throws Throwable {
        final DefracConfig localConfig = readConfig();

        if(localConfig == null) {
          return null;
        }

        final DefracConfig globalConfig = readGlobalConfig();

        if(globalConfig == null) {
          return null;
        }

        return DefracConfigOracle.join(getPlatform(), localConfig, globalConfig);
      }
    });
  } catch(final Throwable t) {
    return null;
  }
}
项目:tools-idea    文件:EncodingRegistry.java   
public static <E extends Throwable> VirtualFile doActionAndRestoreEncoding(@NotNull VirtualFile fileBefore,
                                                                           @NotNull ThrowableComputable<VirtualFile, E> action) throws E {
  EncodingRegistry registry = getInstance();
  Charset charsetBefore = registry.getEncoding(fileBefore, true);
  VirtualFile fileAfter = null;
  try {
    fileAfter = action.compute();
    return fileAfter;
  }
  finally {
    if (fileAfter != null) {
      Charset actual = registry.getEncoding(fileAfter, true);
      if (!Comparing.equal(actual, charsetBefore)) {
        registry.setEncoding(fileAfter, charsetBefore);
      }
    }
  }
}
项目:tools-idea    文件:VirtualFileSystemEntry.java   
@Override
public VirtualFile copy(final Object requestor, @NotNull final VirtualFile newParent, @NotNull final String copyName) throws IOException {
  if (getFileSystem() != newParent.getFileSystem()) {
    throw new IOException(VfsBundle.message("file.copy.error", newParent.getPresentableUrl()));
  }

  if (!newParent.isDirectory()) {
    throw new IOException(VfsBundle.message("file.copy.target.must.be.directory"));
  }

  return EncodingRegistry.doActionAndRestoreEncoding(this, new ThrowableComputable<VirtualFile, IOException>() {
    @Override
    public VirtualFile compute() throws IOException {
      return ourPersistence.copyFile(requestor, VirtualFileSystemEntry.this, newParent, copyName);
    }
  });
}
项目:tools-idea    文件:ProgressManagerImpl.java   
@Override
public <T, E extends Exception> T runProcessWithProgressSynchronously(@NotNull final ThrowableComputable<T, E> process,
                                                 @NotNull @Nls String progressTitle,
                                                 boolean canBeCanceled,
                                                 @Nullable Project project) throws E {

  final Ref<T> result = new Ref<T>();
  final Ref<E> exceptionRef = new Ref<E>();
  Task.Modal task = new Task.Modal(project, progressTitle, canBeCanceled) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      try {
        T compute = process.compute();
        result.set(compute);
      }
      catch (Exception e) {
        exceptionRef.set((E)e);
      }
    }
  };
  runProcessWithProgressSynchronously(task, null);
  if (!exceptionRef.isNull()) throw exceptionRef.get();
  return result.get();
}
项目:tools-idea    文件:ModuleBuilder.java   
@Nullable
public Module commitModule(@NotNull final Project project, @Nullable final ModifiableModuleModel model) {
  if (canCreateModule()) {
    if (myName == null) {
      myName = project.getName();
    }
    if (myModuleFilePath == null) {
      myModuleFilePath = project.getBaseDir().getPath() + File.separator + myName + ModuleFileType.DOT_DEFAULT_EXTENSION;
    }
    try {
      return ApplicationManager.getApplication().runWriteAction(new ThrowableComputable<Module, Exception>() {
        @Override
        public Module compute() throws Exception {
          return createAndCommitIfNeeded(project, model, true);
        }
      });
    }
    catch (Exception ex) {
      LOG.warn(ex);
      Messages.showErrorDialog(IdeBundle.message("error.adding.module.to.project", ex.getMessage()), IdeBundle.message("title.add.module"));
    }
  }
  return null;
}
项目:tools-idea    文件:VcsBackgroundableComputable.java   
private VcsBackgroundableComputable(final Project project, final String title,
                                final String errorTitle,
                                final ThrowableComputable<T, VcsException> backgroundable,
                                final Consumer<T> awtSuccessContinuation,
                                final Runnable awtErrorContinuation,
                                final BackgroundableActionEnabledHandler handler,
                                final Object actionParameter) {
  super(project, title, true, BackgroundFromStartOption.getInstance());
  myErrorTitle = errorTitle;
  myBackgroundable = backgroundable;
  myAwtSuccessContinuation = awtSuccessContinuation;
  myAwtErrorContinuation = awtErrorContinuation;
  myProject = project;
  myHandler = handler;
  myActionParameter = actionParameter;
}
项目:tools-idea    文件:VcsBackgroundableComputable.java   
private static <T> void createAndRun(final Project project, @Nullable final VcsBackgroundableActions actionKey,
                               @Nullable final Object actionParameter,
                               final String title,
                               final String errorTitle,
                               final ThrowableComputable<T, VcsException> backgroundable,
                               @Nullable final Consumer<T> awtSuccessContinuation,
                               @Nullable final Runnable awtErrorContinuation, final boolean silent) {
  final ProjectLevelVcsManagerImpl vcsManager = (ProjectLevelVcsManagerImpl) ProjectLevelVcsManager.getInstance(project);
  final BackgroundableActionEnabledHandler handler;
  if (actionKey != null) {
    handler = vcsManager.getBackgroundableActionHandler(actionKey);
    // fo not start same action twice
    if (handler.isInProgress(actionParameter)) return;
  } else {
    handler = null;
  }

  final VcsBackgroundableComputable<T> backgroundableComputable =
    new VcsBackgroundableComputable<T>(project, title, errorTitle, backgroundable, awtSuccessContinuation, awtErrorContinuation,
                                handler, actionParameter);
  backgroundableComputable.setSilent(silent);
  if (handler != null) {
    handler.register(actionParameter);
  }
  ProgressManager.getInstance().run(backgroundableComputable);
}
项目:tools-idea    文件:VcsHistoryProviderBackgroundableProxy.java   
public VcsHistoryProviderBackgroundableProxy(final AbstractVcs vcs, final VcsHistoryProvider delegate, DiffProvider diffProvider) {
  myDelegate = delegate;
  myProject = vcs.getProject();
  myConfiguration = VcsConfiguration.getInstance(myProject);
  myCachesHistory = myDelegate instanceof VcsCacheableHistorySessionFactory;
  myDiffProvider = diffProvider;
  myVcsHistoryCache = ProjectLevelVcsManager.getInstance(myProject).getVcsHistoryCache();
  myType = vcs.getType();
  myHistoryComputerFactory = new HistoryComputerFactory() {
    @Override
    public ThrowableComputable<VcsHistorySession, VcsException> create(FilePath filePath,
                                                                       Consumer<VcsHistorySession> consumer,
                                                                       VcsKey vcsKey) {
      if (myCachesHistory) {
        return new CachingHistoryComputer(filePath, consumer, vcsKey);
      } else {
        return new SimpelHistoryComputer(filePath, consumer);
      }
    }
  };
}
项目:tools-idea    文件:VcsHistoryProviderBackgroundableProxy.java   
public void createSessionFor(final VcsKey vcsKey, final FilePath filePath, final Consumer<VcsHistorySession> continuation,
                             @Nullable VcsBackgroundableActions actionKey,
                             final boolean silent,
                             @Nullable final Consumer<VcsHistorySession> backgroundSpecialization) {
  final ThrowableComputable<VcsHistorySession, VcsException> throwableComputable =
    myHistoryComputerFactory.create(filePath, backgroundSpecialization, vcsKey);
  final VcsBackgroundableActions resultingActionKey = actionKey == null ? VcsBackgroundableActions.CREATE_HISTORY_SESSION : actionKey;
  final Object key = VcsBackgroundableActions.keyFrom(filePath);

  if (silent) {
    VcsBackgroundableComputable.createAndRunSilent(myProject, resultingActionKey, key, VcsBundle.message("loading.file.history.progress"),
                                                   throwableComputable, continuation);
  } else {
    VcsBackgroundableComputable.createAndRun(myProject, resultingActionKey, key, VcsBundle.message("loading.file.history.progress"),
                                             VcsBundle.message("message.title.could.not.load.file.history"), throwableComputable, continuation, null);
  }
}
项目:tools-idea    文件:RemoteProcessSupport.java   
private EntryPoint acquire(final RunningInfo port) throws Exception {
  EntryPoint result = RemoteUtil.executeWithClassLoader(new ThrowableComputable<EntryPoint, Exception>() {
    @Override
    public EntryPoint compute() throws Exception {
      Registry registry = LocateRegistry.getRegistry("localhost", port.port);
      Remote remote = registry.lookup(port.name);
      if (Remote.class.isAssignableFrom(myValueClass)) {
        return RemoteUtil.substituteClassLoader(narrowImpl(remote, myValueClass), myValueClass.getClassLoader());
      }
      else {
        return RemoteUtil.castToLocal(remote, myValueClass);
      }
    }
  }, getClass().getClassLoader()); // should be the loader of client plugin
  // init hard ref that will keep it from DGC and thus preventing from System.exit
  port.entryPointHardRef = result;
  return result;
}
项目:tools-idea    文件:MavenTemplateFileProcessor.java   
@Nullable
@Override
protected String encodeFileText(final String content, final VirtualFile file, final Project project) throws IOException {
  if ("pom.xml".equals(file.getName())) {
    return ApplicationManager.getApplication().runReadAction(new ThrowableComputable<String, IOException>() {
      @Override
      public String compute() throws IOException {
        PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("pom.xml", XmlFileType.INSTANCE, content);
        final MavenDomProjectModel model = MavenDomUtil.getMavenDomModel(psiFile, MavenDomProjectModel.class);
        if (model == null) return null;
        String text = psiFile.getText();
        XmlElement element = model.getName().getXmlElement();
        if (element instanceof XmlTag) {
          text = ((XmlTag)element).getValue().getTextRange().replace(text, wrap(ProjectTemplateParameterFactory.IJ_PROJECT_NAME));
        }
        element = model.getArtifactId().getXmlElement();
        if (element instanceof XmlTag) {
          text = ((XmlTag)element).getValue().getTextRange().replace(text, wrap(ProjectTemplateParameterFactory.IJ_PROJECT_NAME));
        }
        return text;
      }
    });
  }
  return null;
}
项目:tools-idea    文件:SshSharedConnection.java   
public SshSharedConnection(final String repository, final ConnectionSettings connectionSettings, final SshAuthentication authentication) {
  myValid = new AtomicBoolean(true);
  myRepository = repository;
  myConnectionSettings = connectionSettings;
  myLock = new Object();

  myConnectionFactory = new ThrowableComputable<Connection, AuthenticationException>() {
    public Connection compute() throws AuthenticationException {
      try {
        SshLogger.debug("connection factory called");
        return SshConnectionUtils.openConnection(connectionSettings, authentication);
      }
      catch (AuthenticationException e) {
        // todo +-
        myValid.set(false);
        throw e;
      } catch (IOException e) {
        // todo +-
        myValid.set(false);
        throw new AuthenticationException(e.getMessage(), e);
      }
    }
  };
  myQueue = new LinkedList<Cell>();
}
项目:nosql4idea    文件:NoSqlConfigurable.java   
private void testPath(final DatabaseVendor databaseVendor) {
    ProcessOutput processOutput;
    try {
        processOutput = ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<ProcessOutput, Exception>() {
            @Override
            public ProcessOutput compute() throws Exception {
                return checkShellPath(databaseVendor, getShellPath());
            }
        }, "Testing " + databaseVendor.name + " CLI Executable...", true, NoSqlConfigurable.this.project);
    } catch (ProcessCanceledException pce) {
        return;
    } catch (Exception e) {
        Messages.showErrorDialog(mainPanel, e.getMessage(), "Something wrong happened");
        return;
    }
    if (processOutput != null && processOutput.getExitCode() == 0) {
        Messages.showInfoMessage(mainPanel, processOutput.getStdout(), databaseVendor.name + " CLI Path Checked");
    }
}
项目:consulo    文件:EncodingRegistry.java   
public static <E extends Throwable> VirtualFile doActionAndRestoreEncoding(@Nonnull VirtualFile fileBefore,
                                                                           @Nonnull ThrowableComputable<VirtualFile, E> action) throws E {
  EncodingRegistry registry = getInstance();
  Charset charsetBefore = registry.getEncoding(fileBefore, true);
  VirtualFile fileAfter = null;
  try {
    fileAfter = action.compute();
    return fileAfter;
  }
  finally {
    if (fileAfter != null) {
      Charset actual = registry.getEncoding(fileAfter, true);
      if (!Comparing.equal(actual, charsetBefore)) {
        registry.setEncoding(fileAfter, charsetBefore);
      }
    }
  }
}