private static Change createPackageFragmentRootDeleteChange(IPackageFragmentRoot root)
      throws JavaModelException {
    IResource resource = root.getResource();
    if (resource != null && resource.isLinked()) {
      // XXX using this code is a workaround for jcore bug 31998
      // jcore cannot handle linked stuff
      // normally, we should always create DeletePackageFragmentRootChange
      CompositeChange composite =
          new DynamicValidationStateChange(
              RefactoringCoreMessages.DeleteRefactoring_delete_package_fragment_root);

      ClasspathChange change =
          ClasspathChange.removeEntryChange(root.getJavaProject(), root.getRawClasspathEntry());
      if (change != null) {
        composite.add(change);
      }
      Assert.isTrue(!Checks.isClasspathDelete(root)); // checked in preconditions
      composite.add(createDeleteChange(resource));

      return composite;
    } else {
      Assert.isTrue(!root.isExternal());
      // TODO remove the query argument
      return new DeletePackageFragmentRootChange(root, true, null);
    }
  }
  public void setTask(Task task) {
    Assert.isTrue(task != null);
    InputOutputSpecification iospec = task.getIoSpecification();
    Assert.isTrue(iospec != null && iospec.getInputSets().size() > 0);

    this.task = task;
  }
Example #3
0
  /**
   * This method is not meant for public use. Only for testing. use {@link
   * #removePluginDependency(IProject, IProject)} instead. If doMangle is true, then add an extra
   * space in the text to remove so that previously mangled plugin entries can be removed
   */
  public static IStatus removePluginDependency(
      IProject dependent, IProject plugin, boolean doMangle) throws CoreException {
    Assert.isTrue(
        GrailsNature.isGrailsProject(dependent), dependent.getName() + " is not a grails project");
    Assert.isTrue(
        GrailsNature.isGrailsPluginProject(plugin),
        plugin.getName() + " is not a grails plugin project");

    IFile buildConfigFile = dependent.getFile(BUILD_CONFIG_LOCATION);

    String textToRemove = createDependencyText(dependent, plugin, doMangle);

    if (dependencyExists(buildConfigFile, textToRemove)) {
      char[] contents = ((CompilationUnit) JavaCore.create(buildConfigFile)).getContents();
      String newText = String.valueOf(contents).replace(textToRemove, "");
      InputStream stream = createInputStream(dependent, newText);
      buildConfigFile.setContents(stream, true, true, null);
      return Status.OK_STATUS;
    } else {
      return new Status(
          IStatus.WARNING,
          GrailsCoreActivator.PLUGIN_ID,
          "Could not remove a dependency from "
              + dependent.getName()
              + " to in place plugin "
              + plugin.getName()
              + ". Try manually editing the BuildConfig.groovy file.");
    }
  }
Example #4
0
  public String suggestNewVariableName(
      String[] prefixes,
      String[] suffixes,
      String oldVariableName,
      String oldTypeName,
      String newTypeName) {

    Assert.isNotNull(prefixes);
    Assert.isNotNull(suffixes);
    Assert.isNotNull(oldVariableName);
    Assert.isNotNull(oldTypeName);
    Assert.isNotNull(newTypeName);
    Assert.isTrue(oldVariableName.length() > 0);
    Assert.isTrue(oldTypeName.length() > 0);
    Assert.isTrue(newTypeName.length() > 0);

    final String usedPrefix = findLongestPrefix(oldVariableName, prefixes);
    final String usedSuffix = findLongestSuffix(oldVariableName, suffixes);
    final String strippedVariableName =
        oldVariableName.substring(
            usedPrefix.length(), oldVariableName.length() - usedSuffix.length());

    String newVariableName = match(oldTypeName, newTypeName, strippedVariableName);
    return (newVariableName != null) ? usedPrefix + newVariableName + usedSuffix : null;
  }
  /**
   * Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>
   * length</code>) contains the <code>new</code> keyword.
   *
   * @param document the document being modified
   * @param offset the first character position in <code>document</code> to be considered
   * @param length the length of the character range to be considered
   * @param partitioning the document partitioning
   * @return <code>true</code> if the specified character range contains a <code>new</code> keyword,
   *     <code>false</code> otherwise.
   */
  private static boolean isNewMatch(
      IDocument document, int offset, int length, String partitioning) {
    Assert.isTrue(length >= 0);
    Assert.isTrue(offset >= 0);
    Assert.isTrue(offset + length < document.getLength() + 1);

    try {
      String text = document.get(offset, length);
      int pos = text.indexOf("new"); // $NON-NLS-1$

      while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
        pos = text.indexOf("new", pos + 2); // $NON-NLS-1$

      if (pos < 0) return false;

      if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1))) return false;

      if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3))) return false;

      return true;

    } catch (BadLocationException e) {
    }
    return false;
  }
Example #6
0
  /**
   * This method is not meant for public use. Only for testing. use {@link
   * #addPluginDependency(IProject, IProject)} instead. If doMangle is true, then add an extra space
   * in the added text so that it cannot be removed.
   */
  public static IStatus addPluginDependency(IProject dependent, IProject plugin, boolean doMangle)
      throws CoreException {
    Assert.isTrue(
        GrailsNature.isGrailsProject(dependent), dependent.getName() + " is not a grails project");
    Assert.isTrue(
        GrailsNature.isGrailsPluginProject(plugin),
        plugin.getName() + " is not a grails plugin project");

    IFile buildConfigFile = dependent.getFile(BUILD_CONFIG_LOCATION);

    // next create the text to add to BuildConfig.groovy

    String textToAdd = createDependencyText(dependent, plugin, doMangle);

    if (!dependencyExists(buildConfigFile, textToAdd)) {
      InputStream stream = createInputStream(dependent, textToAdd);
      buildConfigFile.appendContents(stream, true, true, null);
      return Status.OK_STATUS;
    } else {
      return new Status(
          IStatus.WARNING,
          GrailsCoreActivator.PLUGIN_ID,
          "Could not add a dependency from "
              + dependent.getName()
              + " to in place plugin "
              + plugin.getName()
              + ". Try manually editing the BuildConfig.groovy file.");
    }
  }
Example #7
0
 private RefactoringStatus checkAccessorDeclarations(IProgressMonitor pm, IMethod existingAccessor)
     throws CoreException {
   RefactoringStatus result = new RefactoringStatus();
   SearchPattern pattern =
       SearchPattern.createPattern(
           existingAccessor,
           IJavaSearchConstants.DECLARATIONS,
           SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
   IJavaSearchScope scope = SearchEngine.createHierarchyScope(fField.getDeclaringType());
   SearchResultGroup[] groupDeclarations =
       RefactoringSearchEngine.search(pattern, scope, pm, result);
   Assert.isTrue(groupDeclarations.length > 0);
   if (groupDeclarations.length != 1) {
     String message =
         Messages.format(
             RefactoringCoreMessages.RenameFieldRefactoring_overridden,
             JavaElementUtil.createMethodSignature(existingAccessor));
     result.addError(message);
   } else {
     SearchResultGroup group = groupDeclarations[0];
     Assert.isTrue(group.getSearchResults().length > 0);
     if (group.getSearchResults().length != 1) {
       String message =
           Messages.format(
               RefactoringCoreMessages.RenameFieldRefactoring_overridden_or_overrides,
               JavaElementUtil.createMethodSignature(existingAccessor));
       result.addError(message);
     }
   }
   return result;
 }
  private void testInvariants(int node) {
    if (node == -1) {
      return;
    }

    // Get the current tree size (we will later force the tree size
    // to be recomputed from scratch -- if everything works properly, then
    // there should be no change.
    int treeSize = getSubtreeSize(node);

    int left = leftSubTree[node];
    int right = rightSubTree[node];
    int unsorted = nextUnsorted[node];

    if (isUnsorted(node)) {
      Assert.isTrue(left == -1, "unsorted nodes shouldn't have a left subtree"); // $NON-NLS-1$
      Assert.isTrue(right == -1, "unsorted nodes shouldn't have a right subtree"); // $NON-NLS-1$
    }

    if (left != -1) {
      testInvariants(left);
      Assert.isTrue(
          parentTree[left] == node, "left node has invalid parent pointer"); // $NON-NLS-1$
    }
    if (right != -1) {
      testInvariants(right);
      Assert.isTrue(
          parentTree[right] == node, "right node has invalid parent pointer"); // $NON-NLS-1$
    }

    int previous = node;
    while (unsorted != -1) {
      int oldTreeSize = this.treeSize[unsorted];
      recomputeTreeSize(unsorted);

      Assert.isTrue(
          this.treeSize[unsorted] == oldTreeSize,
          "Invalid node size for unsorted node"); //$NON-NLS-1$
      Assert.isTrue(
          leftSubTree[unsorted] == -1,
          "unsorted nodes shouldn't have left subtrees"); //$NON-NLS-1$
      Assert.isTrue(
          rightSubTree[unsorted] == -1,
          "unsorted nodes shouldn't have right subtrees"); //$NON-NLS-1$
      Assert.isTrue(
          parentTree[unsorted] == previous,
          "unsorted node has invalid parent pointer"); //$NON-NLS-1$
      Assert.isTrue(
          contents[unsorted] != lazyRemovalFlag,
          "unsorted nodes should not be lazily removed"); //$NON-NLS-1$
      previous = unsorted;
      unsorted = nextUnsorted[unsorted];
    }

    // Note that we've already tested that the child sizes are correct... if our size is
    // correct, then recomputing it now should not cause any change.
    recomputeTreeSize(node);

    Assert.isTrue(treeSize == getSubtreeSize(node), "invalid tree size"); // $NON-NLS-1$
  }
 /** Constructor. */
 public EEnumComboBoxDataProvider(Object axisElement) {
   Object object = AxisUtils.getRepresentedElement(axisElement);
   Assert.isTrue(object instanceof EStructuralFeature);
   EStructuralFeature feature = (EStructuralFeature) object;
   EClassifier type = feature.getEType();
   Assert.isTrue(type instanceof EEnum);
   this.eenum = (EEnum) type;
 }
Example #10
0
 @Override
 public void setInput(IWorkbenchPart part, ISelection selection) {
   super.setInput(part, selection);
   Assert.isTrue(selection instanceof IStructuredSelection);
   Object input = ((IStructuredSelection) selection).getFirstElement();
   Assert.isTrue(input instanceof UserGroup);
   this.userGroup = (UserGroup) input;
 }
 /**
  * Creates a new extract constant refactoring
  *
  * @param unit the compilation unit, or <code>null</code> if invoked by scripting
  * @param selectionStart
  * @param selectionLength
  */
 public ExtractConstantRefactoring(IJavaScriptUnit unit, int selectionStart, int selectionLength) {
   Assert.isTrue(selectionStart >= 0);
   Assert.isTrue(selectionLength >= 0);
   fSelectionStart = selectionStart;
   fSelectionLength = selectionLength;
   fCu = unit;
   fCuRewrite = null;
   fLinkedProposalModel = null;
   fConstantName = ""; // $NON-NLS-1$
 }
 /**
  * Creates a new extract constant refactoring
  *
  * @param unit the compilation unit, or <code>null</code> if invoked by scripting
  * @param selectionStart start
  * @param selectionLength length
  */
 public ExtractConstantRefactoring(
     ICompilationUnit unit, int selectionStart, int selectionLength) {
   Assert.isTrue(selectionStart >= 0);
   Assert.isTrue(selectionLength >= 0);
   fSelectionStart = selectionStart;
   fSelectionLength = selectionLength;
   fCu = unit;
   fCuRewrite = null;
   fLinkedProposalModel = null;
   fConstantName = ""; // $NON-NLS-1$
   fCheckResultForCompileProblems = true;
 }
  public ExtractConstantRefactoring(
      JavaScriptUnit astRoot, int selectionStart, int selectionLength) {
    Assert.isTrue(selectionStart >= 0);
    Assert.isTrue(selectionLength >= 0);
    Assert.isTrue(astRoot.getTypeRoot() instanceof IJavaScriptUnit);

    fSelectionStart = selectionStart;
    fSelectionLength = selectionLength;
    fCu = (IJavaScriptUnit) astRoot.getTypeRoot();
    fCuRewrite = new CompilationUnitRewrite(fCu, astRoot);
    fLinkedProposalModel = null;
    fConstantName = ""; // $NON-NLS-1$
  }
  /**
   * Checks whether <code>position</code> resides in a default (Java) partition of <code>document
   * </code>.
   *
   * @param document the document being modified
   * @param position the position to be checked
   * @param partitioning the document partitioning
   * @return <code>true</code> if <code>position</code> is in the default partition of <code>
   *     document</code>, <code>false</code> otherwise
   */
  private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
    Assert.isTrue(position >= 0);
    Assert.isTrue(position <= document.getLength());

    try {
      ITypedRegion region = TextUtilities.getPartition(document, partitioning, position, false);
      return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);

    } catch (BadLocationException e) {
    }

    return false;
  }
Example #15
0
 @Override
 public void setInput(IWorkbenchPart part, ISelection selection) {
   super.setInput(part, selection);
   if (test != null) {
     test.getAllLanguages().removePropertyChangeListener(this);
   }
   Assert.isTrue(selection instanceof IStructuredSelection);
   Object input = ((IStructuredSelection) selection).getFirstElement();
   Assert.isTrue(input instanceof TestEditPart);
   test = (Test) ((TestEditPart) input).getModel();
   AllLanguages langs = test.getAllLanguages();
   langs.addPropertyChangeListener(this);
 }
Example #16
0
  public String suggestNewMethodName(String oldMethodName, String oldTypeName, String newTypeName) {

    Assert.isNotNull(oldMethodName);
    Assert.isNotNull(oldTypeName);
    Assert.isNotNull(newTypeName);
    Assert.isTrue(oldMethodName.length() > 0);
    Assert.isTrue(oldTypeName.length() > 0);
    Assert.isTrue(newTypeName.length() > 0);

    resetPrefixes();

    return match(oldTypeName, newTypeName, oldMethodName);
  }
  private static boolean hasReadOnlyResourcesAndSubResources(IJavaScriptElement javaElement)
      throws CoreException {
    switch (javaElement.getElementType()) {
      case IJavaScriptElement.CLASS_FILE:
        // if this assert fails, it means that a precondition is missing
        Assert.isTrue(((IClassFile) javaElement).getResource() instanceof IFile);
        // fall thru
      case IJavaScriptElement.JAVASCRIPT_UNIT:
        IResource resource = ReorgUtils.getResource(javaElement);
        return (resource != null && Resources.isReadOnly(resource));
      case IJavaScriptElement.PACKAGE_FRAGMENT:
        IResource packResource = ReorgUtils.getResource(javaElement);
        if (packResource == null) return false;
        IPackageFragment pack = (IPackageFragment) javaElement;
        if (Resources.isReadOnly(packResource)) return true;
        Object[] nonJava = pack.getNonJavaScriptResources();
        for (int i = 0; i < nonJava.length; i++) {
          Object object = nonJava[i];
          if (object instanceof IResource
              && hasReadOnlyResourcesAndSubResources((IResource) object)) return true;
        }
        return hasReadOnlyResourcesAndSubResources(pack.getChildren());
      case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT:
        IPackageFragmentRoot root = (IPackageFragmentRoot) javaElement;
        if (root.isArchive()) return false;
        IResource pfrResource = ReorgUtils.getResource(javaElement);
        if (pfrResource == null) return false;
        if (Resources.isReadOnly(pfrResource)) return true;
        Object[] nonJava1 = root.getNonJavaScriptResources();
        for (int i = 0; i < nonJava1.length; i++) {
          Object object = nonJava1[i];
          if (object instanceof IResource
              && hasReadOnlyResourcesAndSubResources((IResource) object)) return true;
        }
        return hasReadOnlyResourcesAndSubResources(root.getChildren());

      case IJavaScriptElement.FIELD:
      case IJavaScriptElement.IMPORT_CONTAINER:
      case IJavaScriptElement.IMPORT_DECLARATION:
      case IJavaScriptElement.INITIALIZER:
      case IJavaScriptElement.METHOD:
      case IJavaScriptElement.TYPE:
        return false;
      default:
        Assert.isTrue(false); // not handled here
        return false;
    }
  }
  /**
   * Creates a group with border (label in border). Accepted button styles are: SWT.RADIO,
   * SWT.CHECK, SWT.TOGGLE For border styles see <code>Group</code>
   */
  public SelectionButtonDialogFieldGroup(
      final int buttonsStyle,
      final String[] buttonNames,
      final int nColumns,
      final int borderStyle) {
    super();

    Assert.isTrue(
        buttonsStyle == SWT.RADIO || buttonsStyle == SWT.CHECK || buttonsStyle == SWT.TOGGLE);
    fButtonNames = buttonNames;

    final int nButtons = buttonNames.length;
    fButtonsSelected = new boolean[nButtons];
    fButtonsEnabled = new boolean[nButtons];
    for (int i = 0; i < nButtons; i++) {
      fButtonsSelected[i] = false;
      fButtonsEnabled[i] = true;
    }
    if (buttonsStyle == SWT.RADIO) {
      fButtonsSelected[0] = true;
    }

    fGroupBorderStyle = borderStyle;
    fGroupNumberOfColumns = nColumns <= 0 ? nButtons : nColumns;

    fButtonsStyle = buttonsStyle;
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets
   * .Composite)
   */
  public void createPartControl(Composite parent) {
    Assert.isTrue(fViewer == null);

    fTypeComparator = new ScriptElementTypeComparator();

    // Setup viewer
    fViewer = createViewer(parent);

    initDragAndDrop();

    fLabelProvider = createLabelProvider();
    fViewer.setLabelProvider(createDecoratingLabelProvider(fLabelProvider));

    fViewer.setComparator(createModelElementComparator());
    fViewer.setUseHashlookup(true);
    fTitleProvider = createTitleProvider();

    createContextMenu();
    getSite().setSelectionProvider(fViewer);

    if (fMemento != null) { // initialize linking state before creating the
      // actions
      restoreLinkingEnabled(fMemento);
    }

    createActions(); // call before registering for selection changes
    addKeyListener();

    if (fMemento != null) restoreState(fMemento);

    getSite().setSelectionProvider(fViewer);

    // Status line
    IStatusLineManager slManager = getViewSite().getActionBars().getStatusLineManager();
    fViewer.addSelectionChangedListener(createStatusBarUpdater(slManager));

    hookViewerListeners();

    // Filters
    addFilters();

    // Initialize viewer input
    fViewer.setContentProvider(createContentProvider());
    setInitialInput();

    // Initialize selection
    setInitialSelection();
    fMemento = null;

    // Listen to page changes
    getViewSite().getPage().addPostSelectionListener(this);
    getViewSite().getPage().addPartListener(fPartListener);

    fillActionBars(getViewSite().getActionBars());
    IContextService ctxService = (IContextService) getSite().getService(IContextService.class);
    if (ctxService != null) {
      fContextActivation = ctxService.activateContext(DLTKUIPlugin.CONTEXT_VIEWS);
    }
    setHelp();
  }
  /* (non-Javadoc)
   * @see org.eclipse.tm.tcf.protocol.Protocol.ChannelOpenListener#onChannelOpen(org.eclipse.tm.tcf.protocol.IChannel)
   */
  @Override
  public void onChannelOpen(IChannel channel) {
    Assert.isNotNull(channel);
    Assert.isTrue(Protocol.isDispatchThread());

    // Trace the channel opening
    LogUtils.logMessageForChannel(
        channel,
        Messages.InternalChannelOpenListener_onChannelOpen_message,
        "debug/channels",
        this); //$NON-NLS-1$

    // As the channel has just opened, there should be no channel listener, but better be safe and
    // check.
    IChannel.IChannelListener channelListener = channelListeners.remove(channel);
    if (channelListener != null) channel.removeChannelListener(channelListener);
    // Create a new channel listener instance
    channelListener = new InternalChannelListener(channel);
    // Add the channel listener to the global map
    setChannelListener(channel, channelListener);
    // Attach channel listener to the channel
    channel.addChannelListener(channelListener);

    // Fire the property change event for the channel
    Tcf.fireChannelStateChangeListeners(channel, IChannel.STATE_OPEN);
  }
 /**
  * Adds the given change to the list of children. The change to be added can be <code>null</code>.
  * Adding a "null" change does nothing.
  *
  * @param change the change to add
  */
 public void add(Change change) {
   if (change != null) {
     Assert.isTrue(change.getParent() == null);
     fChanges.add(change);
     change.setParent(this);
   }
 }
 /**
  * Adapts the behavior of the contained components to the change encoded in the given event.
  *
  * <p>Clients are not allowed to call this method if the old setup with text tools is in use.
  *
  * @param event the event to which to adapt
  * @see DartSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager,
  *     IPreferenceStore, ITextEditor, String)
  */
 public void handlePropertyChangeEvent(PropertyChangeEvent event) {
   Assert.isTrue(isNewSetup());
   if (fCodeScanner.affectsBehavior(event)) {
     fCodeScanner.adaptToPreferenceChange(event);
   }
   if (fMultilineCommentScanner.affectsBehavior(event)) {
     fMultilineCommentScanner.adaptToPreferenceChange(event);
   }
   if (fSinglelineCommentScanner.affectsBehavior(event)) {
     fSinglelineCommentScanner.adaptToPreferenceChange(event);
   }
   if (fStringScanner.affectsBehavior(event)) {
     fStringScanner.adaptToPreferenceChange(event);
   }
   if (fMultilineStringScanner.affectsBehavior(event)) {
     fMultilineStringScanner.adaptToPreferenceChange(event);
   }
   if (fJavaDocScanner.affectsBehavior(event)) {
     fJavaDocScanner.adaptToPreferenceChange(event);
   }
   if (fJavaDoubleClickSelector != null
       && JavaScriptCore.COMPILER_SOURCE.equals(event.getProperty())) {
     if (event.getNewValue() instanceof String) {
       fJavaDoubleClickSelector.setSourceVersion((String) event.getNewValue());
     }
   }
 }
Example #23
0
  /**
   * Returns this field editor's text control.
   *
   * <p>The control is created if it does not yet exist
   *
   * @param parent the parent
   * @return the text control
   */
  public Text getTextControl(Composite parent) {
    if (textField == null) {
      textField = new Text(parent, SWT.SINGLE | SWT.BORDER);

      textField.setEchoChar('*');

      textField.setFont(parent.getFont());
      switch (validateStrategy) {
        case VALIDATE_ON_KEY_STROKE:
          textField.addKeyListener(
              new KeyAdapter() {

                /** {@inheritDoc} */
                @Override
                public void keyReleased(KeyEvent e) {
                  valueChanged();
                }
              });

          break;
        case VALIDATE_ON_FOCUS_LOST:
          textField.addKeyListener(
              new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                  clearErrorMessage();
                }
              });
          textField.addFocusListener(
              new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                  refreshValidState();
                }

                @Override
                public void focusLost(FocusEvent e) {
                  valueChanged();
                  clearErrorMessage();
                }
              });
          break;
        default:
          Assert.isTrue(false, "Unknown validate strategy"); // $NON-NLS-1$
      }
      textField.addDisposeListener(
          new DisposeListener() {
            @Override
            public void widgetDisposed(DisposeEvent event) {
              textField = null;
            }
          });
      if (textLimit > 0) { // Only set limits above 0 - see SWT spec
        textField.setTextLimit(textLimit);
      }
    } else {
      checkParent(textField, parent);
    }
    return textField;
  }
 /**
  * The limit is the maximum number of directories managed by this store. This number must be power
  * of 2 and do not exceed 256. The location should be an existing valid directory.
  */
 public BlobStore(IFileStore store, int limit) {
   Assert.isNotNull(store);
   localStore = store;
   Assert.isTrue(localStore.fetchInfo().isDirectory());
   Assert.isTrue(
       limit == 256
           || limit == 128
           || limit == 64
           || limit == 32
           || limit == 16
           || limit == 8
           || limit == 4
           || limit == 2
           || limit == 1);
   mask = (byte) (limit - 1);
 }
 /**
  * Method to be called if the initialization of the collector is finished. The creator of the
  * collector must call this method in order to "activate" the collector finally.
  */
 public final synchronized void initDone() {
   Assert.isTrue(initDone == false);
   if (callback != null) {
     removeCallback(callback);
   }
   initDone = true;
 }
  public ArrayType createArrayType(TType elementType, int dimensions) {
    Assert.isTrue(!elementType.isArrayType());
    Assert.isTrue(!elementType.isAnonymous());
    Assert.isTrue(dimensions > 0);

    int index = dimensions - 1;
    Map arrayTypes = getArrayTypesMap(index);
    ArrayType result = (ArrayType) arrayTypes.get(elementType);
    if (result != null) return result;
    result =
        new ArrayType(
            this, BindingKey.createArrayTypeBindingKey(elementType.getBindingKey(), dimensions));
    arrayTypes.put(elementType, result);
    result.initialize(elementType, dimensions);
    return result;
  }
Example #27
0
  /** Restores the object state from the memento. */
  public IStatus restoreState() {
    Assert.isTrue(!isRestored());

    IStatus result = Status.OK_STATUS;
    IMemento memento = this.memento;
    this.memento = null;

    String factoryId = memento.getString(IWorkbenchConstants.TAG_FACTORY_ID);
    if (factoryId == null) {
      WorkbenchPlugin.log("Unable to restore mru list - no input factory ID."); // $NON-NLS-1$
      return result;
    }
    IElementFactory factory = PlatformUI.getWorkbench().getElementFactory(factoryId);
    if (factory == null) {
      return result;
    }
    IMemento persistableMemento = memento.getChild(IWorkbenchConstants.TAG_PERSISTABLE);
    if (persistableMemento == null) {
      WorkbenchPlugin.log(
          "Unable to restore mru list - no input element state: " + factoryId); // $NON-NLS-1$
      return result;
    }
    IAdaptable adaptable = factory.createElement(persistableMemento);
    if (adaptable == null || (adaptable instanceof IEditorInput) == false) {
      return result;
    }
    input = (IEditorInput) adaptable;
    // Get the editor descriptor.
    String editorId = memento.getString(IWorkbenchConstants.TAG_ID);
    if (editorId != null) {
      IEditorRegistry registry = WorkbenchPlugin.getDefault().getEditorRegistry();
      descriptor = registry.findEditor(editorId);
    }
    return result;
  }
  /**
   * Writes the given AbstractDataTree to the given stream. This writes a single DataTree or
   * DeltaDataTree, ignoring parent trees.
   *
   * @param path Only writes data for the subtree rooted at the given path, and for all nodes
   *     directly between the root and the subtree.
   * @param depth In the subtree rooted at the given path, only write up to this depth. A depth of
   *     infinity is given by the constant D_INFINITE.
   */
  public void writeTree(AbstractDataTree tree, IPath path, int depth, DataOutput output)
      throws IOException {
    this.output = output;
    /* tunnel down relevant path */
    AbstractDataTreeNode node = tree.getRootNode();
    IPath currentPath = Path.ROOT;
    String[] segments = path.segments();
    for (int i = 0; i < segments.length; i++) {
      String nextSegment = segments[i];

      /* write this node to the output */
      writeSingleNode(node, currentPath);

      currentPath = currentPath.append(nextSegment);
      node = node.childAtOrNull(nextSegment);

      /* write the number of children for this node */
      if (node != null) {
        writeNumber(1);
      } else {
        /* can't navigate down the path, just give up with what we have so far */
        writeNumber(0);
        return;
      }
    }

    Assert.isTrue(currentPath.equals(path), "dtree.navigationError"); // $NON-NLS-1$

    /* recursively write the subtree we're interested in */
    writeNode(node, path, depth);
  }
  public static String asString(ASTNode node) {
    Assert.isTrue(node.getAST().apiLevel() == AST.JLS3);

    ASTFlattener flattener = new ASTFlattener();
    node.accept(flattener);
    return flattener.getResult();
  }
 TableColumnLayout getTableLayout() {
   Layout layout = table.getParent().getLayout();
   Assert.isTrue(
       layout instanceof TableColumnLayout,
       "Table parent layout needs to be a TableColumnLayout!");
   return (TableColumnLayout) layout;
 }