Java Code Examples for com.intellij.openapi.progress.ProgressIndicator.checkCanceled()

The following are Jave code examples for showing how to use checkCanceled() of the com.intellij.openapi.progress.ProgressIndicator class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: StAnalysisRunner   File: AnalysisTask.java   Source Code and License Vote up 6 votes
@NotNull
private String getAnalysisOutput(@NotNull final ProgressIndicator progressIndicator) throws Exception {
    final List<String> gradlewCommand = System.getProperty("os.name").startsWith("Windows")
            ? Arrays.asList("cmd", "/c", "gradlew.bat", "staticAnalys")
            : Arrays.asList("./gradlew", "staticAnalys");
    gradlewProcess = new ProcessBuilder(gradlewCommand)
            .directory(new File(project.getBasePath()))
            .redirectErrorStream(true)
            .start();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gradlewProcess.getInputStream()));
    StringBuilder analysisOutputBuilder = new StringBuilder();

    String outputLine;
    while ((outputLine = bufferedReader.readLine()) != null) {
        progressIndicator.setText2(outputLine);
        progressIndicator.checkCanceled();
        analysisOutputBuilder.append(outputLine);
        analysisOutputBuilder.append('\n');
    }

    return analysisOutputBuilder.toString();
}
 
Example 2
Project: intellij-ce-playground   File: GeneralHighlightingPass.java   Source Code and License Vote up 6 votes
static void highlightTodos(@NotNull PsiFile file,
                           @NotNull CharSequence text,
                           int startOffset,
                           int endOffset,
                           @NotNull ProgressIndicator progress,
                           @NotNull ProperTextRange priorityRange,
                           @NotNull Collection<HighlightInfo> insideResult,
                           @NotNull Collection<HighlightInfo> outsideResult) {
  PsiTodoSearchHelper helper = PsiTodoSearchHelper.SERVICE.getInstance(file.getProject());
  if (helper == null) return;
  TodoItem[] todoItems = helper.findTodoItems(file, startOffset, endOffset);
  if (todoItems.length == 0) return;

  for (TodoItem todoItem : todoItems) {
    progress.checkCanceled();
    TextRange range = todoItem.getTextRange();
    String description = text.subSequence(range.getStartOffset(), range.getEndOffset()).toString();
    TextAttributes attributes = todoItem.getPattern().getAttributes().getTextAttributes();
    HighlightInfo.Builder builder = HighlightInfo.newHighlightInfo(HighlightInfoType.TODO).range(range);
    builder.textAttributes(attributes);
    builder.descriptionAndTooltip(description);
    HighlightInfo info = builder.createUnconditionally();
    (priorityRange.containsRange(info.getStartOffset(), info.getEndOffset()) ? insideResult : outsideResult).add(info);
  }
}
 
Example 3
Project: intellij-ce-playground   File: Waiter.java   Source Code and License Vote up 6 votes
public void run(@NotNull ProgressIndicator indicator) {
  indicator.setIndeterminate(true);
  indicator.setText2(VcsBundle.message("commit.wait.util.synched.text"));
  synchronized (myLock) {
    if (myStarted) {
      LOG.error("Waiter running under progress being started again.");
      return;
    }
    myStarted = true;
    while (! myDone) {
      try {
        // every second check whether we are canceled
        myLock.wait(500);
      }
      catch (InterruptedException e) {
        // ok
      }
      indicator.checkCanceled();
    }
  }
}
 
Example 4
Project: intellij-ce-playground   File: GitTextHandler.java   Source Code and License Vote up 6 votes
protected void waitForProcess() {
  if (myHandler != null) {
    ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    while (!myHandler.waitFor(50)) {
      try {
        if (indicator != null) {
          indicator.checkCanceled();
        }
      }
      catch (ProcessCanceledException pce) {
        myHandler.destroyProcess();
        throw pce;
      }
    }
  }
}
 
Example 5
Project: intellij-ce-playground   File: LowLevelSearchUtil.java   Source Code and License Vote up 6 votes
public static boolean processTextOccurrences(@NotNull CharSequence text,
                                             int startOffset,
                                             int endOffset,
                                             @NotNull StringSearcher searcher,
                                             @Nullable ProgressIndicator progress,
                                             @NotNull TIntProcedure processor) {
  if (endOffset > text.length()) {
    throw new AssertionError("end>length");
  }
  for (int index = startOffset; index < endOffset; index++) {
    if (progress != null) progress.checkCanceled();
    //noinspection AssignmentToForLoopParameter
    index = searcher.scan(text, index, endOffset);
    if (index < 0) break;
    if (checkJavaIdentifier(text, startOffset, endOffset, searcher, index)) {
      if (!processor.execute(index)) return false;
    }
  }
  return true;
}
 
Example 6
Project: educational-plugin   File: CCStepicConnector.java   Source Code and License Vote up 5 votes
public static int postLesson(@NotNull final Project project, @NotNull final Lesson lesson) {
  if (!checkIfAuthorized(project, "postLesson")) return -1;

  final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/lessons");

  String requestBody = new Gson().toJson(new StepicWrappers.LessonWrapper(lesson));
  request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));

  try {
    final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
    if (client == null) return -1;
    final CloseableHttpResponse response = client.execute(request);
    final HttpEntity responseEntity = response.getEntity();
    final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
    final StatusLine line = response.getStatusLine();
    EntityUtils.consume(responseEntity);
    if (line.getStatusCode() != HttpStatus.SC_CREATED) {
      final String message = FAILED_TITLE + "lesson ";
      LOG.error(message + responseString);
      showErrorNotification(project, message, responseString);
      return 0;
    }
    final Lesson postedLesson = new Gson().fromJson(responseString, RemoteCourse.class).getLessons(true).get(0);
    lesson.setId(postedLesson.getId());
    for (Task task : lesson.getTaskList()) {
      final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      if (indicator != null) {
        indicator.checkCanceled();
      }
      postTask(project, task, postedLesson.getId());
    }
    return postedLesson.getId();
  }
  catch (IOException e) {
    LOG.error(e.getMessage());
  }
  return -1;
}
 
Example 7
Project: intellij-ce-playground   File: NetUtils.java   Source Code and License Vote up 5 votes
/**
 * @param indicator           Progress indicator.
 * @param inputStream         source stream
 * @param outputStream        destination stream
 * @param expectedContentSize expected content size, used in progress indicator (negative means unknown length)
 * @return bytes copied
 * @throws IOException              if IO error occur
 * @throws ProcessCanceledException if process was canceled.
 */
public static int copyStreamContent(@Nullable ProgressIndicator indicator,
                                    @NotNull InputStream inputStream,
                                    @NotNull OutputStream outputStream,
                                    int expectedContentSize) throws IOException, ProcessCanceledException {
  if (indicator != null) {
    indicator.checkCanceled();
    if (expectedContentSize < 0) {
      indicator.setIndeterminate(true);
    }
  }

  final byte[] buffer = new byte[8 * 1024];
  int count;
  int total = 0;
  while ((count = inputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, count);
    total += count;

    if (indicator != null) {
      indicator.checkCanceled();

      if (expectedContentSize > 0) {
        indicator.setFraction((double)total / expectedContentSize);
      }
    }
  }

  if (indicator != null) {
    indicator.checkCanceled();
  }

  if (total < expectedContentSize) {
    throw new IOException(String.format("Connection closed at byte %d. Expected %d bytes.", total, expectedContentSize));
  }

  return total;
}
 
Example 8
Project: intellij-ce-playground   File: CommitHelper.java   Source Code and License Vote up 5 votes
private void delegateCommitToVcsThread(final GeneralCommitProcessor processor) {
  final ProgressIndicator indicator = new DelegatingProgressIndicator();

  final Semaphore endSemaphore = new Semaphore();
  endSemaphore.down();

  ChangeListManagerImpl.getInstanceImpl(myProject).executeOnUpdaterThread(new Runnable() {
    @Override
    public void run() {
      indicator.setText("Performing VCS commit...");
      try {
        ProgressManager.getInstance().runProcess(new Runnable() {
          @Override
          public void run() {
            indicator.checkCanceled();
            generalCommit(processor);
          }
        }, indicator);
      }
      finally {
        endSemaphore.up();
      }
    }
  });

  indicator.setText("Waiting for VCS background tasks to finish...");
  while (!endSemaphore.waitFor(20)) {
    indicator.checkCanceled();
  }
}
 
Example 9
Project: intellij-ce-playground   File: ShowImageDuplicatesAction.java   Source Code and License Vote up 5 votes
private static void collectAndShowDuplicates(final Project project) {
  final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null && !indicator.isCanceled()) {
    indicator.setText("Collecting project images...");
    indicator.setIndeterminate(false);
    final List<VirtualFile> images = new ArrayList<VirtualFile>();
    for (String ext : IMAGE_EXTENSIONS) {
      images.addAll(FilenameIndex.getAllFilesByExt(project, ext));
    }

    final Map<Long, Set<VirtualFile>> duplicates = new HashMap<Long, Set<VirtualFile>>();
    final Map<Long, VirtualFile> all = new HashMap<Long, VirtualFile>();
    for (int i = 0; i < images.size(); i++) {
      indicator.setFraction((double)(i + 1) / (double)images.size());
      final VirtualFile file = images.get(i);
      if (!(file.getFileSystem() instanceof LocalFileSystem)) continue;
      final long length = file.getLength();
      if (all.containsKey(length)) {
        if (!duplicates.containsKey(length)) {
          final HashSet<VirtualFile> files = new HashSet<VirtualFile>();
          files.add(all.get(length));
          duplicates.put(length, files);
        }
        duplicates.get(length).add(file);
      } else {
        all.put(length, file);
      }
      indicator.checkCanceled();
    }
    showResults(project, images, duplicates, all);
  }
}
 
Example 10
Project: intellij-ce-playground   File: PostHighlightingVisitor.java   Source Code and License Vote up 5 votes
private void optimizeImportsOnTheFlyLater(@NotNull final ProgressIndicator progress) {
  if ((myHasRedundantImports || myHasMissortedImports) && !progress.isCanceled()) {
    // schedule optimise action at the time of session disposal, which is after all applyInformation() calls
    Disposable invokeFixLater = new Disposable() {
      @Override
      public void dispose() {
        // later because should invoke when highlighting is finished
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            if (myProject.isDisposed() || !myFile.isValid() || !myFile.isWritable()) return;
            IntentionAction optimizeImportsFix = QuickFixFactory.getInstance().createOptimizeImportsFix(true);
            if (optimizeImportsFix.isAvailable(myProject, null, myFile)) {
              optimizeImportsFix.invoke(myProject, null, myFile);
            }
          }
        });
      }
    };
    Disposer.register((DaemonProgressIndicator)progress, invokeFixLater);
    if (progress.isCanceled()) {
      Disposer.dispose(invokeFixLater);
      Disposer.dispose((DaemonProgressIndicator)progress);
      progress.checkCanceled();
    }
  }
}
 
Example 11
Project: intellij-ce-playground   File: FileContentQueue.java   Source Code and License Vote up 5 votes
@Nullable
public FileContent take(@NotNull ProgressIndicator indicator) throws ProcessCanceledException {
  final FileContent content = doTake();
  if (content == null) {
    return null;
  }
  final long length = content.getLength();
  while (true) {
    try {
      indicator.checkCanceled();
    }
    catch (ProcessCanceledException e) {
      pushback(content);
      throw e;
    }

    synchronized (myProceedWithProcessingLock) {
      final boolean requestingLargeSize = length > LARGE_SIZE_REQUEST_THRESHOLD;
      if (requestingLargeSize) {
        myLargeSizeRequested = true;
      }
      try {
        if (myLargeSizeRequested && !requestingLargeSize ||
            myBytesBeingProcessed + length > Math.max(PROCESSED_FILE_BYTES_THRESHOLD, length)) {
          myProceedWithProcessingLock.wait(300);
        }
        else {
          myBytesBeingProcessed += length;
          if (requestingLargeSize) {
            myLargeSizeRequested = false;
          }
          return content;
        }
      }
      catch (InterruptedException ignore) {
      }
    }
  }
}
 
Example 12
Project: intellij-ce-playground   File: LowLevelSearchUtil.java   Source Code and License Vote up 5 votes
public static boolean processElementsContainingWordInElement(@NotNull final TextOccurenceProcessor processor,
                                                             @NotNull final PsiElement scope,
                                                             @NotNull final StringSearcher searcher,
                                                             final boolean processInjectedPsi,
                                                             final ProgressIndicator progress) {
  if (progress != null) progress.checkCanceled();

  PsiFile file = scope.getContainingFile();
  FileViewProvider viewProvider = file.getViewProvider();
  final CharSequence buffer = viewProvider.getContents();

  TextRange range = scope.getTextRange();
  if (range == null) {
    LOG.error("Element " + scope + " of class " + scope.getClass() + " has null range");
    return true;
  }

  final int scopeStart = range.getStartOffset();
  final int startOffset = scopeStart;
  int endOffset = range.getEndOffset();
  if (endOffset > buffer.length()) {
    diagnoseInvalidRange(scope, file, viewProvider, buffer, range);
    return true;
  }

  final Project project = file.getProject();
  final TreeElement[] lastElement = {null};
  return processTextOccurrences(buffer, startOffset, endOffset, searcher, progress, new TIntProcedure() {
    @Override
    public boolean execute(int offset) {
      if (progress != null) progress.checkCanceled();
      lastElement[0] = processTreeUp(project, processor, scope, searcher, offset - scopeStart, processInjectedPsi, progress,
                                     lastElement[0]);
      return lastElement[0] != null;
    }
  });
}
 
Example 13
Project: intellij-ce-playground   File: LocalInspectionsPass.java   Source Code and License Vote up 5 votes
private void addHighlightsFromResults(@NotNull List<HighlightInfo> outInfos, @NotNull ProgressIndicator indicator) {
  InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(myProject).getInspectionProfile();
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
  InjectedLanguageManager ilManager = InjectedLanguageManager.getInstance(myProject);
  Set<Pair<TextRange, String>> emptyActionRegistered = new THashSet<Pair<TextRange, String>>();

  for (Map.Entry<PsiFile, List<InspectionResult>> entry : result.entrySet()) {
    indicator.checkCanceled();
    PsiFile file = entry.getKey();
    Document documentRange = documentManager.getDocument(file);
    if (documentRange == null) continue;
    List<InspectionResult> resultList = entry.getValue();
    synchronized (resultList) {
      for (InspectionResult inspectionResult : resultList) {
        indicator.checkCanceled();
        LocalInspectionToolWrapper tool = inspectionResult.tool;
        HighlightSeverity severity = inspectionProfile.getErrorLevel(HighlightDisplayKey.find(tool.getShortName()), file).getSeverity();
        for (ProblemDescriptor descriptor : inspectionResult.foundProblems) {
          indicator.checkCanceled();
          PsiElement element = descriptor.getPsiElement();
          if (element != null) {
            createHighlightsForDescriptor(outInfos, emptyActionRegistered, ilManager, file, documentRange, tool, severity, descriptor, element);
          }
        }
      }
    }
  }
}
 
Example 14
Project: intellij-ce-playground   File: DiffIterableUtil.java   Source Code and License Vote up 5 votes
@NotNull
public static <T> FairDiffIterable diff(@NotNull T[] data1, @NotNull T[] data2, @NotNull ProgressIndicator indicator) {
  indicator.checkCanceled();

  try {
    // TODO: use ProgressIndicator inside
    Diff.Change change = Diff.buildChanges(data1, data2);
    return fair(create(change, data1.length, data2.length));
  }
  catch (FilesTooBigForDiffException e) {
    throw new DiffTooBigException();
  }
}
 
Example 15
Project: intellij-ce-playground   File: DownloadOperation.java   Source Code and License Vote up 5 votes
private static void download(@NotNull String url, @NotNull File destination, @NotNull ProgressIndicator indicator) throws IOException {
  indicator.setText(String.format("Downloading %s", destination.getName()));
  HttpURLConnection connection = HttpConfigurable.getInstance().openHttpConnection(url);
  int contentLength = connection.getContentLength();
  if (contentLength <= 0) {
    indicator.setIndeterminate(true);
  }
  InputStream readStream = null;
  OutputStream stream = null;
  try {
    readStream = connection.getInputStream();
    //noinspection IOResourceOpenedButNotSafelyClosed
    stream = new BufferedOutputStream(new FileOutputStream(destination));
    byte[] buffer = new byte[2 * 1024 * 1024];
    int read;
    int totalRead = 0;
    final long startTime = System.currentTimeMillis();
    for (read = readStream.read(buffer); read > 0; read = readStream.read(buffer)) {
      totalRead += read;
      stream.write(buffer, 0, read);
      long duration = System.currentTimeMillis() - startTime; // Duration is in ms
      long downloadRate = duration == 0 ? 0 : (totalRead / duration);
      String message =
        String.format("Downloading %1$s (%2$s/s)", destination.getName(), WelcomeUIUtils.getSizeLabel(downloadRate * 1000));
      indicator.setText(message);
      if (contentLength > 0) {
        indicator.setFraction(((double)totalRead) / contentLength);
      }
      indicator.checkCanceled();
    }
  }
  finally {
    if (stream != null) {
      stream.close();
    }
    if (readStream != null) {
      readStream.close();
    }
  }
}
 
Example 16
Project: intellij-ce-playground   File: HgUpdateEnvironment.java   Source Code and License Vote up 5 votes
@NotNull
public UpdateSession updateDirectories(@NotNull FilePath[] contentRoots,
  UpdatedFiles updatedFiles, ProgressIndicator indicator,
  @NotNull Ref<SequentialUpdatesContext> context) {
  
  List<VcsException> exceptions = new LinkedList<VcsException>();

  boolean result = true;
  for (FilePath contentRoot : contentRoots) {
    if (indicator != null) {
      indicator.checkCanceled();
      indicator.startNonCancelableSection();
    }
    VirtualFile repository =
      ProjectLevelVcsManager.getInstance(project).getVcsRootFor(contentRoot);
    if (repository == null) {
      continue;
    }
    try {
      HgUpdater updater = new HgRegularUpdater(project, repository, updateConfiguration);
      result &= updater.update(updatedFiles, indicator, exceptions);
    } catch (VcsException e) {
      //TODO include module name where exception occurred
      exceptions.add(e);
    }
    if (indicator != null) {
      indicator.finishNonCancelableSection();
    }
  }
  return new UpdateSessionAdapter(exceptions, !result);
}
 
Example 17
Project: intellij-ce-playground   File: SvnPhantomChangeDiffRequestProvider.java   Source Code and License Vote up 5 votes
@NotNull
@Override
public DiffRequest process(@NotNull ChangeDiffRequestProducer presentable,
                           @NotNull UserDataHolder context,
                           @NotNull ProgressIndicator indicator) throws DiffRequestProducerException, ProcessCanceledException {
  indicator.checkCanceled();
  return new SvnPhantomDiffRequest(presentable.getChange());
}
 
Example 18
Project: educational-plugin   File: EduAdaptiveStepicConnector.java   Source Code and License Vote up 4 votes
public static void addNextRecommendedTask(@NotNull Project project,
                                          @NotNull Lesson lesson,
                                          @NotNull ProgressIndicator indicator,
                                          int reactionToPost) {
  final Course course = StudyTaskManager.getInstance(project).getCourse();
  if (!(course instanceof RemoteCourse)) {
    LOG.warn("Course is in incorrect state");
    ApplicationManager.getApplication().invokeLater(() -> StudyUtils.showErrorPopupOnToolbar(project,
                                                                                             "Can't get next recommendation: course is broken"));
    return;
  }

  indicator.checkCanceled();
  final StepicUser user = StudySettings.getInstance().getUser();
  if (user == null) {
    LOG.warn("Can't get next recommendation: user is null");
    ApplicationManager.getApplication().invokeLater(() -> StudyUtils.showErrorPopupOnToolbar(project,
                                                                                             "Can't get next recommendation: you're not logged in"));
    return;
  }

  final boolean reactionPosted = postRecommendationReaction(String.valueOf(lesson.getId()), String.valueOf(user.getId()), reactionToPost);
  if (!reactionPosted) {
    LOG.warn("Recommendation reaction wasn't posted");
    ApplicationManager.getApplication().invokeLater(() -> StudyUtils.showErrorPopupOnToolbar(project, "Couldn't post your reactionToPost"));
    return;
  }

  indicator.checkCanceled();
  final Task task = getNextRecommendation(project, (RemoteCourse)course);
  if (task == null) {
    ApplicationManager.getApplication().invokeLater(() -> StudyUtils.showErrorPopupOnToolbar(project,
                                                                                             "Couldn't load a new recommendation"));
    return;
  }

  task.initTask(lesson, false);
  boolean replaceCurrentTask = reactionToPost == TOO_HARD_RECOMMENDATION_REACTION || reactionToPost == TOO_BORING_RECOMMENDATION_REACTION;
  if (replaceCurrentTask) {
    replaceCurrentTask(project, task, lesson);
  }
  else {
    addAsNextTask(project, task, lesson);
  }

  ApplicationManager.getApplication().invokeLater(() -> {
    VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
    ProjectView.getInstance(project).refresh();
    StudyNavigator.navigateToTask(project, task);
  });
}
 
Example 19
Project: educational-plugin   File: CCStepicConnector.java   Source Code and License Vote up 4 votes
private static void postCourse(final Project project, @NotNull Course course) {
  if (!checkIfAuthorized(project, "post course")) return;

  final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null) {
    indicator.setText("Uploading course to " + EduStepicNames.STEPIC_URL);
    indicator.setIndeterminate(false);
  }
  final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/courses");

  final StepicUser currentUser = EduStepicAuthorizedClient.getCurrentUser();
  if (currentUser != null) {
    final List<StepicUser> courseAuthors = course.getAuthors();
    for (int i = 0; i < courseAuthors.size(); i++) {
      if (courseAuthors.size() > i) {
        final StepicUser courseAuthor = courseAuthors.get(i);
        currentUser.setFirstName(courseAuthor.getFirstName());
        currentUser.setLastName(courseAuthor.getLastName());
      }
    }
    course.setAuthors(Collections.singletonList(currentUser));
  }

  String requestBody = new Gson().toJson(new StepicWrappers.CourseWrapper(course));
  request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));

  try {
    final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
    if (client == null) {
      LOG.warn("Http client is null");
      return;
    }
    final CloseableHttpResponse response = client.execute(request);
    final HttpEntity responseEntity = response.getEntity();
    final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
    final StatusLine line = response.getStatusLine();
    EntityUtils.consume(responseEntity);
    if (line.getStatusCode() != HttpStatus.SC_CREATED) {
      final String message = FAILED_TITLE + "course ";
      LOG.error(message + responseString);
      showErrorNotification(project, FAILED_TITLE, responseString);
      return;
    }
    final RemoteCourse postedCourse = new Gson().fromJson(responseString, StepicWrappers.CoursesContainer.class).courses.get(0);
    postedCourse.setLessons(course.getLessons(true));
    postedCourse.setAuthors(course.getAuthors());
    postedCourse.setCourseMode(CCUtils.COURSE_MODE);
    postedCourse.setLanguage(course.getLanguageID());
    final int sectionId = postModule(postedCourse.getId(), 1, String.valueOf(postedCourse.getName()), project);
    int position = 1;
    for (Lesson lesson : course.getLessons()) {
      if (indicator != null) {
        indicator.checkCanceled();
        indicator.setText2("Publishing lesson " + lesson.getIndex());
      }
      final int lessonId = postLesson(project, lesson);
      postUnit(lessonId, position, sectionId, project);
      if (indicator != null) {
        indicator.setFraction((double)lesson.getIndex()/course.getLessons().size());
        indicator.checkCanceled();
      }
      position += 1;
    }
    ApplicationManager.getApplication().runReadAction(() -> postAdditionalFiles(course, project, postedCourse.getId()));
    StudyTaskManager.getInstance(project).setCourse(postedCourse);
    showNotification(project, "Course published");
  }
  catch (IOException e) {
    LOG.error(e.getMessage());
  }
}
 
Example 20
Project: educational-plugin   File: CCStepicConnector.java   Source Code and License Vote up 4 votes
public static int updateLesson(@NotNull final Project project, @NotNull final Lesson lesson) {
  if(!checkIfAuthorized(project, "update lesson")) return -1;

  final HttpPut request = new HttpPut(EduStepicNames.STEPIC_API_URL + EduStepicNames.LESSONS + String.valueOf(lesson.getId()));

  String requestBody = new Gson().toJson(new StepicWrappers.LessonWrapper(lesson));
  request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));

  try {
    final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
    if (client == null) return -1;
    final CloseableHttpResponse response = client.execute(request);
    final HttpEntity responseEntity = response.getEntity();
    final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
    final StatusLine line = response.getStatusLine();
    EntityUtils.consume(responseEntity);
    if (line.getStatusCode() != HttpStatus.SC_OK) {
      final String message = "Failed to update lesson ";
      LOG.error(message + responseString);
      showErrorNotification(project, message, responseString);
      return -1;
    }
    else {
      showNotification(project, "Lesson updated");
    }

    final Lesson postedLesson = new Gson().fromJson(responseString, RemoteCourse.class).getLessons().get(0);
    for (Integer step : postedLesson.steps) {
      deleteTask(step, project);
    }

    for (Task task : lesson.getTaskList()) {
      final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      if (indicator != null) {
        indicator.checkCanceled();
      }
      postTask(project, task, lesson.getId());
    }
    return lesson.getId();
  }
  catch (IOException e) {
    LOG.error(e.getMessage());
  }
  return -1;
}
 
Example 21
Project: intellij-ce-playground   File: AbstractSvnUpdateIntegrateEnvironment.java   Source Code and License Vote up 4 votes
@NotNull
public UpdateSession updateDirectories(@NotNull final FilePath[] contentRoots,
                                       final UpdatedFiles updatedFiles,
                                       final ProgressIndicator progressIndicator, @NotNull final Ref<SequentialUpdatesContext> context)
  throws ProcessCanceledException {

  if (context.isNull()) {
    context.set(new SvnUpdateContext(myVcs, contentRoots));
  }

  final ArrayList<VcsException> exceptions = new ArrayList<VcsException>();
  UpdateEventHandler eventHandler = new UpdateEventHandler(myVcs, progressIndicator, (SvnUpdateContext) context.get());
  eventHandler.setUpdatedFiles(updatedFiles);

  boolean totalUpdate = true;
  AbstractUpdateIntegrateCrawler crawler = createCrawler(eventHandler, totalUpdate, exceptions, updatedFiles);

  Collection<VirtualFile> updatedRoots = new HashSet<VirtualFile>();
  Arrays.sort(contentRoots, new Comparator<FilePath>() {
    public int compare(FilePath o1, FilePath o2) {
      return SystemInfo.isFileSystemCaseSensitive ? o1.getPath().replace("/", "\\").compareTo(o2.getPath().replace("/", "\\")) :
        o1.getPath().replace("/", "\\").compareToIgnoreCase(o2.getPath().replace("/", "\\"));
    }
  });
  for (FilePath contentRoot : contentRoots) {
    if (progressIndicator != null) {
      progressIndicator.checkCanceled();
    }
    final File ioRoot = contentRoot.getIOFile();
    if (! ((SvnUpdateContext)context.get()).shouldRunFor(ioRoot)) continue;

    Collection<VirtualFile> roots = SvnUtil.crawlWCRoots(myVcs.getProject(), ioRoot, crawler, progressIndicator);
    updatedRoots.addAll(roots);
  }
  if (updatedRoots.isEmpty()) {
    WaitForProgressToShow.runOrInvokeLaterAboveProgress(new Runnable() {
      public void run() {
        Messages.showErrorDialog(myVcs.getProject(), SvnBundle.message("message.text.update.no.directories.found"),
                                 SvnBundle.message("messate.text.update.error"));
      }
    }, null, myVcs.getProject());
    return new UpdateSessionAdapter(Collections.<VcsException>emptyList(), true);
  }

  return new MyUpdateSessionAdapter(contentRoots, updatedFiles, exceptions);
}
 
Example 22
Project: intellij-ce-playground   File: BaseProjectTreeBuilder.java   Source Code and License Vote up 4 votes
private void expandChild(@NotNull final List<AbstractTreeNode> kids,
                         int i,
                         @NotNull final Condition<AbstractTreeNode> nonStopCondition,
                         final VirtualFile file,
                         final Object element,
                         @NotNull final AsyncResult<AbstractTreeNode> async,
                         @NotNull final ProgressIndicator indicator,
                         final Ref<Object> virtualSelectTarget) {
  while (i < kids.size()) {
    final AbstractTreeNode eachKid = kids.get(i);
    final boolean[] nodeWasCollapsed = {true};
    final DefaultMutableTreeNode nodeForElement = getNodeForElement(eachKid);
    if (nodeForElement != null) {
      nodeWasCollapsed[0] = getTree().isCollapsed(new TreePath(nodeForElement.getPath()));
    }

    if (nonStopCondition.value(eachKid)) {
      final AsyncResult<AbstractTreeNode> result = expandPathTo(file, eachKid, element, nonStopCondition, indicator, virtualSelectTarget);
      result.doWhenDone(new Consumer<AbstractTreeNode>() {
        @Override
        public void consume(AbstractTreeNode abstractTreeNode) {
          indicator.checkCanceled();
          async.setDone(abstractTreeNode);
        }
      });

      if (!result.isProcessed()) {
        final int next = i + 1;
        result.doWhenRejected(new Runnable() {
          @Override
          public void run() {
            indicator.checkCanceled();

            if (nodeWasCollapsed[0] && virtualSelectTarget == null) {
              collapseChildren(eachKid, null);
            }
            expandChild(kids, next, nonStopCondition, file, element, async, indicator, virtualSelectTarget);
          }
        });
        return;
      } else {
        if (result.isRejected()) {
          indicator.checkCanceled();
          if (nodeWasCollapsed[0] && virtualSelectTarget == null) {
            collapseChildren(eachKid, null);
          }
          i++;
        } else {
          return;
        }
      }
    } else {
      //filter tells us to stop here (for instance, in case of module nodes)
      break;
    }
  }
  async.setRejected();
}
 
Example 23
Project: intellij-ce-playground   File: SvnChangeDiffViewerProvider.java   Source Code and License Vote up 4 votes
@NotNull
private static SvnPropertiesDiffRequest createPropertyRequest(@NotNull Change change, @NotNull ProgressIndicator indicator)
  throws DiffRequestProducerException {
  try {
    Change propertiesChange = getSvnChangeLayer(change);
    if (propertiesChange == null) throw new DiffRequestProducerException(SvnBundle.getString("diff.cant.get.properties.changes"));

    ContentRevision bRevRaw = propertiesChange.getBeforeRevision();
    ContentRevision aRevRaw = propertiesChange.getAfterRevision();

    if (bRevRaw != null && !(bRevRaw instanceof PropertyRevision)) {
      LOG.warn("Before change is not PropertyRevision");
      throw new DiffRequestProducerException(SvnBundle.getString("diff.cant.get.properties.changes"));
    }
    if (aRevRaw != null && !(aRevRaw instanceof PropertyRevision)) {
      LOG.warn("After change is not PropertyRevision");
      throw new DiffRequestProducerException(SvnBundle.getString("diff.cant.get.properties.changes"));
    }

    PropertyRevision bRev = (PropertyRevision)bRevRaw;
    PropertyRevision aRev = (PropertyRevision)aRevRaw;

    indicator.checkCanceled();
    List<PropertyData> bContent = bRev != null ? bRev.getProperties() : null;

    indicator.checkCanceled();
    List<PropertyData> aContent = aRev != null ? aRev.getProperties() : null;

    if (aRev == null && bRev == null) throw new DiffRequestProducerException(SvnBundle.getString("diff.cant.get.properties.changes"));

    ContentRevision bRevMain = change.getBeforeRevision();
    ContentRevision aRevMain = change.getAfterRevision();
    String title1 = bRevMain != null ? StringUtil.nullize(bRevMain.getRevisionNumber().asString()) : null;
    String title2 = aRevMain != null ? StringUtil.nullize(aRevMain.getRevisionNumber().asString()) : null;

    return new SvnPropertiesDiffRequest(bContent, aContent, title1, title2);
  }
  catch (VcsException e) {
    throw new DiffRequestProducerException(e);
  }
}
 
Example 24
Project: intellij-ce-playground   File: XPathEvalAction.java   Source Code and License Vote up 4 votes
@Override
public void generate(@NotNull final Processor<Usage> processor) {
    Runnable runnable = new Runnable() {
        @Override
        @SuppressWarnings({"unchecked"})
        public void run() {
            final List<?> list;
            if (myResult.isEmpty()) {
                try {
                    list = (List<?>)myXPath.selectNodes(myContextNode);
                } catch (JaxenException e) {
                    LOG.debug(e);
                    Messages.showMessageDialog(myContextNode.getProject(), e.getMessage(), "XPath error", Messages.getErrorIcon());
                    return;
                }
            } else {
                list = myResult;
            }

            final int size = list.size();
            final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
            indicator.setText("Collecting matches...");

            Collections.sort(list, new Comparator() {
                @Override
                public int compare(Object o1, Object o2) {
                    indicator.checkCanceled();
                    if (o1 instanceof PsiElement && o2 instanceof PsiElement) {
                        return ((PsiElement)o1).getTextRange().getStartOffset() - ((PsiElement)o2).getTextRange().getStartOffset();
                    } else {
                        return String.valueOf(o1).compareTo(String.valueOf(o2));
                    }
                }
            });
            for (int i = 0; i < size; i++) {
                indicator.checkCanceled();
                Object o = list.get(i);
                if (o instanceof PsiElement) {
                    final PsiElement element = (PsiElement)o;
                    processor.process(new UsageInfo2UsageAdapter(new UsageInfo(element)));
                    indicator.setText2(element.getContainingFile().getName());
                }
                indicator.setFraction(i / (double)size);
            }
            list.clear();
        }
    };
    ApplicationManager.getApplication().runReadAction(runnable);
}
 
Example 25
Project: intellij-ce-playground   File: ComponentManagerImpl.java   Source Code and License Vote up 4 votes
@Override
public Object getComponentInstance(PicoContainer picoContainer) throws PicoInitializationException, PicoIntrospectionException, ProcessCanceledException {
  Object instance = myInitializedComponentInstance;
  if (instance != null) {
    return instance;
  }

  try {
    //noinspection SynchronizeOnThis
    synchronized (this) {
      instance = myInitializedComponentInstance;
      if (instance != null) {
        return instance;
      }

      long startTime = System.nanoTime();

      instance = super.getComponentInstance(picoContainer);

      if (myInitializing) {
        String errorMessage = "Cyclic component initialization: " + getComponentKey();
        if (myPluginId != null) {
          LOG.error(new PluginException(errorMessage, myPluginId));
        }
        else {
          LOG.error(new Throwable(errorMessage));
        }
      }

      try {
        myInitializing = true;
        registerComponentInstance(instance);

        ProgressIndicator indicator = getProgressIndicator();
        if (indicator != null) {
          indicator.checkCanceled();
          setProgressDuringInit(indicator);
        }
        initializeComponent(instance, false);
        if (instance instanceof BaseComponent) {
          ((BaseComponent)instance).initComponent();
        }

        long ms = (System.nanoTime() - startTime) / 1000000;
        if (ms > 10 && logSlowComponents()) {
          LOG.info(instance.getClass().getName() + " initialized in " + ms + " ms");
        }
      }
      finally {
        myInitializing = false;
      }
      myInitializedComponentInstance = instance;
    }
  }
  catch (ProcessCanceledException e) {
    throw e;
  }
  catch (Throwable t) {
    handleInitComponentError(t, ((Class)getComponentKey()).getName(), myPluginId);
  }

  return instance;
}