Java 类com.intellij.util.ThrowableConvertor 实例源码

项目:intellij-ce-playground    文件:CacheJdbcConnection.java   
public PreparedStatement getOrCreatePreparedStatement(@NotNull final String name, final ThrowableConvertor<Connection, PreparedStatement, SQLException> getter)
  throws VcsException {
  synchronized (myLock) {
    getConnection();
    final PreparedStatement statement = myPreparedStatementsMap.get(name);
    if (statement != null) {
      return statement;
    }
    final PreparedStatement newStatement;
    try {
      newStatement = getter.convert(myConnection);
    }
    catch (SQLException e) {
      throw new VcsException(e);
    }
    myPreparedStatementsMap.put(name, newStatement);
    return newStatement;
  }
}
项目:intellij-ce-playground    文件:VcsSqliteLayer.java   
private void insertPathsChanges(Map<String, Long> paths, CommittedChangeList list, long listId) throws VcsException {
  final PreparedStatement insert = myConnection.getOrCreatePreparedStatement(SqliteTables.PREPARED_INSERT_PATH_2_REVS,
    new ThrowableConvertor<Connection, PreparedStatement, SQLException>() {
      @Override
      public PreparedStatement convert(Connection connection) throws SQLException {
        return connection.prepareStatement("INSERT INTO " + SqliteTables.PATHS_2_REVS.TABLE_NAME +
          " ( " + StringUtil.join(Arrays.asList(SqliteTables.PATHS_2_REVS.PATH_FK, SqliteTables.PATHS_2_REVS.REVISION_FK,
          SqliteTables.PATHS_2_REVS.TYPE, SqliteTables.PATHS_2_REVS.COPY_PATH_ID, SqliteTables.PATHS_2_REVS.DELETE_PATH_ID,
          SqliteTables.PATHS_2_REVS.VISIBLE), " , ") +
          ") VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
      }
    });
  try {
    insert.setLong(2, listId);
    final Collection<Change> withMoved = list.getChangesWithMovedTrees();
    final Set<Change> simple = new HashSet<Change>(list.getChanges());
    for (Change change : withMoved) {
      insertOneChange(paths, insert, change, simple.contains(change));
    }
  }
  catch (SQLException e) {
    throw new VcsException(e);
  }
}
项目:intellij-ce-playground    文件:GithubShareAction.java   
@Nullable
private static String createGithubRepository(@NotNull Project project,
                                             @NotNull GithubAuthDataHolder authHolder,
                                             @NotNull ProgressIndicator indicator,
                                             @NotNull final String name,
                                             @NotNull final String description,
                                             final boolean isPrivate) {

  try {
    return GithubUtil.runTask(project, authHolder, indicator, new ThrowableConvertor<GithubConnection, GithubRepo, IOException>() {
      @NotNull
      @Override
      public GithubRepo convert(@NotNull GithubConnection connection) throws IOException {
        return GithubApiUtil.createRepo(connection, name, description, isPrivate);
      }
    }).getHtmlUrl();
  }
  catch (IOException e) {
    GithubNotifications.showError(project, "Failed to create GitHub Repository", e);
    return null;
  }
}
项目:intellij-ce-playground    文件:GithubRepositoryEditor.java   
private void generateToken() {
  try {
    myToken.setText(
      GithubUtil.computeValueInModal(myProject, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, String, IOException>() {
        @NotNull
        @Override
        public String convert(ProgressIndicator indicator) throws IOException {
          return GithubUtil
            .runTaskWithBasicAuthForHost(myProject, GithubAuthDataHolder.createFromSettings(), indicator, getHost(),
                                         new ThrowableConvertor<GithubConnection, String, IOException>() {
                                           @NotNull
                                           @Override
                                           public String convert(@NotNull GithubConnection connection) throws IOException {
                                             return GithubApiUtil
                                               .getTasksToken(connection, getRepoAuthor(), getRepoName(), "IntelliJ tasks plugin");
                                           }
                                         }
            );
        }
      })
    );
  }
  catch (IOException e) {
    GithubNotifications.showErrorDialog(myProject, "Can't Get Access Token", e);
  }
}
项目:intellij-ce-playground    文件:GithubCreateGistAction.java   
@Nullable
private static GithubAuthDataHolder getValidAuthData(@NotNull final Project project, boolean isAnonymous) {
  if (isAnonymous) {
    return new GithubAuthDataHolder(GithubAuthData.createAnonymous());
  }
  else {
    try {
      return GithubUtil
        .computeValueInModal(project, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, GithubAuthDataHolder, IOException>() {
                               @NotNull
                               @Override
                               public GithubAuthDataHolder convert(ProgressIndicator indicator) throws IOException {
                                 return GithubUtil.getValidAuthDataHolderFromConfig(project, indicator);
                               }
                             }
        );
    }
    catch (IOException e) {
      GithubNotifications.showError(project, "Can't create gist", e);
      return null;
    }

  }
}
项目:intellij-ce-playground    文件:GithubLoginDialog.java   
@Override
protected void doOKAction() {
  final GithubAuthDataHolder authHolder = new GithubAuthDataHolder(myGithubLoginPanel.getAuthData());
  try {
    GithubUtil.computeValueInModal(myProject, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, GithubUser, IOException>() {
      @NotNull
      @Override
      public GithubUser convert(ProgressIndicator indicator) throws IOException {
        return GithubUtil.checkAuthData(myProject, authHolder, indicator);
      }
    });

    myAuthData = authHolder.getAuthData();

    if (mySettings.isSavePasswordMakesSense()) {
      mySettings.setSavePassword(myGithubLoginPanel.isSavePasswordSelected());
    }
    super.doOKAction();
  }
  catch (IOException e) {
    LOG.info(e);
    setErrorText("Can't login: " + GithubUtil.getErrorTextFromException(e));
  }
}
项目:intellij-ce-playground    文件:GithubCreatePullRequestWorker.java   
private void doLoadForksFromGithub(@NotNull ProgressIndicator indicator) throws IOException {
  GithubRepoDetailed repo =
    GithubUtil.runTask(myProject, myAuthHolder, indicator, new ThrowableConvertor<GithubConnection, GithubRepoDetailed, IOException>() {
      @NotNull
      @Override
      public GithubRepoDetailed convert(@NotNull GithubConnection connection) throws IOException {
        return GithubApiUtil.getDetailedRepoInfo(connection, myPath.getUser(), myPath.getRepository());
      }
    });

  doAddFork(repo, indicator);
  if (repo.getParent() != null) {
    doAddFork(repo.getParent(), indicator);
  }
  if (repo.getSource() != null) {
    doAddFork(repo.getSource(), indicator);
  }

  mySource = repo.getSource() == null ? repo.getFullPath() : repo.getSource().getFullPath();
}
项目:intellij-ce-playground    文件:GithubCreatePullRequestWorker.java   
@NotNull
private List<String> loadBranches(@NotNull final GithubFullPath fork, @NotNull ProgressIndicator indicator) throws IOException {
  return ContainerUtil.map(
    GithubUtil.runTask(myProject, myAuthHolder, indicator, new ThrowableConvertor<GithubConnection, List<GithubBranch>, IOException>() {
      @Override
      public List<GithubBranch> convert(@NotNull GithubConnection connection) throws IOException {
        return GithubApiUtil.getRepoBranches(connection, fork.getUser(), fork.getRepository());
      }
    }),
    new Function<GithubBranch, String>() {
      @Override
      public String fun(@NotNull GithubBranch branch) {
        return branch.getName();
      }
    }
  );
}
项目:intellij-ce-playground    文件:GithubCreatePullRequestWorker.java   
@Nullable
private GithubPullRequest doCreatePullRequest(@NotNull ProgressIndicator indicator,
                                              @NotNull final BranchInfo branch,
                                              @NotNull final String title,
                                              @NotNull final String description) {
  final ForkInfo fork = branch.getForkInfo();

  final String head = myPath.getUser() + ":" + myCurrentBranch;
  final String base = branch.getRemoteName();

  try {
    return GithubUtil
      .runTask(myProject, myAuthHolder, indicator, new ThrowableConvertor<GithubConnection, GithubPullRequest, IOException>() {
        @NotNull
        @Override
        public GithubPullRequest convert(@NotNull GithubConnection connection) throws IOException {
          return GithubApiUtil
            .createPullRequest(connection, fork.getPath().getUser(), fork.getPath().getRepository(), title, description, head, base);
        }
      });
  }
  catch (IOException e) {
    GithubNotifications.showError(myProject, CANNOT_CREATE_PULL_REQUEST, e);
    return null;
  }
}
项目:intellij-ce-playground    文件:CachingSvnRepositoryPool.java   
public CachingSvnRepositoryPool(ThrowableConvertor<SVNURL, SVNRepository, SVNException> creator,
                                final int maxCached, final int maxConcurrent,
                                ThrowableConsumer<Pair<SVNURL, SVNRepository>, SVNException> adjuster,
                                final ApplicationLevelNumberConnectionsGuard guard) {
  myGuard = guard;
  myLock = new Object();
  myConnectionTimeout = DEFAULT_IDLE_TIMEOUT;
  myCreator = creator;
  myAdjuster = adjuster;
  myMaxCached = maxCached > 0 ? maxCached : ourMaxCachedDefault;
  myMaxConcurrent = maxConcurrent > 0 ? maxConcurrent : ourMaxConcurrentDefault;
  if (myMaxConcurrent < myMaxCached) {
    myMaxConcurrent = myMaxCached;
  }
  myGroups = new HashMap<String, RepoGroup>();
  myDisposed = false;
}
项目:intellij-ce-playground    文件:CachingSvnRepositoryPool.java   
private RepoGroup(ThrowableConvertor<SVNURL, SVNRepository, SVNException> creator, int cached, int concurrent,
                  final ThrowableConsumer<Pair<SVNURL, SVNRepository>, SVNException> adjuster,
                  final ApplicationLevelNumberConnectionsGuard guard, final Object waitObj, final long connectionTimeout) {
  myCreator = creator;
  myMaxCached = cached;
  myMaxConcurrent = concurrent;
  myAdjuster = adjuster;
  myGuard = guard;
  myConnectionTimeout = connectionTimeout;

  myInactive = new TreeMap<Long, SVNRepository>();
  myUsed = new HashSet<SVNRepository>();

  myDisposed = false;
  myWait = waitObj;
}
项目:tools-idea    文件:CacheJdbcConnection.java   
public PreparedStatement getOrCreatePreparedStatement(@NotNull final String name, final ThrowableConvertor<Connection, PreparedStatement, SQLException> getter)
  throws VcsException {
  synchronized (myLock) {
    getConnection();
    final PreparedStatement statement = myPreparedStatementsMap.get(name);
    if (statement != null) {
      return statement;
    }
    final PreparedStatement newStatement;
    try {
      newStatement = getter.convert(myConnection);
    }
    catch (SQLException e) {
      throw new VcsException(e);
    }
    myPreparedStatementsMap.put(name, newStatement);
    return newStatement;
  }
}
项目:tools-idea    文件:VcsSqliteLayer.java   
private void insertPathsChanges(Map<String, Long> paths, CommittedChangeList list, long listId) throws VcsException {
  final PreparedStatement insert = myConnection.getOrCreatePreparedStatement(SqliteTables.PREPARED_INSERT_PATH_2_REVS,
    new ThrowableConvertor<Connection, PreparedStatement, SQLException>() {
      @Override
      public PreparedStatement convert(Connection connection) throws SQLException {
        return connection.prepareStatement("INSERT INTO " + SqliteTables.PATHS_2_REVS.TABLE_NAME +
          " ( " + StringUtil.join(Arrays.asList(SqliteTables.PATHS_2_REVS.PATH_FK, SqliteTables.PATHS_2_REVS.REVISION_FK,
          SqliteTables.PATHS_2_REVS.TYPE, SqliteTables.PATHS_2_REVS.COPY_PATH_ID, SqliteTables.PATHS_2_REVS.DELETE_PATH_ID,
          SqliteTables.PATHS_2_REVS.VISIBLE), " , ") +
          ") VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
      }
    });
  try {
    insert.setLong(2, listId);
    final Collection<Change> withMoved = list.getChangesWithMovedTrees();
    final Set<Change> simple = new HashSet<Change>(list.getChanges());
    for (Change change : withMoved) {
      insertOneChange(paths, insert, change, simple.contains(change));
    }
  }
  catch (SQLException e) {
    throw new VcsException(e);
  }
}
项目:tools-idea    文件:GithubSslSupport.java   
/**
 * Tries to execute the {@link HttpMethod} and captures the {@link ValidatorException exception} which is thrown if user connects
 * to an HTTPS server with a non-trusted (probably, self-signed) SSL certificate. In which case proposes to cancel the connection
 * or to proceed without certificate check.
 *
 * @param methodCreator a function to create the HttpMethod. This is required instead of just {@link HttpMethod} instance, because the
 *                      implementation requires the HttpMethod to be recreated in certain circumstances.
 * @return the HttpMethod instance which was actually executed
 *         and which can be {@link HttpMethod#getResponseBodyAsString() asked for the response}.
 * @throws IOException in case of other errors or if user declines the proposal of non-trusted connection.
 */
@NotNull
public HttpMethod executeSelfSignedCertificateAwareRequest(@NotNull HttpClient client, @NotNull String uri,
                                                           @NotNull ThrowableConvertor<String, HttpMethod, IOException> methodCreator)
                                                           throws IOException {
  HttpMethod method = methodCreator.convert(uri);
  try {
    client.executeMethod(method);
    return method;
  }
  catch (IOException e) {
    HttpMethod m = handleCertificateExceptionAndRetry(e, method.getURI().getHost(), client, method.getURI(), methodCreator);
    if (m == null) {
      throw e;
    }
    return m;
  }
}
项目:tools-idea    文件:GithubSslSupport.java   
@Nullable
private static HttpMethod handleCertificateExceptionAndRetry(@NotNull IOException e, @NotNull String host,
                                                             @NotNull HttpClient client, @NotNull URI uri,
                                                             @NotNull ThrowableConvertor<String, HttpMethod, IOException> methodCreator)
                                                             throws IOException {
  if (!isCertificateException(e)) {
    throw e;
  }

  if (isTrusted(host)) {
    // creating a special configuration that allows connections to non-trusted HTTPS hosts
    // see the javadoc to EasySSLProtocolSocketFactory for details
    Protocol easyHttps = new Protocol("https", (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443);
    HostConfiguration hc = new HostConfiguration();
    hc.setHost(host, 443, easyHttps);
    String relativeUri = new URI(uri.getPathQuery(), false).getURI();
    // it is important to use relative URI here, otherwise our custom protocol won't work.
    // we have to recreate the method, because HttpMethod#setUri won't overwrite the host,
    // and changing host by hands (HttpMethodBase#setHostConfiguration) is deprecated.
    HttpMethod method = methodCreator.convert(relativeUri);
    client.executeMethod(hc, method);
    return method;
  }
  throw e;
}
项目:tools-idea    文件:CachingSvnRepositoryPool.java   
public CachingSvnRepositoryPool(ThrowableConvertor<SVNURL, SVNRepository, SVNException> creator,
                                final int maxCached, final int maxConcurrent,
                                ThrowableConsumer<Pair<SVNURL, SVNRepository>, SVNException> adjuster,
                                final ApplicationLevelNumberConnectionsGuard guard) {
  myGuard = guard;
  myLock = new Object();
  myConnectionTimeout = DEFAULT_IDLE_TIMEOUT;
  myCreator = creator;
  myAdjuster = adjuster;
  myMaxCached = maxCached > 0 ? maxCached : ourMaxCachedDefault;
  myMaxConcurrent = maxConcurrent > 0 ? maxConcurrent : ourMaxConcurrentDefault;
  if (myMaxConcurrent < myMaxCached) {
    myMaxConcurrent = myMaxCached;
  }
  myGroups = new HashMap<String, RepoGroup>();
  myDisposed = false;
}
项目:tools-idea    文件:CachingSvnRepositoryPool.java   
private RepoGroup(ThrowableConvertor<SVNURL, SVNRepository, SVNException> creator, int cached, int concurrent,
                  final ThrowableConsumer<Pair<SVNURL, SVNRepository>, SVNException> adjuster,
                  final ApplicationLevelNumberConnectionsGuard guard, final Object waitObj, final long connectionTimeout) {
  myCreator = creator;
  myMaxCached = cached;
  myMaxConcurrent = concurrent;
  myAdjuster = adjuster;
  myGuard = guard;
  myConnectionTimeout = connectionTimeout;

  myInactive = new TreeMap<Long, SVNRepository>();
  myUsed = new HashSet<SVNRepository>();

  myDisposed = false;
  myWait = waitObj;
}
项目:consulo    文件:SchemesManagerImpl.java   
@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);
  }
}
项目:consulo    文件:QuickListsManager.java   
@Override
public void initComponent() {
  for (BundledQuickListsProvider provider : BundledQuickListsProvider.EP_NAME.getExtensions()) {
    for (final String path : provider.getBundledListsRelativePaths()) {
      mySchemesManager.loadBundledScheme(path, provider, new ThrowableConvertor<Element, QuickList, Throwable>() {
        @Override
        public QuickList convert(Element element) throws Throwable {
          QuickList item = createItem(element);
          item.getExternalInfo().setHash(JDOMUtil.getTreeHash(element, true));
          item.getExternalInfo().setPreviouslySavedName(item.getName());
          item.getExternalInfo().setCurrentFileName(PathUtilRt.getFileName(path));
          return item;
        }
      });
    }
  }
  mySchemesManager.loadSchemes();
  registerActions();
}
项目:consulo    文件:CacheJdbcConnection.java   
public PreparedStatement getOrCreatePreparedStatement(@Nonnull final String name, final ThrowableConvertor<Connection, PreparedStatement, SQLException> getter)
  throws VcsException {
  synchronized (myLock) {
    getConnection();
    final PreparedStatement statement = myPreparedStatementsMap.get(name);
    if (statement != null) {
      return statement;
    }
    final PreparedStatement newStatement;
    try {
      newStatement = getter.convert(myConnection);
    }
    catch (SQLException e) {
      throw new VcsException(e);
    }
    myPreparedStatementsMap.put(name, newStatement);
    return newStatement;
  }
}
项目:consulo    文件:VcsSqliteLayer.java   
private void insertPathsChanges(Map<String, Long> paths, CommittedChangeList list, long listId) throws VcsException {
  final PreparedStatement insert = myConnection.getOrCreatePreparedStatement(SqliteTables.PREPARED_INSERT_PATH_2_REVS,
    new ThrowableConvertor<Connection, PreparedStatement, SQLException>() {
      @Override
      public PreparedStatement convert(Connection connection) throws SQLException {
        return connection.prepareStatement("INSERT INTO " + SqliteTables.PATHS_2_REVS.TABLE_NAME +
          " ( " + StringUtil.join(Arrays.asList(SqliteTables.PATHS_2_REVS.PATH_FK, SqliteTables.PATHS_2_REVS.REVISION_FK,
          SqliteTables.PATHS_2_REVS.TYPE, SqliteTables.PATHS_2_REVS.COPY_PATH_ID, SqliteTables.PATHS_2_REVS.DELETE_PATH_ID,
          SqliteTables.PATHS_2_REVS.VISIBLE), " , ") +
          ") VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
      }
    });
  try {
    insert.setLong(2, listId);
    final Collection<Change> withMoved = list.getChangesWithMovedTrees();
    final Set<Change> simple = new HashSet<Change>(list.getChanges());
    for (Change change : withMoved) {
      insertOneChange(paths, insert, change, simple.contains(change));
    }
  }
  catch (SQLException e) {
    throw new VcsException(e);
  }
}
项目:intellij-ce-playground    文件:QuickListsManager.java   
@Override
public void initComponent() {
  for (BundledQuickListsProvider provider : BundledQuickListsProvider.EP_NAME.getExtensions()) {
    for (final String path : provider.getBundledListsRelativePaths()) {
      mySchemeManager.loadBundledScheme(path, provider, new ThrowableConvertor<Element, QuickList, Throwable>() {
        @Override
        public QuickList convert(Element element) throws Throwable {
          return createItem(element);
        }
      });
    }
  }
  mySchemeManager.loadSchemes();
  registerActions();
}
项目:intellij-ce-playground    文件:EditorColorsManagerImpl.java   
private void loadBundledSchemes() {
  if (!isUnitTestOrHeadlessMode()) {
    for (BundledColorSchemeEP ep : BundledColorSchemeEP.EP_NAME.getExtensions()) {
      mySchemeManager.loadBundledScheme(ep.path + ".xml", ep, new ThrowableConvertor<Element, EditorColorsScheme, Throwable>() {
        @Override
        public EditorColorsScheme convert(Element element) throws Throwable {
          return new ReadOnlyColorsSchemeImpl(element);
        }
      });
    }
  }
}
项目:intellij-ce-playground    文件:SelectListsQueryHelper.java   
private PreparedStatement createImpl(final String queryName, final String whereClause) throws VcsException, SQLException {
  final PreparedStatement statement = myConnection.getOrCreatePreparedStatement(queryName,
                                                                                new ThrowableConvertor<Connection, PreparedStatement, SQLException>() {
                                                                                  @Override
                                                                                  public PreparedStatement convert(Connection connection)
                                                                                    throws SQLException {
                                                                                    return connection.prepareStatement("SELECT " +
                                                                                                                       SqliteTables.REVISION.RAW_DATA +
                                                                                                                       " , " + SqliteTables.REVISION.NUMBER_INT +
                                                                                                                       " FROM " +
                                                                                                                       SqliteTables.REVISION.TABLE_NAME +
                                                                                                                       " R INNER JOIN " +
                                                                                                                       SqliteTables.PATHS_2_REVS.TABLE_NAME +
                                                                                                                       " PR ON R." +
                                                                                                                       SqliteTables.REVISION.ID +
                                                                                                                       " = PR." +
                                                                                                                       SqliteTables.PATHS_2_REVS.REVISION_FK +
                                                                                                                       " , " +
                                                                                                                       SqliteTables.PATHS.TABLE_NAME +
                                                                                                                       " P ON PR." +
                                                                                                                       SqliteTables.PATHS_2_REVS.PATH_FK +
                                                                                                                       " = P." +
                                                                                                                       SqliteTables.PATHS.ID +
                                                                                                                       " WHERE R." +
                                                                                                                       SqliteTables.REVISION.ROOT_FK +
                                                                                                                       " = ? AND "
                                                                                                                       +
                                                                                                                       whereClause +
                                                                                                                       " ORDER BY " +
                                                                                                                       SqliteTables.REVISION.NUMBER_INT +
                                                                                                                       " DESC");
                                                                                  }
                                                                                });
  statement.setLong(1, myLocationId);
  return statement;
}
项目:intellij-ce-playground    文件:GithubShareAction.java   
@Nullable
private static GithubInfo loadGithubInfoWithModal(@NotNull final GithubAuthDataHolder authHolder, @NotNull final Project project) {
  try {
    return GithubUtil
      .computeValueInModal(project, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, GithubInfo, IOException>() {
        @NotNull
        @Override
        public GithubInfo convert(ProgressIndicator indicator) throws IOException {
          // get existing github repos (network) and validate auth data
          return GithubUtil.runTask(project, authHolder, indicator, new ThrowableConvertor<GithubConnection, GithubInfo, IOException>() {
            @NotNull
            @Override
            public GithubInfo convert(@NotNull GithubConnection connection) throws IOException {
              // check access to private repos (network)
              GithubUserDetailed userInfo = GithubApiUtil.getCurrentUserDetailed(connection);

              HashSet<String> names = new HashSet<String>();
              for (GithubRepo info : GithubApiUtil.getUserRepos(connection)) {
                names.add(info.getName());
              }
              return new GithubInfo(userInfo, names);
            }
          });
        }
      });
  }
  catch (IOException e) {
    GithubNotifications.showErrorDialog(project, "Failed to Connect to GitHub", e);
    return null;
  }
}
项目:intellij-ce-playground    文件:GithubRebaseAction.java   
@Nullable
private static GithubRepoDetailed loadRepositoryInfo(@NotNull Project project,
                                                     @NotNull GitRepository gitRepository,
                                                     @NotNull ProgressIndicator indicator) {
  final String remoteUrl = GithubUtil.findGithubRemoteUrl(gitRepository);
  if (remoteUrl == null) {
    GithubNotifications.showError(project, CANNOT_PERFORM_GITHUB_REBASE, "Can't find GitHub remote");
    return null;
  }
  final GithubFullPath userAndRepo = GithubUrlUtil.getUserAndRepositoryFromRemoteUrl(remoteUrl);
  if (userAndRepo == null) {
    GithubNotifications.showError(project, CANNOT_PERFORM_GITHUB_REBASE, "Can't process remote: " + remoteUrl);
    return null;
  }

  try {
    return GithubUtil.runTask(project, GithubAuthDataHolder.createFromSettings(), indicator,
                              new ThrowableConvertor<GithubConnection, GithubRepoDetailed, IOException>() {
                                @NotNull
                                @Override
                                public GithubRepoDetailed convert(@NotNull GithubConnection connection) throws IOException {
                                  return GithubApiUtil.getDetailedRepoInfo(connection, userAndRepo.getUser(), userAndRepo.getRepository());
                                }
                              });
  }
  catch (IOException e) {
    GithubNotifications.showError(project, "Can't load repository info", e);
    return null;
  }
}
项目:intellij-ce-playground    文件:GithubCreateGistAction.java   
@Nullable
static String createGist(@NotNull Project project,
                         @NotNull GithubAuthDataHolder auth,
                         @NotNull ProgressIndicator indicator,
                         @NotNull List<FileContent> contents,
                         final boolean isPrivate,
                         @NotNull final String description,
                         @Nullable String filename) {
  if (contents.isEmpty()) {
    GithubNotifications.showWarning(project, FAILED_TO_CREATE_GIST, "Can't create empty gist");
    return null;
  }
  if (contents.size() == 1 && filename != null) {
    FileContent entry = contents.iterator().next();
    contents = Collections.singletonList(new FileContent(filename, entry.getContent()));
  }
  try {
    final List<FileContent> finalContents = contents;
    return GithubUtil.runTask(project, auth, indicator, new ThrowableConvertor<GithubConnection, GithubGist, IOException>() {
      @NotNull
      @Override
      public GithubGist convert(@NotNull GithubConnection connection) throws IOException {
        return GithubApiUtil.createGist(connection, finalContents, description, isPrivate);
      }
    }).getHtmlUrl();
  }
  catch (IOException e) {
    GithubNotifications.showError(project, FAILED_TO_CREATE_GIST, e);
    return null;
  }
}
项目:intellij-ce-playground    文件:GithubCreatePullRequestWorker.java   
@Nullable
private String doLoadDefaultBranch(@NotNull final GithubFullPath fork, @NotNull ProgressIndicator indicator) throws IOException {
  GithubRepo repo =
    GithubUtil.runTask(myProject, myAuthHolder, indicator, new ThrowableConvertor<GithubConnection, GithubRepo, IOException>() {
      @Override
      public GithubRepo convert(@NotNull GithubConnection connection) throws IOException {
        return GithubApiUtil.getDetailedRepoInfo(connection, fork.getUser(), fork.getRepository());
      }
    });
  return repo.getDefaultBranch();
}
项目:intellij-ce-playground    文件:GithubCreatePullRequestWorker.java   
public void showDiffDialog(@Nullable final BranchInfo branch) {
  if (branch == null) {
    GithubNotifications.showWarningDialog(myProject, "Can't Show Diff", "Target branch is not selected");
    return;
  }

  DiffInfo info;
  try {
    info = GithubUtil
      .computeValueInModal(myProject, "Collecting diff data...", new ThrowableConvertor<ProgressIndicator, DiffInfo, IOException>() {
        @Override
        public DiffInfo convert(ProgressIndicator indicator) throws IOException {
          return GithubUtil.runInterruptable(indicator, new ThrowableComputable<DiffInfo, IOException>() {
            @Override
            public DiffInfo compute() throws IOException {
              return getDiffInfo(branch);
            }
          });
        }
      });
  }
  catch (IOException e) {
    GithubNotifications.showError(myProject, "Can't collect diff data", e);
    return;
  }
  if (info == null) {
    GithubNotifications.showErrorDialog(myProject, "Can't Show Diff", "Can't collect diff data");
    return;
  }

  GitCompareBranchesDialog dialog =
    new GitCompareBranchesDialog(myProject, info.getTo(), info.getFrom(), info.getInfo(), myGitRepository, true);
  dialog.show();
}
项目:intellij-ce-playground    文件:GithubCreatePullRequestWorker.java   
@Nullable
private List<GithubFullPath> getAvailableForks(@NotNull ProgressIndicator indicator) {
  try {
    List<GithubFullPath> forks = ContainerUtil.map(
      GithubUtil.runTask(myProject, myAuthHolder, indicator,
                         new ThrowableConvertor<GithubConnection, List<GithubRepo>, IOException>() {
                           @NotNull
                           @Override
                           public List<GithubRepo> convert(@NotNull GithubConnection connection)
                             throws IOException {
                             return GithubApiUtil.getForks(connection, mySource.getUser(), mySource.getRepository());
                           }
                         }
      ),
      new Function<GithubRepo, GithubFullPath>() {
        @Override
        public GithubFullPath fun(GithubRepo repo) {
          return repo.getFullPath();
        }
      }
    );
    if (!forks.contains(mySource)) return ContainerUtil.append(forks, mySource);
    return forks;
  }
  catch (IOException e) {
    GithubNotifications.showWarning(myProject, "Can't load available forks", e);
    return null;
  }
}
项目:intellij-ce-playground    文件:GithubCreatePullRequestWorker.java   
@Nullable
private ForkInfo findRepositoryByUser(@NotNull final ProgressIndicator indicator, @NotNull final String user) {
  for (ForkInfo fork : myForks) {
    if (StringUtil.equalsIgnoreCase(user, fork.getPath().getUser())) {
      return fork;
    }
  }

  try {
    GithubRepo repo =
      GithubUtil.runTask(myProject, myAuthHolder, indicator, new ThrowableConvertor<GithubConnection, GithubRepo, IOException>() {
        @Nullable
        @Override
        public GithubRepo convert(@NotNull GithubConnection connection) throws IOException {
          try {
            GithubRepoDetailed target = GithubApiUtil.getDetailedRepoInfo(connection, user, mySource.getRepository());
            if (target.getSource() != null && StringUtil.equals(target.getSource().getUserName(), mySource.getUser())) {
              return target;
            }
          }
          catch (IOException ignore) {
            // such repo may not exist
          }

          return GithubApiUtil.findForkByUser(connection, mySource.getUser(), mySource.getRepository(), user);
        }
      });

    if (repo == null) return null;
    return doAddFork(repo, indicator);
  }
  catch (IOException e) {
    GithubNotifications.showError(myProject, "Can't find repository", e);
    return null;
  }
}
项目:tools-idea    文件:SelectListsQueryHelper.java   
private PreparedStatement createImpl(final String queryName, final String whereClause) throws VcsException, SQLException {
  final PreparedStatement statement = myConnection.getOrCreatePreparedStatement(queryName,
                                                                                new ThrowableConvertor<Connection, PreparedStatement, SQLException>() {
                                                                                  @Override
                                                                                  public PreparedStatement convert(Connection connection)
                                                                                    throws SQLException {
                                                                                    return connection.prepareStatement("SELECT " +
                                                                                                                       SqliteTables.REVISION.RAW_DATA +
                                                                                                                       " , " + SqliteTables.REVISION.NUMBER_INT +
                                                                                                                       " FROM " +
                                                                                                                       SqliteTables.REVISION.TABLE_NAME +
                                                                                                                       " R INNER JOIN " +
                                                                                                                       SqliteTables.PATHS_2_REVS.TABLE_NAME +
                                                                                                                       " PR ON R." +
                                                                                                                       SqliteTables.REVISION.ID +
                                                                                                                       " = PR." +
                                                                                                                       SqliteTables.PATHS_2_REVS.REVISION_FK +
                                                                                                                       " , " +
                                                                                                                       SqliteTables.PATHS.TABLE_NAME +
                                                                                                                       " P ON PR." +
                                                                                                                       SqliteTables.PATHS_2_REVS.PATH_FK +
                                                                                                                       " = P." +
                                                                                                                       SqliteTables.PATHS.ID +
                                                                                                                       " WHERE R." +
                                                                                                                       SqliteTables.REVISION.ROOT_FK +
                                                                                                                       " = ? AND "
                                                                                                                       +
                                                                                                                       whereClause +
                                                                                                                       " ORDER BY " +
                                                                                                                       SqliteTables.REVISION.NUMBER_INT +
                                                                                                                       " DESC");
                                                                                  }
                                                                                });
  statement.setLong(1, myLocationId);
  return statement;
}
项目:tools-idea    文件:GithubRepositoryEditor.java   
private void generateToken() {
  final Ref<String> tokenRef = new Ref<String>();
  final Ref<IOException> exceptionRef = new Ref<IOException>();
  final Collection<String> scopes = myPrivateRepo.isSelected() ? Collections.singleton("repo") : Collections.<String>emptyList();
  ProgressManager.getInstance().run(new Task.Modal(myProject, "Access to GitHub", true) {
    public void run(@NotNull ProgressIndicator indicator) {
      try {
        tokenRef.set(GithubUtil.runWithValidBasicAuth(myProject, indicator, new ThrowableConvertor<GithubAuthData, String, IOException>() {
          @Nullable
          @Override
          public String convert(GithubAuthData auth) throws IOException {
            return GithubApiUtil.getScopedToken(auth, scopes, "Intellij tasks plugin");

          }
        }));
      }
      catch (IOException e) {
        exceptionRef.set(e);
      }
    }
  });
  if (!exceptionRef.isNull()) {
    if (exceptionRef.get() instanceof GithubAuthenticationCanceledException) {
      return;
    }
    GithubNotifications.showErrorDialog(myProject, "Can't get access token", exceptionRef.get());
    return;
  }
  myToken.setText(tokenRef.get());
}
项目:consulo    文件:SelectListsQueryHelper.java   
private PreparedStatement createImpl(final String queryName, final String whereClause) throws VcsException, SQLException {
  final PreparedStatement statement = myConnection.getOrCreatePreparedStatement(queryName,
                                                                                new ThrowableConvertor<Connection, PreparedStatement, SQLException>() {
                                                                                  @Override
                                                                                  public PreparedStatement convert(Connection connection)
                                                                                    throws SQLException {
                                                                                    return connection.prepareStatement("SELECT " +
                                                                                                                       SqliteTables.REVISION.RAW_DATA +
                                                                                                                       " , " + SqliteTables.REVISION.NUMBER_INT +
                                                                                                                       " FROM " +
                                                                                                                       SqliteTables.REVISION.TABLE_NAME +
                                                                                                                       " R INNER JOIN " +
                                                                                                                       SqliteTables.PATHS_2_REVS.TABLE_NAME +
                                                                                                                       " PR ON R." +
                                                                                                                       SqliteTables.REVISION.ID +
                                                                                                                       " = PR." +
                                                                                                                       SqliteTables.PATHS_2_REVS.REVISION_FK +
                                                                                                                       " , " +
                                                                                                                       SqliteTables.PATHS.TABLE_NAME +
                                                                                                                       " P ON PR." +
                                                                                                                       SqliteTables.PATHS_2_REVS.PATH_FK +
                                                                                                                       " = P." +
                                                                                                                       SqliteTables.PATHS.ID +
                                                                                                                       " WHERE R." +
                                                                                                                       SqliteTables.REVISION.ROOT_FK +
                                                                                                                       " = ? AND "
                                                                                                                       +
                                                                                                                       whereClause +
                                                                                                                       " ORDER BY " +
                                                                                                                       SqliteTables.REVISION.NUMBER_INT +
                                                                                                                       " DESC");
                                                                                  }
                                                                                });
  statement.setLong(1, myLocationId);
  return statement;
}
项目:consulo-java    文件:TestDiscoveryIndex.java   
public void removeTestTrace(@NotNull String testName) throws IOException
{
    myLocalTestRunDataController.withTestDataHolder((ThrowableConvertor<TestInfoHolder, Void, IOException>) localHolder ->
    {
        final int testNameId = localHolder.myTestNameEnumerator.tryEnumerate(testName);  // todo remove remote data isn't possible
        if(testNameId != 0)
        {
            localHolder.doUpdateFromDiff(testNameId, null, localHolder.myTestNameToUsedClassesAndMethodMap.get(testNameId), null);
        }
        return null;
    });
}
项目:consulo-java    文件:TestDiscoveryIndex.java   
public Collection<String> getTestModulesByMethodName(@NotNull String classFQName, @NotNull String methodName, String prefix) throws IOException
{
    return myLocalTestRunDataController.withTestDataHolder(new ThrowableConvertor<TestInfoHolder, Collection<String>, IOException>()
    {
        @Override
        public Collection<String> convert(TestInfoHolder localHolder) throws IOException
        {
            List<String> modules = getTestModules(localHolder);
            List<String> modulesFromRemote = myRemoteTestRunDataController.withTestDataHolder(this::getTestModules);
            THashSet<String> modulesSet = new THashSet<>(modules);
            if(modulesFromRemote != null)
            {
                modulesSet.addAll(modulesFromRemote);
            }
            return modulesSet;
        }

        private List<String> getTestModules(TestInfoHolder holder) throws IOException
        {
            // todo merging with remote
            final TIntArrayList list = holder.myTestNameToNearestModule.get(TestInfoHolder.createKey(holder.myClassEnumerator.enumerate(classFQName), holder.myMethodEnumerator.enumerate
                    (methodName)));
            if(list == null)
            {
                return Collections.emptyList();
            }
            final ArrayList<String> result = new ArrayList<>(list.size());
            for(int moduleNameId : list.toNativeArray())
            {
                final String moduleNameWithPrefix = holder.myModuleNameEnumerator.valueOf(moduleNameId);
                if(moduleNameWithPrefix != null && moduleNameWithPrefix.startsWith(prefix))
                {
                    result.add(moduleNameWithPrefix.substring(prefix.length()));
                }
            }
            return result;
        }
    });
}
项目:consulo-java    文件:TestDiscoveryIndex.java   
public <R> R withTestDataHolder(ThrowableConvertor<TestInfoHolder, R, IOException> action) throws IOException
{
    synchronized(myLock)
    {
        TestInfoHolder holder = getHolder();
        if(holder == null || holder.isDisposed())
        {
            return null;
        }
        try
        {
            return action.convert(holder);
        }
        catch(Throwable throwable)
        {
            if(!myReadOnly)
            {
                thingsWentWrongLetsReinitialize(holder, throwable);
            }
            else
            {
                LOG.error(throwable);
            }
        }
        return null;
    }
}
项目:intellij-ce-playground    文件:VcsSqliteLayer.java   
public List<CommittedChangeList> readLists(final AbstractVcs vcs, final RepositoryLocation location, final long lastRev, final long oldRev)
  throws VcsException {
  final String root = normalizeLocation(location);
  final long lastExisting = getLastRevision(vcs, root).getNumber();
  final long firstExisting = getFirstRevision(vcs, root).getNumber();

  if (lastExisting == -1 || firstExisting == -1) return Collections.emptyList();
  final long operatingFirst = oldRev == -1 ? firstExisting : oldRev;
  final long operatingLast = lastRev == -1 ? lastExisting : lastRev;

  final PreparedStatement statement = myConnection.getOrCreatePreparedStatement(SqliteTables.PREPARED_SELECT_REVISIONS,
    new ThrowableConvertor<Connection, PreparedStatement, SQLException>() {
      @Override
      public PreparedStatement convert(Connection connection) throws SQLException {
        // "real" statement - will be used when each committed changes provider will have the method to restore revision uniformly, through changed paths + #
        // maybe it's safier to call left outer join, but for current VCSes we always have at least one path changed for each revision -> inner join is preferable
        /*return connection.prepareStatement("SELECT * FROM " + SqliteTables.REVISION.TABLE_NAME + "R , " +
          SqliteTables.PATHS + "P , "+ SqliteTables.AUTHOR + "A INNER JOIN " + SqliteTables.PATHS_2_REVS + "PR ON PR." +
          SqliteTables.PATHS_2_REVS.REVISION_FK + "=R." + SqliteTables.REVISION.ID + " AND PR." + SqliteTables.PATHS_2_REVS.PATH_FK +
          "=" + SqliteTables.PATHS.ID + " AND R." + SqliteTables.REVISION.AUTHOR_FK + "=A." + SqliteTables.AUTHOR.ID +
          " WHERE R." + SqliteTables.REVISION.NUMBER_INT + ">=? AND R." + SqliteTables.REVISION.NUMBER_INT + "<=?");*/
        //1=first, 2=last

        return connection.prepareStatement("SELECT * FROM " + SqliteTables.REVISION.TABLE_NAME + " WHERE " +
          SqliteTables.REVISION.NUMBER_INT + ">=? AND " + SqliteTables.REVISION.NUMBER_INT + "<=? ORDER BY " + SqliteTables.REVISION.NUMBER_INT
        + " DESC");
      }
    });
  final List<CommittedChangeList> result = new ArrayList<CommittedChangeList>();
  try {

    statement.setLong(1, operatingFirst);
    statement.setLong(2, operatingLast);
    final CachingCommittedChangesProvider provider = (CachingCommittedChangesProvider)vcs.getCommittedChangesProvider();
    final ResultSet set = statement.executeQuery();
    SqliteUtil.readSelectResults(set, new ThrowableRunnable<SQLException>() {
      @Override
      public void run() throws SQLException {
        final byte[] bytes = set.getBytes(SqliteTables.REVISION.RAW_DATA);
        final CommittedChangeList list = readListByProvider(bytes, provider, location);
        result.add(list);

        /*final long revisionId = set.getLong("R." + SqliteTables.REVISION.ID);
        CommittedChangeList list = lists.get(revisionId);
        if (list == null) {
          final long numberLong = set.getLong("R." + SqliteTables.REVISION.NUMBER_INT);
          final String numberStr = set.getString("R." + SqliteTables.REVISION.NUMBER_STR);
          final String comment = set.getString("R." + SqliteTables.REVISION.COMMENT);
          final Long date = set.getLong("R." + SqliteTables.REVISION.DATE);
          final String author = set.getString("A." + SqliteTables.REVISION.AUTHOR_FK);
          list = new CommittedChangeListImpl("", comment, author, numberLong, new Date(date), Collections.<Change>emptyList());
        }*/
      }
    });
  }
  catch (SQLException e) {
    throw new VcsException(e);
  }
  return result;
}
项目:intellij-ce-playground    文件:GithubCheckoutProvider.java   
@Override
public void doCheckout(@NotNull final Project project, @Nullable final Listener listener) {
  if (!GithubUtil.testGitExecutable(project)) {
    return;
  }
  BasicAction.saveAll();

  List<GithubRepo> availableRepos;
  try {
    availableRepos = GithubUtil
      .computeValueInModal(project, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, List<GithubRepo>, IOException>() {
        @NotNull
        @Override
        public List<GithubRepo> convert(ProgressIndicator indicator) throws IOException {
          return GithubUtil.runTask(project, GithubAuthDataHolder.createFromSettings(), indicator,
                                    new ThrowableConvertor<GithubConnection, List<GithubRepo>, IOException>() {
                                      @NotNull
                                      @Override
                                      public List<GithubRepo> convert(@NotNull GithubConnection connection) throws IOException {
                                        return GithubApiUtil.getAvailableRepos(connection);
                                      }
                                    }
          );
        }
      });
  }
  catch (IOException e) {
    GithubNotifications.showError(project, "Couldn't get the list of GitHub repositories", e);
    return;
  }
  Collections.sort(availableRepos, new Comparator<GithubRepo>() {
    @Override
    public int compare(final GithubRepo r1, final GithubRepo r2) {
      final int comparedOwners = r1.getUserName().compareTo(r2.getUserName());
      return comparedOwners != 0 ? comparedOwners : r1.getName().compareTo(r2.getName());
    }
  });

  final GitCloneDialog dialog = new GitCloneDialog(project);
  // Add predefined repositories to history
  dialog.prependToHistory("-----------------------------------------------");
  for (int i = availableRepos.size() - 1; i >= 0; i--) {
    dialog.prependToHistory(GithubUrlUtil.getCloneUrl(availableRepos.get(i).getFullPath()));
  }
  if (!dialog.showAndGet()) {
    return;
  }
  dialog.rememberSettings();
  final VirtualFile destinationParent = LocalFileSystem.getInstance().findFileByIoFile(new File(dialog.getParentDirectory()));
  if (destinationParent == null) {
    return;
  }
  final String sourceRepositoryURL = dialog.getSourceRepositoryURL();
  final String directoryName = dialog.getDirectoryName();
  final String parentDirectory = dialog.getParentDirectory();

  Git git = ServiceManager.getService(Git.class);
  GitCheckoutProvider.clone(project, git, listener, destinationParent, sourceRepositoryURL, directoryName, parentDirectory);
}
项目:intellij-ce-playground    文件:GithubCreatePullRequestWorker.java   
public boolean checkAction(@Nullable final BranchInfo branch) {
  if (branch == null) {
    GithubNotifications.showWarningDialog(myProject, CANNOT_CREATE_PULL_REQUEST, "Target branch is not selected");
    return false;
  }

  DiffInfo info;
  try {
    info = GithubUtil
      .computeValueInModal(myProject, "Collecting diff data...", new ThrowableConvertor<ProgressIndicator, DiffInfo, IOException>() {
        @Override
        public DiffInfo convert(ProgressIndicator indicator) throws IOException {
          return GithubUtil.runInterruptable(indicator, new ThrowableComputable<DiffInfo, IOException>() {
            @Override
            public DiffInfo compute() throws IOException {
              return getDiffInfo(branch);
            }
          });
        }
      });
  }
  catch (IOException e) {
    GithubNotifications.showError(myProject, "Can't collect diff data", e);
    return true;
  }
  if (info == null) {
    return true;
  }

  ForkInfo fork = branch.getForkInfo();

  String localBranchName = "'" + myCurrentBranch + "'";
  String targetBranchName = "'" + fork.getRemoteName() + "/" + branch.getRemoteName() + "'";
  if (info.getInfo().getBranchToHeadCommits(myGitRepository).isEmpty()) {
    return GithubNotifications
      .showYesNoDialog(myProject, "Empty Pull Request",
                       "The branch " + localBranchName + " is fully merged to the branch " + targetBranchName + '\n' +
                       "Do you want to proceed anyway?");
  }
  if (!info.getInfo().getHeadToBranchCommits(myGitRepository).isEmpty()) {
    return GithubNotifications
      .showYesNoDialog(myProject, "Target Branch Is Not Fully Merged",
                       "The branch " + targetBranchName + " is not fully merged to the branch " + localBranchName + '\n' +
                       "Do you want to proceed anyway?");
  }

  return true;
}