@Override
  protected boolean installInterestFilter(StructuredViewer viewer) {
    if (commonNavigator == null) {
      commonNavigator = (CommonNavigator) super.getPartForAction();
    }

    try {
      // XXX: reflection
      Class<?> clazz2 = CoreExpressionFilter.class;
      filterExpressionField1 = clazz2.getDeclaredField("filterExpression"); // $NON-NLS-1$
      filterExpressionField1.setAccessible(true);

      Class<?> clazz1 = CommonFilterDescriptor.class;
      filterExpressionField2 = clazz1.getDeclaredField("filterExpression"); // $NON-NLS-1$
      filterExpressionField2.setAccessible(true);
    } catch (Exception e) {
      StatusHandler.log(
          new Status(
              IStatus.ERROR,
              ResourcesUiBridgePlugin.ID_PLUGIN,
              "Could not determine filter",
              e)); //$NON-NLS-1$
    }

    filterDescriptors =
        CommonFilterDescriptorManager.getInstance()
            .findVisibleFilters(commonNavigator.getNavigatorContentService());

    return super.installInterestFilter(viewer);
  }
    private static void readBridge(IConfigurationElement element) {
      try {
        Object object = element.createExecutableExtension(BridgesExtensionPointReader.ATTR_CLASS);
        if (!(object instanceof AbstractContextStructureBridge)) {
          StatusHandler.log(
              new Status(
                  IStatus.WARNING,
                  ContextCorePlugin.ID_PLUGIN,
                  "Could not load bridge: "
                      + object.getClass().getCanonicalName()
                      + " must implement " //$NON-NLS-1$ //$NON-NLS-2$
                      + AbstractContextStructureBridge.class.getCanonicalName()));
          return;
        }

        AbstractContextStructureBridge bridge = (AbstractContextStructureBridge) object;
        if (element.getAttribute(BridgesExtensionPointReader.ATTR_PARENT_CONTENT_TYPE) != null) {
          String parentContentType =
              element.getAttribute(BridgesExtensionPointReader.ATTR_PARENT_CONTENT_TYPE);
          if (parentContentType != null) {
            bridge.setParentContentType(parentContentType);
          }
        }
        ContextCorePlugin.getDefault().addStructureBridge(bridge);
      } catch (Throwable e) {
        StatusHandler.log(
            new Status(
                IStatus.WARNING,
                ContextCorePlugin.ID_PLUGIN,
                "Could not load bridge extension",
                e)); //$NON-NLS-1$
      }
    }
  private void populateResourcesTree() {

    resourcesToShow.clear();

    IRunnableWithProgress getModifiedResources =
        new IRunnableWithProgress() {
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            SubMonitor.convert(
                monitor, "Getting workspace resources data", IProgressMonitor.UNKNOWN);

            final Collection<IResource> resources = MiscUtil.buildLinkedHashSet();

            resources.addAll(
                teamConnector.getResourcesByFilterRecursive(
                    roots.toArray(new IResource[roots.size()]),
                    ITeamUiResourceConnector.State.SF_ALL));

            for (IResource resource : resources) {
              if (resource instanceof IFile) {

                // collect all scmPaths in order to find missing mappings
                String path = TeamUiUtils.getScmPath(resource, teamConnector);
                if (path != null) {
                  scmPaths.add(path);
                }

                DecoratedResource dr = TeamUiUtils.getDecoratedResource(resource, teamConnector);
                if (dr != null) {
                  resourcesToShow.add(dr);
                }
              }
            }
          }
        };

    try {
      getContainer().run(false, false, getModifiedResources);
    } catch (InvocationTargetException e) {
      StatusHandler.log(
          new Status(
              IStatus.WARNING,
              CrucibleUiPlugin.PLUGIN_ID,
              "Can't get list of modified resources",
              e));
    } catch (InterruptedException e) {
      StatusHandler.log(
          new Status(
              IStatus.WARNING,
              CrucibleUiPlugin.PLUGIN_ID,
              "Can't get list of modified resources",
              e));
    }

    resourceSelectionTree.setResources(resourcesToShow);
    resourceSelectionTree.refresh();
    resourceSelectionTree.setAllChecked(true);

    validatePage();
  }
Beispiel #4
0
  private void setLocationInternal(File indexLocation) {
    final boolean newLocationExists = indexLocation.exists();
    if (!newLocationExists) {
      if (!indexLocation.mkdirs()) {
        StatusHandler.log(
            new Status(
                IStatus.ERROR,
                TasksIndexCore.ID_PLUGIN,
                "Cannot create task list index folder: " + indexLocation)); // $NON-NLS-1$
      }
    }

    Lock writeLock = indexReaderLock.writeLock();
    writeLock.lock();
    try {
      synchronized (this) {
        if (indexReader != null) {
          try {
            indexReader.close();
          } catch (IOException e) {
            // ignore
          }
          indexReader = null;
        }

        if (indexLocation.exists() && indexLocation.isDirectory()) {
          if (directory != null) {
            try {
              directory.close();
            } catch (IOException e) {
              StatusHandler.log(
                  new Status(
                      IStatus.ERROR,
                      TasksIndexCore.ID_PLUGIN,
                      "Cannot close index: " + e.getMessage(),
                      e)); //$NON-NLS-1$
            }
          }
          try {
            directory = new NIOFSDirectory(indexLocation);
          } catch (IOException e) {
            StatusHandler.log(
                new Status(
                    IStatus.ERROR,
                    TasksIndexCore.ID_PLUGIN,
                    "Cannot create task list index",
                    e)); //$NON-NLS-1$
          }
        }
      }
    } finally {
      writeLock.unlock();
    }
  }
Beispiel #5
0
  private void scheduleIndexMaintenance(MaintainIndexType type) {
    long delay = 0L;
    switch (type) {
      case STARTUP:
        delay = startupDelay;
        break;
      case REINDEX:
        delay = reindexDelay;
    }

    if (delay == 0L) {
      // primarily for testing purposes

      maintainIndexJob.cancel();
      try {
        maintainIndexJob.join();
      } catch (InterruptedException e) {
        // ignore
      }
      try {
        maintainIndex(new NullProgressMonitor());
      } catch (CoreException e) {
        MultiStatus logStatus =
            new MultiStatus(
                TasksIndexCore.ID_PLUGIN,
                0,
                "Failed to update task list index", //$NON-NLS-1$
                e);
        logStatus.add(e.getStatus());
        StatusHandler.log(logStatus);
      }
    } else {
      maintainIndexJob.schedule(delay);
    }
  }
  @Override
  public File createFeedbackFile() {
    finishedSelected();
    IPath rootPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
    String path = rootPath.toString() + File.separator + "questionnaire.txt";
    File questionnaireFile = new File(path);

    if (questionnaireFile.exists()) {
      questionnaireFile.delete();
    }

    OutputStream outputStream;
    try {
      outputStream = new FileOutputStream(questionnaireFile);

      String buffer = "Tasks: " + getTaskPerformedFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "MentalModel: " + getMentalModelFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "DOI: " + getDoiModelFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "Integrate: " + getIntegrateFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "Positive: " + getPositiveFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "Negative: " + getNegativeFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      outputStream.close();
      return questionnaireFile;
    } catch (IOException e) {
      StatusHandler.log(
          new Status(IStatus.ERROR, MylynUserStudyExamplePlugin.ID_PLUGIN, "Failed to submit", e));
    }
    return null;
  }
  /**
   * get a task editor extension for a specific task attribute
   *
   * @param taskRepository
   * @param taskAttribute
   * @return the extension, or null if there is none
   * @see #getTaskEditorExtension(TaskRepository);
   * @since 3.11
   */
  public static AbstractTaskEditorExtension getTaskEditorExtension(
      TaskRepository taskRepository, TaskAttribute taskAttribute) {
    init();
    String input = taskAttribute.getMetaData().getMediaType();
    if (input != null) {
      try {
        MediaType media = MediaType.parse(input);
        Multimap<String, String> parameters = media.parameters();
        if (parameters.containsKey(MARKUP_KEY)) {
          Iterator<String> iter = parameters.get(MARKUP_KEY).iterator();
          String markup = iter.next();
          Iterator<String> baseMarkupIterator = parameters.get(BASE_MARKUP_KEY).iterator();
          String baseMarkup =
              (baseMarkupIterator.hasNext() ? baseMarkupIterator.next() : ""); // $NON-NLS-1$

          SortedSet<RegisteredTaskEditorExtension> extensions = getTaskEditorExtensions();
          for (RegisteredTaskEditorExtension extension : extensions) {
            if (markup.equals(extension.getName()) || baseMarkup.equals(extension.getName())) {
              return extension.getExtension();
            }
          }
        }
      } catch (IllegalArgumentException e) {
        StatusHandler.log(
            new Status(
                IStatus.ERROR,
                TasksUiPlugin.ID_PLUGIN,
                String.format(
                    "Unable to parse markup type for attribute %s", taskAttribute.toString()),
                e)); //$NON-NLS-1$
      }
    }
    return getTaskEditorExtension(taskRepository);
  }
 public void focusOnLines(ILocation range) {
   if (range instanceof ILineLocation) {
     ILineLocation lineLocation = (ILineLocation) range;
     // editors count lines from 0, Crucible counts from 1
     final int startLine = lineLocation.getRangeMin() - 1;
     final int endLine = lineLocation.getRangeMax() - 1;
     if (sourceViewer != null) {
       IDocument document = sourceViewer.getDocument();
       if (document != null) {
         try {
           int offset = document.getLineOffset(startLine);
           int length = document.getLineOffset(endLine) - offset;
           StyledText widget = sourceViewer.getTextWidget();
           try {
             widget.setRedraw(false);
             // sourceViewer.revealRange(offset, length);
             // sourceViewer.setSelectedRange(offset, 0);
             sourceViewer.setSelection(new TextSelection(offset, length), true);
           } finally {
             widget.setRedraw(true);
           }
         } catch (BadLocationException e) {
           StatusHandler.log(
               new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, e.getMessage(), e));
         }
       }
     }
   }
 }
  public static List<ContextComputationStrategy> readContextComputationStrategies() {
    List<ContextComputationStrategy> strategies = new ArrayList<ContextComputationStrategy>();

    IExtensionPoint extensionPoint =
        Platform.getExtensionRegistry().getExtensionPoint(STRATEGIES_EXTENSION_POINT_ID);
    IExtension[] extensions = extensionPoint.getExtensions();
    for (IExtension extension : extensions) {
      IConfigurationElement[] configurationElements = extension.getConfigurationElements();
      for (IConfigurationElement element : configurationElements) {
        if (element.getName().equals(CONTEXT_COMPUTATION_STRATEGY)) {
          try {
            ContextComputationStrategy strategy =
                (ContextComputationStrategy) element.createExecutableExtension(ATTRIBUTE_CLASS);
            strategies.add(strategy);
          } catch (Throwable t) {
            StatusHandler.log(
                new Status(
                    IStatus.ERROR,
                    ContextCorePlugin.ID_PLUGIN,
                    NLS.bind(
                        "Cannot instantiate {0} from bundle {1}: {2}", //$NON-NLS-1$
                        new Object[] {
                          element.getAttribute(ATTRIBUTE_CLASS),
                          extension.getContributor().getName(),
                          t.getMessage()
                        }),
                    t));
          }
        }
      }
    }
    return strategies;
  }
  public static TimeEntry createTimeEntry(
      final TaskRepository repository,
      final TaskData taskData,
      final Set<TaskAttribute> oldAttributes,
      final Configuration cfg)
      throws CoreException {
    TimeEntry timeEntry = null;

    try {
      final String val = getValue(taskData, RedmineAttribute.TIME_ENTRY_HOURS);
      if (!val.isEmpty()) {
        timeEntry = new TimeEntry();

        /* Default Attributes */
        final long milisec = Long.parseLong(val);
        final long minutes = milisec / 60000;
        float hours = minutes / 60;
        hours += minutes % 60 / 60.0;

        timeEntry.setHours(hours);
        timeEntry.setActivityId(
            Integer.parseInt(getValue(taskData, RedmineAttribute.TIME_ENTRY_ACTIVITY)));
        timeEntry.setComments(getValue(taskData, RedmineAttribute.TIME_ENTRY_COMMENTS));

        /* Custom Attributes */
        final List<CustomField> customFields = cfg.getCustomFields().getTimeEntryCustomFields();
        if (customFields != null && customFields.size() > 0) {
          final CustomValues customValues = new CustomValues();
          timeEntry.setCustomValues(customValues);
          for (final CustomField customField : customFields) {
            final String value =
                getValue(
                    taskData, IRedmineConstants.TASK_KEY_PREFIX_TIMEENTRY_CF + customField.getId());
            customValues.setCustomValue(
                customField.getId(), formatCustomValue(value, customField.getId(), cfg));
          }
        }

        /* Extension/Additional Attributes */
        final IRedmineExtensionField additionalFields[] =
            RedmineCorePlugin.getDefault()
                .getExtensionManager()
                .getAdditionalTimeEntryFields(repository);
        for (final IRedmineExtensionField additionalField : additionalFields) {
          final String value =
              getValue(
                  taskData,
                  IRedmineConstants.TASK_KEY_PREFIX_TIMEENTRY_EX + additionalField.getTaskKey());
          timeEntry.addExtensionValue(additionalField.getSubmitKey(), value);
        }
      }
    } catch (final NumberFormatException e) {
      timeEntry = null;
      final IStatus status = RedmineCorePlugin.toStatus(e, Messages.ERRMSG_ILLEGAL_ATTRIBUTE_VALUE);
      StatusHandler.log(status);
    }

    return timeEntry;
  }
 public static int parseIntegerId(String intVal) {
   if (intVal != null && !intVal.isEmpty()) {
     try {
       return Integer.parseInt(intVal);
     } catch (NumberFormatException e) {
       IStatus status = RedmineCorePlugin.toStatus(e, Messages.ERRMSG_X_VALID_INTEGER, intVal);
       StatusHandler.log(status);
     }
   }
   return 0;
 }
  @Override
  protected boolean isPreservedFilter(ViewerFilter filter) {
    if (filter instanceof CoreExpressionFilter) {
      CoreExpressionFilter expressionFilter = (CoreExpressionFilter) filter;

      Set<String> preservedIds =
          ContextUiPlugin.getDefault().getPreservedFilterIds(viewPart.getSite().getId());
      if (!preservedIds.isEmpty()) {
        try {
          Expression expression2 = (Expression) filterExpressionField1.get(expressionFilter);

          for (CommonFilterDescriptor commonFilterDescriptor : filterDescriptors) {
            if (preservedIds.contains(commonFilterDescriptor.getId())) {
              Expression expression1 =
                  (Expression) filterExpressionField2.get(commonFilterDescriptor);
              if (expression1 != null && expression1.equals(expression2)) {
                return true;
              }
            }
          }
        } catch (IllegalArgumentException e) {
          StatusHandler.log(
              new Status(
                  IStatus.ERROR,
                  ResourcesUiBridgePlugin.ID_PLUGIN,
                  "Could not determine filter",
                  e)); //$NON-NLS-1$
        } catch (IllegalAccessException e) {
          StatusHandler.log(
              new Status(
                  IStatus.ERROR,
                  ResourcesUiBridgePlugin.ID_PLUGIN,
                  "Could not determine filter",
                  e)); //$NON-NLS-1$
        }
      }
    }
    return false;
  }
  private void openMoreInformaionInBrowser() {
    String moreInformationUrl = studyParameters.getMoreInformationUrl();
    try {
      if (WebBrowserPreference.getBrowserChoice() == WebBrowserPreference.EXTERNAL) {
        try {
          IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
          support.getExternalBrowser().openURL(new URL(moreInformationUrl));
        } catch (Exception e) {
          StatusHandler.fail(
              new Status(
                  IStatus.ERROR,
                  UiUsageMonitorPlugin.ID_PLUGIN,
                  "Could not open url",
                  e)); //$NON-NLS-1$
        }
      } else {
        IWebBrowser browser = null;
        int flags = 0;
        if (WorkbenchBrowserSupport.getInstance().isInternalWebBrowserAvailable()) {
          flags =
              IWorkbenchBrowserSupport.AS_EDITOR
                  | IWorkbenchBrowserSupport.LOCATION_BAR
                  | IWorkbenchBrowserSupport.NAVIGATION_BAR;

        } else {
          flags =
              IWorkbenchBrowserSupport.AS_EXTERNAL
                  | IWorkbenchBrowserSupport.LOCATION_BAR
                  | IWorkbenchBrowserSupport.NAVIGATION_BAR;
        }

        String generatedId =
            "org.eclipse.mylyn.web.browser-"
                + Calendar.getInstance().getTimeInMillis(); // $NON-NLS-1$
        browser =
            WorkbenchBrowserSupport.getInstance().createBrowser(flags, generatedId, null, null);
        browser.openURL(new URL(moreInformationUrl));
      }
    } catch (PartInitException e) {
      MessageDialog.openError(
          Display.getDefault().getActiveShell(),
          "Browser init error", //$NON-NLS-1$
          "Browser could not be initiated"); //$NON-NLS-1$
    } catch (MalformedURLException e) {
      MessageDialog.openError(
          Display.getDefault().getActiveShell(),
          Messages.UsageDataPreferencePage_Url_Not_Found,
          NLS.bind(Messages.UsageDataPreferencePage_Unable_To_Open_X, moreInformationUrl));
    }
  }
  @Override
  public void run() {
    if (selectedTask == null) {
      return;
    }

    if (selectedTask instanceof LocalTask) {
      // XXX code copied from NewLocalTaskWizard.performFinish() and
      // TaskListManager.createNewLocalTask()
      TaskList taskList = TasksUiPlugin.getTaskList();
      LocalTask newTask =
          new LocalTask(
              "" + taskList.getNextLocalTaskId(), // $NON-NLS-1$
              LocalRepositoryConnector.DEFAULT_SUMMARY);
      newTask.setPriority(PriorityLevel.P3.toString());
      TasksUiInternal.scheduleNewTask(newTask);
      taskList.addTask(newTask, selectedTask);
      TasksUiUtil.openTask(newTask);
      return;
    }

    AbstractRepositoryConnector connector =
        TasksUi.getRepositoryManager().getRepositoryConnector(selectedTask.getConnectorKind());
    IWizard wizard = getNewSubTaskWizard();
    if (wizard != null) {
      WizardDialog dialog = new WizardDialog(WorkbenchUtil.getShell(), wizard);
      dialog.setBlockOnOpen(true);
      dialog.open();
      return;
    }
    TaskData taskData = createTaskData(connector);
    if (taskData != null) {
      try {
        TasksUiInternal.createAndOpenNewTask(taskData);
      } catch (CoreException e) {
        StatusHandler.log(
            new Status(
                IStatus.ERROR,
                TasksUiPlugin.ID_PLUGIN,
                "Failed to open new sub task",
                e)); //$NON-NLS-1$
        TasksUiInternal.displayStatus(
            Messages.NewSubTaskAction_Unable_to_create_subtask,
            new Status(
                IStatus.ERROR,
                TasksUiPlugin.ID_PLUGIN,
                Messages.NewSubTaskAction_Failed_to_create_new_sub_task_ + e.getMessage()));
      }
    }
  }
    private static void readInternalBridge(IConfigurationElement element) {
      String baseContent = element.getAttribute(ATTR_BASE_CONTENT);
      String shadowedByContent = element.getAttribute(ATTR_SHADOWED_BY_CONTENT);

      if (baseContent == null || shadowedByContent == null) {
        StatusHandler.log(
            new Status(
                IStatus.WARNING,
                ContextCorePlugin.ID_PLUGIN,
                "Ignoring bridge shadowing because of invalid extension point " //$NON-NLS-1$
                    + BridgesExtensionPointReader.ELEMENT_STRUCTURE_BRIDGE,
                new Exception()));
      }
      ContextCorePlugin.getDefault().addShadowsContent(baseContent, shadowedByContent);
    }
 public static void addRepositoryAssociation(String connectorKind, String extensionId) {
   if (connectorKind == null || extensionId == null) {
     throw new IllegalArgumentException();
   }
   String previous = associationByConnectorKind.put(connectorKind, extensionId);
   if (previous != null) {
     StatusHandler.log(
         new Status(
             IStatus.ERROR,
             TasksUiPlugin.ID_PLUGIN,
             String.format(
                 "Duplicate association for repository %s: %s replaces %s",
                 connectorKind, extensionId, previous), // $NON-NLS-1$
             null));
   }
 }
 private void release(RevWalk revWalk) {
   try {
     MethodUtils.invokeMethod(revWalk, "release", null); // $NON-NLS-1$
   } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
     try {
       MethodUtils.invokeMethod(revWalk, "close", null); // $NON-NLS-1$
     } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e1) {
       StatusHandler.log(
           new Status(
               IStatus.ERROR,
               ID_PLUGIN,
               "Failed to release revWalk " + revWalk,
               e1)); //$NON-NLS-1$
     }
   }
 }
 /**
  * Contributes an extension to the {@link TaskEditor}.
  *
  * @param pluginId the id of the contributing plug-in, may be <code>null</code>
  * @param id the id of the extension, may not be <code>null</code>
  * @param name the name of the extension that is displayed in the settings page
  * @param extension the extension implementation
  */
 public static void addTaskEditorExtension(
     String pluginId, String id, String name, AbstractTaskEditorExtension extension) {
   Assert.isNotNull(id);
   RegisteredTaskEditorExtension descriptor =
       new RegisteredTaskEditorExtension(extension, id, name);
   descriptor.setPluginId(pluginId);
   RegisteredTaskEditorExtension previous = extensionsById.put(id, descriptor);
   if (previous != null) {
     StatusHandler.log(
         new Status(
             IStatus.ERROR,
             TasksUiPlugin.ID_PLUGIN,
             "Duplicate taskEditorExtension id=" //$NON-NLS-1$
                 + id,
             null));
   }
 }
 @Override
 public void stop(BundleContext context) throws Exception {
   try {
     super.stop(context);
     INSTANCE = null;
     for (AbstractRelationProvider provider : getRelationProviders()) {
       provider.stopAllRunningJobs();
     }
   } catch (Exception e) {
     StatusHandler.log(
         new Status(
             IStatus.ERROR,
             ContextCorePlugin.ID_PLUGIN,
             "Mylyn Core stop failed",
             e)); //$NON-NLS-1$
   }
 }
 /**
  * Galileo hack to deal with slaveDocuments (when clicking on java structure elements). The
  * styledText will not contain the whole text anymore, so our line numbering is off
  *
  * @param event
  * @return
  */
 @SuppressWarnings("unused")
 private int getDocumentOffset(LineBackgroundEvent event) {
   /*
    * there is no access to DefaultDocumentAdapter and thus the (master or slave) document.. so we have to assume
    * that on first call this event actually has the full text. this text, and the text of the current styled text
    * will be used to calculate the offset
    */
   if (event.widget instanceof StyledText) {
     String currentText = ((StyledText) event.widget).getText();
     if (initialText == null) {
       initialText = currentText;
       // since it is initial call, offset should be 0 anyway
       return 0;
     }
     // if text is unchanged, offset it 0
     if (currentText.equals(initialText)) {
       return 0;
     }
     // current text is different, check if it is contained in initialText
     if (initialText.contains(currentText)) {
       // calculate the offset
       int charoffset = initialText.indexOf(currentText);
       int lineOffset = 0;
       String delimiter = ((StyledText) event.widget).getLineDelimiter();
       for (String line : initialText.split(delimiter)) {
         if (charoffset > 0) {
           charoffset -= (line.length() + delimiter.length());
           lineOffset++;
         } else {
           break;
         }
       }
       return lineOffset;
     } else {
       // log error since we assume the initial text contains all slaveTexts.
       StatusHandler.log(
           new Status(
               IStatus.ERROR,
               ReviewsUiPlugin.PLUGIN_ID,
               "Could not find text offset for annotation highlighting"
                   + " - current text not contained in initial text."));
     }
   }
   return 0;
 }
 private static void readRelationProvider(IConfigurationElement element) {
   try {
     String contentType = element.getAttribute(BridgesExtensionPointReader.ATTR_CONTENT_TYPE);
     AbstractRelationProvider relationProvider =
         (AbstractRelationProvider)
             element.createExecutableExtension(BridgesExtensionPointReader.ATTR_CLASS);
     if (contentType != null) {
       ContextCorePlugin.getDefault().addRelationProvider(contentType, relationProvider);
     }
   } catch (Throwable e) {
     StatusHandler.log(
         new Status(
             IStatus.WARNING,
             ContextCorePlugin.ID_PLUGIN,
             "Could not load relation provider",
             e)); //$NON-NLS-1$
   }
 }
Beispiel #22
0
  private void maintainIndex(IProgressMonitor m) throws CoreException {
    final int WORK_PER_SEGMENT = 1000;
    SubMonitor monitor = SubMonitor.convert(m, 2 * WORK_PER_SEGMENT);
    try {
      try {
        if (!rebuildIndex) {
          try {
            IndexReader reader = IndexReader.open(directory, false);
            reader.close();
          } catch (CorruptIndexException e) {
            rebuildIndex = true;
          }
        }

        if (rebuildIndex) {
          synchronized (reindexQueue) {
            reindexQueue.clear();
          }

          IStatus status = rebuildIndexCompletely(monitor.newChild(WORK_PER_SEGMENT));
          if (!status.isOK()) {
            StatusHandler.log(status);
          }
        } else {
          monitor.worked(WORK_PER_SEGMENT);
        }

        // index any tasks that have been changed
        indexQueuedTasks(monitor.newChild(WORK_PER_SEGMENT));

        // prevent new searches from reading the now-stale index
        closeIndexReader();
      } catch (IOException e) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                TasksIndexCore.ID_PLUGIN,
                "Unexpected exception: " + e.getMessage(),
                e)); //$NON-NLS-1$
      }
    } finally {
      monitor.done();
    }
  }
Beispiel #23
0
 @Override
 public IStatus run(IProgressMonitor m) {
   if (m.isCanceled()) {
     return Status.CANCEL_STATUS;
   }
   try {
     maintainIndex(m);
   } catch (CoreException e) {
     MultiStatus logStatus =
         new MultiStatus(
             TasksIndexCore.ID_PLUGIN,
             0,
             "Failed to update task list index", //$NON-NLS-1$
             e);
     logStatus.add(e.getStatus());
     StatusHandler.log(logStatus);
   }
   return Status.OK_STATUS;
 }
 public static Date parseRedmineDate(String value) {
   if (value != null && !value.isEmpty()) {
     try {
       // try timestamp
       long timestamp = Long.parseLong(value);
       return new Date(timestamp * 1000);
     } catch (NumberFormatException e) {
       try {
         // try formated date
         return df.parse(value);
       } catch (ParseException e1) {
         IStatus status =
             RedmineCorePlugin.toStatus(e, Messages.ERRMSG_X_VALID_UNIXTIME_DATE, value);
         StatusHandler.log(status);
       }
     }
   }
   return null;
 }
Beispiel #25
0
  /**
   * finds tasks that match the given pattern string
   *
   * @param patternString the pattern string, used to match tasks
   * @param collector the collector that receives tasks
   * @param resultsLimit the maximum number of tasks to find. Specifying a limit enables the index
   *     to be more efficient since it can skip over matching tasks that do not score highly enough.
   *     Specify {@link Integer#MAX_VALUE} if there should be no limit.
   */
  public void find(String patternString, TaskCollector collector, int resultsLimit) {
    Assert.isNotNull(patternString);
    Assert.isNotNull(collector);
    Assert.isTrue(resultsLimit > 0);

    Lock readLock = indexReaderLock.readLock();
    readLock.lock();
    try {
      IndexReader indexReader = getIndexReader();
      if (indexReader != null) {
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        try {
          Query query = computeQuery(patternString);
          TopDocs results = indexSearcher.search(query, resultsLimit);
          for (ScoreDoc scoreDoc : results.scoreDocs) {
            Document document = indexReader.document(scoreDoc.doc);
            String taskIdentifier = document.get(FIELD_IDENTIFIER.getIndexKey());
            AbstractTask task = taskList.getTask(taskIdentifier);
            if (task != null) {
              collector.collect(task);
            }
          }
        } catch (IOException e) {
          StatusHandler.log(
              new Status(
                  IStatus.ERROR,
                  TasksIndexCore.ID_PLUGIN,
                  "Unexpected failure within task list index",
                  e)); //$NON-NLS-1$
        } finally {
          try {
            indexSearcher.close();
          } catch (IOException e) {
            // ignore
          }
        }
      }
    } finally {
      readLock.unlock();
    }
  }
Beispiel #26
0
  public void close() {
    dataManager.removeListener(this);
    taskList.removeChangeListener(this);
    repositoryManager.removeListener(this);

    maintainIndexJob.cancel();
    try {
      maintainIndexJob.join();
    } catch (InterruptedException e) {
      // ignore
    }

    Lock writeLock = indexReaderLock.writeLock();
    writeLock.lock();
    try {
      synchronized (this) {
        if (indexReader != null) {
          try {
            indexReader.close();
          } catch (IOException e) {
            // ignore
          }
          indexReader = null;
        }
      }
      if (directory != null) {
        try {
          directory.close();
        } catch (IOException e) {
          StatusHandler.log(
              new Status(
                  IStatus.ERROR,
                  TasksIndexCore.ID_PLUGIN,
                  "Cannot close index: " + e.getMessage(),
                  e)); //$NON-NLS-1$
        }
      }
    } finally {
      writeLock.unlock();
    }
  }
  private void startWork(JiraTaskEditorPage page) {
    Job job = null;

    if (isTaskInStop(taskData, task)) {
      job = getStartWorkJob(taskData, task);
    } else if (isTaskInProgress(taskData, task)) {
      if (!showLogWorkDialog(taskData, task)) {
        return;
      }
      job = getStopWorkJob(taskData, task, workLog);
    } else {
      StatusHandler.log(
          new Status(
              IStatus.ERROR, JiraUiPlugin.ID_PLUGIN, Messages.StartWorkAction_cannot_perform));
      return;
    }

    if (page == null) {
      doActionOutsideEditor(job);
    } else {
      doActionInsideEditor(job, page);
    }
  }
  public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
    if (oldInput != null) {
      annotationModel.disconnect(oldInput);
    }
    if (newInput != null && sourceViewer != null) {
      IAnnotationModel originalAnnotationModel = sourceViewer.getAnnotationModel();
      if (originalAnnotationModel instanceof IAnnotationModelExtension) {
        IAnnotationModelExtension annotationModelExtension =
            (IAnnotationModelExtension) originalAnnotationModel;
        annotationModelExtension.addAnnotationModel(
            ReviewsUiPlugin.PLUGIN_ID, originalAnnotationModel);
      } else {
        try {
          Class<SourceViewer> sourceViewerClazz = SourceViewer.class;
          Field declaredField2 = sourceViewerClazz.getDeclaredField("fVisualAnnotationModel");
          declaredField2.setAccessible(true);
          Method declaredMethod =
              sourceViewerClazz.getDeclaredMethod(
                  "createVisualAnnotationModel", IAnnotationModel.class);
          declaredMethod.setAccessible(true);
          originalAnnotationModel =
              (IAnnotationModel) declaredMethod.invoke(sourceViewer, annotationModel);
          declaredField2.set(sourceViewer, originalAnnotationModel);
          originalAnnotationModel.connect(newInput);
          sourceViewer.showAnnotations(true);

          createVerticalRuler(newInput, sourceViewerClazz);
          createOverviewRuler(newInput, sourceViewerClazz);
          createHighlighting(sourceViewerClazz);
        } catch (Throwable t) {
          StatusHandler.log(
              new Status(
                  IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, "Error attaching annotation model", t));
        }
      }
    }
  }
  /** Public for testing */
  public IInteractionContext readContextFromXml(
      String handleIdentifier,
      File fromFile,
      IInteractionContextReader reader,
      IInteractionContextScaling scaling) {
    try {
      if (!fromFile.exists()) {
        return null;
      } else {
        if (reader instanceof SaxContextReader) {
          ((SaxContextReader) reader).setContextScaling(scaling);
        }

        InteractionContext context = reader.readContext(handleIdentifier, fromFile);
        if (context == null) {
          String firstHandle = getFirstContextHandle(fromFile);
          if (firstHandle != null && !firstHandle.equals(handleIdentifier)) {
            context = reader.readContext(firstHandle, fromFile);
            if (context != null) {
              context.setHandleIdentifier(handleIdentifier);
            }
          }
        }
        return context;
      }
    } catch (Exception e) {
      // TODO: propagate exception instead?
      StatusHandler.log(
          new Status(
              IStatus.ERROR,
              ContextCorePlugin.ID_PLUGIN,
              "Could not read: " //$NON-NLS-1$
                  + fromFile.getAbsolutePath(),
              e));
    }
    return null;
  }
Beispiel #30
0
  @Override
  protected void addPages() {
    initialize();

    // determine factories
    Set<String> conflictingIds = new HashSet<String>();
    ArrayList<AbstractTaskEditorPageFactory> pageFactories =
        new ArrayList<AbstractTaskEditorPageFactory>();
    for (AbstractTaskEditorPageFactory pageFactory :
        TasksUiPlugin.getDefault().getTaskEditorPageFactories()) {
      if (pageFactory.canCreatePageFor(getTaskEditorInput())
          && WorkbenchUtil.allowUseOf(pageFactory)) {
        pageFactories.add(pageFactory);
        String[] ids = pageFactory.getConflictingIds(getTaskEditorInput());
        if (ids != null) {
          conflictingIds.addAll(Arrays.asList(ids));
        }
      }
    }
    for (Iterator<AbstractTaskEditorPageFactory> it = pageFactories.iterator(); it.hasNext(); ) {
      if (conflictingIds.contains(it.next().getId())) {
        it.remove();
      }
    }

    // sort by priority
    Collections.sort(
        pageFactories,
        new Comparator<AbstractTaskEditorPageFactory>() {
          public int compare(AbstractTaskEditorPageFactory o1, AbstractTaskEditorPageFactory o2) {
            return o1.getPriority() - o2.getPriority();
          }
        });

    // create pages
    for (AbstractTaskEditorPageFactory factory : pageFactories) {
      try {
        IFormPage page = factory.createPage(this);
        int index = addPage(page);
        setPageImage(index, factory.getPageImage(this, page));
        setPageText(index, factory.getPageText(this, page));
        if (factory.getPriority() == AbstractTaskEditorPageFactory.PRIORITY_TASK) {
          setActivePage(index);
        }
        if (page instanceof ISelectionProvider) {
          ((ISelectionProvider) page).addSelectionChangedListener(getActionBarContributor());
        }
      } catch (Exception e) {
        StatusHandler.log(
            new Status(
                IStatus.ERROR,
                TasksUiPlugin.ID_PLUGIN,
                "Could not create editor via factory: " + factory,
                e)); //$NON-NLS-1$
      }
    }

    updateTitleImage();
    updateHeaderToolBar();
    installTitleDrag(getHeaderForm().getForm().getForm());

    // do this late to allow pages to replace the selection provider
    getEditorSite().registerContextMenu(menuManager, getEditorSite().getSelectionProvider(), true);
  }