Java Code Examples for org.eclipse.ui.IEditorPart#doSave()

The following examples show how to use org.eclipse.ui.IEditorPart#doSave() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RunAnalysisHandler.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	final AnalysisKickOff akf = new AnalysisKickOff();
	IEditorPart openEditor = UIUtils.getCurrentlyOpenEditor();

	// check if there are unsaved changes
	if (openEditor != null && openEditor.isDirty()) {
		int answr = saveFile(Utils.getCurrentlyOpenFile());
		// save file and analyze
		if (answr == JOptionPane.YES_OPTION) {
			openEditor.doSave(null);
		}
		// no analyze no save file
		else if (answr == JOptionPane.CLOSED_OPTION) {
			return null;
		}
	}
	if (akf.setUp(JavaCore.create(Utils.getCurrentlySelectedIProject()))) {
		akf.run();
	}
	return null;
}
 
Example 2
Source File: ToServlet25SourceQuickFixTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertServlet() throws CoreException {
  IProject project = projectCreator.getProject();
  IFile file = project.getFile("web.xml");
  String webXml = "<web-app xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\" version='3.1'/>";
  file.create(ValidationTestUtils.stringToInputStream(webXml), IFile.FORCE, null);

  IWorkbench workbench = PlatformUI.getWorkbench();
  IEditorPart editorPart = WorkbenchUtil.openInEditor(workbench, file);
  ITextViewer viewer = ValidationTestUtils.getViewer(file);
  String preContents = viewer.getDocument().get();

  assertTrue(preContents.contains("version='3.1'"));

  XsltSourceQuickFix quickFix = new ToServlet25SourceQuickFix();
  quickFix.apply(viewer, 'a', 0, 0);

  IDocument document = viewer.getDocument();
  String contents = document.get();
  assertFalse(contents.contains("version='3.1'"));
  assertTrue(contents.contains("version=\"2.5\""));

  // https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/1527
  editorPart.doSave(new NullProgressMonitor());
}
 
Example 3
Source File: XsltQuickFixPluginTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Test
public void testRun_existingEditor() throws CoreException {
  file.create(ValidationTestUtils.stringToInputStream(APPLICATION_XML), IFile.FORCE, null);

  IWorkbench workbench = PlatformUI.getWorkbench();
  IEditorPart editor = WorkbenchUtil.openInEditor(workbench, file);

  IDocument preDocument = XsltQuickFix.getCurrentDocument(file);
  String preContents = preDocument.get();
  assertTrue(preContents.contains("application"));

  IMarker marker = Mockito.mock(IMarker.class);
  Mockito.when(marker.getResource()).thenReturn(file);
  XsltQuickFix fix = new XsltQuickFix("/xslt/removeApplication.xsl",
      Messages.getString("remove.application.element"));
  fix.run(marker);

  IDocument document = XsltQuickFix.getCurrentDocument(file);
  String contents = document.get();
  assertFalse(contents.contains("application"));

  // https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/1527
  editor.doSave(new NullProgressMonitor());
}
 
Example 4
Source File: GWTProjectPropertyPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public static void reopenWithGWTJavaEditor(IEditorReference[] openEditors) {
  IWorkbenchPage page = JavaPlugin.getActivePage();

  for (IEditorReference editorRef : openEditors) {
    try {
      IEditorPart editor = editorRef.getEditor(false);
      IEditorInput input = editorRef.getEditorInput();

      // Close the editor, prompting the user to save if document is dirty
      if (page.closeEditor(editor, true)) {
        // Re-open the .java file in the GWT Java Editor
        IEditorPart gwtEditor = page.openEditor(input, GWTJavaEditor.EDITOR_ID);

        // Save the file from the new editor if the Java editor's
        // auto-format-on-save action screwed up the JSNI formatting
        gwtEditor.doSave(null);
      }
    } catch (PartInitException e) {
      GWTPluginLog.logError(e, "Could not open GWT Java editor on {0}", editorRef.getTitleToolTip());
    }
  }
}
 
Example 5
Source File: CodeGenerator.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method organizes imports for all generated files and the file, in which the call code for the generated classes is inserted.
 *
 * @param editor
 *        Editor with the currently open file
 * @throws CoreException
 *         {@link DeveloperProject#refresh() refresh()} and {@link DeveloperProject#getPackagesOfProject(String) getPackagesOfProject()}
 */
protected void cleanUpProject(IEditorPart editor) throws CoreException {
	this.project.refresh();
	final ICompilationUnit[] generatedCUnits = this.project.getPackagesOfProject(Constants.PackageNameAsName).getCompilationUnits();
	boolean anyFileOpen = false;

	if (editor == null && generatedCUnits[0].getResource().getType() == IResource.FILE) {
		IFile genClass = (IFile) generatedCUnits[0].getResource();
		IDE.openEditor(UIUtils.getCurrentlyOpenPage(), genClass);
		editor = UIUtils.getCurrentlyOpenPage().getActiveEditor();
		anyFileOpen = true;
	}

	final OrganizeImportsAction organizeImportsActionForAllFilesTouchedDuringGeneration = new OrganizeImportsAction(editor.getSite());
	final FormatAllAction faa = new FormatAllAction(editor.getSite());
	faa.runOnMultiple(generatedCUnits);
	organizeImportsActionForAllFilesTouchedDuringGeneration.runOnMultiple(generatedCUnits);

	if (anyFileOpen) {
		UIUtils.closeEditor(editor);
	}

	final ICompilationUnit openClass = JavaCore.createCompilationUnitFrom(UIUtils.getCurrentlyOpenFile(editor));
	organizeImportsActionForAllFilesTouchedDuringGeneration.run(openClass);
	faa.runOnMultiple(new ICompilationUnit[] { openClass });
	editor.doSave(null);
}
 
Example 6
Source File: UpgradeRuntimeQuickFixTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private void checkUpgrade(String appengineWebAppJava7) throws CoreException {
  IProject project = appEngineStandardProject.getProject();
  IFile file = project.getFile("appengine-web.xml");
  
  file.create(ValidationTestUtils.stringToInputStream(appengineWebAppJava7), IFile.FORCE, null);

  IWorkbench workbench = PlatformUI.getWorkbench();
  IEditorPart editorPart = WorkbenchUtil.openInEditor(workbench, file);
  ITextViewer viewer = ValidationTestUtils.getViewer(file);
  while (workbench.getDisplay().readAndDispatch()) {
    // spin the event loop
  }

  IMarker[] markers = ProjectUtils.waitUntilMarkersFound(file, MARKER,
      true /* includeSubtypes */, IResource.DEPTH_ZERO);
  assertEquals(1, markers.length);

  XsltSourceQuickFix quickFix = new UpgradeRuntimeSourceQuickFix();
  quickFix.apply(viewer, 'a', 0, 0);

  IDocument document = viewer.getDocument();
  String contents = document.get();
  assertThat(contents, not(containsString("java7")));
  assertThat(contents, containsString("  <runtime>java8</runtime>"));

  // https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/1527
  editorPart.doSave(new NullProgressMonitor());
}
 
Example 7
Source File: XsltQuickFixPluginTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCurrentDocument_existingEditor() throws CoreException {
  file.create(ValidationTestUtils.stringToInputStream(APPLICATION_XML), IFile.FORCE, null);

  IWorkbench workbench = PlatformUI.getWorkbench();
  IEditorPart editor = WorkbenchUtil.openInEditor(workbench, file);

  assertNotNull(XsltQuickFix.getCurrentDocument(file));

  // https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/1527
  editor.doSave(new NullProgressMonitor());
}
 
Example 8
Source File: ApplicationSourceQuickFixTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Test
public void testApply() throws CoreException {

  IProject project = appEngineStandardProject.getProject();
  IFile file = project.getFile("appengine-web.xml");
  file.create(ValidationTestUtils.stringToInputStream(APPLICATION_XML), IFile.FORCE, null);

  IWorkbench workbench = PlatformUI.getWorkbench();
  IEditorPart editorPart = WorkbenchUtil.openInEditor(workbench, file);
  ITextViewer viewer = ValidationTestUtils.getViewer(file);
  while (workbench.getDisplay().readAndDispatch()) {
    // spin the event loop
  }

  String preContents = viewer.getDocument().get();
  assertThat(preContents, containsString("application"));

  IMarker[] markers = ProjectUtils.waitUntilMarkersFound(file, MARKER,
      true /* includeSubtypes */, IResource.DEPTH_ZERO);
  assertEquals(1, markers.length);

  XsltSourceQuickFix quickFix = new ApplicationSourceQuickFix();
  quickFix.apply(viewer, 'a', 0, 0);

  IDocument document = viewer.getDocument();
  String contents = document.get();
  assertThat(contents, not(containsString("application")));
  assertThat(contents, not(containsString("?><appengine")));

  // https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/1527
  editorPart.doSave(new NullProgressMonitor());

  ProjectUtils.waitUntilNoMarkersFound(file, MARKER, true /* includeSubtypes */,
      IResource.DEPTH_ZERO);
}
 
Example 9
Source File: ERDiagramMultiPageEditor.java    From ermasterr with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void doSave(final IProgressMonitor monitor) {
    final ZoomManager zoomManager = (ZoomManager) getActiveEditor().getAdapter(ZoomManager.class);
    final double zoom = zoomManager.getZoom();
    diagram.setZoom(zoom);

    final ERDiagramEditor activeEditor = getActiveEditor();
    final Point location = activeEditor.getLocation();
    diagram.setLocation(location.x, location.y);

    final Persistent persistent = Persistent.getInstance();

    try {
        diagram.getDiagramContents().getSettings().getModelProperties().setUpdatedDate(new Date());

        final InputStream source = persistent.createInputStream(diagram);

        if (inputFile != null) {
            if (!inputFile.exists()) {
                inputFile.create(source, true, monitor);

            } else {
                inputFile.setContents(source, true, false, monitor);
            }
        }

    } catch (final Exception e) {
        ERDiagramActivator.showExceptionDialog(e);
    }

    for (int i = 0; i < getPageCount(); i++) {
        final IEditorPart editor = getEditor(i);
        editor.doSave(monitor);
    }

    validate();
}
 
Example 10
Source File: ERFluteMultiPageEditor.java    From erflute with Apache License 2.0 5 votes vote down vote up
@Override
public void doSave(IProgressMonitor monitor) {
    monitor.setTaskName("save initialize...");
    final ZoomManager zoomManager = (ZoomManager) getActiveEditor().getAdapter(ZoomManager.class);
    final double zoom = zoomManager.getZoom();
    diagram.setZoom(zoom);

    final MainDiagramEditor activeEditor = (MainDiagramEditor) getActiveEditor();
    final Point location = activeEditor.getLocation();
    diagram.setLocation(location.x, location.y);
    final Persistent persistent = Persistent.getInstance();
    final IFile file = ((IFileEditorInput) getEditorInput()).getFile();
    try {
        monitor.setTaskName("create stream...");
        final InputStream source = persistent.write(diagram);
        if (!file.exists()) {
            file.create(source, true, monitor);
        } else {
            file.setContents(source, true, false, monitor);
        }
    } catch (final Exception e) {
        Activator.showExceptionDialog(e);
    }
    monitor.beginTask("saving...", getPageCount());
    for (int i = 0; i < getPageCount(); i++) {
        final IEditorPart editor = getEditor(i);
        editor.doSave(monitor);
        monitor.worked(i + 1);
    }
    monitor.done();
    monitor.setTaskName("finalize...");

    validate();
    monitor.done();
}
 
Example 11
Source File: SaveHelper.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected void saveDeclaringEditor(IRenameElementContext context, IWorkbenchPage workbenchPage) {
	IEditorPart declaringEditor = getOpenEditor(context.getTargetElementURI(), workbenchPage);
	if (declaringEditor != null && declaringEditor.isDirty())
		declaringEditor.doSave(new NullProgressMonitor());
}
 
Example 12
Source File: PublishTemplateNavigatorAction.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
 */
public void run( IAction action )
{
	IFile file = getSelectedFile( );
	if ( file != null )
	{
		String url = file.getLocation( ).toOSString( );
		try
		{
			ModuleHandle handle = SessionHandleAdapter.getInstance( )
					.getSessionHandle( )
					.openDesign( url );

			if ( handle == null )
			{
				action.setEnabled( false );
				return;
			}

			IEditorPart editor = org.eclipse.birt.report.designer.internal.ui.util.UIUtil.findOpenedEditor( url );

			if ( editor != null && editor.isDirty( ) )
			{
				MessageDialog md = new MessageDialog( UIUtil.getDefaultShell( ),
						Messages.getString( "PublishTemplateAction.SaveBeforeGenerating.dialog.title" ), //$NON-NLS-1$
						null,
						Messages.getFormattedString( "PublishTemplateAction.SaveBeforeGenerating.dialog.message", new Object[]{file.getName( )} ), //$NON-NLS-1$
						MessageDialog.CONFIRM,
						new String[]{
								Messages.getString( "PublishTemplateAction.SaveBeforeGenerating.dialog.button.yes" ), //$NON-NLS-1$
								Messages.getString( "PublishTemplateAction.SaveBeforeGenerating.dialog.button.no" ) //$NON-NLS-1$
						},
						0 );
				switch ( md.open( ) )
				{
					case 0 :
						editor.doSave( null );
						break;
					case 1 :
					default :
				}
			}

			WizardDialog dialog = new BaseWizardDialog( UIUtil.getDefaultShell( ),
					new PublishTemplateWizard( (ReportDesignHandle) handle ) );
			dialog.setPageSize( 500, 250 );
			dialog.open( );

			handle.close( );
		}
		catch ( Exception e )
		{
			ExceptionUtil.handle( e );
			return;
		}
	}
	else
	{
		action.setEnabled( false );
	}
}
 
Example 13
Source File: SaveCommandHandler.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
protected void doSaveDiagram(final DiagramEditor editorPart) {
    boolean changed = false;
    final DiagramRepositoryStore diagramStore = RepositoryManager.getInstance().getRepositoryStore(DiagramRepositoryStore.class);
    final MainProcess proc = findProc(editorPart);
    DiagramFileStore oldArtifact = null;
    final List<DiagramDocumentEditor> editorsWithSameResourceSet = new ArrayList<DiagramDocumentEditor>();
    if (nameOrVersionChanged(proc, editorPart)) {
        IEditorReference[] editorReferences;
        editorReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences();
        final IEditorInput editorInput = editorPart.getEditorInput();
        final ResourceSet resourceSet = proc.eResource().getResourceSet();
        maintainListOfEditorsWithSameResourceSet(editorsWithSameResourceSet, editorReferences, editorInput, resourceSet);
        oldArtifact = diagramStore.getChild(NamingUtils.toDiagramFilename(getOldProcess(proc)), true);
        changed = true;
    }

    try {
        final IEditorPart editorToSave = editorPart;
        if (changed && oldArtifact != null) {
            editorToSave.doSave(Repository.NULL_PROGRESS_MONITOR);
            ((DiagramDocumentEditor) editorToSave).close(true);
            final Set<String> formIds = new HashSet<String>();
            for (final DiagramDocumentEditor diagramDocumentEditor : editorsWithSameResourceSet) {
                formIds.add(ModelHelper.getEObjectID(diagramDocumentEditor.getDiagramEditPart().resolveSemanticElement()));
                diagramDocumentEditor.close(true);
            }
            oldArtifact.renameLegacy(NamingUtils.toDiagramFilename(proc));
            oldArtifact.open();
        } else {
            final EObject root = editorPart.getDiagramEditPart().resolveSemanticElement();
            final Resource res = root.eResource();
            if (res != null) {
                final String procFile = URI.decode(res.getURI().lastSegment());
                final DiagramFileStore fileStore = diagramStore.getChild(procFile, true);
                if (fileStore != null) {
                    fileStore.save(editorPart);
                }
            } else {
                editorPart.doSave(Repository.NULL_PROGRESS_MONITOR);
            }

        }
    } catch (final Exception ex) {
        BonitaStudioLog.error(ex);
    }
}
 
Example 14
Source File: ERDiagramMultiPageEditor.java    From ermaster-b with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void doSave(IProgressMonitor monitor) {
	monitor.setTaskName("save initialize...");
	ZoomManager zoomManager = (ZoomManager) this.getActiveEditor()
			.getAdapter(ZoomManager.class);
	double zoom = zoomManager.getZoom();
	this.diagram.setZoom(zoom);

	ERDiagramEditor activeEditor = (ERDiagramEditor) this.getActiveEditor();
	Point location = activeEditor.getLocation();
	this.diagram.setLocation(location.x, location.y);

	Persistent persistent = Persistent.getInstance();

	IFile file = ((IFileEditorInput) this.getEditorInput()).getFile();

	try {
		monitor.setTaskName("create stream...");
		diagram.getDiagramContents().getSettings().getModelProperties()
				.setUpdatedDate(new Date());

		InputStream source = persistent.createInputStream(this.diagram);

		if (!file.exists()) {
			file.create(source, true, monitor);

		} else {
			file.setContents(source, true, false, monitor);
		}

	} catch (Exception e) {
		Activator.showExceptionDialog(e);
	}

	monitor.beginTask("saving...", this.getPageCount());
	for (int i = 0; i < this.getPageCount(); i++) {
		IEditorPart editor = this.getEditor(i);
		editor.doSave(monitor);
		monitor.worked(i + 1);
	}
	monitor.done();
	monitor.setTaskName("finalize...");

	validate();
	monitor.done();
}