Example #1
1
 public void read(JarPackageData jarPackage) throws CoreException {
   try {
     readXML(jarPackage);
   } catch (IOException ex) {
     String message =
         (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             JavaPlugin.getPluginId(),
             IJavaStatusConstants.INTERNAL_ERROR,
             message,
             ex));
   } catch (SAXException ex) {
     String message =
         (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             JavaPlugin.getPluginId(),
             IJavaStatusConstants.INTERNAL_ERROR,
             message,
             ex));
   }
 }
  /**
   * Read the available profiles from the internal XML file and return them as collection.
   *
   * @return returns a list of <code>CustomProfile</code> or <code>null</code>
   */
  private List<Profile> readOldForCompatibility(IScopeContext instanceScope) {

    // in 3.0 M9 and less the profiles were stored in a file in the plugin's meta data
    final String STORE_FILE = "code_formatter_profiles.xml"; // $NON-NLS-1$

    File file = JavaPlugin.getDefault().getStateLocation().append(STORE_FILE).toFile();
    if (!file.exists()) return null;

    try {
      // note that it's wrong to use a file reader when XML declares UTF-8: Kept for compatibility
      final FileReader reader = new FileReader(file);
      try {
        List<Profile> res = readProfilesFromStream(new InputSource(reader));
        if (res != null) {
          for (int i = 0; i < res.size(); i++) {
            fProfileVersioner.update((CustomProfile) res.get(i));
          }
          writeProfiles(res, instanceScope);
        }
        file.delete(); // remove after successful write
        return res;
      } finally {
        reader.close();
      }
    } catch (CoreException e) {
      JavaPlugin.log(e); // log but ignore
    } catch (IOException e) {
      JavaPlugin.log(e); // log but ignore
    }
    return null;
  }
  public static void checkCurrentOptionsVersion() {
    PreferencesAccess access = PreferencesAccess.getOriginalPreferences();
    ProfileVersioner profileVersioner = new ProfileVersioner();

    IScopeContext instanceScope = access.getInstanceScope();
    IEclipsePreferences uiPreferences = instanceScope.getNode(JavaUI.ID_PLUGIN);
    int version = uiPreferences.getInt(PREF_FORMATTER_PROFILES + VERSION_KEY_SUFFIX, 0);
    if (version >= profileVersioner.getCurrentVersion()) {
      return; // is up to date
    }
    try {
      List<Profile> profiles =
          (new FormatterProfileStore(profileVersioner)).readProfiles(instanceScope);
      if (profiles == null) {
        profiles = new ArrayList<Profile>();
      }
      ProfileManager manager =
          new FormatterProfileManager(profiles, instanceScope, access, profileVersioner);
      if (manager.getSelected() instanceof CustomProfile) {
        manager.commitChanges(instanceScope); // updates JavaCore options
      }
      uiPreferences.putInt(
          PREF_FORMATTER_PROFILES + VERSION_KEY_SUFFIX, profileVersioner.getCurrentVersion());
      savePreferences(instanceScope);
    } catch (CoreException e) {
      JavaPlugin.log(e);
    } catch (BackingStoreException e) {
      JavaPlugin.log(e);
    }
  }
  /*
   * @see IPreferencePage#performOk()
   */
  @Override
  public boolean performOk() {
    IPreferenceStore store = getPreferenceStore();
    for (int i = 0; i < fCheckBoxes.size(); i++) {
      Button button = fCheckBoxes.get(i);
      String key = (String) button.getData();
      store.setValue(key, button.getSelection());
    }
    for (int i = 0; i < fRadioButtons.size(); i++) {
      Button button = fRadioButtons.get(i);
      if (button.getSelection()) {
        String[] info = (String[]) button.getData();
        store.setValue(info[0], info[1]);
      }
    }
    for (int i = 0; i < fTextControls.size(); i++) {
      Text text = fTextControls.get(i);
      String key = (String) text.getData();
      store.setValue(key, text.getText());
    }

    if (fJRECombo != null) {
      store.setValue(CLASSPATH_JRELIBRARY_INDEX, fJRECombo.getSelectionIndex());
    }

    JavaPlugin.flushInstanceScope();
    return super.performOk();
  }
Example #5
0
 private void addFile(Set<IAdaptable> selectedElements, Element element) throws IOException {
   IPath path = getPath(element);
   if (path != null) {
     IFile file = JavaPlugin.getWorkspace().getRoot().getFile(path);
     if (file != null) selectedElements.add(file);
   }
 }
Example #6
0
 private void addFolder(Set<IAdaptable> selectedElements, Element element) throws IOException {
   IPath path = getPath(element);
   if (path != null) {
     IFolder folder = JavaPlugin.getWorkspace().getRoot().getFolder(path);
     if (folder != null) selectedElements.add(folder);
   }
 }
  private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
    if (c.offset == -1 || d.getLength() == 0) return;

    try {
      int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
      int line = d.getLineOfOffset(p);
      int start = d.getLineOffset(line);
      int whiteend = findEndOfWhiteSpace(d, start, c.offset);

      JavaHeuristicScanner scanner = new JavaHeuristicScanner(d);
      JavaIndenter indenter = new JavaIndenter(d, scanner, fProject);

      // shift only when line does not contain any text up to the closing bracket
      if (whiteend == c.offset) {
        // evaluate the line with the opening bracket that matches out closing bracket
        int reference = indenter.findReferencePosition(c.offset, false, true, false, false);
        int indLine = d.getLineOfOffset(reference);
        if (indLine != -1 && indLine != line) {
          // take the indent of the found line
          StringBuffer replaceText = new StringBuffer(getIndentOfLine(d, indLine));
          // add the rest of the current line including the just added close bracket
          replaceText.append(d.get(whiteend, c.offset - whiteend));
          replaceText.append(c.text);
          // modify document command
          c.length += c.offset - start;
          c.offset = start;
          c.text = replaceText.toString();
        }
      }
    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }
Example #8
0
 private void addProject(Set<IAdaptable> selectedElements, Element element) throws IOException {
   String name = element.getAttribute("name"); // $NON-NLS-1$
   if (name.length() == 0)
     throw new IOException(JarPackagerMessages.JarPackageReader_error_tagNameNotFound);
   IProject project = JavaPlugin.getWorkspace().getRoot().getProject(name);
   if (project != null) selectedElements.add(project);
 }
Example #9
0
  private void runOnMultiple(final ICompilationUnit[] cus) {
    ICleanUp[] cleanUps = getCleanUps(cus);
    if (cleanUps == null) return;

    MultiStatus status =
        new MultiStatus(
            JavaUI.ID_PLUGIN, IStatus.OK, ActionMessages.CleanUpAction_MultiStateErrorTitle, null);
    for (int i = 0; i < cus.length; i++) {
      ICompilationUnit cu = cus[i];

      if (!ActionUtil.isOnBuildPath(cu)) {
        String cuLocation = BasicElementLabels.getPathLabel(cu.getPath(), false);
        String message =
            Messages.format(ActionMessages.CleanUpAction_CUNotOnBuildpathMessage, cuLocation);
        status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null));
      }
    }
    if (!status.isOK()) {
      ErrorDialog.openError(getShell(), getActionName(), null, status);
      return;
    }

    try {
      performRefactoring(cus, cleanUps);
    } catch (InvocationTargetException e) {
      JavaPlugin.log(e);
      if (e.getCause() instanceof CoreException) showUnexpectedError((CoreException) e.getCause());
    }
  }
  public NewJavaProjectPreferencePage() {
    super();
    setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
    setDescription(PreferencesMessages.NewJavaProjectPreferencePage_description);

    // title used when opened programatically
    setTitle(PreferencesMessages.NewJavaProjectPreferencePage_title);

    fRadioButtons = new ArrayList<Button>();
    fCheckBoxes = new ArrayList<Button>();
    fTextControls = new ArrayList<Text>();

    fSelectionListener =
        new SelectionListener() {
          public void widgetDefaultSelected(SelectionEvent e) {}

          public void widgetSelected(SelectionEvent e) {
            controlChanged(e.widget);
          }
        };

    fModifyListener =
        new ModifyListener() {
          public void modifyText(ModifyEvent e) {
            controlModified(e.widget);
          }
        };
  }
 private static String encode(String str) {
   try {
     return URLEncoder.encode(str, fgDefaultEncoding);
   } catch (UnsupportedEncodingException e) {
     JavaPlugin.log(e);
   }
   return ""; //$NON-NLS-1$
 }
  private void validateFolders() {
    boolean useFolders = fFoldersAsSourceFolder.getSelection();

    fSrcFolderNameText.setEnabled(useFolders);
    fBinFolderNameText.setEnabled(useFolders);
    fSrcFolderNameLabel.setEnabled(useFolders);
    fBinFolderNameLabel.setEnabled(useFolders);
    if (useFolders) {
      String srcName = fSrcFolderNameText.getText();
      String binName = fBinFolderNameText.getText();
      if (srcName.length() + binName.length() == 0) {
        updateStatus(
            new StatusInfo(
                IStatus.ERROR,
                PreferencesMessages.NewJavaProjectPreferencePage_folders_error_namesempty));
        return;
      }
      IWorkspace workspace = JavaPlugin.getWorkspace();
      IProject dmy = workspace.getRoot().getProject("project"); // $NON-NLS-1$

      IStatus status;
      IPath srcPath = dmy.getFullPath().append(srcName);
      if (srcName.length() != 0) {
        status = workspace.validatePath(srcPath.toString(), IResource.FOLDER);
        if (!status.isOK()) {
          String message =
              Messages.format(
                  PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidsrcname,
                  status.getMessage());
          updateStatus(new StatusInfo(IStatus.ERROR, message));
          return;
        }
      }
      IPath binPath = dmy.getFullPath().append(binName);
      if (binName.length() != 0) {
        status = workspace.validatePath(binPath.toString(), IResource.FOLDER);
        if (!status.isOK()) {
          String message =
              Messages.format(
                  PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidbinname,
                  status.getMessage());
          updateStatus(new StatusInfo(IStatus.ERROR, message));
          return;
        }
      }
      IClasspathEntry entry = JavaCore.newSourceEntry(srcPath);
      status =
          JavaConventions.validateClasspath(
              JavaCore.create(dmy), new IClasspathEntry[] {entry}, binPath);
      if (!status.isOK()) {
        String message = PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidcp;
        updateStatus(new StatusInfo(IStatus.ERROR, message));
        return;
      }
    }
    updateStatus(new StatusInfo()); // set to OK
  }
  private void restoreFromPreferences() {
    String compiledTextHoverModifiers =
        fStore.getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS);

    StringTokenizer tokenizer =
        new StringTokenizer(
            compiledTextHoverModifiers, JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
    HashMap<String, String> idToModifier = new HashMap<String, String>(tokenizer.countTokens() / 2);

    while (tokenizer.hasMoreTokens()) {
      String id = tokenizer.nextToken();
      if (tokenizer.hasMoreTokens()) idToModifier.put(id, tokenizer.nextToken());
    }

    String compiledTextHoverModifierMasks =
        JavaPlugin.getDefault()
            .getPreferenceStore()
            .getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS);

    tokenizer =
        new StringTokenizer(
            compiledTextHoverModifierMasks, JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
    HashMap<String, String> idToModifierMask =
        new HashMap<String, String>(tokenizer.countTokens() / 2);

    while (tokenizer.hasMoreTokens()) {
      String id = tokenizer.nextToken();
      if (tokenizer.hasMoreTokens()) idToModifierMask.put(id, tokenizer.nextToken());
    }

    for (int i = 0; i < fHoverConfigs.length; i++) {
      String modifierString = idToModifier.get(getContributedHovers()[i].getId());
      boolean enabled = true;
      if (modifierString == null) modifierString = JavaEditorTextHoverDescriptor.DISABLED_TAG;

      if (modifierString.startsWith(JavaEditorTextHoverDescriptor.DISABLED_TAG)) {
        enabled = false;
        modifierString = modifierString.substring(1);
      }

      if (modifierString.equals(JavaEditorTextHoverDescriptor.NO_MODIFIER))
        modifierString = ""; // $NON-NLS-1$

      fHoverConfigs[i].fModifierString = modifierString;
      fHoverConfigs[i].fIsEnabled = enabled;
      fHoverConfigs[i].fStateMask = JavaEditorTextHoverDescriptor.computeStateMask(modifierString);

      if (fHoverConfigs[i].fStateMask == -1) {
        try {
          fHoverConfigs[i].fStateMask =
              Integer.parseInt(idToModifierMask.get(getContributedHovers()[i].getId()));
        } catch (NumberFormatException ex) {
          fHoverConfigs[i].fStateMask = -1;
        }
      }
    }
  }
 /*
  * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection)
  */
 @Override
 public void selectionChanged(IStructuredSelection selection) {
   try {
     setEnabled(canEnable(selection));
   } catch (JavaModelException exception) {
     if (JavaModelUtil.isExceptionToBeLogged(exception)) JavaPlugin.log(exception);
     setEnabled(false);
   }
 }
Example #15
0
 /**
  * Reads a Jar Package from the underlying stream. It is the client's responsibility to close the
  * stream.
  *
  * @param inputStream the input stream
  */
 public JarPackageReader(InputStream inputStream) {
   Assert.isNotNull(inputStream);
   fInputStream = new BufferedInputStream(inputStream);
   fWarnings =
       new MultiStatus(
           JavaPlugin.getPluginId(),
           0,
           JarPackagerMessages.JarPackageReader_jarPackageReaderWarnings,
           null);
 }
Example #16
0
 private void xmlReadRefactoring(JarPackageData jarPackage, Element element)
     throws java.io.IOException {
   if (element.getNodeName().equals("storedRefactorings")) { // $NON-NLS-1$
     jarPackage.setExportStructuralOnly(
         getBooleanAttribute(
             element, "structuralOnly", jarPackage.isExportStructuralOnly())); // $NON-NLS-1$
     jarPackage.setDeprecationAware(
         getBooleanAttribute(
             element, "deprecationInfo", jarPackage.isDeprecationAware())); // $NON-NLS-1$
     List<IAdaptable> elements = new ArrayList<IAdaptable>();
     int count = 1;
     String value = element.getAttribute("project" + count); // $NON-NLS-1$
     while (value != null && !"".equals(value)) { // $NON-NLS-1$
       final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(value);
       if (project.exists()) elements.add(project);
       count++;
       value = element.getAttribute("project" + count); // $NON-NLS-1$
     }
     jarPackage.setRefactoringProjects(elements.toArray(new IProject[elements.size()]));
     elements.clear();
     count = 1;
     IRefactoringHistoryService service = RefactoringCore.getHistoryService();
     try {
       service.connect();
       value = element.getAttribute("refactoring" + count); // $NON-NLS-1$
       while (value != null && !"".equals(value)) { // $NON-NLS-1$
         final ByteArrayInputStream stream =
             new ByteArrayInputStream(value.getBytes("UTF-8")); // $NON-NLS-1$
         try {
           final RefactoringHistory history =
               service.readRefactoringHistory(stream, RefactoringDescriptor.NONE);
           if (history != null) {
             final RefactoringDescriptorProxy[] descriptors = history.getDescriptors();
             if (descriptors.length > 0) {
               for (int index = 0; index < descriptors.length; index++) {
                 elements.add(descriptors[index]);
               }
             }
           }
         } catch (CoreException exception) {
           JavaPlugin.log(exception);
         }
         count++;
         value = element.getAttribute("refactoring" + count); // $NON-NLS-1$
       }
     } finally {
       service.disconnect();
     }
     jarPackage.setRefactoringDescriptors(
         elements.toArray(new RefactoringDescriptorProxy[elements.size()]));
   }
 }
 public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encoded) {
   StringTokenizer tok = new StringTokenizer(encoded, " "); // $NON-NLS-1$
   ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
   while (tok.hasMoreTokens()) {
     try {
       tok.nextToken(); // desc: ignore
       int kind = Integer.parseInt(tok.nextToken());
       IPath path = decodePath(tok.nextToken());
       IPath attachPath = decodePath(tok.nextToken());
       IPath attachRoot = decodePath(tok.nextToken());
       boolean isExported = Boolean.valueOf(tok.nextToken()).booleanValue();
       switch (kind) {
         case IClasspathEntry.CPE_SOURCE:
           res.add(JavaCore.newSourceEntry(path));
           break;
         case IClasspathEntry.CPE_LIBRARY:
           res.add(JavaCore.newLibraryEntry(path, attachPath, attachRoot, isExported));
           break;
         case IClasspathEntry.CPE_VARIABLE:
           res.add(JavaCore.newVariableEntry(path, attachPath, attachRoot, isExported));
           break;
         case IClasspathEntry.CPE_PROJECT:
           res.add(JavaCore.newProjectEntry(path, isExported));
           break;
         case IClasspathEntry.CPE_CONTAINER:
           res.add(JavaCore.newContainerEntry(path, isExported));
           break;
       }
     } catch (NumberFormatException e) {
       String message = PreferencesMessages.NewJavaProjectPreferencePage_error_decode;
       JavaPlugin.log(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, e));
     } catch (NoSuchElementException e) {
       String message = PreferencesMessages.NewJavaProjectPreferencePage_error_decode;
       JavaPlugin.log(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, e));
     }
   }
   return res.toArray(new IClasspathEntry[res.size()]);
 }
  /** {@inheritDoc} */
  public void run(IAction action) {
    IWorkbenchPart activePart = JavaPlugin.getActivePage().getActivePart();
    if (!(activePart instanceof CompilationUnitEditor)) return;

    final CompilationUnitEditor editor = (CompilationUnitEditor) activePart;

    new JDTQuickMenuCreator(editor) {
      @Override
      protected void fillMenu(IMenuManager menu) {
        SurroundWithTryCatchAction surroundWithTryCatch = createSurroundWithTryCatchAction(editor);
        SurroundWithTemplateMenuAction.fillMenu(menu, editor, surroundWithTryCatch);
      }
    }.createMenu();
  }
Example #19
0
 private void collectCompilationUnits(Object element, Collection<IJavaElement> result) {
   try {
     if (element instanceof IJavaElement) {
       IJavaElement elem = (IJavaElement) element;
       if (elem.exists()) {
         switch (elem.getElementType()) {
           case IJavaElement.TYPE:
             if (elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) {
               result.add(elem.getParent());
             }
             break;
           case IJavaElement.COMPILATION_UNIT:
             result.add(elem);
             break;
           case IJavaElement.IMPORT_CONTAINER:
             result.add(elem.getParent());
             break;
           case IJavaElement.PACKAGE_FRAGMENT:
             collectCompilationUnits((IPackageFragment) elem, result);
             break;
           case IJavaElement.PACKAGE_FRAGMENT_ROOT:
             collectCompilationUnits((IPackageFragmentRoot) elem, result);
             break;
           case IJavaElement.JAVA_PROJECT:
             IPackageFragmentRoot[] roots = ((IJavaProject) elem).getPackageFragmentRoots();
             for (int k = 0; k < roots.length; k++) {
               collectCompilationUnits(roots[k], result);
             }
             break;
         }
       }
     } else if (element instanceof LogicalPackage) {
       IPackageFragment[] packageFragments = ((LogicalPackage) element).getFragments();
       for (int k = 0; k < packageFragments.length; k++) {
         IPackageFragment pack = packageFragments[k];
         if (pack.exists()) {
           collectCompilationUnits(pack, result);
         }
       }
     } else if (element instanceof IWorkingSet) {
       IWorkingSet workingSet = (IWorkingSet) element;
       IAdaptable[] elements = workingSet.getElements();
       for (int j = 0; j < elements.length; j++) {
         collectCompilationUnits(elements[j], result);
       }
     }
   } catch (JavaModelException e) {
     if (JavaModelUtil.isExceptionToBeLogged(e)) JavaPlugin.log(e);
   }
 }
Example #20
0
  private void run(ICompilationUnit cu) {
    if (!ActionUtil.isEditable(fEditor, getShell(), cu)) return;

    ICleanUp[] cleanUps = getCleanUps(new ICompilationUnit[] {cu});
    if (cleanUps == null) return;

    if (!ElementValidator.check(cu, getShell(), getActionName(), fEditor != null)) return;

    try {
      performRefactoring(new ICompilationUnit[] {cu}, cleanUps);
    } catch (InvocationTargetException e) {
      JavaPlugin.log(e);
      if (e.getCause() instanceof CoreException) showUnexpectedError((CoreException) e.getCause());
    }
  }
  /**
   * The menu to show in the workbench menu
   *
   * @param menu the menu to fill entries into it
   */
  protected void fillMenu(Menu menu) {

    IWorkbenchPart activePart = JavaPlugin.getActivePage().getActivePart();
    if (!(activePart instanceof CompilationUnitEditor)) {
      ActionContributionItem item = new ActionContributionItem(NONE_APPLICABLE_ACTION);
      item.fill(menu, -1);
      return;
    }

    CompilationUnitEditor editor = (CompilationUnitEditor) activePart;
    if (editor.isBreadcrumbActive()) {
      ActionContributionItem item = new ActionContributionItem(NONE_APPLICABLE_ACTION);
      item.fill(menu, -1);
      return;
    }

    IAction[] actions = getTemplateActions(editor);

    boolean addSurroundWith = !isInJavadoc(editor);
    if (addSurroundWith) {
      SurroundWithTryCatchAction surroundAction = createSurroundWithTryCatchAction(editor);
      ActionContributionItem surroundItem = new ActionContributionItem(surroundAction);
      surroundItem.fill(menu, -1);
    }

    boolean hasTemplateActions = actions != null && actions.length > 0;
    if (!hasTemplateActions && !addSurroundWith) {
      ActionContributionItem item = new ActionContributionItem(NONE_APPLICABLE_ACTION);
      item.fill(menu, -1);
    } else if (hasTemplateActions) {
      if (addSurroundWith) {
        Separator templateGroup = new Separator(TEMPLATE_GROUP);
        templateGroup.fill(menu, -1);
      }

      for (int i = 0; i < actions.length; i++) {
        ActionContributionItem item = new ActionContributionItem(actions[i]);
        item.fill(menu, -1);
      }
    }

    Separator configGroup = new Separator(CONFIG_GROUP);
    configGroup.fill(menu, -1);

    ActionContributionItem configAction =
        new ActionContributionItem(new ConfigureTemplatesAction());
    configAction.fill(menu, -1);
  }
 private boolean computeSmartMode() {
   IWorkbenchPage page = JavaPlugin.getActivePage();
   if (page != null) {
     IEditorPart part = page.getActiveEditor();
     if (part instanceof ITextEditorExtension3) {
       ITextEditorExtension3 extension = (ITextEditorExtension3) part;
       return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
     } else if (part != null && EditorUtility.isCompareEditorInput(part.getEditorInput())) {
       ITextEditorExtension3 extension =
           (ITextEditorExtension3) part.getAdapter(ITextEditorExtension3.class);
       if (extension != null)
         return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
     }
   }
   return false;
 }
Example #23
0
 /**
  * Closes this stream. It is the clients responsibility to close the stream.
  *
  * @exception CoreException if closing the stream fails
  */
 public void close() throws CoreException {
   if (fInputStream != null)
     try {
       fInputStream.close();
     } catch (IOException ex) {
       String message =
           (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$
       throw new CoreException(
           new Status(
               IStatus.ERROR,
               JavaPlugin.getPluginId(),
               IJavaStatusConstants.INTERNAL_ERROR,
               message,
               ex));
     }
 }
  private String getIndentMode() {
    String indentMode =
        JavaPlugin.getDefault()
            .getCombinedPreferenceStore()
            .getString(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);

    if (JavaCore.SPACE.equals(indentMode))
      return PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_spaces;

    if (JavaCore.TAB.equals(indentMode))
      return PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tabs;

    if (DefaultCodeFormatterConstants.MIXED.equals(indentMode))
      return PreferencesMessages.SmartTypingConfigurationBlock_tabs_message_tabsAndSpaces;

    Assert.isTrue(false, "Illegal indent mode - must not happen"); // $NON-NLS-1$
    return null;
  }
  /**
   * Remembers the selection of a right hand side type (proposal type) for a certain left hand side
   * (expected type) in content assist.
   *
   * @param lhs the left hand side / expected type
   * @param rhs the selected right hand side
   */
  public void remember(IType lhs, IType rhs) {
    Assert.isLegal(lhs != null);
    Assert.isLegal(rhs != null);

    try {
      if (!isCacheableRHS(rhs)) return;
      ITypeHierarchy hierarchy = rhs.newSupertypeHierarchy(getProgressMonitor());
      if (hierarchy.contains(lhs)) {
        // TODO remember for every member of the LHS hierarchy or not? Yes for now.
        IType[] allLHSides = hierarchy.getAllSupertypes(lhs);
        String rhsQualifiedName = rhs.getFullyQualifiedName();
        for (int i = 0; i < allLHSides.length; i++)
          rememberInternal(allLHSides[i], rhsQualifiedName);
        rememberInternal(lhs, rhsQualifiedName);
      }
    } catch (JavaModelException x) {
      JavaPlugin.log(x);
    }
  }
  public static IClasspathEntry[] getDefaultJRELibrary() {
    IPreferenceStore store = JavaPlugin.getDefault().getPreferenceStore();

    String str = store.getString(CLASSPATH_JRELIBRARY_LIST);
    int index = store.getInt(CLASSPATH_JRELIBRARY_INDEX);

    StringTokenizer tok = new StringTokenizer(str, ";"); // $NON-NLS-1$
    while (tok.hasMoreTokens() && index > 0) {
      tok.nextToken();
      index--;
    }

    if (tok.hasMoreTokens()) {
      IClasspathEntry[] res = decodeJRELibraryClasspathEntries(tok.nextToken());
      if (res.length > 0) {
        return res;
      }
    }
    return new IClasspathEntry[] {getJREContainerEntry()};
  }
  private static IAction[] getTemplateActions(JavaEditor editor) {
    ITextSelection textSelection = getTextSelection(editor);
    if (textSelection == null || textSelection.getLength() == 0) return null;

    ICompilationUnit cu = JavaUI.getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
    if (cu == null) return null;

    QuickTemplateProcessor quickTemplateProcessor = new QuickTemplateProcessor();
    IInvocationContext context =
        new AssistContext(cu, textSelection.getOffset(), textSelection.getLength());

    try {
      IJavaCompletionProposal[] proposals = quickTemplateProcessor.getAssists(context, null);
      if (proposals == null || proposals.length == 0) return null;

      return getActionsFromProposals(proposals, context.getSelectionOffset(), editor.getViewer());
    } catch (CoreException e) {
      JavaPlugin.log(e);
    }
    return null;
  }
Example #28
0
 private boolean isEnabled(IStructuredSelection selection) {
   Object[] selected = selection.toArray();
   for (int i = 0; i < selected.length; i++) {
     try {
       if (selected[i] instanceof IJavaElement) {
         IJavaElement elem = (IJavaElement) selected[i];
         if (elem.exists()) {
           switch (elem.getElementType()) {
             case IJavaElement.TYPE:
               return elem.getParent().getElementType()
                   == IJavaElement.COMPILATION_UNIT; // for browsing perspective
             case IJavaElement.COMPILATION_UNIT:
               return true;
             case IJavaElement.IMPORT_CONTAINER:
               return true;
             case IJavaElement.PACKAGE_FRAGMENT:
             case IJavaElement.PACKAGE_FRAGMENT_ROOT:
               IPackageFragmentRoot root =
                   (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
               return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
             case IJavaElement.JAVA_PROJECT:
               // https://bugs.eclipse.org/bugs/show_bug.cgi?id=65638
               return true;
           }
         }
       } else if (selected[i] instanceof LogicalPackage) {
         return true;
       } else if (selected[i] instanceof IWorkingSet) {
         IWorkingSet workingSet = (IWorkingSet) selected[i];
         return IWorkingSetIDs.JAVA.equals(workingSet.getId());
       }
     } catch (JavaModelException e) {
       if (!e.isDoesNotExist()) {
         JavaPlugin.log(e);
       }
     }
   }
   return false;
 }
  public void performOk() {
    StringBuffer buf = new StringBuffer();
    StringBuffer maskBuf = new StringBuffer();
    for (int i = 0; i < fHoverConfigs.length; i++) {
      buf.append(getContributedHovers()[i].getId());
      buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
      if (!fHoverConfigs[i].fIsEnabled) buf.append(JavaEditorTextHoverDescriptor.DISABLED_TAG);
      String modifier = fHoverConfigs[i].fModifierString;
      if (modifier == null || modifier.length() == 0)
        modifier = JavaEditorTextHoverDescriptor.NO_MODIFIER;
      buf.append(modifier);
      buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);

      maskBuf.append(getContributedHovers()[i].getId());
      maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
      maskBuf.append(fHoverConfigs[i].fStateMask);
      maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR);
    }
    fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, buf.toString());
    fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, maskBuf.toString());

    JavaPlugin.getDefault().resetJavaEditorTextHoverDescriptors();
  }
  private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
    if (c.offset < 1 || d.getLength() == 0) return;

    JavaHeuristicScanner scanner = new JavaHeuristicScanner(d);

    int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);

    try {
      // current line
      int line = d.getLineOfOffset(p);
      int lineOffset = d.getLineOffset(line);

      // make sure we don't have any leading comments etc.
      if (d.get(lineOffset, p - lineOffset).trim().length() != 0) return;

      // line of last Java code
      int pos = scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND);
      if (pos == -1) return;
      int lastLine = d.getLineOfOffset(pos);

      // only shift if the last java line is further up and is a braceless block candidate
      if (lastLine < line) {

        JavaIndenter indenter = new JavaIndenter(d, scanner, fProject);
        StringBuffer indent = indenter.computeIndentation(p, true);
        String toDelete = d.get(lineOffset, c.offset - lineOffset);
        if (indent != null && !indent.toString().equals(toDelete)) {
          c.text = indent.append(c.text).toString();
          c.length += c.offset - lineOffset;
          c.offset = lineOffset;
        }
      }

    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }