Java Code Examples for org.eclipse.swt.widgets.FileDialog#setOverwrite()

The following examples show how to use org.eclipse.swt.widgets.FileDialog#setOverwrite() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
protected void updateFile ()
{
    final FileDialog dlg = new FileDialog ( getShell (), SWT.APPLICATION_MODAL | SWT.SAVE );

    dlg.setFilterExtensions ( new String[] { Messages.FileSelectionPage_FilterExtension } );
    dlg.setFilterNames ( new String[] { Messages.FileSelectionPage_FilterName } );
    dlg.setOverwrite ( true );
    dlg.setText ( Messages.FileSelectionPage_FileDialog_Text );

    final String fileName = dlg.open ();
    if ( fileName == null )
    {
        setFile ( null );
        update ();
    }
    else
    {
        setFile ( new File ( fileName ) );
        update ();
    }
}
 
Example 2
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    List<TmfEventTableColumn> columns = getColumns(event.getApplicationContext());
    ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace();
    ITmfFilter filter = TmfTraceManager.getInstance().getCurrentTraceContext().getFilter();
    if (trace != null) {
        FileDialog fd = TmfFileDialogFactory.create(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
        fd.setFilterExtensions(new String[] { "*.csv", "*.*", "*" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        fd.setOverwrite(true);
        final String s = fd.open();
        if (s != null) {
            Job j = new ExportToTextJob(trace, filter, columns, s);
            j.setUser(true);
            j.schedule();
        }
    }
    return null;
}
 
Example 3
Source Project: tracecompass   File: ColorsView.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void run() {
    FileDialog fileDialog = TmfFileDialogFactory.create(fShell, SWT.SAVE);
    fileDialog.setFilterExtensions(new String[] {"*.xml"}); //$NON-NLS-1$
    fileDialog.setOverwrite(true);
    String pathName = fileDialog.open();
    if (pathName != null) {
        ColorSettingsXML.save(pathName, fColorSettings.toArray(new ColorSetting[0]));
    }
}
 
Example 4
/**
 * Override this to plugin custom OutputStream.
 */
protected OutputStream getOutputStream(ExportToExcelCommand command) throws IOException {
	FileDialog dialog = new FileDialog (command.getShell(), SWT.SAVE);
	dialog.setFilterPath ("/");
	dialog.setOverwrite(true);

	dialog.setFileName ("table_export.xls");
	dialog.setFilterExtensions(new String [] {"Microsoft Office Excel Workbook(.xls)"});
	String fileName = dialog.open();
	if(fileName == null){
		return null;
	}
	return new PrintStream(fileName);
}
 
Example 5
Source Project: Rel   File: ExporterDialog.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create the dialog.
 * @param parent
 * @param style
 */
public ExporterDialog(Shell parent, String name, Value result) {
	super(parent, SWT.DIALOG_TRIM | SWT.RESIZE);
	exportDialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
	exportDialog.setOverwrite(true);
	this.name = name;
	this.result = result;
	setText("Export to File");
}
 
Example 6
protected void getSaveURI() {
	FileDialog dialog = new FileDialog(getParentShell(), SWT.SAVE);
	dialog.setFilterExtensions(new String[] { "*.tmx" });
	dialog.setOverwrite(true);
	String path = dialog.open();
	if (path != null) {
		txtSaveAs.setText(path);
	}
}
 
Example 7
/**
 * Override this to plugin custom OutputStream.
 */
protected OutputStream getOutputStream(ExportToExcelCommand command) throws IOException {
	FileDialog dialog = new FileDialog (command.getShell(), SWT.SAVE);
	dialog.setFilterPath ("/");
	dialog.setOverwrite(true);

	dialog.setFileName ("table_export.xls");
	dialog.setFilterExtensions(new String [] {"Microsoft Office Excel Workbook(.xls)"});
	String fileName = dialog.open();
	if(fileName == null){
		return null;
	}
	return new PrintStream(fileName);
}
 
Example 8
private void handleRequest(XMPPFileTransferRequest request) {
  String filename = request.getFileName();
  long fileSize = request.getFileSize();

  if (!MessageDialog.openQuestion(
      SWTUtils.getShell(),
      "File Transfer Request",
      request.getContact().getDisplayableName()
          + " wants to send a file."
          + "\nName: "
          + filename
          + "\nSize: "
          + CoreUtils.formatByte(fileSize)
          + (fileSize < 1000 ? "yte" : "")
          + "\n\nAccept the file?")) {
    request.reject();
    return;
  }

  FileDialog fd = new FileDialog(SWTUtils.getShell(), SWT.SAVE);
  fd.setText(Messages.SendFileAction_filedialog_text);
  fd.setOverwrite(true);
  fd.setFileName(filename);

  String destination = fd.open();
  if (destination == null) {
    request.reject();
    return;
  }

  File file = new File(destination);
  if (file.isDirectory()) {
    request.reject();
    return;
  }

  Job job = new IncomingFileTransferJob(request, file);
  job.setUser(true);
  job.schedule();
}
 
Example 9
Source Project: jbt   File: SaveBTAsAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @see org.eclipse.jface.action.Action#run()
 */
public void run() {
	FileDialog dialog = new FileDialog(
			PlatformUI.getWorkbench().getWorkbenchWindows()[0].getShell(), SWT.SAVE);
	
	dialog.setOverwrite(true);
	dialog.setFilterExtensions(Extensions.getFiltersFromExtensions(Extensions
			.getBTFileExtensions()));
	dialog.setText("Save BT as");
	dialog.setFileName(this.initialFileName);
	
	String fileName = dialog.open();

	if (fileName != null) {
		List<BTEditor> editors = Utilities.getBTEditors();

		for (BTEditor editor : editors) {
			BTEditorInput editorInput = (BTEditorInput) editor.getEditorInput();
			if (editorInput.isFromFile() && editorInput.getTreeName().equals(fileName)) {
				throw new RuntimeException(
						"There is a behaviour tree already open with the same name ("
								+ fileName + "). Close it first.");
			}
		}

		String targetFileName = Extensions.joinFileNameAndExtension(fileName,
				Extensions.getBTFileExtensions()[dialog.getFilterIndex()]);

		new SaveBTAction(this.tree, targetFileName).run();

		this.selectedFile = targetFileName;
	}
}
 
Example 10
@Override
public void run ()
{
    if ( this.chart == null )
    {
        return;
    }

    final Shell shell = PlatformUI.getWorkbench ().getActiveWorkbenchWindow ().getShell ();

    final FileDialog dlg = new FileDialog ( shell, SWT.SAVE );
    dlg.setFilterExtensions ( new String[] { "*.chart" } );
    dlg.setFilterNames ( new String[] { "Eclipse SCADA Chart Configuration" } );
    dlg.setOverwrite ( true );
    dlg.setText ( "Select the file to store the chart configurationt to" );

    final String file = dlg.open ();

    if ( file != null )
    {
        new Job ( "Perform save" ) {
            @Override
            protected org.eclipse.core.runtime.IStatus run ( final org.eclipse.core.runtime.IProgressMonitor monitor )
            {
                try
                {
                    doSave ( file );
                }
                catch ( final IOException e )
                {
                    return StatusHelper.convertStatus ( Activator.PLUGIN_ID, e );
                }
                finally
                {
                    monitor.done ();
                }
                return Status.OK_STATUS;
            };
        }.schedule ();
    }
}
 
Example 11
Source Project: ice   File: AnalysisView.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Given an SWT Canvas, this method creates a save file dialog and will save
 * the Canvas as an image file. Supported extensions include PNG, JPG, and
 * BMP.
 * 
 * @param canvas
 *            The Canvas to save as an image.
 */
protected static void saveCanvasImage(Canvas canvas) {
	// FIXME - It's possible to get a graphical glitch where there are black
	// pixels at the bottom of the image. My guess is that the GC never
	// actually bothers to paint because that part is not visible on the
	// screen. Currently, this issue is unresolved.

	// Store the allowed extensions in a HashMap.
	HashMap<String, Integer> extensions = new HashMap<String, Integer>(4);
	extensions.put("png", SWT.IMAGE_PNG);
	extensions.put("jpg", SWT.IMAGE_JPEG);
	extensions.put("bmp", SWT.IMAGE_BMP);

	// Make the array of strings needed to pass to the file dialog.
	String[] extensionStrings = new String[extensions.keySet().size()];
	int i = 0;
	for (String extension : extensions.keySet()) {
		extensionStrings[i++] = "*." + extension;
	}

	// Create the file save dialog.
	FileDialog fileDialog = new FileDialog(canvas.getShell(), SWT.SAVE);
	fileDialog.setFilterExtensions(extensionStrings);
	fileDialog.setOverwrite(true);

	// Get the path of the new/overwritten image file.
	String path = fileDialog.open();

	// Return if the user cancelled.
	if (path == null) {
		return;
	}
	// Get the image type to save from the path's extension.
	String[] splitPath = path.split("\\.");
	int extensionSWT = extensions.get(splitPath[splitPath.length - 1]);

	// Get the image from the canvas.
	Rectangle bounds = canvas.getBounds();
	Image image = new Image(null, bounds.width, bounds.height);
	GC gc = new GC(image);
	// SWT XYGraph uses this method to center the saved image.
	canvas.print(gc);
	gc.dispose();

	// Save the file.
	ImageLoader loader = new ImageLoader();
	loader.data = new ImageData[] { image.getImageData() };
	loader.save(path, extensionSWT);
	image.dispose();

	return;
}
 
Example 12
Source Project: ice   File: AnalysisView.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Given a GEF GraphicalViewer, this method creates a save file dialog and
 * will save the contents of the viewer as an image file. Supported
 * extensions include PNG, JPG, and BMP.
 * 
 * @param viewer
 *            The GraphicalViewer to save as an image.
 */
protected static void saveViewerImage(GraphicalViewer viewer) {

	// Store the allowed extensions in a HashMap.
	HashMap<String, Integer> extensions = new HashMap<String, Integer>(4);
	extensions.put("png", SWT.IMAGE_PNG);
	extensions.put("jpg", SWT.IMAGE_JPEG);
	extensions.put("bmp", SWT.IMAGE_BMP);

	// Make the array of strings needed to pass to the file dialog.
	String[] extensionStrings = new String[extensions.keySet().size()];
	int i = 0;
	for (String extension : extensions.keySet()) {
		extensionStrings[i++] = "*." + extension;
	}

	// Create the file save dialog.
	FileDialog fileDialog = new FileDialog(viewer.getControl().getShell(),
			SWT.SAVE);
	fileDialog.setFilterExtensions(extensionStrings);
	fileDialog.setOverwrite(true);

	// Get the path of the new/overwritten image file.
	String path = fileDialog.open();

	// Return if the user cancelled.
	if (path == null) {
		return;
	}

	// Get the image type to save from the path's extension.
	String[] splitPath = path.split("\\.");
	int extensionSWT = extensions.get(splitPath[splitPath.length - 1]);

	// Get the root EditPart and its draw2d Figure.
	SimpleRootEditPart rootEditPart = (SimpleRootEditPart) viewer
			.getRootEditPart();
	IFigure figure = rootEditPart.getFigure();

	// Get the image from the Figure.
	org.eclipse.draw2d.geometry.Rectangle bounds = figure.getBounds();
	Image image = new Image(null, bounds.width, bounds.height);
	GC gc = new GC(image);
	SWTGraphics g = new SWTGraphics(gc);
	figure.paint(g);
	g.dispose();
	gc.dispose();

	// Save the file.
	ImageLoader loader = new ImageLoader();
	loader.data = new ImageData[] { image.getImageData() };
	loader.save(path, extensionSWT);
	image.dispose();

	return;
}
 
Example 13
public String doExport(String destination, String stickerName){
	if (stickerName != null) {
		List<Sticker> ls =
			new Query<Sticker>(Sticker.class, Sticker.FLD_NAME, stickerName).execute();
		if (ls != null && ls.size() > 0) {
			sticker = ls.get(0);
		} else {
			return "Sticker " + stickerName + " nicht gefunden.";
		}
	}
	IDocumentManager mgr =
		(IDocumentManager) Extensions.findBestService(
			GlobalServiceDescriptors.DOCUMENT_MANAGEMENT, null);
	if (mgr == null) {
		return "Keine Dokumente gefunden";
	}
	try {
		if (destination == null) {
			FileDialog fd = new FileDialog(UiDesk.getTopShell(), SWT.SAVE);
			fd.setFilterExtensions(new String[] {
				"*.csv"
			});
			fd.setFilterNames(new String[] {
				"Comma Separated Values (CVS)"
			});
			fd.setOverwrite(true);
			destination = fd.open();
		}
		if (destination != null) {
			File csv = new File(destination);
			File parent = csv.getParentFile();
			File dir = new File(parent, FileTool.getNakedFilename(destination));
			dir.mkdirs();
			
			CSVWriter writer = new CSVWriter(new FileWriter(csv));
			String[] header = new String[] {
				"Patient", "Name", "Kategorie", "Datum", "Stichwörter", "Pfad"
			};
			List<IOpaqueDocument> dox = mgr.listDocuments(null, null, null, null, null, null);
			writer.writeNext(header);
			for (IOpaqueDocument doc : dox) {
				Patient pat = doc.getPatient();
				if (pat != null) {
					if (sticker != null) {
						if (pf.accept(pat, sticker) != IPatFilter.ACCEPT) {
							continue;
						}
					}
					
					String subdirname = pat.get(Patient.FLD_PATID);
					if (subdirname != null) {
						File subdir = new File(dir, subdirname);
						subdir.mkdirs();
						String[] line = new String[header.length];
						line[0] = pat.getId();
						line[1] = doc.getTitle();
						line[2] = doc.getCategory();
						line[3] = doc.getCreationDate();
						line[4] = doc.getKeywords();
						String docfilename = doc.getGUID() + "." + doc.getMimeType();
						line[5] =
							dir.getName() + File.separator + subdir.getName() + File.separator
								+ docfilename;
						byte[] bin = doc.getContentsAsBytes();
						if (bin != null) {
							File f = new File(subdir, docfilename);
							FileOutputStream fos = new FileOutputStream(f);
							fos.write(bin);
							fos.close();
							writer.writeNext(line);
						}
					}
					
				}
			}
			return "Export ok";
		} else {
			return "Abgebrochen.";
			
		}
	} catch (Exception e) {
		ElexisStatus status =
			new ElexisStatus(ElexisStatus.ERROR, Hub.PLUGIN_ID, ElexisStatus.CODE_NONE,
				"Fehler beim Export: " + e.getMessage(), e);
		throw new ScriptingException(status);
	}
	
}
 
Example 14
public String doExport(String filename, String stickerName){
	if (stickerName != null) {
		List<Sticker> ls =
			new Query<Sticker>(Sticker.class, Sticker.FLD_NAME, stickerName).execute();
		if (ls != null && ls.size() > 0) {
			sticker = ls.get(0);
		} else {
			return "Sticker " + stickerName + " nicht gefunden.";
		}
	}
	if (filename == null) {
		FileDialog fd = new FileDialog(UiDesk.getTopShell(), SWT.SAVE);
		fd.setFilterExtensions(new String[] {
			"*.csv"
		});
		fd.setFilterNames(new String[] {
			"Comma Separated Values (CVS)"
		});
		fd.setOverwrite(true);
		filename = fd.open();
	}
	if (filename != null) {
		List<Brief> briefe = new Query<Brief>(Brief.class).execute();
		File csv = new File(filename);
		File parent = csv.getParentFile();
		File dir = new File(parent, FileTool.getNakedFilename(filename));
		dir.mkdirs();
		try {
			CSVWriter writer = new CSVWriter(new FileWriter(csv));
			String[] header = new String[] {
				"Betreff", "Datum", "Adressat", "Mimetype", "Typ", "Patient", "Pfad"
			};
			String[] fields =
				new String[] {
					Brief.FLD_SUBJECT, Brief.FLD_DATE, Brief.FLD_DESTINATION_ID,
					Brief.FLD_MIME_TYPE, Brief.FLD_TYPE, Brief.FLD_PATIENT_ID,
					Brief.FLD_PATIENT_ID
				};
			writer.writeNext(header);
			for (Brief brief : briefe) {
				Person pers = brief.getPatient();
				if (pers != null) {
					if (!pers.istPatient()) {
						continue;
					}
					if (sticker != null) {
						if (pf.accept(Patient.load(pers.getId()), sticker) != IPatFilter.ACCEPT) {
							continue;
						}
					}
					String subdirname = pers.get(Patient.FLD_PATID);
					if (subdirname != null) {
						File subdir = new File(dir, subdirname);
						subdir.mkdirs();
						String[] line = new String[fields.length];
						brief.get(fields, line);
						byte[] bin = brief.loadBinary();
						if (bin != null) {
							File f = new File(subdir, brief.getId() + ".odt");
							FileOutputStream fos = new FileOutputStream(f);
							fos.write(bin);
							fos.close();
							line[line.length - 1] =
								dir.getName() + File.separator + subdir.getName()
									+ File.separator + f.getName();
							writer.writeNext(line);
						}
					}
				}
			}
			writer.close();
			return "Export ok";
		} catch (Exception ex) {
			ElexisStatus status =
				new ElexisStatus(ElexisStatus.ERROR, Hub.PLUGIN_ID, ElexisStatus.CODE_NONE,
					"Fehler beim Export: " + ex.getMessage(), ex);
			throw new ScriptingException(status);
		}
	}
	return "Abgebrochen";
}
 
Example 15
private MenuManager createMenu(TableViewer tableViewer){
	MenuManager menuManager = new MenuManager();
	
	Action clearAction = new Action("Leeren") { //$NON-NLS-1$
		{
			setImageDescriptor(Images.IMG_DELETE.getImageDescriptor());
			setToolTipText("Statistik Leeren"); //$NON-NLS-1$
		}
		
		@Override
		public void run(){
			StatisticsManager.INSTANCE.getStatistics().getStatistics().clear();
			tableViewer.refresh();
		}
	};
		
	Action exportAction = new Action("Exportieren") { //$NON-NLS-1$
		{
			setImageDescriptor(Images.IMG_EXPORT.getImageDescriptor());
			setToolTipText("Statistik Exportieren"); //$NON-NLS-1$
		}
		
		@Override
		public void run(){
			FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
			dialog.setFilterNames(new String[] {
				"xml"
			});
			dialog.setFilterExtensions(new String[] {
				"*.xml"
			});
			dialog.setOverwrite(true);
			dialog.setFilterPath(CoreHub.getWritableUserDir().getAbsolutePath()); // Windows path
			dialog.setFileName("statistics_export.xml");
			String path = dialog.open();
			if (path != null) {
				try {
					StatisticsManager.INSTANCE.exportStatisticsToFile(path);
				} catch (IOException e) {
					LoggerFactory.getLogger(UsageSettings.class)
						.error("statistics export error", e);
					MessageDialog.openError(getShell(), "Fehler",
						"Statistik Export nicht möglich. [" + e.getMessage() + "]");
				}
			}
		}
	};
		
	menuManager.add(clearAction);
	menuManager.add(exportAction);
	return menuManager;
}
 
Example 16
/**
 * File dialog factory, creates a {@link FileDialog}.
 * <p>
 * Constructs a new instance of this class given its parent and a style
 * value describing its behavior and appearance.
 * </p>
 * <p>
 * The style value is either one of the style constants defined in class
 * <code>SWT</code> which is applicable to instances of this class, or must
 * be built by <em>bitwise OR</em>'ing together (that is, using the
 * <code>int</code> "|" operator) two or more of those <code>SWT</code>
 * style constants. The class description lists the style constants that are
 * applicable to the class. Style bits are also inherited from superclasses.
 * </p>
 * <p>
 * If the factory is overridden with {@link #setOverrideFiles(String[])},
 * the FileDialog will return the set String when open is called instead of
 * opening a system window
 * </p>
 *
 * @param parent
 *            a shell which will be the parent of the new instance
 * @param style
 *            the style of dialog to construct
 * @return the {@link FileDialog}
 *
 * @exception IllegalArgumentException
 *                <ul>
 *                <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
 *                </ul>
 * @exception SWTException
 *                <ul>
 *                <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
 *                thread that created the parent</li>
 *                <li>ERROR_INVALID_SUBCLASS - if this class is not an
 *                allowed subclass</li>
 *                </ul>
 *
 * @see SWT#SAVE
 * @see SWT#OPEN
 * @see SWT#MULTI
 */
public static FileDialog create(Shell parent, int style) {
    String[] overridePath = fOverridePaths;
    if (overridePath != null) {
        fOverridePaths = null;
        return createNewFileDialog(parent, style, Arrays.asList(overridePath));
    }
    FileDialog fileDialog = new FileDialog(parent, style);
    if ((style & SWT.SAVE) != 0) {
        fileDialog.setOverwrite(true);
    }
    return fileDialog;
}