@Override
  public boolean matches(IEditorReference editorRef, IEditorInput input) {
    IQ7Element inputElement = getElement(input);
    if (inputElement != null && editorRef.getId().startsWith("org.eclipse.rcptt.ui.editors")) {
      IWorkbenchPart part = editorRef.getPart(false);
      if (part instanceof EclEditor) {
        IQ7NamedElement model = ((EclEditor) part).getModel();
        if (model != null) {
          return inputElement.equals(model);
        }
      } else if (part instanceof NamedElementEditor) {
        IQ7NamedElement model = ((NamedElementEditor) part).getModel();
        if (model != null) {
          return inputElement.equals(model);
        }
      }

      // try figure out using ref editor input
      IEditorInput editRefInput;
      try {
        editRefInput = editorRef.getEditorInput();
        if (editRefInput != null) {
          IQ7Element refElement = getElement(editRefInput);
          return inputElement.equals(refElement);
        }
      } catch (PartInitException e) {
        RcpttPlugin.log(e.getMessage(), e);
      }
    }
    return false;
  }
  private static void getOpenTabs(IWorkbenchWindow window) {
    openTabs.clear();
    WorkbenchPage activePage = (WorkbenchPage) window.getActivePage();
    IEditorReference[] editorRefs = ((WorkbenchPage) activePage).getSortedEditors();

    // WorkbenchPage.getSortedEditors() returns the editors in activation order (oldest
    // first). We want most recently activated to be first, so reverse the list.
    List<IEditorReference> editorRefsAsList = Arrays.asList(editorRefs);
    Collections.reverse(editorRefsAsList);

    try {
      for (IEditorReference ref : editorRefsAsList) {
        if (ref.getEditorInput() instanceof FileEditorInput) {
          IFile file = ((FileEditorInput) ref.getEditorInput()).getFile();
          IJavaElement editorElt = JavaCore.create(file);
          if (editorElt instanceof ICompilationUnit) {
            openTabs.addAll(Arrays.asList(((ICompilationUnit) editorElt).getAllTypes()));
          }
        }
      }
    } catch (PartInitException e) {
      System.out.print("Exception while getting all open tabs. " + e.getMessage());
      e.printStackTrace();
    } catch (JavaModelException e) {
      System.out.print("Exception while getting all open tabs. " + e.getMessage());
      e.printStackTrace();
    }
  }
 /** @generated */
 private static boolean openEditor(IWorkbench workbench, URI fileURI) {
   IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
   IWorkbenchPage page = workbenchWindow.getActivePage();
   IEditorDescriptor editorDescriptor =
       workbench.getEditorRegistry().getDefaultEditor(fileURI.toFileString());
   if (editorDescriptor == null) {
     MessageDialog.openError(
         workbenchWindow.getShell(),
         Messages.DiagramEditorActionBarAdvisor_DefaultFileEditorTitle,
         NLS.bind(
             Messages.DiagramEditorActionBarAdvisor_DefaultFileEditorMessage,
             fileURI.toFileString()));
     return false;
   } else {
     try {
       page.openEditor(new URIEditorInput(fileURI), editorDescriptor.getId());
     } catch (PartInitException exception) {
       MessageDialog.openError(
           workbenchWindow.getShell(),
           Messages.DiagramEditorActionBarAdvisor_DefaultEditorOpenErrorTitle,
           exception.getMessage());
       return false;
     }
   }
   return true;
 }
  @Override
  public void run(IAction action) {
    UserDBDAO userDB = (UserDBDAO) sel.getFirstElement();

    if (DBDefine.getDBDefine(userDB) == DBDefine.MYSQL_DEFAULT
        || DBDefine.getDBDefine(userDB) == DBDefine.MARIADB_DEFAULT
        || DBDefine.getDBDefine(userDB) == DBDefine.ORACLE_DEFAULT
        || DBDefine.getDBDefine(userDB) == DBDefine.MSSQL_DEFAULT) {

      try {
        SessionListEditorInput sleInput = new SessionListEditorInput(userDB);
        PlatformUI.getWorkbench()
            .getActiveWorkbenchWindow()
            .getActivePage()
            .openEditor(sleInput, SessionListEditor.ID);
      } catch (PartInitException e) {
        logger.error("open session list", e); // $NON-NLS-1$

        Status errStatus =
            new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); // $NON-NLS-1$
        ExceptionDetailsErrorDialog.openError(
            null, "Error", Messages.AbstractQueryAction_1, errStatus); // $NON-NLS-1$
      }
    } else {
      MessageDialog.openWarning(null, "Information", "Not support database.");
    }
  }
Exemplo n.º 5
0
 /**
  * Open commit in editor
  *
  * @param commit
  * @param activateOnOpen <code>true</code> if the newly opened editor should be activated
  * @return opened editor part or null if opening fails
  * @since 2.1
  */
 public static final IEditorPart openQuiet(RepositoryCommit commit, boolean activateOnOpen) {
   try {
     return open(commit, activateOnOpen);
   } catch (PartInitException e) {
     Activator.logError(e.getMessage(), e);
     return null;
   }
 }
 @Override
 public void run() {
   IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
   Assert.isNotNull(window);
   Shell shell = window.getShell();
   if (status.getSeverity() == IStatus.ERROR) {
     MessageDialog.openError(shell, "文件转换失败", status.getMessage());
   } else {
     // 转换完成后直接打开编辑器,不再进行弹框提示。
     // MessageDialog.openInformation(shell, "文件转换完成", status.getMessage());
     final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor";
     String xliffFile = conversionResult.get(Converter.ATTR_XLIFF_FILE);
     IWorkbenchPage page = window.getActivePage();
     Assert.isNotNull(page, "当前的 Active Page 为 null。无法打开转换后的文件。");
     if (xliffFile != null) {
       IEditorDescriptor editorDescriptor =
           PlatformUI.getWorkbench().getEditorRegistry().findEditor(XLIFF_EDITOR_ID);
       if (editorDescriptor != null) {
         try {
           IDE.openEditor(page, new File(xliffFile).toURI(), XLIFF_EDITOR_ID, true);
         } catch (PartInitException e) {
           MessageDialog.openInformation(
               shell, "提示", "转换完成!但是在尝试打开该 XLIFF 文件时发生异常:\n" + e.getMessage());
           e.printStackTrace();
         }
       }
     } else {
       String targetFile = conversionResult.get(Converter.ATTR_TARGET_FILE);
       if (targetFile == null) {
         MessageDialog.openError(shell, "错误", "为找到已转换文件的路径!");
       } else {
         IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
         IFile input = root.getFileForLocation(new Path(targetFile));
         try {
           // 使用外部编辑器(系统默认编辑器)打开文件。
           IDE.openEditor(page, input, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
         } catch (PartInitException e) {
           MessageDialog.openInformation(
               shell, "提示", "转换完成!但是在尝试使用系统默认程序打开该文件时发生异常:\n" + e.getMessage());
           e.printStackTrace();
         }
       }
     }
   }
 }
Exemplo n.º 7
0
 public void run() {
   if (window != null) {
     try {
       window
           .getActivePage()
           .showView(viewId, Integer.toString(instanceNum++), IWorkbenchPage.VIEW_ACTIVATE);
     } catch (PartInitException e) {
       MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e.getMessage());
     }
   }
 }
Exemplo n.º 8
0
 public static void show() {
   IWorkbench wb = PlatformUI.getWorkbench();
   IWorkbenchPage wbPage = wb.getActiveWorkbenchWindow().getActivePage();
   if (wbPage != null) {
     try {
       IConsoleView conView = (IConsoleView) wbPage.showView(IConsoleConstants.ID_CONSOLE_VIEW);
       conView.display(getRhinoConsole());
     } catch (PartInitException e) {
       PluginLogger.log("Console.show() - PartInitException: " + e.getMessage());
     }
   }
 }
 @Override
 public Object execute(ExecutionEvent event) throws ExecutionException {
   try {
     PlatformUI.getWorkbench()
         .getActiveWorkbenchWindow()
         .getActivePage()
         .showView("com.sap.dirigible.ide.publish.ui.view.RuntimeViewerView"); // $NON-NLS-1$
   } catch (PartInitException e) {
     logger.error(e.getMessage(), e);
   }
   return null;
 }
Exemplo n.º 10
0
  /**
   * Test method for {@link
   * org.talend.dataprofiler.core.CorePlugin#itemIsOpening(org.talend.core.model.properties.Item,
   * boolean)}.
   */
  @Test
  public void testItemIsOpeningItemBoolean() {
    try {
      CorePlugin cpMock = mock(CorePlugin.class);
      PowerMockito.mockStatic(CorePlugin.class);
      when(CorePlugin.getDefault()).thenReturn(cpMock);

      IWorkbench workbenchMock = mock(IWorkbench.class);
      when(cpMock.getWorkbench()).thenReturn(workbenchMock);

      IWorkbenchWindow workbenchWindowMock = mock(IWorkbenchWindow.class);
      when(workbenchMock.getActiveWorkbenchWindow()).thenReturn(workbenchWindowMock);

      IWorkbenchPage workbenchPageMock = mock(IWorkbenchPage.class);
      when(workbenchWindowMock.getActivePage()).thenReturn(workbenchPageMock);

      IEditorReference editorRefMock = mock(IEditorReference.class);
      IEditorReference[] editorRefMocks = new IEditorReference[] {editorRefMock};
      when(workbenchPageMock.getEditorReferences()).thenReturn(editorRefMocks);

      FileEditorInput fileEditorInputMock = mock(FileEditorInput.class);
      when(editorRefMock.getEditorInput()).thenReturn(fileEditorInputMock);

      String path1 = "/abc1"; // $NON-NLS-1$
      String path2 = "/abc2"; // $NON-NLS-1$

      IFile inputFileMock = mock(IFile.class);
      when(fileEditorInputMock.getFile()).thenReturn(inputFileMock);

      IPath inputFilePathMock = mock(IPath.class);
      when(inputFileMock.getFullPath()).thenReturn(inputFilePathMock);

      when(inputFilePathMock.toString()).thenReturn(path1);

      Item itemMock = mock(Item.class);
      Property propertyMock = mock(Property.class);
      when(itemMock.getProperty()).thenReturn(propertyMock);

      Resource resourceMock = mock(Resource.class);
      when(propertyMock.eResource()).thenReturn(resourceMock);

      IPath ipathMock = mock(IPath.class);
      PowerMockito.mockStatic(PropertyHelper.class);
      when(PropertyHelper.getItemPath(propertyMock)).thenReturn(ipathMock);
      when(ipathMock.toString()).thenReturn(path2);

      CorePlugin cp = new CorePlugin();
      assertFalse(cp.itemIsOpening(itemMock, false));
    } catch (PartInitException e) {
      fail(e.getMessage());
    }
  }
Exemplo n.º 11
0
 /**
  * Display the evaluation result
  *
  * @param result An {@link IWatchExpressionResult}.
  */
 protected void displayResult(IWatchExpressionResult result) {
   IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
   if (activeWorkbenchWindow != null) {
     IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
     if (activePage != null) {
       try {
         activePage.showView(IDebugUIConstants.ID_EXPRESSION_VIEW);
       } catch (PartInitException e) {
         PHPDebugEPLPlugin.logError(e.getMessage(), e);
       }
     }
   }
 }
Exemplo n.º 12
0
 public void run() {
   if (win != null) {
     try {
       DiskUsageView view =
           (DiskUsageView)
               win.getActivePage()
                   .showView(DiskUsageView.ID, "" + objHash, IWorkbenchPage.VIEW_ACTIVATE);
       if (view != null) view.setInput(serverId, objHash);
     } catch (PartInitException e) {
       MessageDialog.openError(win.getShell(), "Error", "Error opening view:" + e.getMessage());
     }
   }
 }
  public Object execute(ExecutionEvent event) throws ExecutionException {
    final Repository repository = getRepository(true, event);
    // assert all resources map to the same repository
    if (repository == null) return null;
    final IResource[] resources = getSelectedResources(event);

    if (resources.length == 1 && resources[0] instanceof IFile) {
      final IFile baseFile = (IFile) resources[0];
      final String gitPath =
          RepositoryMapping.getMapping(baseFile.getProject()).getRepoRelativePath(baseFile);
      final ITypedElement base = SaveableCompareEditorInput.createFileElement(baseFile);

      ITypedElement next;
      try {
        Ref head = repository.getRef(Constants.HEAD);
        RevWalk rw = new RevWalk(repository);
        RevCommit commit = rw.parseCommit(head.getObjectId());

        next = CompareUtils.getFileRevisionTypedElement(gitPath, commit, repository);
      } catch (IOException e) {
        Activator.handleError(e.getMessage(), e, true);
        return null;
      }

      final GitCompareFileRevisionEditorInput in =
          new GitCompareFileRevisionEditorInput(base, next, null);
      CompareUI.openCompareEditor(in);
      return null;

    } else {
      CompareTreeView view;
      try {
        view =
            (CompareTreeView)
                PlatformUI.getWorkbench()
                    .getActiveWorkbenchWindow()
                    .getActivePage()
                    .showView(CompareTreeView.ID);
        try {
          view.setInput(resources, repository.resolve(Constants.HEAD).name());
        } catch (IOException e) {
          Activator.handleError(e.getMessage(), e, true);
          return null;
        }
      } catch (PartInitException e) {
        Activator.handleError(e.getMessage(), e, true);
        return null;
      }
      return null;
    }
  }
  /**
   * 디비의 화면을 오픈합니다.
   *
   * @param userDB
   */
  public void run(UserDBDAO userDB) {

    // mongodb인지 검사하여..
    if (userDB.getDBDefine() != DBDefine.MONGODB_DEFAULT) {
      MainEditorInput mei = new MainEditorInput(userDB);

      try {
        PlatformUI.getWorkbench()
            .getActiveWorkbenchWindow()
            .getActivePage()
            .openEditor(mei, MainEditor.ID);
      } catch (PartInitException e) {
        logger.error("open editor", e); // $NON-NLS-1$

        Status errStatus =
            new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); // $NON-NLS-1$
        ExceptionDetailsErrorDialog.openError(
            null, "Error", Messages.AbstractQueryAction_1, errStatus); // $NON-NLS-1$
      }
    } else if (userDB.getDBDefine() == DBDefine.MONGODB_DEFAULT) {
      MongoDBInfosInput mongoInput =
          new MongoDBInfosInput(userDB, MongoDBInfosEditor.PAGES.COLLECTION_SUMMERY);
      try {
        PlatformUI.getWorkbench()
            .getActiveWorkbenchWindow()
            .getActivePage()
            .openEditor(mongoInput, MongoDBInfosEditor.ID);
      } catch (PartInitException e) {
        logger.error("open editor", e); // $NON-NLS-1$

        Status errStatus =
            new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); // $NON-NLS-1$
        ExceptionDetailsErrorDialog.openError(
            null, "Error", Messages.AbstractQueryAction_1, errStatus); // $NON-NLS-1$
      }
    }
  }
  @Override
  public void run(IAction action) {
    UserDBDAO userDB = (UserDBDAO) sel.getFirstElement();

    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    try {
      ProfilingEditorInput input = new ProfilingEditorInput(userDB);
      page.openEditor(input, ProfilingEditor.ID, false);

    } catch (PartInitException e) {
      logger.error("Mongodb profilling", e);

      Status errStatus =
          new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); // $NON-NLS-1$
      ExceptionDetailsErrorDialog.openError(
          null, "Error", "Profilling Exception", errStatus); // $NON-NLS-1$
    }
  }
Exemplo n.º 16
0
  @Override
  public void linkActivated(HyperlinkEvent event) {
    try {
      String target = (String) event.getHref();

      if ("action:open".equals(target)) // $NON-NLS-1$
      {
        IHandlerService handlerService =
            (IHandlerService) getIntroSite().getService(IHandlerService.class);
        Object result =
            handlerService.executeCommand(
                "name.abuchen.portfolio.ui.commands.openFileCommand", null); // $NON-NLS-1$
        if (result != null) PlatformUI.getWorkbench().getIntroManager().closeIntro(this);
      } else if ("action:new".equals(target)) // $NON-NLS-1$
      {
        IHandlerService handlerService =
            (IHandlerService) getIntroSite().getService(IHandlerService.class);
        handlerService.executeCommand(
            "name.abuchen.portfolio.ui.commands.newFileCommand", null); // $NON-NLS-1$
        PlatformUI.getWorkbench().getIntroManager().closeIntro(this);
      } else if ("action:sample".equals(target)) // $NON-NLS-1$
      {
        openSample("kommer.xml"); // $NON-NLS-1$
      } else if ("action:daxsample".equals(target)) // $NON-NLS-1$
      {
        openSample("dax.xml"); // $NON-NLS-1$
      } else if (target.startsWith("http://")) // $NON-NLS-1$
      {
        IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
        IWebBrowser browser = support.getExternalBrowser();
        browser.openURL(new URL(target));
      }

    } catch (CommandException e) {
      PortfolioPlugin.log(e);
      MessageDialog.openError(getIntroSite().getShell(), Messages.LabelError, e.getMessage());
    } catch (PartInitException e) {
      PortfolioPlugin.log(e);
      MessageDialog.openError(getIntroSite().getShell(), Messages.LabelError, e.getMessage());
    } catch (MalformedURLException e) {
      PortfolioPlugin.log(e);
      MessageDialog.openError(getIntroSite().getShell(), Messages.LabelError, e.getMessage());
    }
  }
Exemplo n.º 17
0
 public static IEditorPart openFileInEditor(IFile input, String id) {
   if (input != null && input.exists()) {
     try {
       if (id == null) {
         IWorkbenchPage page =
             PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
         return IDE.openEditor(page, input, true);
       } else {
         IWorkbenchPage page =
             PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
         return IDE.openEditor(page, input, id, true);
       }
     } catch (PartInitException pie) {
       pie.printStackTrace();
       fail(pie.getMessage());
     }
   }
   return null;
 }
  /**
   * 트리를 갱신하고 쿼리 창을 엽니다.
   *
   * @param dto
   */
  public void selectAndOpenView(UserDBDAO dto) {
    treeViewer.refresh();
    treeViewer.setSelection(new StructuredSelection(dto), true);

    // mongodb 일경우 열지 않는다.
    if (DBDefine.getDBDefine(dto) != DBDefine.MONGODB_DEFAULT) {
      MainEditorInput mei = new MainEditorInput(dto);
      IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
      try {
        page.openEditor(mei, MainEditor.ID);
      } catch (PartInitException e) {
        logger.error("main editor open", e); // $NON-NLS-1$

        Status errStatus =
            new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); // $NON-NLS-1$
        ExceptionDetailsErrorDialog.openError(
            getSite().getShell(), "Error", "Can't open resource. ", errStatus); // $NON-NLS-1$
      }
    }
  }
Exemplo n.º 19
0
  @Override
  public boolean performFinish() {
    if (super.performFinish()) {
      IFile genModelFile = getFile(getModelImporter().getGenModelPath());
      if (getModelImporter().getOriginalGenModelPath() == null) {
        selectFile(genModelFile);
      }

      try {
        openEditor(genModelFile);
      } catch (PartInitException partInitException) {
        MessageDialog.openError(
            getShell(),
            ImporterPlugin.INSTANCE.getString("_UI_OpenEditor_title"),
            partInitException.getMessage());
        return false;
      }

      return true;
    } else {
      return false;
    }
  }
 /** @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */
 public void run(IAction action) {
   ShellView shellView = null;
   if (!ShellViewUtil.isTargetAvailable()) {
     // No ShellView available
     if (MessageDialogHandler.openConfirmationMessage(
         targetPart.getSite().getShell(),
         "There is no Shell available, do you want to open a new one?")) {
       try {
         shellView = (ShellView) targetPart.getSite().getPage().showView(ShellID.SHELL_VIEW_ID);
       } catch (PartInitException exception) {
         shellLogger.error(exception.getMessage(), exception);
       }
     }
   } else {
     shellView = ShellViewUtil.selectTargetFromAvailable("Change To Folder", true);
   }
   if (shellView != null) {
     IShellDescriptor shellDescriptor =
         shellView.getShellViewer().getShellFacade().getShellDescriptor();
     ICommandProvider commandProvider = shellDescriptor.getCommandProvider();
     File file;
     if (currentResource.getLocation().toFile().isDirectory()) {
       file = new File(currentResource.getLocation().toOSString());
     } else {
       file = new File(currentResource.getLocation().toOSString()).getParentFile();
     }
     String changeDirectoryCommand =
         commandProvider.getChangeDirectoryCommand(shellDescriptor, file);
     shellView.getShellViewer().getShellFacade().executeCommand(changeDirectoryCommand);
     shellView.setFocus();
   } else {
     MessageDialogHandler.openInformationMessage(
         targetPart.getSite().getShell(),
         "No Shell was selected. Please choose one to change to the selected folder.");
   }
 }
Exemplo n.º 21
0
  /*
   * (non-Javadoc) Method declared on IWizard.
   */
  public boolean performFinish() {
    IFile file = mainPage.createNewFile();
    if (file == null) {
      return false;
    }

    selectAndReveal(file);

    // Open editor on new file.
    IWorkbenchWindow dw = getWorkbench().getActiveWorkbenchWindow();
    try {
      if (dw != null) {
        IWorkbenchPage page = dw.getActivePage();
        if (page != null) {
          IDE.openEditor(page, file, true);
        }
      }
    } catch (PartInitException e) {
      DialogUtil.openError(
          dw.getShell(), ResourceMessages.FileResource_errorMessage, e.getMessage(), e);
    }

    return true;
  }
Exemplo n.º 22
0
  /**
   *
   * <!-- begin-user-doc -->
   * <!-- end-user-doc -->
   *
   * @generated
   */
  public static boolean openEditor(IWorkbench workbench, URI uri) {
    IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
    IWorkbenchPage page = workbenchWindow.getActivePage();

    IEditorDescriptor editorDescriptor = EditUIUtil.getDefaultEditor(uri, null);
    if (editorDescriptor == null) {
      MessageDialog.openError(
          workbenchWindow.getShell(),
          getString("_UI_Error_title"),
          getString("_WARN_No_Editor", uri.lastSegment()));
      return false;
    } else {
      try {
        page.openEditor(new URIEditorInput(uri), editorDescriptor.getId());
      } catch (PartInitException exception) {
        MessageDialog.openError(
            workbenchWindow.getShell(),
            getString("_UI_OpenEditorError_label"),
            exception.getMessage());
        return false;
      }
    }
    return true;
  }
  protected void performUIAfterNetExecute() {
    ResourceExplorerView resourceExplorerView = (ResourceExplorerView) super.view;
    TreeViewer treeViewer = resourceExplorerView.getTreeViewer();
    IEditorInput resourceEditorInput = resourceExplorerView.getResourceEditorInput();
    String editor_id = resourceExplorerView.getEDITOR_ID();

    if (this.items.size() == 0) {
      boolean expandedState = !treeViewer.getExpandedState(product);
      treeViewer.setExpandedState(product, expandedState);
    } else {
      IWorkbenchPage page = window.getActivePage();
      IEditorPart editorPart = page.findEditor(resourceEditorInput);
      if (editorPart != null) {
        page.closeEditor(editorPart, false);
      }
      try {
        editorPart = page.openEditor(resourceEditorInput, editor_id);
        ResourceEditor resourceEditor = (ResourceEditor) editorPart;
        resourceEditor.showResourceFromProduct(items);
      } catch (PartInitException e) {
        MessageDialog.openError(window.getShell(), "Open resource editor error.", e.getMessage());
      }
    }
  }
Exemplo n.º 24
0
  /**
   * Do the work after everything is specified.
   * <!-- begin-user-doc -->
   * <!-- end-user-doc -->
   *
   * @generated
   */
  @Override
  public boolean performFinish() {
    try {
      // Remember the file.
      //
      final IFile modelFile = getModelFile();

      // Do the work within an operation.
      //
      WorkspaceModifyOperation operation =
          new WorkspaceModifyOperation() {
            @Override
            protected void execute(IProgressMonitor progressMonitor) {
              try {
                // Create a resource set
                //
                ResourceSet resourceSet = new ResourceSetImpl();

                // Get the URI of the model file.
                //
                URI fileURI =
                    URI.createPlatformResourceURI(modelFile.getFullPath().toString(), true);

                // Create a resource for this file.
                //
                Resource resource = resourceSet.createResource(fileURI);

                // Add the initial model object to the contents.
                //
                EObject rootObject = createInitialModel();
                if (rootObject != null) {
                  resource.getContents().add(rootObject);
                }

                // Save the contents of the resource to the file system.
                //
                Map<Object, Object> options = new HashMap<Object, Object>();
                options.put(XMLResource.OPTION_ENCODING, initialObjectCreationPage.getEncoding());
                resource.save(options);
              } catch (Exception exception) {
                WebPageEditorPlugin.INSTANCE.log(exception);
              } finally {
                progressMonitor.done();
              }
            }
          };

      getContainer().run(false, false, operation);

      // Select the new file resource in the current view.
      //
      IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
      IWorkbenchPage page = workbenchWindow.getActivePage();
      final IWorkbenchPart activePart = page.getActivePart();
      if (activePart instanceof ISetSelectionTarget) {
        final ISelection targetSelection = new StructuredSelection(modelFile);
        getShell()
            .getDisplay()
            .asyncExec(
                new Runnable() {
                  public void run() {
                    ((ISetSelectionTarget) activePart).selectReveal(targetSelection);
                  }
                });
      }

      // Open an editor on the new file.
      //
      try {
        page.openEditor(
            new FileEditorInput(modelFile),
            workbench
                .getEditorRegistry()
                .getDefaultEditor(modelFile.getFullPath().toString())
                .getId());
      } catch (PartInitException exception) {
        MessageDialog.openError(
            workbenchWindow.getShell(),
            WebPageEditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"),
            exception.getMessage());
        return false;
      }

      return true;
    } catch (Exception exception) {
      WebPageEditorPlugin.INSTANCE.log(exception);
      return false;
    }
  }
  @Override
  public boolean performFinish() {
    try {
      // Remember the file.
      //
      final IFile modelFile = getModelFile();

      // Do the work within an operation.
      //
      WorkspaceModifyOperation operation =
          new WorkspaceModifyOperation() {
            @Override
            protected void execute(IProgressMonitor progressMonitor) {

              // Create a resource set
              //
              ResourceSet resourceSet = new ResourceSetImpl();

              // Get the URI of the model file.
              //
              URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString(), true);

              // Create a resource for this file.
              //
              Resource resource = resourceSet.createResource(fileURI);

              // Add the initial model object to the contents.
              //
              MDescriptorList rootObject = createInitialModel();
              if (rootObject != null) {
                resource.getContents().add(rootObject);
              }

              // Save the contents of the resource to the file system.
              //
              Map<Object, Object> options = new HashMap<Object, Object>();
              options.put(XMLResource.OPTION_ENCODING, "UTF-8");

              for (Iterator<?> i = selection.iterator(); i.hasNext(); ) {
                Object object = i.next();
                if (object instanceof MCommonPackageVersionedItem) {
                  MCommonPackageVersionedItem versionedItem = (MCommonPackageVersionedItem) object;
                  EObject root = EcoreUtil.getRootContainer(versionedItem);
                  String libraryID =
                      LibraryAdapterFactory.getAdapterFactory()
                          .getLibraryID(root.eClass().getName());
                  LibraryAdapter adapter =
                      LibraryAdapterFactory.getAdapterFactory().getAdapter(libraryID);
                  if (adapter != null) {
                    try {
                      ILibraryEncoder encoder =
                          (ILibraryEncoder) adapter.adapt(ILibraryEncoder.class);
                      if (encoder != null) {
                        List<MDescriptor> descriptors = encoder.getDescriptors(versionedItem);
                        rootObject.getDescriptors().addAll(descriptors);
                      }
                    } catch (LibraryManagerException e) {
                      MICOBSPlugin.INSTANCE.log(e);
                    }
                  }
                } else if (object instanceof MCommonPackageItem) {
                  MCommonPackageItem item = (MCommonPackageItem) object;
                  EObject root = EcoreUtil.getRootContainer(item);
                  String libraryID =
                      LibraryAdapterFactory.getAdapterFactory()
                          .getLibraryID(root.eClass().getName());
                  LibraryAdapter adapter =
                      LibraryAdapterFactory.getAdapterFactory().getAdapter(libraryID);
                  if (adapter != null) {
                    try {
                      ILibraryEncoder encoder =
                          (ILibraryEncoder) adapter.adapt(ILibraryEncoder.class);
                      if (encoder != null) {
                        List<MDescriptor> descriptors = encoder.getDescriptors(item);
                        rootObject.getDescriptors().addAll(descriptors);
                      }
                    } catch (LibraryManagerException e) {
                      MICOBSPlugin.INSTANCE.log(e);
                    }
                  }
                } else if (object instanceof MCommonPackage) {
                  MCommonPackage pack = (MCommonPackage) object;
                  EObject root = EcoreUtil.getRootContainer(pack);
                  String libraryID =
                      LibraryAdapterFactory.getAdapterFactory()
                          .getLibraryID(root.eClass().getName());
                  LibraryAdapter adapter =
                      LibraryAdapterFactory.getAdapterFactory().getAdapter(libraryID);
                  if (adapter != null) {
                    try {
                      ILibraryEncoder encoder =
                          (ILibraryEncoder) adapter.adapt(ILibraryEncoder.class);
                      if (encoder != null) {
                        List<MDescriptor> descriptors = encoder.getDescriptors(pack);
                        rootObject.getDescriptors().addAll(descriptors);
                      }
                    } catch (LibraryManagerException e) {
                      MICOBSPlugin.INSTANCE.log(e);
                    }
                  }
                } else if (object instanceof MCommonLibrary) {
                  MCommonLibrary library = (MCommonLibrary) object;
                  String libraryID =
                      LibraryAdapterFactory.getAdapterFactory()
                          .getLibraryID(library.eClass().getName());
                  LibraryAdapter adapter =
                      LibraryAdapterFactory.getAdapterFactory().getAdapter(libraryID);
                  if (adapter != null) {
                    try {
                      ILibraryEncoder encoder =
                          (ILibraryEncoder) adapter.adapt(ILibraryEncoder.class);
                      if (encoder != null) {
                        for (MCommonPackage pack : library.getPackages()) {
                          rootObject.getDescriptors().addAll(encoder.getDescriptors(pack));
                        }
                      }
                    } catch (LibraryManagerException e) {
                      MICOBSPlugin.INSTANCE.log(e);
                    }
                  }
                }
                LibraryDescriptor.removeDuplicatedDescriptors(rootObject);
              }
              try {
                resource.save(options);
              } catch (IOException e) {
                MICOBSPlugin.INSTANCE.log(e);
              }
              progressMonitor.done();
            }
          };

      getContainer().run(false, false, operation);

      // Select the new file resource in the current view.
      //
      IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
      IWorkbenchPage page = workbenchWindow.getActivePage();
      final IWorkbenchPart activePart = page.getActivePart();
      if (activePart instanceof ISetSelectionTarget) {
        final ISelection targetSelection = new StructuredSelection(modelFile);
        getShell()
            .getDisplay()
            .asyncExec(
                new Runnable() {
                  public void run() {
                    ((ISetSelectionTarget) activePart).selectReveal(targetSelection);
                  }
                });
      }

      // Open an editor on the new file.
      //
      try {
        page.openEditor(
            new FileEditorInput(modelFile),
            workbench
                .getEditorRegistry()
                .getDefaultEditor(modelFile.getFullPath().toString())
                .getId());
      } catch (PartInitException exception) {
        MessageDialog.openError(
            workbenchWindow.getShell(),
            MICOBSPlugin.INSTANCE.getString("_UI_OpenEditorError_label"),
            exception.getMessage());
        return false;
      }

      return true;
    } catch (Exception exception) {
      MICOBSPlugin.INSTANCE.log(exception);
      return false;
    }
  }
Exemplo n.º 26
0
  /**
   * Guesses the function effected/modified by the patch from local file(newer file).
   *
   * @param patchFileInfo patch file
   * @return array of unique function names
   */
  private String[] guessFunctionNames(PatchFile patchFileInfo) {

    // if this file is new file or removed file, do not guess function files
    // TODO: create an option to include function names on
    // new files or not
    if (patchFileInfo.isNewfile() || patchFileInfo.isRemovedFile()) {
      return new String[] {""};
    }

    String[] fnames = new String[0];
    String editorName = ""; // $NON-NLS-1$

    try {
      IEditorDescriptor ed =
          org.eclipse.ui.ide.IDE.getEditorDescriptor(patchFileInfo.getPath().toOSString());
      editorName = ed.getId().substring(ed.getId().lastIndexOf(".") + 1); // $NON-NLS-1$
    } catch (PartInitException e1) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e1.getMessage(), e1));
      return new String[0];
    }

    // check if the file type is supported

    // get editor input for target file

    IFileEditorInput fei = new FileEditorInput((IFile) patchFileInfo.getResource());

    SourceEditorInput sei = new SourceEditorInput(patchFileInfo.getStorage());

    MyDocumentProvider mdp = new MyDocumentProvider();
    MyStorageDocumentProvider msdp = new MyStorageDocumentProvider();

    try {
      // get document for target file (one for local file, one for repository storage)
      IDocument doc = mdp.createDocument(fei);
      IDocument olddoc = msdp.createDocument(sei);

      HashMap<String, String> functionNamesMap = new HashMap<String, String>();
      ArrayList<String> nameList = new ArrayList<String>();

      // for all the ranges
      for (PatchRangeElement tpre : patchFileInfo.getRanges()) {

        for (int j = tpre.ffromLine; j <= tpre.ftoLine; j++) {

          String functionGuess = "";
          // add func that determines type of file.
          // right now it assumes it's java file.
          if (tpre.isLocalChange()) {
            if ((j < 0) || (j > doc.getNumberOfLines() - 1)) continue; // ignore out of bound lines
            functionGuess = parseCurrentFunctionAtOffset(editorName, fei, doc.getLineOffset(j));
          } else {
            if ((j < 0) || (j > olddoc.getNumberOfLines() - 1))
              continue; // ignore out of bound lines
            functionGuess = parseCurrentFunctionAtOffset(editorName, sei, olddoc.getLineOffset(j));
          }

          // putting it in hashmap will eliminate duplicate
          // guesses.  We use a list to keep track of ordering which
          // is helpful when trying to document a large set of changes.
          if (functionNamesMap.get(functionGuess) == null) nameList.add(functionGuess);
          functionNamesMap.put(functionGuess, functionGuess);
        }
      }

      // dump all unique func. guesses in the order found
      fnames = new String[nameList.size()];
      fnames = nameList.toArray(fnames);

    } catch (CoreException e) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e));
    } catch (BadLocationException e) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e));
    } catch (Exception e) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e));
      e.printStackTrace();
    }
    return fnames;
  }