/**
   * Copied from Util.getAdapter (from eclipse 3.3: not available in eclipse 3.2)
   *
   * <p>If it is possible to adapt the given object to the given type, this returns the adapter.
   * Performs the following checks:
   *
   * <ol>
   *   <li>Returns <code>sourceObject</code> if it is an instance of the adapter type.
   *   <li>If sourceObject implements IAdaptable, it is queried for adapters.
   *   <li>If sourceObject is not an instance of PlatformObject (which would have already done so),
   *       the adapter manager is queried for adapters
   * </ol>
   *
   * Otherwise returns null.
   *
   * @param sourceObject object to adapt, or null
   * @param adapterType type to adapt to
   * @return a representation of sourceObject that is assignable to the adapter type, or null if no
   *     such representation exists
   */
  public static Object utilGetAdapter(Object sourceObject, Class adapterType) {
    Assert.isNotNull(adapterType);
    if (sourceObject == null) {
      return null;
    }
    if (adapterType.isInstance(sourceObject)) {
      return sourceObject;
    }

    if (sourceObject instanceof IAdaptable) {
      IAdaptable adaptable = (IAdaptable) sourceObject;

      Object result = adaptable.getAdapter(adapterType);
      if (result != null) {
        // Sanity-check
        Assert.isTrue(adapterType.isInstance(result));
        return result;
      }
    }

    if (!(sourceObject instanceof PlatformObject)) {
      Object result = Platform.getAdapterManager().getAdapter(sourceObject, adapterType);
      if (result != null) {
        return result;
      }
    }

    return null;
  }
  /**
   * Creates a new default spell checker.
   *
   * @param store the preference store for this spell checker
   * @param locale the locale
   */
  public DefaultSpellChecker(IPreferenceStore store, Locale locale) {
    Assert.isLegal(store != null);
    Assert.isLegal(locale != null);

    fPreferences = store;
    fLocale = locale;
  }
  /**
   * 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;
  }
  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);
    }
  }
Example #5
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 #6
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.");
    }
  }
  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$
  }
Example #8
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;
 }
 /**
  * Creates a new authorization database, or opens an existing one, whose data is, or can be, saved
  * to a file with the given filename. A password must be given to create a new database and an
  * existing database is opened by supplying the password that was given to create it.
  *
  * @param filename the location of the database on disk. For example, "c:/temp/database"
  * @param password the password to access the database. For example, "secret"
  * @exception CoreException if there are problems creating the database. Reasons include:
  *     <ul>
  *       <li>The database could not be opened because the wrong password was given.
  *       <li>The database could not be opened because the specified file is corrupt.
  *     </ul>
  */
 public AuthorizationDatabase(String filename, String password) throws CoreException {
   Assert.isNotNull(filename);
   Assert.isNotNull(password);
   this.password = password;
   file = new File(filename);
   load();
 }
 /**
  * Creates a new history.
  *
  * @param maxLHS the maximum number of tracked left hand sides (&gt; 0)
  * @param maxRHS the maximum number of tracked right hand sides per left hand side(&gt; 0)
  */
 public ContentAssistHistory(int maxLHS, int maxRHS) {
   Assert.isLegal(maxLHS > 0);
   Assert.isLegal(maxRHS > 0);
   fMaxLHS = maxLHS;
   fMaxRHS = maxRHS;
   fLHSCache = new MRUMap<String, MRUSet<String>>(fMaxLHS);
 }
  /**
   * Adds the specified resource to the protection space specified by the given realm. All resources
   * at or deeper than the depth of the last symbolic element in the path of the given resource URL
   * are assumed to be in the same protection space.
   *
   * @param resourceUrl the URL identifying the resources to be added to the specified protection
   *     space. For example, "http://www.hostname.com/folder/".
   * @param realm the name of the protection space. For example, "*****@*****.**"
   */
  public void addProtectionSpace(URL resourceUrl, String realm) {
    Assert.isNotNull(resourceUrl);
    Assert.isNotNull(realm);

    if (!resourceUrl.getFile().endsWith("/")) { // $NON-NLS-1$
      resourceUrl = URLTool.getParent(resourceUrl);
    }

    String oldRealm = getProtectionSpace(resourceUrl);
    if (oldRealm != null && oldRealm.equals(realm)) {
      return;
    }

    String url1 = resourceUrl.toString();
    Enumeration urls = protectionSpace.keys();
    while (urls.hasMoreElements()) {
      String url2 = (String) urls.nextElement();
      if (url1.startsWith(url2) || url2.startsWith(url1)) {
        protectionSpace.remove(url2);
        break;
      }
    }

    protectionSpace.put(url1, realm);
    needsSaving = true;
  }
 protected StructureSelectionAction(String text, DartEditor editor, SelectionHistory history) {
   super(text);
   Assert.isNotNull(editor);
   Assert.isNotNull(history);
   fEditor = editor;
   fSelectionHistory = history;
 }
  /**
   * Tries to nest the given <code>LinkedModeModel</code> onto the top of the stack of environments
   * managed by the receiver. If <code>force</code> is <code>true</code>, any environments on the
   * stack that create a conflict are killed.
   *
   * @param model the model to nest
   * @param force whether to force the addition of the model
   * @return <code>true</code> if nesting was successful, <code>false</code> otherwise (only
   *     possible if <code>force</code> is <code>false</code>
   */
  public boolean nestEnvironment(LinkedModeModel model, boolean force) {
    Assert.isNotNull(model);

    try {
      while (true) {
        if (fEnvironments.isEmpty()) {
          model.addLinkingListener(fListener);
          fEnvironments.push(model);
          return true;
        }

        LinkedModeModel top = (LinkedModeModel) fEnvironments.peek();
        if (model.canNestInto(top)) {
          model.addLinkingListener(fListener);
          fEnvironments.push(model);
          return true;
        } else if (!force) {
          return false;
        } else { // force
          fEnvironments.pop();
          top.exit(ILinkedModeListener.NONE);
          // continue;
        }
      }
    } finally {
      // if we remove any, make sure the new one got inserted
      Assert.isTrue(fEnvironments.size() > 0);
    }
  }
  private static IEditorPart openInEditor(IEditorInput input, String editorID, boolean activate)
      throws PartInitException {

    UIInstrumentationBuilder instrumentation =
        UIInstrumentation.builder("EditorUtility.openInEditor-IEditorInput");
    try {

      Assert.isNotNull(input);
      Assert.isNotNull(editorID);

      instrumentation.data("Name", input.getName());
      instrumentation.data("EditorID", editorID);
      instrumentation.metric("activate", activate);

      IWorkbenchPage p = DartToolsPlugin.getActivePage();
      if (p == null) {
        throwPartInitException(DartEditorMessages.EditorUtility_no_active_WorkbenchPage);
      }

      IEditorPart editorPart = p.openEditor(input, editorID, activate);
      initializeHighlightRange(editorPart);
      return editorPart;
    } catch (RuntimeException e) {
      instrumentation.metric("Exception", e.getClass().toString());
      instrumentation.data("Exception", e.toString());
      throw e;
    } finally {
      instrumentation.log();
    }
  }
  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 #16
0
  /**
   * @param va
   * @param fw
   * @throws Exception
   * @throws IOException
   */
  public void generate(VelocityAction va, Writer fw) throws Exception, IOException {
    Assert.isNotNull(va.getContext(), "velocity context must be given");
    Assert.isNotNull(va.getTemplatePath(), "velocity template must be given");

    // get Template
    VelocityContext context = va.getContext();
    String templatePath = va.getTemplatePath();
    InputStream template = null;
    File templateFile = new File(templatePath);
    if (templateFile.exists()) {
      // the template is located on File System
      template = new FileInputStream(templateFile);
    } else {
      // resource may be acceded in classPath
      template = getClass().getResourceAsStream(templatePath);
    }

    Assert.isNotNull(template, "velocity template resource can't be loaded");
    // execute
    Velocity.init();
    String s = IOUtils.toString(template);
    Velocity.evaluate(context, fw, "log", s);

    // close streams
    template.close();
    fw.flush();
    fw.close();
  }
 public boolean initialize(EObject xtendMethod, IRenameElementContext context) {
   Assert.isLegal(xtendMethod instanceof XtendFunction);
   Assert.isLegal(((XtendFunction) xtendMethod).isDispatch());
   Assert.isLegal(context instanceof DispatchMethodRenameContext);
   ResourceSet resourceSet = xtendMethod.eResource().getResourceSet();
   Map<URI, IJavaElement> jvm2JavaElements =
       ((DispatchMethodRenameContext) context).getJvm2JavaElements();
   for (URI dispatchOperationURI : jvm2JavaElements.keySet()) {
     JvmOperation dispatchOperation =
         (JvmOperation) resourceSet.getEObject(dispatchOperationURI, true);
     XtendFunction xtendDispatchMethod = associations.getXtendFunction(dispatchOperation);
     if (xtendDispatchMethod != null) {
       if (equal(xtendDispatchMethod.getName(), dispatchOperation.getSimpleName())) {
         // synthetic dispatcher
         dispatchers.add(dispatchOperation);
       } else {
         // xtend dispatch method
         XtendDispatchMethodChildStrategy xtendChildStrategy = childStrategyProvider.get();
         xtendChildStrategy.initialize(xtendDispatchMethod, context);
         children.add(xtendChildStrategy);
       }
     } else {
       // a dispatch method form a Java class
       JavaDispatchMethodChildStrategy jvmChildStrategy = javaStrategyProvider.get();
       jvmChildStrategy.initialize(dispatchOperation, context);
       children.add(jvmChildStrategy);
     }
   }
   return !children.isEmpty();
 }
  /* (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);
  }
  public MethodDeclarationCompletionProposal(
      Type type, String methodName, String returnTypeSig, int start, int length, int relevance) {
    super(
        "",
        type.getCompilationUnit(),
        start,
        length,
        null,
        getDisplayName(methodName, returnTypeSig),
        relevance); //$NON-NLS-1$
    Assert.isNotNull(type);
    Assert.isNotNull(methodName);

    fType = type;
    fMethodName = methodName;
    fReturnTypeSig = returnTypeSig;

    if (returnTypeSig == null) {
      setProposalInfo(new ProposalInfo(type));

      ImageDescriptor desc =
          new DartElementImageDescriptor(
              DartPluginImages.DESC_MISC_PUBLIC,
              DartElementImageDescriptor.CONSTRUCTOR,
              DartElementImageProvider.SMALL_SIZE);
      setImage(DartToolsPlugin.getImageDescriptorRegistry().get(desc));
    } else {
      setImage(DartPluginImages.get(DartPluginImages.IMG_MISC_PRIVATE));
    }
  }
Example #20
0
  /**
   * Constructor.
   *
   * @param model The parent locator model. Must not be <code>null</code>.
   * @param peer The peer. Must not be <code>null</code>.
   */
  public PeerModel(ILocatorModel model, IPeer peer) {
    super();

    Assert.isNotNull(model);
    this.model = model;

    Assert.isNotNull(peer);

    // Set the default properties before enabling the change events.
    // The properties changed listeners should not be called from the
    // constructor.
    setProperty(IPeerModelProperties.PROP_INSTANCE, peer);

    // Initialize the peer id
    peerId = peer.getID();
    Assert.isNotNull(peerId);

    // Peer model nodes can change the node parent at any time
    allowSetParentOnNonNullParent = true;
    // Peer model nodes does not have a parent by default
    //   -> allow change events with null parent
    suppressEventsOnNullParent = false;

    // Enable change events
    setChangeEventsEnabled(true);
  }
Example #21
0
 public AbstractClientService(
     AbstractClientContainer container, RemoteServiceClientRegistration registration) {
   this.container = container;
   Assert.isNotNull(container);
   this.registration = registration;
   Assert.isNotNull(this.registration);
 }
Example #22
0
 /**
  * Constructs a path identifying a leaf node in a tree.
  *
  * @param segments path of elements to a leaf node in a tree, starting with the root element
  */
 public TreePath(Object[] segments) {
   Assert.isNotNull(segments);
   for (int i = 0; i < segments.length; i++) {
     Assert.isNotNull(segments[i]);
   }
   this.segments = segments;
 }
 /**
  * Initialize the filter descriptor from the specified configuration element.
  *
  * @param descriptor The new descriptor to be initialized.
  * @param configuration The configuration element to initialize the filter.
  * @throws CoreException Thrown during parsing.
  */
 void initFilter(FilterDescriptor descriptor, IConfigurationElement configuration)
     throws CoreException {
   String attribute = configuration.getAttribute("name"); // $NON-NLS-1$
   Assert.isNotNull(attribute);
   descriptor.setName(attribute);
   attribute = configuration.getAttribute("description"); // $NON-NLS-1$
   if (attribute != null) {
     descriptor.setDescription(attribute);
   }
   attribute = configuration.getAttribute("image"); // $NON-NLS-1$
   if (attribute != null) {
     String symbolicName = configuration.getContributor().getName();
     URL resource = Platform.getBundle(symbolicName).getResource(attribute);
     Image image = ImageDescriptor.createFromURL(resource).createImage();
     descriptor.setImage(image);
   }
   attribute = configuration.getAttribute("enabled"); // $NON-NLS-1$
   if (attribute != null) {
     descriptor.setEnabled(Boolean.valueOf(attribute).booleanValue());
   }
   attribute = configuration.getAttribute("class"); // $NON-NLS-1$
   Assert.isNotNull(attribute);
   ViewerFilter filter =
       (ViewerFilter) configuration.createExecutableExtension("class"); // $NON-NLS-1$
   Assert.isNotNull(filter);
   descriptor.setFilter(filter);
   attribute = configuration.getAttribute("visibleInUI"); // $NON-NLS-1$
   if (attribute != null) {
     descriptor.setVisible(Boolean.valueOf(attribute).booleanValue());
   }
 }
 public RenameLinkedMode(DartElement element, CompilationUnitEditor editor) {
   Assert.isNotNull(element);
   Assert.isNotNull(editor);
   fEditor = editor;
   fDartElement = element;
   fFocusEditingSupport = new FocusEditingSupport();
 }
  @Override
  public MPart showPart(MPart part, PartState partState) {
    Assert.isNotNull(part);
    Assert.isNotNull(partState);

    MPart addedPart = addPart(part);
    MPlaceholder localPlaceholder = getLocalPlaceholder(addedPart);
    // correct the placeholder setting if necessary
    if (localPlaceholder != null && addedPart.getCurSharedRef() != localPlaceholder) {
      addedPart.setCurSharedRef(localPlaceholder);
    }

    switch (partState) {
      case ACTIVATE:
        activate(addedPart);
        return addedPart;
      case VISIBLE:
        MPart activePart = getActivePart();
        if (activePart == null
            || (activePart != addedPart && getParent(activePart) == getParent(addedPart))) {
          delegateBringToTop(addedPart);
          activate(addedPart);
        } else {
          bringToTop(addedPart);
        }
        return addedPart;
      case CREATE:
        createElement(addedPart);
        return addedPart;
    }
    return addedPart;
  }
  /**
   * Adds the necessary imports for an AST node to the specified compilation unit.
   *
   * @param rewrite the compilation unit rewrite whose compilation unit's imports should be updated
   * @param node the AST node specifying the element for which imports should be added
   * @param typeImports the map of name nodes to strings (element type: Map <Name, String>).
   * @param staticImports the map of name nodes to strings (element type: Map <Name, String>).
   * @param excludeBindings the set of bindings to exclude (element type: Set <IBinding>).
   * @param declarations <code>true</code> if method declarations are treated as abstract, <code>
   *     false</code> otherwise
   */
  public static void addImports(
      final CompilationUnitRewrite rewrite,
      final ASTNode node,
      final Map typeImports,
      final Map staticImports,
      final Collection excludeBindings,
      final boolean declarations) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(node);
    Assert.isNotNull(typeImports);
    Assert.isNotNull(staticImports);
    final Set types = new HashSet();
    final Set members = new HashSet();
    final ImportReferencesCollector collector =
        new ImportReferencesCollector(
            rewrite.getCu().getJavaScriptProject(), null, types, members) {

          public final boolean visit(final Block block) {
            Assert.isNotNull(block);
            if (declarations && block.getParent() instanceof FunctionDeclaration) return false;
            return super.visit(block);
          }
        };
    node.accept(collector);
    final ImportRewrite rewriter = rewrite.getImportRewrite();
    final ImportRemover remover = rewrite.getImportRemover();
    Name name = null;
    IBinding binding = null;
    for (final Iterator iterator = types.iterator(); iterator.hasNext(); ) {
      name = (Name) iterator.next();
      binding = name.resolveBinding();
      if (binding instanceof ITypeBinding) {
        final ITypeBinding type = (ITypeBinding) binding;
        if (excludeBindings == null || !excludeBindings.contains(type)) {
          typeImports.put(name, rewriter.addImport(type));
          remover.registerAddedImport(type.getQualifiedName());
        }
      }
    }
    for (final Iterator iterator = members.iterator(); iterator.hasNext(); ) {
      name = (Name) iterator.next();
      binding = name.resolveBinding();
      if (binding instanceof IVariableBinding) {
        final IVariableBinding variable = (IVariableBinding) binding;
        final ITypeBinding declaring = variable.getDeclaringClass();
        if (declaring != null && (excludeBindings == null || !excludeBindings.contains(variable))) {
          staticImports.put(name, rewriter.addStaticImport(variable));
          remover.registerAddedStaticImport(declaring.getQualifiedName(), variable.getName(), true);
        }
      } else if (binding instanceof IFunctionBinding) {
        final IFunctionBinding method = (IFunctionBinding) binding;
        final ITypeBinding declaring = method.getDeclaringClass();
        if (declaring != null && (excludeBindings == null || !excludeBindings.contains(method))) {
          staticImports.put(name, rewriter.addStaticImport(method));
          remover.registerAddedStaticImport(declaring.getQualifiedName(), method.getName(), false);
        }
      }
    }
  }
Example #27
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 SourceEntityImageDescriptor.
  *
  * @param baseImage an image descriptor used as the base image
  * @param flags flags indicating which adornments are to be rendered. See {@link
  *     #setAdornments(int)} for valid values.
  * @param size the size of the resulting image
  */
 public DecoratedImageDescriptor(ImageDescriptor baseImage, int flags, Point size) {
   fBaseImage = baseImage;
   Assert.isNotNull(fBaseImage);
   fFlags = flags;
   Assert.isTrue(fFlags >= 0);
   fSize = size;
   Assert.isNotNull(fSize);
 }
  public AbstractFeatureChangeFilter(EObject object, EStructuralFeature feature) {

    Assert.isNotNull(object);
    Assert.isNotNull(feature);

    this.object = object;
    this.feature = feature;
  }
 /**
  * constructor.
  *
  * @param containerID the container ID.
  * @param reg the R-OSGi internal service registration.
  */
 public RemoteServiceRegistrationImpl(
     final IRemoteServiceID remoteServiceID, final ServiceRegistration reg) {
   Assert.isNotNull(remoteServiceID);
   Assert.isNotNull(reg);
   this.remoteServiceID = remoteServiceID;
   this.reg = reg;
   this.remoteReference = new LocalRemoteServiceReferenceImpl(remoteServiceID, reg.getReference());
 }