예제 #1
0
파일: ViewData.java 프로젝트: schugabe/FWS
  /** Export the selected values from the table to a csv file */
  private void export() {

    FileDialog dialog = new FileDialog(shell, SWT.SAVE);
    String[] filterNames = new String[] {"CSV Files", "All Files (*)"};
    String[] filterExtensions = new String[] {"*.csv;", "*"};
    String filterPath = "/";
    String platform = SWT.getPlatform();
    if (platform.equals("win32") || platform.equals("wpf")) {
      filterNames = new String[] {"CSV Files", "All Files (*.*)"};
      filterExtensions = new String[] {"*.csv", "*.*"};
      filterPath = "c:\\";
    }
    dialog.setFilterNames(filterNames);
    dialog.setFilterExtensions(filterExtensions);
    dialog.setFilterPath(filterPath);
    try {
      dialog.setFileName(this.getCurrentKey() + ".csv");
    } catch (Exception e) {
      dialog.setFileName("export.csv");
    }
    String fileName = dialog.open();

    FileOutputStream fos;
    OutputStreamWriter out;
    try {
      fos = new FileOutputStream(fileName);
      out = new OutputStreamWriter(fos, "UTF-8");
    } catch (Exception e) {
      MessageBox messageBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
      messageBox.setMessage("Error creating export file " + fileName + " : " + e.getMessage());
      messageBox.open();
      return;
    }

    Vector<TableItem> sel = new Vector<TableItem>(this.dataTable.getSelection().length);

    sel.addAll(Arrays.asList(this.dataTable.getSelection()));
    Collections.reverse(sel);

    for (TableItem item : sel) {
      String date = item.getText(0);
      String value = item.getText(1);
      try {
        out.write(date + ";" + value + "\n");
      } catch (IOException e) {
        continue;
      }
    }

    try {
      out.close();
      fos.close();
    } catch (IOException e) {
      MessageBox messageBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
      messageBox.setMessage("Error writing export file " + fileName + " : " + e.getMessage());
      messageBox.open();
      e.printStackTrace();
    }
  }
예제 #2
0
 public void selectOutputFile() {
   FileDialog dlg = new FileDialog(getParentShell(), SWT.SAVE);
   ArrayList<String> extensionList = new ArrayList<String>();
   if (chosenOutputFormat != null && chosenOutputFormat.getFileSuffix() != null) {
     extensionList.add("*." + chosenOutputFormat.getFileSuffix()); // $NON-NLS-1$
   }
   extensionList.add("*.*"); // $NON-NLS-1$
   dlg.setFilterExtensions(extensionList.toArray(new String[extensionList.size()]));
   dlg.setFileName(getDefaultOutputFilename());
   dlg.setOverwrite(true);
   String path;
   if (isFilePath()) {
     path = getOldFolderPath();
   } else {
     path = defaultFolder;
   }
   if (LOG.isDebugEnabled()) {
     LOG.debug("File dialog path set to: " + path); // $NON-NLS-1$
   }
   dlg.setFilterPath(path);
   String fn = dlg.open();
   if (fn != null) {
     textFile.setText(fn);
     getButton(IDialogConstants.OK_ID).setEnabled(true);
   }
 }
  public OutputStream getOutputStream(Shell shell) {
    FileDialog dialog = new FileDialog(shell, SWT.SAVE);

    String filterPath;
    String relativeFileName;

    int lastIndexOfFileSeparator = defaultFileName.lastIndexOf(File.separator);
    if (lastIndexOfFileSeparator >= 0) {
      filterPath = defaultFileName.substring(0, lastIndexOfFileSeparator);
      relativeFileName = defaultFileName.substring(lastIndexOfFileSeparator + 1);
    } else {
      filterPath = "/"; // $NON-NLS-1$
      relativeFileName = defaultFileName;
    }

    dialog.setFilterPath(filterPath);
    dialog.setOverwrite(true);

    dialog.setFileName(relativeFileName);
    dialog.setFilterNames(defaultFilterNames);
    dialog.setFilterExtensions(defaultFilterExtensions);
    String fileName = dialog.open();
    if (fileName == null) {
      return null;
    }

    try {
      return new PrintStream(fileName);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    }
  }
 private static String saveAs(Shell parent) {
   FileDialog fd = new FileDialog(parent, SWT.SAVE);
   fd.setText(Messages.Screenshots_SaveAsDialog);
   String[] filterExt = {"*" + EXTENSION}; // $NON-NLS-1$
   fd.setFilterExtensions(filterExt);
   fd.setFileName(getDefaultFilename());
   return fd.open();
 }
 private String browseForSourceFile(String[] extensions) {
   FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
   String wkspRoot = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString();
   dialog.setFileName(wkspRoot);
   dialog.setFilterExtensions(extensions);
   String result = dialog.open();
   return result;
 }
예제 #6
0
 public void widgetSelected(SelectionEvent e) {
   FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
   dialog.setFileName(fileText.getText());
   String text = dialog.open();
   if (text != null) {
     fileText.setText(text);
   }
 }
  public String askUserForOutputFilename() {
    Shell shell = UiPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell();
    FileDialog dlg = new FileDialog(shell, SWT.SAVE);
    dlg.setFilterExtensions(new String[] {"*.txt", "*.*"}); // $NON-NLS-1$ //$NON-NLS-2$
    dlg.setText(UiConstants.Util.getString(EXPORT_SQL_DIALOG_TITLE));
    dlg.setFileName(UiConstants.Util.getString(EXPORT_DEFAULT_FILENAME));

    return dlg.open();
  }
예제 #8
0
  private void browse() {
    FileDialog dialog = new FileDialog(base.getShell(), SWT.SAVE);
    String file = getFile();
    if (file != null) {
      dialog.setFileName(file);
    }

    String selection = dialog.open();
    if (selection != null) {
      setFile(selection);
    }
  }
 private void selectFile() {
   FileDialog fileDialog = new FileDialog(getShell(), SWT.OPEN);
   fileDialog.setText("Select JSHint library file");
   File file = new File(preferences.getCustomLibPath());
   fileDialog.setFileName(file.getName());
   fileDialog.setFilterPath(file.getParent());
   fileDialog.setFilterNames(new String[] {"JavaScript files"});
   fileDialog.setFilterExtensions(new String[] {"*.js", ""});
   String selectedPath = fileDialog.open();
   if (selectedPath != null) {
     customLibPathText.setText(selectedPath);
   }
 }
예제 #10
0
 /** Open a resource chooser to select a PDA program */
 protected void browseLispExeFiles() {
   FileDialog fd = new FileDialog(getShell());
   fd.setFileName(fProgramText.getText());
   if (exename != null && exename != "") {
     fd.setFilterNames(new String[] {exename});
   } else if (System.getProperty("os.name").toLowerCase().contains("windows")) {
     fd.setFilterExtensions(new String[] {"*.exe"});
   }
   String fileName = fd.open();
   if (fileName != null) {
     fProgramText.setText(fileName);
   }
 }
  /** 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);
  }
  /** {@inheritDoc} */
  @Override
  void commandButtonExecute(MigrationEditorOperation editor) {
    LOGGER.info(MessageUtil.INF_ACTION_SAVE_CSV);

    TreeViewer treeViewer = editor.getTreeViewer();
    List<JbmEditorMigrationRow> list = createEditorViewData(treeViewer);
    try {
      String temporaryCsvFilePath =
          PluginUtil.getPluginDir() + ApplicationPropertyUtil.OUTPUT_TEMPORARY_CSV;
      outputTemporaryCsv(list, temporaryCsvFilePath);

      FileDialog dialog = new FileDialog(treeViewer.getControl().getShell(), SWT.SAVE);
      String[] extensions = {ApplicationPropertyUtil.EXTENSION_CSV};
      dialog.setFilterExtensions(extensions);
      dialog.setFileName(ApplicationPropertyUtil.DEFAULT_CSV_FILENAME);
      outputFilePath = temporaryCsvFilePath.replaceFirst(StringUtil.SLASH, StringUtil.EMPTY);
      final String formPath = outputFilePath;
      final String toPath = dialog.open();
      if (toPath != null) {
        Job job =
            new Job(MessageUtil.INF_SAVE_CSV_START) {
              @Override
              protected IStatus run(IProgressMonitor monitor) {

                monitor.beginTask(MessageUtil.INF_SAVE_CSV_START, IProgressMonitor.UNKNOWN);

                // Cancellation process
                if (monitor.isCanceled()) {
                  return Status.CANCEL_STATUS;
                }
                // CSV output
                CmnFileUtil.copyFile(formPath, toPath);
                monitor.done();
                return Status.OK_STATUS;
              }
            };
        job.setUser(true);
        job.schedule();
      }
    } catch (JbmException e) {
      PluginUtil.viewErrorDialog(ResourceUtil.OUTPUT_CSV, MessageUtil.ERR_OUTPUT_CSV, e);
    } catch (IOException e) {
      PluginUtil.viewErrorDialog(ResourceUtil.OUTPUT_CSV, MessageUtil.ERR_OUTPUT_CSV, e);
    }
  }
  private String browse(final String path) {
    final FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
    dialog.setFilterExtensions(m_filenameExtensions);
    dialog.setFilterNames(m_fileTypes);
    if (path != "") // $NON-NLS-1$
    dialog.setFileName(path);
    final String fileName = dialog.open();

    if (fileName == null) return ""; // $NON-NLS-1$

    final String[] filterExtensions = dialog.getFilterExtensions();
    boolean regularExtension = false;
    for (final String filterExtension : filterExtensions)
      if (fileName.endsWith(filterExtension.substring(1))) {
        regularExtension = true;
        break;
      }
    if (!regularExtension && filterExtensions.length == 1)
      return fileName + filterExtensions[0].substring(1);
    return fileName;
  }
  private void saveImportOrder(List elements) {
    IDialogSettings dialogSettings = JavaScriptPlugin.getDefault().getDialogSettings();

    FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
    dialog.setText(PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_title);
    dialog.setFilterExtensions(new String[] {"*.importorder", "*.*"}); // $NON-NLS-1$ //$NON-NLS-2$
    dialog.setFileName("example.importorder"); // $NON-NLS-1$
    String lastPath = dialogSettings.get(DIALOGSETTING_LASTSAVEPATH);
    if (lastPath != null) {
      dialog.setFilterPath(lastPath);
    }
    String fileName = dialog.open();
    if (fileName != null) {
      dialogSettings.put(DIALOGSETTING_LASTSAVEPATH, dialog.getFilterPath());

      Properties properties = new Properties();
      for (int i = 0; i < elements.size(); i++) {
        ImportOrderEntry entry = (ImportOrderEntry) elements.get(i);
        properties.setProperty(String.valueOf(i), entry.serialize());
      }
      FileOutputStream fos = null;
      try {
        fos = new FileOutputStream(fileName);
        properties.store(fos, "Organize Import Order"); // $NON-NLS-1$
      } catch (IOException e) {
        JavaScriptPlugin.log(e);
        String title = PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_title;
        String message =
            PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_message;
        MessageDialog.openError(getShell(), title, message);
      } finally {
        if (fos != null) {
          try {
            fos.close();
          } catch (IOException e) {
          }
        }
      }
    }
  }
 protected void handleDestinationBrowseButtonPressed() {
   String idealSuffix;
   FileDialog dialog = new FileDialog(getContainer().getShell(), SWT.SAVE);
   if (isAddMavenScript()) {
     idealSuffix = OUTPUT_FILE_SUFFIX;
   } else {
     idealSuffix = getOutputSuffix();
   }
   dialog.setFilterExtensions(new String[] {'*' + idealSuffix, "*.*"}); // $NON-NLS-1$
   File destination = new File(getDestinationValue());
   dialog.setFileName(destination.getName());
   dialog.setFilterPath(destination.getParent());
   String selectedFileName = dialog.open();
   if (selectedFileName == null) {
     return;
   }
   if (!selectedFileName.endsWith(idealSuffix)) {
     selectedFileName += idealSuffix;
   }
   checkDestination(selectedFileName);
   destinationValue = selectedFileName;
 }
예제 #16
0
  private void init() throws IOException {
    FileDialog fd = new FileDialog(GUI.getShell(), SWT.SAVE);
    fd.setText("Ausgabedatei wählen.");
    String path = settings.getString("lastdir", System.getProperty("user.home"));
    if (path != null && path.length() > 0) {
      fd.setFilterPath(path);
    }
    fd.setFileName(
        new Dateiname(
                "kontoauszug", "", Einstellungen.getEinstellung().getDateinamenmuster(), "PDF")
            .get());
    fd.setFilterExtensions(new String[] {"*.PDF"});

    String s = fd.open();
    if (s == null || s.length() == 0) {
      return;
    }
    if (!s.endsWith(".PDF")) {
      s = s + ".PDF";
    }
    file = new File(s);
    settings.setAttribute("lastdir", file.getParent());
  }
예제 #17
0
  private String getFilePathByFileDialog(String modelElementName) {
    FileDialog dialog =
        new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
    dialog.setFilterNames(FILTER_NAMES);
    dialog.setFilterExtensions(FILTER_EXTS);
    String initialPath =
        PreferenceHelper.getPreference(EXPORT_MODEL_PATH, System.getProperty("user.home"));
    dialog.setFilterPath(initialPath);
    dialog.setOverwrite(true);

    try {
      // String initialFileName = projectSpace.getProjectName() + "@"
      // + projectSpace.getBaseVersion().getIdentifier() + ".ucp";
      String initialFileName = "ModelElement_" + modelElementName + "." + FILE_EXTENSION;
      dialog.setFileName(initialFileName);

    } catch (NullPointerException e) {
      // do nothing
    }

    String filePath = dialog.open();

    return filePath;
  }
예제 #18
0
  private File getFile(Object exportItem) {
    File file = null;
    if (exportItem instanceof Class) {
      DirectoryDialog directoryDialog = new DirectoryDialog(getShell());

      directoryDialog.setMessage(Messages.ExportWizardSelectDirectory);

      String dir = directoryDialog.open();
      if (dir != null) file = new File(dir);
    } else {
      String name = null;
      if (exportItem instanceof Account) name = ((Account) exportItem).getName();
      else if (exportItem instanceof Portfolio) name = ((Portfolio) exportItem).getName();
      else if (exportItem instanceof Security) name = ((Security) exportItem).getIsin();
      else if (exportItem instanceof String) name = (String) exportItem;

      FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
      if (name != null) dialog.setFileName(name + ".csv"); // $NON-NLS-1$
      String fileName = dialog.open();

      if (fileName != null) file = new File(fileName);
    }
    return file;
  }
예제 #19
0
 public void open(TreeItem items[], String defaultFilename) {
   try {
     String html = getHtml(items);
     final FileDialog dialog =
         new FileDialog(Display.getCurrent().getActiveShell().getShell(), SWT.SAVE);
     dialog.setFilterExtensions(new String[] {"*.html"}); // $NON-NLS-1$
     if (defaultFilename != null && !defaultFilename.equals("")) { // $NON-NLS-1$
       dialog.setFileName(defaultFilename);
     }
     String filename = dialog.open();
     if (filename == null || filename.equals("")) { // $NON-NLS-1$
       return;
     }
     try {
       XViewerLib.writeStringToFile(html, new File(filename));
     } catch (IOException ex) {
       XViewerLog.log(Activator.class, Level.SEVERE, ex);
       return;
     }
     Program.launch(filename);
   } catch (Exception ex) {
     XViewerLog.logAndPopup(Activator.class, Level.SEVERE, ex);
   }
 }
예제 #20
0
 public Gfui_dlg_file Init_file_(String v) {
   under.setFileName(v);
   return this;
 }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.jface.action.Action#run()
   */
  protected void doRun() {
    RepositoryNode node =
        (RepositoryNode) ((IStructuredSelection) getSelection()).getFirstElement();

    final Item item = node.getObject().getProperty().getItem();
    if (item == null) {
      return;
    }
    String initialFileName = null;
    String initialExtension = null;
    if (item instanceof DocumentationItem) {
      DocumentationItem documentationItem = (DocumentationItem) item;
      initialFileName = documentationItem.getName();
      if (documentationItem.getExtension() != null) {
        initialExtension = documentationItem.getExtension();
      }
    } else if (item instanceof LinkDocumentationItem) { // link documenation
      LinkDocumentationItem linkDocItem = (LinkDocumentationItem) item;

      if (!LinkUtils.validateLink(linkDocItem.getLink())) {
        MessageDialog.openError(
            Display.getCurrent().getActiveShell(),
            Messages.getString("ExtractDocumentationAction.fileErrorTitle"), // $NON-NLS-1$
            Messages.getString("ExtractDocumentationAction.fileErrorMessages")); // $NON-NLS-1$
        return;
      }

      initialFileName = linkDocItem.getName();
      if (linkDocItem.getExtension() != null) {
        initialExtension = linkDocItem.getExtension();
      }
    }
    if (initialFileName != null) {
      FileDialog fileDlg = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);

      if (initialExtension != null) {
        initialFileName = initialFileName + LinkUtils.DOT + initialExtension; // $NON-NLS-1$
        fileDlg.setFilterExtensions(
            new String[] {"*." + initialExtension, "*.*"}); // $NON-NLS-1$ //$NON-NLS-2$
      }
      fileDlg.setFileName(initialFileName);
      String filename = fileDlg.open();
      if (filename != null) {
        final File file = new File(filename);

        ProgressDialog progressDialog =
            new ProgressDialog(Display.getCurrent().getActiveShell()) {

              @Override
              public void run(IProgressMonitor monitor)
                  throws InvocationTargetException, InterruptedException {
                try {
                  if (item instanceof DocumentationItem) {
                    DocumentationItem documentationItem = (DocumentationItem) item;
                    documentationItem.getContent().setInnerContentToFile(file);
                  } else if (item instanceof LinkDocumentationItem) { // link documenation
                    LinkDocumentationItem linkDocItem = (LinkDocumentationItem) item;
                    ByteArray byteArray = LinkDocumentationHelper.getLinkItemContent(linkDocItem);
                    if (byteArray != null) {
                      byteArray.setInnerContentToFile(file);
                    }
                  }

                } catch (IOException ioe) {
                  MessageBoxExceptionHandler.process(ioe);
                }
              }
            };
        try {
          progressDialog.executeProcess();
        } catch (InvocationTargetException e) {
          ExceptionHandler.process(e);
        } catch (InterruptedException e) {
          // Nothing to do
        }
      }
    }
  }
        @Override
        public void widgetSelected(SelectionEvent e) {
          BarcodeViewGuiData guiData = null;

          try {
            guiData = new BarcodeViewGuiData();

            // save dialog for pdf file.
            FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
            fileDialog.setFilterPath(
                perferenceStore.getString(PreferenceConstants.PDF_DIRECTORY_PATH));
            fileDialog.setOverwrite(true);
            fileDialog.setFileName("default.pdf"); // $NON-NLS-1$
            String pdfFilePath = fileDialog.open();

            if (pdfFilePath == null) return;

            List<String> patientNumbers =
                SessionManager.getAppService().executeGetSourceSpecimenUniqueInventoryIds(32);

            SaveOperation saveOperation = new SaveOperation(guiData, patientNumbers, pdfFilePath);

            try {
              new ProgressMonitorDialog(shell).run(true, true, saveOperation);

            } catch (InvocationTargetException e1) {
              saveOperation.saveFailed();
              saveOperation.setError(
                  Messages.PatientLabelEntryForm_saveop_error_title,
                  "InvocationTargetException: " //$NON-NLS-1$
                      + e1.getCause().getMessage());

            } catch (InterruptedException e2) {
              BgcPlugin.openAsyncError(Messages.PatientLabelEntryForm_save_error_title, e2);
            }

            if (saveOperation.isSuccessful()) {
              String parentDir = new File(pdfFilePath).getParentFile().getPath();
              if (parentDir != null)
                perferenceStore.setValue(PreferenceConstants.PDF_DIRECTORY_PATH, parentDir);

              updateSavePreferences();
              clearFieldsConfirm();
              return;
            }

            if (saveOperation.errorExists()) {
              BgcPlugin.openAsyncError(saveOperation.getError()[0], saveOperation.getError()[1]);
            }

          } catch (CBSRGuiVerificationException e1) {
            BgcPlugin.openAsyncError(e1.title, e1.messsage);
            return;
          } catch (BiobankServerException e2) {
            BgcPlugin.openAsyncError(
                Messages.PatientLabelEntryForm_specId_error_title, e2.getMessage());
          } catch (ApplicationException e3) {
            BgcPlugin.openAsyncError(
                Messages.PatientLabelEntryForm_server_error_title, e3.getMessage());
          }
        }
예제 #23
0
  public Result export(String speratorChar, String fileExtension) {
    if (!popupConfirm
        || popupConfirm
            && MessageDialog.openConfirm(
                Displays.getActiveShell(), "Export Table", "Export Table to CSV?")) {
      StringBuilder sb = new StringBuilder();
      sb.append(title + "\n");
      String htmlStr = AHTML.htmlToText(html);
      Matcher m =
          Pattern.compile(
                  "<table.*?</table>",
                  Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
              .matcher(htmlStr);
      if (m.find()) {
        String csv = m.group();
        Matcher rowM =
            Pattern.compile(
                    "<tr.*?>(.*?)</tr>",
                    Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(csv);
        while (rowM.find()) {
          String row = rowM.group(1);
          row = row.replaceAll("[\n\r]*", "");
          // Handle all the headers
          for (String tag : elementTags) {
            Matcher thM =
                Pattern.compile(
                        "<" + tag + ".*?>(.*?)</" + tag + ">",
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                    .matcher(row);
            String csvRow = "";
            while (thM.find()) {
              String cellStr = removeLeadTrailSpaces(thM.group(1));
              String excelTextPrefix = (excelTextFields && !cellStr.contains(",")) ? "=" : "";
              csvRow += excelTextPrefix + "\"" + cellStr + "\"" + speratorChar;
            }
            if (!csvRow.equals("")) {
              csvRow = csvRow.replaceFirst(speratorChar + "$", "\n");
              sb.append(csvRow);
            }
          }
        }
        String path = "";
        if (popupConfirm) {
          FileDialog dialog = new FileDialog(Displays.getActiveShell(), SWT.SAVE | SWT.SINGLE);
          dialog.setFilterExtensions(new String[] {"*." + fileExtension});
          dialog.setFilterPath(System.getProperty("user.home"));
          dialog.setFileName("table.csv");
          path = dialog.open();
        } else {
          path = System.getProperty("user.home") + File.separator + "table." + fileExtension;
        }

        if (path != null) {
          try {
            File file = new File(path);
            Lib.writeStringToFile(sb.toString(), file);
            if (openInSystem) {
              Program.launch(file.getAbsolutePath());
            }
            return Result.TrueResult;
          } catch (IOException ex) {
            OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex);
          }
        }
      } else {
        AWorkbench.popup("ERROR", "Can't find table in results.\n\nNothing to export");
      }
    }
    return Result.FalseResult;
  }
  @Override
  protected String browse(final SapphireRenderingContext context) {
    final Property property = property();
    final List<Path> roots = getBasePaths();
    String selectedAbsolutePath = null;

    final List<String> extensions;

    if (this.fileExtensionService == null) {
      extensions = this.staticFileExtensionsList;
    } else {
      extensions = this.fileExtensionService.extensions();
    }

    if (enclosed()) {
      final List<IContainer> baseContainers = new ArrayList<IContainer>();

      for (Path path : roots) {
        final IContainer baseContainer = getWorkspaceContainer(path.toFile());

        if (baseContainer != null) {
          baseContainers.add(baseContainer);
        } else {
          break;
        }
      }

      final ITreeContentProvider contentProvider;
      final ILabelProvider labelProvider;
      final ViewerComparator viewerComparator;
      final Object input;

      if (roots.size() == baseContainers.size()) {
        // All paths are in the Eclipse Workspace. Use the available content and label
        // providers.

        contentProvider = new WorkspaceContentProvider(baseContainers);
        labelProvider = new WorkbenchLabelProvider();
        viewerComparator = new ResourceComparator();
        input = ResourcesPlugin.getWorkspace().getRoot();
      } else {
        // At least one of the roots is not in the Eclipse Workspace. Use custom file
        // system content and label providers.

        contentProvider = new FileSystemContentProvider(roots);
        labelProvider = new FileSystemLabelProvider(context);
        viewerComparator = new FileSystemNodeComparator();
        input = new Object();
      }

      final ElementTreeSelectionDialog dialog =
          new ElementTreeSelectionDialog(context.getShell(), labelProvider, contentProvider);

      dialog.setTitle(property.definition().getLabel(false, CapitalizationType.TITLE_STYLE, false));
      dialog.setMessage(
          createBrowseDialogMessage(
              property.definition().getLabel(true, CapitalizationType.NO_CAPS, false)));
      dialog.setAllowMultiple(false);
      dialog.setHelpAvailable(false);
      dialog.setInput(input);
      dialog.setComparator(viewerComparator);

      final Path currentPathAbsolute = convertToAbsolute((Path) ((Value<?>) property).content());

      if (currentPathAbsolute != null) {
        Object initialSelection = null;

        if (contentProvider instanceof WorkspaceContentProvider) {
          final URI uri = currentPathAbsolute.toFile().toURI();
          final IWorkspaceRoot wsroot = ResourcesPlugin.getWorkspace().getRoot();

          final IFile[] files = wsroot.findFilesForLocationURI(uri);

          if (files.length > 0) {
            final IFile file = files[0];

            if (file.exists()) {
              initialSelection = file;
            }
          }

          if (initialSelection == null) {
            final IContainer[] containers = wsroot.findContainersForLocationURI(uri);

            if (containers.length > 0) {
              final IContainer container = containers[0];

              if (container.exists()) {
                initialSelection = container;
              }
            }
          }
        } else {
          initialSelection =
              ((FileSystemContentProvider) contentProvider).find(currentPathAbsolute);
        }

        if (initialSelection != null) {
          dialog.setInitialSelection(initialSelection);
        }
      }

      if (this.type == FileSystemResourceType.FILE) {
        dialog.setValidator(new FileSelectionStatusValidator());
      } else if (this.type == FileSystemResourceType.FOLDER) {
        dialog.addFilter(new ContainersOnlyViewerFilter());
      }

      if (!extensions.isEmpty()) {
        dialog.addFilter(new ExtensionBasedViewerFilter(extensions));
      }

      if (dialog.open() == Window.OK) {
        final Object firstResult = dialog.getFirstResult();

        if (firstResult instanceof IResource) {
          selectedAbsolutePath = ((IResource) firstResult).getLocation().toString();
        } else {
          selectedAbsolutePath = ((FileSystemNode) firstResult).getFile().getPath();
        }
      }
    } else if (this.type == FileSystemResourceType.FOLDER) {
      final DirectoryDialog dialog = new DirectoryDialog(context.getShell());
      dialog.setText(
          property.definition().getLabel(true, CapitalizationType.FIRST_WORD_ONLY, false));
      dialog.setMessage(
          createBrowseDialogMessage(
              property.definition().getLabel(true, CapitalizationType.NO_CAPS, false)));

      final Value<?> value = (Value<?>) property;
      final Path path = (Path) value.content();

      if (path != null) {
        dialog.setFilterPath(path.toOSString());
      } else if (roots.size() > 0) {
        dialog.setFilterPath(roots.get(0).toOSString());
      }

      selectedAbsolutePath = dialog.open();
    } else {
      final FileDialog dialog = new FileDialog(context.getShell());
      dialog.setText(
          property.definition().getLabel(true, CapitalizationType.FIRST_WORD_ONLY, false));

      final Value<?> value = (Value<?>) property;
      final Path path = (Path) value.content();

      if (path != null && path.segmentCount() > 1) {
        dialog.setFilterPath(path.removeLastSegments(1).toOSString());
        dialog.setFileName(path.lastSegment());
      } else if (roots.size() > 0) {
        dialog.setFilterPath(roots.get(0).toOSString());
      }

      if (!extensions.isEmpty()) {
        final StringBuilder buf = new StringBuilder();

        for (String extension : extensions) {
          if (buf.length() > 0) {
            buf.append(';');
          }

          buf.append("*.");
          buf.append(extension);
        }

        dialog.setFilterExtensions(new String[] {buf.toString()});
      }

      selectedAbsolutePath = dialog.open();
    }

    if (selectedAbsolutePath != null) {
      final Path relativePath = convertToRelative(new Path(selectedAbsolutePath));

      if (relativePath != null) {
        String result = relativePath.toPortableString();

        if (this.includeLeadingSlash) {
          result = "/" + result;
        }

        return result;
      }
    }

    return null;
  }
예제 #25
0
  /**
   * Handle the create button selection event.
   *
   * @param event org.eclipse.swt.events.SelectionEvent
   */
  void createButtonSelected(SelectionEvent event) {

    /* Compute the appropriate dialog style */
    int style = getDefaultStyle();
    if (okButton.getEnabled() && okButton.getSelection()) style |= SWT.OK;
    if (cancelButton.getEnabled() && cancelButton.getSelection()) style |= SWT.CANCEL;
    if (yesButton.getEnabled() && yesButton.getSelection()) style |= SWT.YES;
    if (noButton.getEnabled() && noButton.getSelection()) style |= SWT.NO;
    if (retryButton.getEnabled() && retryButton.getSelection()) style |= SWT.RETRY;
    if (abortButton.getEnabled() && abortButton.getSelection()) style |= SWT.ABORT;
    if (ignoreButton.getEnabled() && ignoreButton.getSelection()) style |= SWT.IGNORE;
    if (iconErrorButton.getEnabled() && iconErrorButton.getSelection()) style |= SWT.ICON_ERROR;
    if (iconInformationButton.getEnabled() && iconInformationButton.getSelection())
      style |= SWT.ICON_INFORMATION;
    if (iconQuestionButton.getEnabled() && iconQuestionButton.getSelection())
      style |= SWT.ICON_QUESTION;
    if (iconWarningButton.getEnabled() && iconWarningButton.getSelection())
      style |= SWT.ICON_WARNING;
    if (iconWorkingButton.getEnabled() && iconWorkingButton.getSelection())
      style |= SWT.ICON_WORKING;
    if (primaryModalButton.getEnabled() && primaryModalButton.getSelection())
      style |= SWT.PRIMARY_MODAL;
    if (applicationModalButton.getEnabled() && applicationModalButton.getSelection())
      style |= SWT.APPLICATION_MODAL;
    if (systemModalButton.getEnabled() && systemModalButton.getSelection())
      style |= SWT.SYSTEM_MODAL;
    if (saveButton.getEnabled() && saveButton.getSelection()) style |= SWT.SAVE;
    if (openButton.getEnabled() && openButton.getSelection()) style |= SWT.OPEN;
    if (multiButton.getEnabled() && multiButton.getSelection()) style |= SWT.MULTI;

    /* Open the appropriate dialog type */
    String name = dialogCombo.getText();

    if (name.equals(ControlExample.getResourceString("ColorDialog"))) {
      ColorDialog dialog = new ColorDialog(shell, style);
      dialog.setRGB(new RGB(100, 100, 100));
      dialog.setText(ControlExample.getResourceString("Title"));
      RGB result = dialog.open();
      textWidget.append(ControlExample.getResourceString("ColorDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result}) + Text.DELIMITER);
      textWidget.append("getRGB() = " + dialog.getRGB() + Text.DELIMITER + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("DirectoryDialog"))) {
      DirectoryDialog dialog = new DirectoryDialog(shell, style);
      dialog.setMessage(ControlExample.getResourceString("Example_string"));
      dialog.setText(ControlExample.getResourceString("Title"));
      String result = dialog.open();
      textWidget.append(ControlExample.getResourceString("DirectoryDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result})
              + Text.DELIMITER
              + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("FileDialog"))) {
      FileDialog dialog = new FileDialog(shell, style);
      dialog.setFileName(ControlExample.getResourceString("readme_txt"));
      dialog.setFilterNames(FilterNames);
      dialog.setFilterExtensions(FilterExtensions);
      dialog.setText(ControlExample.getResourceString("Title"));
      String result = dialog.open();
      textWidget.append(ControlExample.getResourceString("FileDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result}) + Text.DELIMITER);
      textWidget.append("getFileNames() =" + Text.DELIMITER);
      if ((dialog.getStyle() & SWT.MULTI) != 0) {
        String[] files = dialog.getFileNames();
        for (int i = 0; i < files.length; i++) {
          textWidget.append("\t" + files[i] + Text.DELIMITER);
        }
      }
      textWidget.append(
          "getFilterIndex() = " + dialog.getFilterIndex() + Text.DELIMITER + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("FontDialog"))) {
      FontDialog dialog = new FontDialog(shell, style);
      dialog.setText(ControlExample.getResourceString("Title"));
      FontData result = dialog.open();
      textWidget.append(ControlExample.getResourceString("FontDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result}) + Text.DELIMITER);
      textWidget.append("getFontList() =" + Text.DELIMITER);
      FontData[] fonts = dialog.getFontList();
      if (fonts != null) {
        for (int i = 0; i < fonts.length; i++) {
          textWidget.append("\t" + fonts[i] + Text.DELIMITER);
        }
      }
      textWidget.append("getRGB() = " + dialog.getRGB() + Text.DELIMITER + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("PrintDialog"))) {
      PrintDialog dialog = new PrintDialog(shell, style);
      dialog.setText(ControlExample.getResourceString("Title"));
      PrinterData result = dialog.open();
      textWidget.append(ControlExample.getResourceString("PrintDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result}) + Text.DELIMITER);
      textWidget.append("getScope() = " + dialog.getScope() + Text.DELIMITER);
      textWidget.append("getStartPage() = " + dialog.getStartPage() + Text.DELIMITER);
      textWidget.append("getEndPage() = " + dialog.getEndPage() + Text.DELIMITER);
      textWidget.append(
          "getPrintToFile() = " + dialog.getPrintToFile() + Text.DELIMITER + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("MessageBox"))) {
      MessageBox dialog = new MessageBox(shell, style);
      dialog.setMessage(ControlExample.getResourceString("Example_string"));
      dialog.setText(ControlExample.getResourceString("Title"));
      int result = dialog.open();
      textWidget.append(ControlExample.getResourceString("MessageBox") + Text.DELIMITER);
      /*
       * The resulting integer depends on the original
       * dialog style.  Decode the result and display it.
       */
      switch (result) {
        case SWT.OK:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.OK"}));
          break;
        case SWT.YES:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.YES"}));
          break;
        case SWT.NO:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.NO"}));
          break;
        case SWT.CANCEL:
          textWidget.append(
              ControlExample.getResourceString("Result", new String[] {"SWT.CANCEL"}));
          break;
        case SWT.ABORT:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.ABORT"}));
          break;
        case SWT.RETRY:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.RETRY"}));
          break;
        case SWT.IGNORE:
          textWidget.append(
              ControlExample.getResourceString("Result", new String[] {"SWT.IGNORE"}));
          break;
        default:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"" + result}));
          break;
      }
      textWidget.append(Text.DELIMITER + Text.DELIMITER);
    }
  }
예제 #26
0
 /**
  * Show a dialog that lets the user select a file. This method allows to set the title of the
  * dialog.
  *
  * @param title The title the dialog should show.
  * @since 2.1
  */
 protected String handleBrowseButtonSelected(String title) {
   FileDialog fileDialog = new FileDialog(getShell(), SWT.NONE);
   fileDialog.setText(title);
   fileDialog.setFileName(fProgText.getText());
   return fileDialog.open();
 }
  /** @see de.willuhn.jameica.gui.Action#handleAction(java.lang.Object) */
  public void handleAction(Object context) {
    try {
      DBIterator it = Einstellungen.getDBService().createList(Mitglied.class);
      if (it.size() > 0) {
        SimpleDialog dialog = new SimpleDialog(SimpleDialog.POSITION_CENTER);
        dialog.setTitle("Fehler");
        dialog.setText("Datenbank ist nicht leer!");
        dialog.open();
        return;
      }

      // Vom System eingefügte Sätze löschen. Ansonsten gibt es duplicate keys
      it = Einstellungen.getDBService().createList(Adresstyp.class);
      while (it.hasNext()) {
        Adresstyp a = (Adresstyp) it.next();
        a.delete();
      }

    } catch (Exception e1) {
      Logger.error("Fehler: ", e1);
    }

    FileDialog fd = new FileDialog(GUI.getShell(), SWT.OPEN);
    fd.setFileName("jverein-" + new JVDateFormatJJJJMMTT().format(new Date()) + ".xml");
    fd.setFilterExtensions(new String[] {"*.xml"});
    fd.setText(JVereinPlugin.getI18n().tr("Bitte wählen Sie die Backup-Datei aus"));
    String f = fd.open();
    if (f == null || f.length() == 0) {
      return;
    }

    final File file = new File(f);
    if (!file.exists()) {
      return;
    }

    Application.getController()
        .start(
            new BackgroundTask() {

              private boolean cancel = false;

              /**
               * @see de.willuhn.jameica.system.BackgroundTask#run(de.willuhn.util.ProgressMonitor)
               */
              public void run(ProgressMonitor monitor) throws ApplicationException {
                monitor.setStatusText(JVereinPlugin.getI18n().tr("Importiere Backup"));
                Logger.info("importing backup " + file.getAbsolutePath());
                final ClassLoader loader =
                    Application.getPluginLoader()
                        .getPlugin(JVereinPlugin.class)
                        .getResources()
                        .getClassLoader();

                try {
                  EigenschaftGruppe eg =
                      (EigenschaftGruppe)
                          Einstellungen.getDBService().createObject(EigenschaftGruppe.class, "1");
                  eg.delete();
                } catch (RemoteException e1) {
                  Logger.error("EigenschaftGruppe mit id=1 kann nicht gelöscht werden", e1);
                }

                Reader reader = null;
                try {
                  InputStream is = new BufferedInputStream(new FileInputStream(file));
                  reader =
                      new XmlReader(
                          is,
                          new ObjectFactory() {

                            public GenericObject create(String type, String id, Map values)
                                throws Exception {
                              AbstractDBObject object =
                                  (AbstractDBObject)
                                      Einstellungen.getDBService()
                                          .createObject(loader.loadClass(type), null);
                              object.setID(id);
                              Iterator<?> i = values.keySet().iterator();
                              while (i.hasNext()) {
                                String name = (String) i.next();
                                object.setAttribute(name, values.get(name));
                              }
                              return object;
                            }
                          });

                  long count = 1;
                  GenericObject o = null;
                  while ((o = reader.read()) != null) {
                    try {
                      ((AbstractDBObject) o).insert();
                    } catch (Exception e) {
                      Logger.error(
                          "unable to import "
                              + o.getClass().getName()
                              + ":"
                              + o.getID()
                              + ", skipping",
                          e);
                      monitor.log(
                          JVereinPlugin.getI18n()
                              .tr(
                                  " {0} fehlerhaft: {1}, überspringe ",
                                  new String[] {BeanUtil.toString(o), e.getMessage()}));
                    }
                    if (count++ % 100 == 0) {
                      monitor.addPercentComplete(1);
                    }
                  }
                  monitor.setStatus(ProgressMonitor.STATUS_DONE);
                  monitor.setStatusText(JVereinPlugin.getI18n().tr("Backup importiert"));
                  monitor.setPercentComplete(100);
                } catch (Exception e) {
                  Logger.error("error while importing data", e);
                  throw new ApplicationException(e.getMessage());
                } finally {
                  if (reader != null) {
                    try {
                      reader.close();
                      Logger.info("backup imported");
                    } catch (Exception e) {
                      /* useless */
                    }
                  }
                }
              }

              /** @see de.willuhn.jameica.system.BackgroundTask#isInterrupted() */
              public boolean isInterrupted() {
                return this.cancel;
              }

              /** @see de.willuhn.jameica.system.BackgroundTask#interrupt() */
              public void interrupt() {
                this.cancel = true;
              }
            });
  }