示例#1
0
  @Override
  protected String perform(IAction action, IProgressMonitor monitor) throws Exception {
    try {
      final PyHierarchyView view;
      IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
      IWorkbenchPage page = workbenchWindow.getActivePage();
      view =
          (PyHierarchyView)
              page.showView(
                  "com.python.pydev.ui.hierarchy.PyHierarchyView",
                  null,
                  IWorkbenchPage.VIEW_VISIBLE);

      ProgressMonitorDialog monitorDialog =
          new AsynchronousProgressMonitorDialog(EditorUtils.getShell());
      try {
        IRunnableWithProgress operation =
            new IRunnableWithProgress() {

              public void run(final IProgressMonitor monitor)
                  throws InvocationTargetException, InterruptedException {
                try {
                  final HierarchyNodeModel model;

                  // set whatever is needed for the hierarchy
                  IPyRefactoring pyRefactoring = AbstractPyRefactoring.getPyRefactoring();
                  if (pyRefactoring instanceof IPyRefactoring2) {
                    RefactoringRequest refactoringRequest = getRefactoringRequest(monitor);
                    IPyRefactoring2 r2 = (IPyRefactoring2) pyRefactoring;
                    model = r2.findClassHierarchy(refactoringRequest, false);

                    if (monitor.isCanceled()) {
                      return;
                    }
                    Runnable r =
                        new Runnable() {
                          public void run() {
                            if (!monitor.isCanceled()) {
                              view.setHierarchy(model);
                            }
                          }
                        };
                    Display.getDefault().asyncExec(r);
                  }
                } catch (Exception e) {
                  Log.log(e);
                }
              }
            };

        boolean fork = true;
        monitorDialog.run(fork, true, operation);
      } catch (Throwable e) {
        Log.log(e);
      }
    } catch (Exception e) {
      Log.log(e);
    }
    return "";
  }
  public boolean performFinish() {
    if (resolvedOperation.getResolutionResult().getSeverity() != IStatus.ERROR) {
      ProgressMonitorDialog progress = new ProgressMonitorDialog(getShell());
      try {
        progress.run(
            true,
            true,
            new IRunnableWithProgress() {

              public void run(IProgressMonitor monitor)
                  throws InvocationTargetException, InterruptedException {
                getProvisioningUI()
                    .schedule(
                        resolvedOperation.getProvisioningJob(monitor),
                        StatusManager.SHOW | StatusManager.LOG);
              }
            });
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return true;
    }
    return false;
  }
示例#3
0
  @Inject
  @Optional
  public void listDevices(
      @UIEventTopic(EventConstants.SHOW_SENSORS) final Object data,
      @Named(IServiceConstants.ACTIVE_SHELL) Shell shell)
      throws InvocationTargetException, InterruptedException {
    final List<String> list = new ArrayList<String>();
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
    dialog.run(
        false,
        false,
        new IRunnableWithProgress() {

          @Override
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            monitor.beginTask("Fetching Sensors Names Under Device " + data, 100);
            for (int i = 0; i < 5; i++) {
              TimeUnit.SECONDS.sleep(2);
              monitor.worked(20);
              if (i == 3)
                for (int j = 0; j < 100; j++) {
                  list.add("C");
                }
            }
            viewer.setInput(list);
            monitor.done();
          }
        });
  }
  /** Handler for the "Build" button. */
  private void buildConfig() {
    final IStatus[] problem = new IStatus[1];

    try {
      ProgressMonitorDialog dlg = new ProgressMonitorDialog(tree.getControl().getShell());
      dlg.run(
          true,
          true,
          new IRunnableWithProgress() {

            public void run(IProgressMonitor monitor) {
              IStatus status = currentConfig.build(monitor);
              if (status.matches(IStatus.WARNING | IStatus.ERROR)) {
                problem[0] = status;
              }
            }
          });
    } catch (Exception e) {
      CUIPlugin.log(WorkingSetMessages.WSConfigsController_buildFailedLog, e);
    }

    // it is possible that some project configurations had to applied in
    // order to effect a build. Refresh to handle that case
    updateForActivation();

    if (problem[0] != null) {
      // show the problem
      ErrorDialog.openError(
          tree.getControl().getShell(),
          WorkingSetMessages.WSConfigsController_buildFailedDlgTitle,
          WorkingSetMessages.WSConfigsController_buildFailedDlgMsg,
          problem[0]);
    }
  }
示例#5
0
  @Execute
  public void execute(
      IEclipseContext context,
      @Named(IServiceConstants.ACTIVE_SHELL) Shell shell,
      @Named(IServiceConstants.ACTIVE_PART) final MContribution contribution)
      throws InvocationTargetException, InterruptedException {
    final IEclipseContext pmContext = context.createChild();

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
    dialog.open();
    dialog.run(
        true,
        true,
        new IRunnableWithProgress() {
          @Override
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            pmContext.set(IProgressMonitor.class.getName(), monitor);
            if (contribution != null) {
              //			Object clientObject = contribution.getObject();
              //					ContextInjectionFactory.invoke(clientObject, Persist.class, //$NON-NLS-1$
              //							pmContext, null);
            }
          }
        });

    pmContext.dispose();
  }
  /** @see IActionDelegate#run(IAction) */
  protected void doRun() {
    IRunnableWithProgress code =
        new IRunnableWithProgress() {

          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            monitor.beginTask(
                Messages.getString("ChangeLog.PrepareChangeLog"), 1000); // $NON-NLS-1$
            prepareChangeLog(monitor);
            monitor.done();
          }
        };

    ProgressMonitorDialog pd =
        new ProgressMonitorDialog(getWorkbench().getActiveWorkbenchWindow().getShell());

    try {
      pd.run(false /* fork */, false /* cancelable */, code);
    } catch (InvocationTargetException e) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e));
      return;
    } catch (InterruptedException e) {
      ChangelogPlugin.getDefault()
          .getLog()
          .log(
              new Status(
                  IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e));
    }
  }
  @Override
  public void run() {
    final VirtualViewerListener listener = new VirtualViewerListener();
    VirtualTreeModelViewer virtualViewer = initVirtualViewer(fClientViewer, listener);

    ProgressMonitorDialog dialog =
        new TimeTriggeredProgressMonitorDialog(fClientViewer.getControl().getShell(), 500);
    final IProgressMonitor monitor = dialog.getProgressMonitor();
    dialog.setCancelable(true);

    try {
      dialog.run(
          true,
          true,
          new IRunnableWithProgress() {
            @Override
            public void run(final IProgressMonitor m)
                throws InvocationTargetException, InterruptedException {
              synchronized (listener) {
                listener.fProgressMonitor = m;
                listener.fProgressMonitor.beginTask(
                    DebugUIPlugin.removeAccelerators(getText()), listener.fRemainingUpdatesCount);
              }

              while ((!listener.fLabelUpdatesComplete || !listener.fViewerUpdatesComplete)
                  && !listener.fProgressMonitor.isCanceled()) {
                Thread.sleep(1);
              }
              synchronized (listener) {
                listener.fProgressMonitor = null;
              }
            }
          });
    } catch (InvocationTargetException e) {
      DebugUIPlugin.log(e);
      return;
    } catch (InterruptedException e) {
      return;
    }

    VirtualItem root = virtualViewer.getTree();
    if (!monitor.isCanceled()) {
      List<VirtualItem> list = new ArrayList<VirtualItem>();
      collectAllChildren(root, list);
      FindLabelProvider labelProvider = new FindLabelProvider(virtualViewer, list);
      VirtualItem result = performFind(list, labelProvider);
      if (result != null) {
        setSelectionToClient(virtualViewer, labelProvider, result);
      }
    }

    virtualViewer.removeLabelUpdateListener(listener);
    virtualViewer.removeViewerUpdateListener(listener);
    virtualViewer.dispose();
  }
  private boolean checkHCatalogConnection(final HCatalogConnection connection) {
    final boolean[] result = new boolean[] {true};
    IRunnableWithProgress runnableWithProgress =
        new IRunnableWithProgress() {

          @Override
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            monitor.beginTask(
                Messages.getString("CreateHCatalogSchemaAction.checkConnection"),
                IProgressMonitor.UNKNOWN);
            try {
              final ConnectionStatus connectionStatus =
                  HCatalogServiceUtil.testConnection(connection);
              if (!connectionStatus.getResult()) {
                PlatformUI.getWorkbench()
                    .getDisplay()
                    .syncExec(
                        new Runnable() {

                          @Override
                          public void run() {
                            new ErrorDialogWidthDetailArea(
                                PlatformUI.getWorkbench().getDisplay().getActiveShell(),
                                Activator.PLUGIN_ID,
                                Messages.getString(
                                    "CreateHCatalogSchemaAction.connectionFailure.mainMsg"),
                                connectionStatus //$NON-NLS-1$
                                    .getMessageException());
                            result[0] = false;
                            return;
                          }
                        });
              }

            } catch (Exception e) {
            } finally {
              monitor.done();
            }
          }
        };
    ProgressMonitorDialog dialog = new ProgressMonitorDialog(Display.getDefault().getActiveShell());
    try {
      dialog.run(true, true, runnableWithProgress);
    } catch (Exception e) {
      result[0] = false;
      ExceptionHandler.process(e);
    }

    return result[0];
  }
  /**
   * Restores the modules. Is called when the user changed something in the editor and applies the
   * change.
   *
   * <p>Gathers all the info and calls the hook that really restores things within a thread, so that
   * the user can get information on the progress.
   *
   * <p>Only the information on the default interpreter is stored.
   *
   * @param editorChanged whether the editor was changed (if it wasn't, we'll ask the user what to
   *     restore).
   * @return true if the info was restored and false otherwise.
   */
  protected void restoreInterpreterInfos(boolean editorChanged) {
    final Set<String> interpreterNamesToRestore =
        pathEditor.getInterpreterExeOrJarToRestoreAndClear();
    final IInterpreterInfo[] exesList = pathEditor.getExesList();

    if (!editorChanged && interpreterNamesToRestore.size() == 0) {
      IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
      SelectionDialog listDialog =
          createChooseIntepreterInfoDialog(
              workbenchWindow, exesList, "Select interpreters to be restored", true);

      int open = listDialog.open();
      if (open != ListDialog.OK) {
        return;
      }
      Object[] result = (Object[]) listDialog.getResult();
      if (result == null || result.length == 0) {
        return;
      }
      for (Object o : result) {
        interpreterNamesToRestore.add(((IInterpreterInfo) o).getExecutableOrJar());
      }
    }

    // this is the default interpreter
    ProgressMonitorDialog monitorDialog = new AsynchronousProgressMonitorDialog(this.getShell());
    monitorDialog.setBlockOnOpen(false);

    try {
      IRunnableWithProgress operation =
          new IRunnableWithProgress() {

            public void run(IProgressMonitor monitor)
                throws InvocationTargetException, InterruptedException {
              monitor.beginTask("Restoring PYTHONPATH", IProgressMonitor.UNKNOWN);
              try {
                // clear all but the ones that appear
                getInterpreterManager().setInfos(exesList, interpreterNamesToRestore, monitor);
              } finally {
                monitor.done();
              }
            }
          };

      monitorDialog.run(true, true, operation);

    } catch (Exception e) {
      Log.log(e);
    }
  }
示例#10
0
 @Override
 public void saveResources() throws IOException, URISyntaxException {
   String[] messageFiles = MessageAssistant.getInstance().getMessageFiles();
   log.log(Level.INFO, "SAVE EXCEL TO FILE -- " + file);
   ProgressMonitorDialog progressMonitorDialog =
       new ProgressMonitorDialog(Display.getCurrent().getActiveShell());
   try {
     progressMonitorDialog.run(false, true, new SavingProgress(messageFiles));
   } catch (InvocationTargetException e) {
     log.log(Level.WARNING, "SAVE PROPERTIES TO EXCEL -- INVOCATION TARGET EXCEPTION");
   } catch (InterruptedException e) {
     log.log(Level.WARNING, "SAVE PROPERTIES TO EXCEL -- INTERRUPTED EXCEPTION");
   }
 }
 public static boolean waitForServerToChangeState(
     IServer server, Shell shell, int changeStateFrom, int changeStateTo, String msg) {
   ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(shell);
   CarbonServerStateChange serverStateChange =
       new CarbonServerStateChange(server, changeStateFrom, changeStateTo, 180000, msg);
   progressMonitorDialog.setBlockOnOpen(false);
   try {
     progressMonitorDialog.run(true, true, serverStateChange);
     return progressMonitorDialog.getReturnCode() != ProgressMonitorDialog.CANCEL;
   } catch (InvocationTargetException e) {
     log.error(e);
   } catch (InterruptedException e) {
     log.error(e);
   }
   return false;
 }
  /** Executes the Action */
  public void run() {
    try {
      final ProgressMonitorDialog dialog =
          new ProgressMonitorDialog(Display.getCurrent().getActiveShell());
      dialog.setCancelable(true);

      dialog.run(
          false,
          false,
          new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor)
                throws InvocationTargetException, InterruptedException {
              final TreeItem[] items = getViewer().getTree().getItems();
              final int unitCount = calculateWorkUnits(items);
              monitor.beginTask(getString(StringKeys.MONITOR_CALC_STATS_TASK), unitCount);
              for (TreeItem item : items) {
                if (monitor.isCanceled()) {
                  break;
                }
                if (item.getData() instanceof PackageRecord) {
                  final PackageRecord record = (PackageRecord) item.getData();
                  final AbstractPMDRecord[] children = record.getChildren();
                  monitor.subTask(
                      getString(StringKeys.MONITOR_CALC_STATS_OF_PACKAGE)
                          + ": "
                          + record.getName());
                  for (AbstractPMDRecord kid : children) {
                    if (kid instanceof FileRecord) {
                      calculateFileRecord((FileRecord) kid);
                      monitor.worked(1);
                    }
                  }
                } else if (item.getData() instanceof FileRecord) {
                  calculateFileRecord((FileRecord) item.getData());
                  monitor.worked(1);
                }
              }

              getViewer().refresh(true);
            }
          });
    } catch (InvocationTargetException e) {
      logErrorByKey(StringKeys.ERROR_INVOCATIONTARGET_EXCEPTION, e);
    } catch (InterruptedException e) {
      logErrorByKey(StringKeys.ERROR_INTERRUPTED_EXCEPTION, e);
    }
  }
示例#13
0
  @Override
  public boolean performFinish() {
    // validate the status output
    String outputDirName = getFinishPage().getOutputDir();
    File statusDir = new File(outputDirName);
    if (!statusDir.exists() || !statusDir.isDirectory()) {
      UIUtils.errorMessageBox(
          getShell(), Labels.getString("LoadWizard.errorValidDirectory")); // $NON-NLS-1$
      return false;
    }
    // set the files for status output
    try {
      getController().setStatusFiles(outputDirName, false, true);
      getController().saveConfig();
    } catch (ProcessInitializationException e) {
      UIUtils.errorMessageBox(getShell(), e);
      return false;
    }

    int val = UIUtils.warningConfMessageBox(getShell(), getConfirmationText());

    if (val != SWT.YES) {
      return false;
    }

    if (!wizardhook_validateFinish()) {
      return false;
    }

    try {
      ProgressMonitorDialog dlg = new ProgressMonitorDialog(getShell());
      dlg.run(true, true, new SWTLoadRunable(getController()));

    } catch (InvocationTargetException e) {
      logger.error(Labels.getString("LoadWizard.errorAction"), e); // $NON-NLS-1$
      UIUtils.errorMessageBox(getShell(), e.getCause() != null ? e.getCause() : e);
      return false;
    } catch (InterruptedException e) {
      logger.error(Labels.getString("LoadWizard.errorAction"), e); // $NON-NLS-1$
      UIUtils.errorMessageBox(getShell(), e.getCause() != null ? e.getCause() : e);
      return false;
    }

    return true;
  }
示例#14
0
 private void showProgressDialog() {
   ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
   try {
     dialog.run(
         true,
         true,
         new IRunnableWithProgress() {
           public void run(final IProgressMonitor monitor)
               throws InvocationTargetException, InterruptedException {
             monitor.beginTask("Counting from one to 20...", 20);
             for (int i = 1; !monitor.isCanceled() && i <= 20; i++) {
               monitor.worked(1);
               Thread.sleep(1000);
             }
             monitor.done();
           }
         });
   } catch (Exception e) {
     MessageDialog.openError(getShell(), "Error", e.getMessage());
   }
 }
  /** Calls out to {@link MacVMSearch} to find all installed JREs in the standard Mac OS location */
  private void doMacSearch() {
    final List<VMStandin> added = new ArrayList<VMStandin>();
    IRunnableWithProgress r =
        new IRunnableWithProgress() {
          @Override
          public void run(IProgressMonitor monitor) throws InvocationTargetException {
            Set<String> exists = new HashSet<String>();
            for (IVMInstall vm : fVMs) {
              exists.add(vm.getId());
            }
            SubMonitor localmonitor = SubMonitor.convert(monitor, JREMessages.MacVMSearch_0, 5);
            VMStandin[] standins = null;
            try {
              standins = MacInstalledJREs.getInstalledJREs(localmonitor);
              for (int i = 0; i < standins.length; i++) {
                if (!exists.contains(standins[i].getId())) {
                  added.add(standins[i]);
                }
              }
            } catch (CoreException ce) {
              JDIDebugUIPlugin.log(ce);
            }
            monitor.done();
          }
        };

    try {
      ProgressMonitorDialog progress = new ProgressMonitorDialog(getShell());
      progress.run(true, true, r);
    } catch (InvocationTargetException e) {
      JDIDebugUIPlugin.log(e);
    } catch (InterruptedException e) {
      // canceled
      return;
    }
    for (VMStandin vm : added) {
      vmAdded(vm);
    }
  }
示例#16
0
 private void connectWithProgress(final MonitorServer server) {
   ProgressMonitorDialog progress = new ProgressMonitorDialog(null);
   progress.setCancelable(true);
   try {
     progress.run(
         true,
         true,
         new IRunnableWithProgress() {
           public void run(IProgressMonitor monitor) throws InvocationTargetException {
             try {
               server.connectAndLogin(monitor);
             } catch (Exception e) {
               e.printStackTrace();
             }
           }
         });
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
  public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
      String name = event.getCommand().getName();
      Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();

      if (!MessageDialog.openConfirm(
          shell,
          Messages.JavaBeansGeneratorAction_MSG_DIALOG_MESSAGE,
          name + Messages.JavaBeansGeneratorAction_MSG_DIALOG_DESC)) {
        return null;
      }

      /* 実行中のダイアログ表示 */
      ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
      dialog.setCancelable(true);

      IWorkbenchPartSite site = HandlerUtil.getActivePartChecked(event).getSite();
      ISelection selection = HandlerUtil.getCurrentSelection(event);
      IStructuredSelection ss = null;
      if (selection instanceof IStructuredSelection) {
        ss = (IStructuredSelection) selection;
      }

      try {
        logger.debug("execute"); // $NON-NLS-1$
        String id = event.getCommand().getId();
        JavaBeansCreatorWithProgress progress = new JavaBeansCreatorWithProgress(ss, site, id);
        dialog.run(true, true, progress);
      } catch (InvocationTargetException e) {
        Activator.logException(e);
      } catch (InterruptedException e) {
        Activator.logException(e, false);
      }
    } catch (NotDefinedException e) {
      Activator.logException(e);
    }
    return null;
  }
  private void runCommand(final List<EObject> exportModelElements, String filePath) {
    final File file = new File(filePath);

    final URI uri = URI.createFileURI(filePath);

    final ProgressMonitorDialog progressDialog =
        new ProgressMonitorDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());

    progressDialog.open();
    progressDialog.getProgressMonitor().beginTask("Export modelelement...", 100);
    progressDialog.getProgressMonitor().worked(10);

    try {
      saveEObjectToResource(exportModelElements, uri);
    } catch (IOException e) {
      DialogHandler.showExceptionDialog(e.getMessage(), e);
    }
    progressDialog.getProgressMonitor().done();
    progressDialog.close();

    MessageDialog.openInformation(
        null, "Export", "Exported modelelement to file " + file.getName());
  }
示例#19
0
 public void executeInBackground(final IExecutableOperation operation) {
   if (!isRunningInUIThread()) {
     operation.execute(new NullProgressMonitor());
   } else if (DLTKUI.isStarted()) {
     if (active) {
       return;
     }
     final ProgressMonitorDialog dialog =
         new ProgressMonitorDialog(null) {
           @Override
           protected void configureShell(Shell shell) {
             super.configureShell(shell);
             shell.setText(operation.getOperationName());
           }
         };
     active = true;
     try {
       dialog.run(
           true,
           false,
           new IRunnableWithProgress() {
             public void run(IProgressMonitor monitor) {
               if (!isRunningInUIThread()) {
                 operation.execute(monitor);
               }
             }
           });
     } catch (InvocationTargetException e) {
       DLTKCore.error(e.getMessage(), e);
     } catch (InterruptedException e) {
       DLTKCore.error(e.getMessage(), e);
     } finally {
       active = false;
     }
   }
 }
示例#20
0
  @Override
  public void run(IAction action) {
    FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);

    dialog.setText("Select text file...");
    String sourceFile = dialog.open();
    if (sourceFile == null) return;
    ProgressMonitorDialog pd = new ProgressMonitorDialog(getShell());
    try {
      List<Type> types = TypeCollector.getData(new File(sourceFile), "UTF-8");
      pd.setBlockOnOpen(false);
      pd.open();
      pd.getProgressMonitor().beginTask("Generating cloud...", 200);
      TagCloudViewer viewer = getViewer();
      viewer.setInput(types, pd.getProgressMonitor());
      long start = System.currentTimeMillis();
      viewer.getCloud().layoutCloud(pd.getProgressMonitor(), false);
      long end = System.currentTimeMillis();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      pd.close();
    }
  }
  public Row open() {
    IRunnableWithProgress op =
        new IRunnableWithProgress() {
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            // This is running in a new process: copy some KettleVariables info
            LocalVariables.getInstance()
                .createKettleVariables(
                    Thread.currentThread().getName(), parentThread.getName(), true);

            db = new Database(dbMeta);
            try {
              db.connect();
              result = db.getQueryFields(sql, false);
              if (monitor.isCanceled()) {
                throw new InvocationTargetException(new Exception("This operation was cancelled!"));
              }
            } catch (Exception e) {
              throw new InvocationTargetException(
                  e, "Problem encountered determining query fields: " + e.toString());
            } finally {
              db.disconnect();
            }
          }
        };

    try {
      final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);

      // Run something in the background to cancel active database queries, forecably if needed!
      Runnable run =
          new Runnable() {
            public void run() {
              IProgressMonitor monitor = pmd.getProgressMonitor();
              while (pmd.getShell() == null
                  || (!pmd.getShell().isDisposed() && !monitor.isCanceled())) {
                try {
                  Thread.sleep(250);
                } catch (InterruptedException e) {
                }
                ;
              }

              if (monitor.isCanceled()) // Disconnect and see what happens!
              {
                try {
                  db.cancelQuery();
                } catch (Exception e) {
                }
                ;
              }
            }
          };
      // Dump the cancel looker in the background!
      new Thread(run).start();

      pmd.run(true, true, op);
    } catch (InvocationTargetException e) {
      showErrorDialog(e);
      return null;
    } catch (InterruptedException e) {
      showErrorDialog(e);
      return null;
    }

    return result;
  }
  public void open() {
    final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);

    IRunnableWithProgress op =
        new IRunnableWithProgress() {
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            try {
              transMeta.checkSteps(
                  remarks,
                  onlySelected,
                  new ProgressMonitorAdapter(monitor),
                  space,
                  repository,
                  metaStore);
            } catch (Exception e) {
              throw new InvocationTargetException(
                  e,
                  BaseMessages.getString(
                      PKG,
                      "AnalyseImpactProgressDialog.RuntimeError.ErrorCheckingTransformation.Exception",
                      e.toString())); // Problem
              // encountered
              // checking
              // transformation:
              // {0}
            }
          }
        };

    try {
      // Run something in the background to cancel active database queries, force this if needed!
      Runnable run =
          new Runnable() {
            public void run() {
              IProgressMonitor monitor = pmd.getProgressMonitor();
              while (pmd.getShell() == null
                  || (!pmd.getShell().isDisposed() && !monitor.isCanceled())) {
                try {
                  Thread.sleep(250);
                } catch (InterruptedException e) {
                }
              }

              if (monitor.isCanceled()) // Disconnect and see what happens!
              {
                try {
                  transMeta.cancelQueries();
                } catch (Exception e) {
                }
              }
            }
          };
      // Dump the cancel looker in the background!
      new Thread(run).start();

      pmd.run(true, true, op);
    } catch (InvocationTargetException e) {
      new ErrorDialog(
          shell,
          BaseMessages.getString(
              PKG, "CheckTransProgressDialog.Dialog.ErrorCheckingTransformation.Title"),
          BaseMessages.getString(
              PKG, "CheckTransProgressDialog.Dialog.ErrorCheckingTransformation.Message"),
          e); // "Error checking transformation","An
      // error occured checking this
      // transformation\!"
    } catch (InterruptedException e) {
      new ErrorDialog(
          shell,
          BaseMessages.getString(
              PKG, "CheckTransProgressDialog.Dialog.ErrorCheckingTransformation.Title"),
          BaseMessages.getString(
              PKG, "CheckTransProgressDialog.Dialog.ErrorCheckingTransformation.Message"),
          e); // "Error checking transformation","An
      // error occured checking this
      // transformation\!"
    }
  }
  private void run(final ServerOperation op, final boolean enforceNonEmptyPassword) {
    try {
      final ModeShapeServer server = op.getServer();

      if (enforceNonEmptyPassword
          && ((server.getPassword() == null) || server.getPassword().isEmpty())) {
        if (MessageDialog.openQuestion(
            getShell(),
            RestClientI18n.missingServerPasswordDialogTitle,
            RestClientI18n.missingServerPasswordDialogMsg)) {
          final NewPasswordDialog dialog = new NewPasswordDialog(getShell());

          if (dialog.open() == Window.OK) {
            getServerManager()
                .updateServer(
                    server,
                    new ModeShapeServer(
                        server.getOriginalUrl(),
                        server.getUser(),
                        dialog.getNewPassword(),
                        server.isPasswordBeingPersisted()));

            // need to obtain changed server from server manager as servers are not mutable
            for (final ModeShapeServer registeredServer : getServerManager().getServers()) {
              if (registeredServer.hasSameKey(server)) {
                op.setUpdatedServer(registeredServer);
                break;
              }
            }
          }
        }
      }

      final ProgressMonitorDialog dialog =
          new ProgressMonitorDialog(getShell()) {

            /**
             * {@inheritDoc}
             *
             * @see
             *     org.eclipse.jface.dialogs.ProgressMonitorDialog#configureShell(org.eclipse.swt.widgets.Shell)
             */
            @Override
            protected void configureShell(final Shell shell) {
              super.configureShell(shell);
              shell.setText(RestClientI18n.requestDialogTitle);
            }
          };

      dialog.run(true, false, op);
    } catch (final InvocationTargetException e) {
      // should not happen as ServerOperation handles this but just in case
      if (op.getUpdatedServer() == null) {
        addOfflineServer(op.getServer());
      } else {
        addOfflineServer(op.getUpdatedServer());
      }

      final org.eclipse.core.runtime.Status error =
          new org.eclipse.core.runtime.Status(
              IStatus.ERROR,
              IUiConstants.PLUGIN_ID,
              RestClientI18n.runningServerRequestErrorMsg,
              e.getCause());
      ErrorDialog.openError(
          getShell(),
          RestClientI18n.runningServerRequestErrorDialogTitle,
          RestClientI18n.runningServerRequestErrorDialogMsg,
          error);
    } catch (final InterruptedException e) {
      // won't happen as runnable is not cancelable
    }
  }
示例#24
0
  @Override
  public void propertyChange(PropertyChangeEvent event) {
    super.propertyChange(event);
    if (event != null && event.getSource() == diagStructFieldEditor) {
      if (event.getNewValue().equals(Boolean.TRUE)) {
        if (MessageDialog.openConfirm(
            getShell(),
            "Strukturierte Diagnosen",
            "Bisher erfasste Text Diagnosen werden automatisch in strukturierte umgewandelt.\n"
                + "Wollen Sie wirklich von nun an strukturierte Diagnosen verwenden?")) {
          ProgressMonitorDialog progressDialog = new ProgressMonitorDialog(getShell());
          try {
            progressDialog.run(
                true,
                true,
                new IRunnableWithProgress() {
                  public void run(IProgressMonitor monitor)
                      throws InvocationTargetException, InterruptedException {
                    Query<Patient> query = new Query<>(Patient.class);
                    List<Patient> patients = query.execute();
                    monitor.beginTask("Strukturierte Diagnosen erzeugen", patients.size());
                    IFindingsService findingsService = FindingsServiceComponent.getService();
                    IMigratorService migratorService = MigratorServiceComponent.getService();
                    for (Patient patient : patients) {
                      String diagnosen = patient.getDiagnosen();
                      List<IFinding> existing =
                          getExistingDiagnoses(patient.getId(), findingsService);
                      // only migrate if there is a diagnosis and no structured diagnosis already
                      // there
                      if (diagnosen != null && !diagnosen.isEmpty() && existing.isEmpty()) {
                        migratorService.migratePatientsFindings(patient.getId(), ICondition.class);
                      }
                      monitor.worked(1);
                      if (monitor.isCanceled()) {
                        break;
                      }
                    }
                    monitor.done();
                    Display.getDefault()
                        .asyncExec(
                            new Runnable() {
                              @Override
                              public void run() {
                                MessageDialog.openInformation(
                                    getShell(),
                                    "Strukturierte Diagnosen",
                                    "Strukturierte Diagnosen erfolgreich erzeugt. Bitte starten sie Elexis neu um mit den strukturierten Diagnosen zu arbeiten.");
                              }
                            });
                  }

                  private List<IFinding> getExistingDiagnoses(
                      String patientId, IFindingsService findingsService) {
                    return findingsService
                        .getPatientsFindings(patientId, ICondition.class)
                        .stream()
                        .filter(
                            condition ->
                                ((ICondition) condition).getCategory()
                                    == ConditionCategory.DIAGNOSIS)
                        .collect(Collectors.toList());
                  };
                });
          } catch (InvocationTargetException | InterruptedException e) {
            MessageDialog.openError(
                getShell(),
                "Diagnosen konvertieren",
                "Fehler beim erzeugen der strukturierten Diagnosen.");
            getLogger().error("Error creating structured diagnosis", e);
          }
        } else {
          getPreferenceStore().setValue(SettingsConstants.DIAGNOSE_SETTINGS_USE_STRUCTURED, false);
          // refresh later, on immediate refresh wasSelected of FieldEditor gets overwritten
          getShell()
              .getDisplay()
              .asyncExec(
                  new Runnable() {
                    @Override
                    public void run() {
                      diagStructFieldEditor.load();
                    }
                  });
        }
      } else {
        if (MessageDialog.openConfirm(
            getShell(),
            "Strukturierte Diagnosen",
            "Bisher erfasste strukturierte Diagnosen werden nicht in Text umgewandelt.\n"
                + "Wollen Sie wirklich von nun an Text Diagnosen verwenden?")) {
          MessageDialog.openInformation(
              getShell(),
              "Text Diagnosen",
              "Bitte starten sie Elexis neu um mit den Text Diagnosen zu arbeiten.");
        } else {
          getPreferenceStore().setValue(SettingsConstants.DIAGNOSE_SETTINGS_USE_STRUCTURED, true);
          // refresh later, on immediate refresh wasSelected of FieldEditor gets overwritten
          getShell()
              .getDisplay()
              .asyncExec(
                  new Runnable() {
                    @Override
                    public void run() {
                      diagStructFieldEditor.load();
                    }
                  });
        }
      }
    }
  }
示例#25
0
  public synchronized void run() {
    Viewer v = this.m_app.getApplication().getViewer();
    if (v != null && v instanceof Viewer) {
      final IStructuredSelection selection = (IStructuredSelection) v.getSelection();
      if (!selection.isEmpty()) {
        if (selection.getFirstElement() instanceof ICaller) {

          ProgressMonitorDialog pmd =
              new ProgressMonitorDialog(DisplayManager.getDefaultDisplay().getActiveShell());
          try {
            IRunnableWithProgress r =
                new IRunnableWithProgress() {
                  public void run(IProgressMonitor progressMonitor) {
                    progressMonitor.beginTask(
                        getI18nManager()
                            .getString(getNamespace(), "identifyprogress", "label", getLanguage()),
                        IProgressMonitor.UNKNOWN);

                    progressMonitor.worked(1);

                    final ICaller caller = (ICaller) selection.getFirstElement();

                    List phones = new ArrayList();
                    if (caller instanceof IMultiPhoneCaller) {
                      phones.addAll(((IMultiPhoneCaller) caller).getPhonenumbers());
                    } else {
                      phones.add(caller.getPhoneNumber());
                    }

                    String ignoreCM = "";
                    IAttribute att = caller.getAttribute(IJAMConst.ATTRIBUTE_NAME_CALLERMANAGER);
                    if (att != null) {
                      ignoreCM = att.getValue();
                    }

                    List activeCMs = getAllActiveCallerManagers(getRuntime(), ignoreCM);

                    ICaller identifiedCaller = null;
                    // identification only makes sence if there are active CMs or if there are
                    // numbers
                    if (activeCMs.size() > 0 && phones.size() > 0) {
                      IPhonenumber pn = null;
                      for (int i = 0; i < phones.size(); i++) {
                        pn = (IPhonenumber) phones.get(i);
                        identifiedCaller = Identifier.identify(getRuntime(), pn, activeCMs);
                        if (identifiedCaller != null) break;
                      }
                    }
                    progressMonitor.done();

                    if (identifiedCaller == null) {
                      progressMonitor.beginTask(
                          getI18nManager()
                              .getString(getNamespace(), "failedidentify", "label", getLanguage()),
                          IProgressMonitor.UNKNOWN);

                      PropagationFactory.getInstance()
                          .fire(
                              new Message(
                                  Message.INFO,
                                  getNamespace(),
                                  "failedidentify",
                                  new Exception(
                                      "Caller with number "
                                          + caller.getPhoneNumber()
                                          + " not identified...")));
                      return;
                    }

                    // remove repository flag and set all numbers
                    if (!(identifiedCaller instanceof IMultiPhoneCaller)) {
                      identifiedCaller =
                          getRuntime().getCallerFactory().toMultiPhoneCaller(identifiedCaller);
                    }
                    ((IMultiPhoneCaller) identifiedCaller).setPhonenumbers(phones);
                    ((IMultiPhoneCaller) identifiedCaller)
                        .setPhoneNumber((IPhonenumber) phones.get(0));

                    IAttributeMap m = getRuntime().getCallerFactory().createAttributeMap();
                    m.addAll(caller.getAttributes());
                    m.addAll(identifiedCaller.getAttributes());
                    m.remove(IJAMConst.ATTRIBUTE_NAME_CALLERMANAGER);
                    identifiedCaller.setAttributes(m);

                    final ICaller theIdentifiedCaller = identifiedCaller;
                    new SWTExecuter() {

                      protected void execute() {
                        if (MessageDialog.openConfirm(
                            new Shell(DisplayManager.getDefaultDisplay()),
                            getI18nManager()
                                .getString(getNamespace(), "identify", "label", getLanguage()),
                            getI18nManager()
                                .getString(
                                    getNamespace(), "identify", "description", getLanguage()))) {

                          ICaller newCaller = openCallerWizard(theIdentifiedCaller);
                          if (newCaller != null) {
                            ICallerList list = getRuntime().getCallerFactory().createCallerList(1);
                            list.add(caller);
                            m_app.getController().deleteElements(list);

                            list.clear();
                            list.add(newCaller);

                            m_app.getController().addElements(list);
                            m_app.updateViews(true);
                          }
                        }
                      }
                    }.start();
                  }
                };
            pmd.setBlockOnOpen(false);
            pmd.run(true, false, r);

            // ModalContext.run(r, true, pmd.getProgressMonitor(),
            // DisplayManager.getDefaultDisplay());
          } catch (InterruptedException e) {
            m_logger.log(Level.SEVERE, e.getMessage(), e);
          } catch (InvocationTargetException e) {
            m_logger.log(Level.SEVERE, e.getMessage(), e);
          }
        }
      }
    }
  }
示例#26
0
  /**
   * Do the "Run Analysis" on a resource (project, folder, or file). Descends to all child nodes,
   * collecting artifacts on each.
   */
  public void run() {
    if (traceOn) {
      System.out.println("RunAnalyseHandlerBase.run()..."); // $NON-NLS-1$
    }

    cancelledByUser = false;
    err = false;
    cumulativeArtifacts = 0;
    readPreferences();

    final int indent = 0;

    if ((selection == null) || selection.isEmpty()) {
      MessageDialog.openWarning(
          null,
          Messages.RunAnalyseHandlerBase_no_files_selected,
          Messages.RunAnalyseHandlerBase_please_select);

      return;
    } else {
      // get preference for include paths
      final List<String> includes = getIncludePath();
      if (areIncludePathsNeeded() && includes.isEmpty()) {
        // System.out.println("RunAnalyseHandlerBase.run(), no include paths found.");
        MessageDialog.openWarning(
            shell,
            name + Messages.RunAnalyseHandlerBase_include_paths_not_found,
            Messages.RunAnalyseHandlerBase_please_first_specify
                + name
                + Messages.RunAnalyseHandlerBase_incl_paths_in_pref_page);

      } else {

        // batch ws modifications *and* report progress
        WorkspaceModifyOperation wmo =
            new WorkspaceModifyOperation() {
              @Override
              protected void execute(IProgressMonitor monitor)
                  throws CoreException, InvocationTargetException, InterruptedException {
                err = runResources(monitor, indent, includes);
              }
            };
        ProgressMonitorDialog pmdialog = new ProgressMonitorDialog(shell);
        try {
          pmdialog.run(true, true, wmo); // fork=true; if false, not
          // cancelable

        } catch (InvocationTargetException e) {
          err = true;
          Throwable cause = e.getCause();
          System.out.println(
              "Error running analysis: ITE: " //$NON-NLS-1$
                  + e.getMessage());
          System.out.println(
              "  cause: "
                  + cause
                  + " - " //$NON-NLS-1$ //$NON-NLS-2$
                  + cause.getMessage());

          cause.printStackTrace();
        } catch (InterruptedException e) {
          cancelledByUser = true;
        }
      } // end else
    }
    if (traceOn) {
      System.out.println(
          "RunAnalyseBase: retd from run iterator, err=" //$NON-NLS-1$
              + err);
    }
    String artsFound =
        "\nNumber of "
            + name
            + " Artifacts found: " //$NON-NLS-1$ //$NON-NLS-2$
            + cumulativeArtifacts;
    if (cancelledByUser) {
      MessageDialog.openInformation(
          null,
          Messages.RunAnalyseHandlerBase_partial_analysis_complete,
          Messages.RunAnalyseHandlerBase_15 + artsFound);
    } else {
      String msg = Messages.RunAnalyseHandlerBase_cancelled_by_user;
      if (!err) {
        String key = IDs.SHOW_ANALYSIS_CONFIRMATION;
        IPreferenceStore pf = CommonPlugin.getDefault().getPreferenceStore();
        boolean showDialog = pf.getBoolean(IDs.SHOW_ANALYSIS_CONFIRMATION);
        if (showDialog) {
          String title = Messages.RunAnalyseHandlerBase_analysis_complete;
          StringBuffer sMsg =
              new StringBuffer(
                  cumulativeArtifacts
                      + " "
                      + name //$NON-NLS-1$
                      + Messages.RunAnalyseHandlerBase_artifacts_found);
          // provide some explanation of why perhaps no artifacts were
          // found.
          // Note: should this perhaps be in a "Details" section of
          // the dialog?
          if (cumulativeArtifacts == 0) {
            // Unless "Recognize artifacts by prefix alone" is set in the preferences (this is the
            // default),
            // this could be a problem with the include file for this API.
            sMsg.append(Messages.RunAnalyseHandlerBase_notfound_0)
                .append(name)
                .append(Messages.RunAnalyseHandlerBase_notfound_1);
            sMsg.append(name).append(Messages.RunAnalyseHandlerBase_notfound_2);
            sMsg.append(Messages.RunAnalyseHandlerBase_notfound_3);
          }
          String togMsg = Messages.RunAnalyseHandlerBase_dont_show_this_again;
          MessageDialogWithToggle.openInformation(
              shell, title, sMsg.toString(), togMsg, false, pf, key);
          showStatusMessage(sMsg.toString(), "RunAnalyseBase.run()"); // $NON-NLS-1$
        }
        activateProblemsView();
        activateArtifactView();
      } else { // error occurred
        showStatusMessage(msg, "RunAnalyseBase.run() error"); // $NON-NLS-1$
        msg = Messages.RunAnalyseHandlerBase_27;
        MessageDialog.openError(null, Messages.RunAnalyseHandlerBase_28, msg + artsFound);
      }
    }
  }
  /**
   * Deploy the given vdb to the given Teiid Instance
   *
   * @param teiidServer the Teiid Instance
   * @param vdbOrVdbFile the VDB
   * @param doCreateDataSource 'true' to create corresponding datasource, 'false' if not.
   */
  public static boolean deployVdb(
      ITeiidServer teiidServer, final Object vdbOrVdbFile, final boolean doCreateDataSource) {
    Shell shell = UiUtil.getWorkbenchShellOnlyIfUiThread();

    try {
      if (!(vdbOrVdbFile instanceof IFile) && !(vdbOrVdbFile instanceof Vdb)) {
        throw new IllegalArgumentException(
            UTIL.getString(I18N_PREFIX + "selectionIsNotAVdb")); // $NON-NLS-1$
      }

      // make sure there is a Teiid connection
      if (!teiidServer.isConnected()) {
        return false;
      }

      Vdb vdb =
          ((vdbOrVdbFile instanceof IFile)
              ? new Vdb((IFile) vdbOrVdbFile, null)
              : (Vdb) vdbOrVdbFile);

      if (!vdb.isSynchronized()) {
        String title = UTIL.getString("VdbNotSyncdDialog.title"); // $NON-NLS-1$
        String msg = UTIL.getString("VdbNotSyncdDialog.msg"); // $NON-NLS-1$
        if (!MessageDialog.openQuestion(shell, title, msg)) return false;
      }

      final VdbDeployer deployer = new VdbDeployer(shell, vdb, teiidServer, doCreateDataSource);
      ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);

      failedModelName = null;

      IRunnableWithProgress runnable =
          new IRunnableWithProgress() {
            /**
             * {@inheritDoc}
             *
             * @see
             *     org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
             */
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException {
              try {
                failedModelName = deployer.deploy(monitor);
              } catch (Exception e) {
                throw new InvocationTargetException(e);
              }
            }
          };

      // deploy using progress monitor (UI is blocked)
      dialog.run(true, false, runnable);

      // process results
      VdbDeployer.DeployStatus status = deployer.getStatus();

      if (status.isError()) {
        String message = null;

        if (VdbDeployer.DeployStatus.CREATE_DATA_SOURCE_FAILED == status) {
          message =
              UTIL.getString(
                  I18N_PREFIX + "createDataSourceFailed",
                  deployer.getVdbName(),
                  failedModelName); //$NON-NLS-1$
        } else if (VdbDeployer.DeployStatus.DEPLOY_VDB_FAILED == status) {
          message =
              UTIL.getString(
                  I18N_PREFIX + "vdbFailedToDeploy", deployer.getVdbName()); // $NON-NLS-1$
        } else if (VdbDeployer.DeployStatus.TRANSLATOR_PROBLEM == status) {
          message =
              UTIL.getString(
                  I18N_PREFIX + "translatorDoesNotExistOnServer",
                  deployer.getVdbName()); // $NON-NLS-1$
        } else if (VdbDeployer.DeployStatus.SOURCE_CONNECTION_INFO_PROBLEM == status) {
          message =
              UTIL.getString(
                  I18N_PREFIX + "sourceMissingConnectionInfo",
                  deployer.getVdbName()); // $NON-NLS-1$
        } else if (VdbDeployer.DeployStatus.EXCEPTION == status) {
          throw deployer.getException(); // let catch block below
          // handle
        } else {
          // unexpected
          message =
              UTIL.getString(
                  I18N_PREFIX + "unknownDeployError", deployer.getVdbName(), status); // $NON-NLS-1$
        }

        // show user the error
        MessageDialog.openError(
            shell, UTIL.getString(I18N_PREFIX + "vdbNotDeployedTitle"), message); // $NON-NLS-1$
        return false;
      } else if (status.isDeployed()) {
        if (teiidServer.wasVdbRemoved(deployer.getVdbName())) {
          StringBuilder message =
              new StringBuilder(
                  UTIL.getString(
                      I18N_PREFIX + "vdbNotActiveMessage", // $NON-NLS-1$
                      vdb.getName()));

          for (String error : teiidServer.retrieveVdbValidityErrors(deployer.getVdbName())) {
            message.append(
                UTIL.getString(I18N_PREFIX + "notActiveErrorMessage", error)); // $NON-NLS-1$
          }

          MessageDialog.openWarning(
              shell,
              UTIL.getString(I18N_PREFIX + "vdbNotActiveTitle"),
              message.toString()); // $NON-NLS-1$
          return true;
        }
      } else {
        return false;
      }
    } catch (Throwable e) {
      if (e instanceof InvocationTargetException) {
        e = ((InvocationTargetException) e).getCause();
      }

      String vdbName = null;

      if (vdbOrVdbFile instanceof IFile) {
        vdbName = ((IFile) vdbOrVdbFile).getName();
      } else if (vdbOrVdbFile instanceof Vdb) {
        vdbName = ((Vdb) vdbOrVdbFile).getFile().getName();
      } else {
        vdbName = UTIL.getString(I18N_PREFIX + "selectionIsNotAVdb"); // $NON-NLS-1$
      }

      String message =
          UTIL.getString(
              I18N_PREFIX + "problemDeployingVdbToServer", vdbName, teiidServer); // $NON-NLS-1$
      UTIL.log(e);
      ErrorDialog.openError(shell, message, null, new Status(IStatus.ERROR, PLUGIN_ID, message, e));

      return false;
    }

    return true;
  }
示例#28
0
  /* (non-Javadoc)
   * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
   */
  @Override
  protected Control createContents(Composite parent) {
    // first try to adapt to IFileStore directly
    final IFileStore fileStore = Utils.getFileStore(getElement());
    if (fileStore == null) {
      Label label = new Label(parent, SWT.NONE);
      label.setText(IDEWorkbenchMessages.ResourceInfoPage_noResource);
      return label;
    }
    try {
      if (getElement().getAdapter(File.class) != null) {
        fFileInfo = fileStore.fetchInfo(EFS.NONE, new NullProgressMonitor());
      } else {
        final IFileInfo[] result = new IFileInfo[1];
        ProgressMonitorDialog dlg = new ProgressMonitorDialog(parent.getShell());
        try {
          dlg.run(
              true,
              true,
              new IRunnableWithProgress() {
                public void run(IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                  try {
                    result[0] = fileStore.fetchInfo(IExtendedFileStore.DETAILED, monitor);
                  } catch (CoreException e) {
                    throw new InvocationTargetException(e, e.getLocalizedMessage());
                  } finally {
                    monitor.done();
                  }
                }
              });
        } catch (InvocationTargetException e) {
          throw (CoreException) e.getTargetException();
        } catch (InterruptedException e) {
          e.getCause();
        }
        fFileInfo = result[0];
      }
    } catch (CoreException e) {
      UIUtils.showErrorMessage(Messages.FileInfoPropertyPage_FailedToFetchInfo, e);
    }
    if (fFileInfo == null) {
      Label label = new Label(parent, SWT.NONE);
      label.setText(IDEWorkbenchMessages.ResourceInfoPage_noResource);
      return label;
    }

    Composite composite = new Composite(parent, SWT.NONE);
    composite.setLayout(GridLayoutFactory.swtDefaults().margins(0, 0).create());
    composite.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());

    Composite basicInfo = createBasicInfoGroup(composite, fileStore, fFileInfo);
    basicInfo.setLayoutData(GridDataFactory.fillDefaults().create());

    Label separator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
    separator.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());

    Composite state = createStateGroup(composite, fileStore, fFileInfo);
    state.setLayoutData(GridDataFactory.fillDefaults().create());

    if (fFileInfo instanceof IExtendedFileInfo) {
      IExtendedFileInfo extendedInfo = (IExtendedFileInfo) fFileInfo;
      Composite owner = createOwnerGroup(composite, extendedInfo);
      owner.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).indent(0, 10).create());

      Composite permissions = createPermissionsGroup(composite, extendedInfo);
      permissions.setLayoutData(
          GridDataFactory.fillDefaults().grab(true, false).indent(0, 5).create());
    }

    /* TODO
    new Label(composite, SWT.NONE); // a vertical spacer
    encodingEditor = new EncodingFieldEditor("",
    		fileInfo.isDirectory() ? IDEWorkbenchMessages.ResourceInfo_fileEncodingTitle : IDEWorkbenchMessages.WorkbenchPreference_encoding,
    		composite);
    encodingEditor.setPreferenceStore(null);
    encodingEditor.setPage(this);
    encodingEditor.load();

    encodingEditor.setPropertyChangeListener(new IPropertyChangeListener() {
    	public void propertyChange(PropertyChangeEvent event) {
    		if (event.getProperty().equals(FieldEditor.IS_VALID)) {
    			setValid(encodingEditor.isValid());
    		}
    	}
    });

    if (fileInfo.isDirectory()) {
    	lineDelimiterEditor = new LineDelimiterEditor(composite, resource.getProject());
    	lineDelimiterEditor.doLoad();
    }
    */

    Dialog.applyDialogFont(composite);

    return composite;
  }
示例#29
0
  private void executeCommand(
      final ObjectDeleteCommand odcDeleteCommand,
      final EObject[] eObjects,
      TransactionSettings ts) {

    if (odcDeleteCommand == null) {
      createObjectDeleteCommand();
    }

    String tempString = UiConstants.Util.getString(DELETE_ONE_TITLE_KEY);
    if (eObjects.length > 1) {
      tempString = UiConstants.Util.getString(DELETE_MANY_TITLE_KEY, eObjects.length);
    }
    final String deleteTitle = tempString;

    WorkspaceModifyOperation operation =
        new WorkspaceModifyOperation() {
          @Override
          public void execute(final IProgressMonitor monitor) {

            if (monitor instanceof SubProgressMonitor) {
              ((SubProgressMonitor) monitor).getWrappedProgressMonitor().setTaskName(deleteTitle);
            }

            monitor.beginTask(CoreStringUtil.Constants.EMPTY_STRING, 100);
            monitor.worked(5);
            // execute the command
            IStatus status = odcDeleteCommand.execute(monitor);

            setResult(status);
          }
        };

    // start the txn
    ts.setSource(this);
    boolean started =
        ModelerCore.startTxn(
            ts.isSignificant(), ts.isUndoable(), ts.getDescription(), ts.getSource());

    boolean succeeded = false;

    try {
      ProgressMonitorDialog progressDialog =
          new ProgressMonitorDialog(Display.getDefault().getActiveShell());

      // run the operation
      progressDialog.run(true, true, operation);
      if (!progressDialog.getProgressMonitor().isCanceled()) {
        succeeded = true;
      }

      if (!getStatus().isOK()) {
        UiConstants.Util.log(getStatus());
      }
    } catch (Exception e) {
      UiConstants.Util.log(IStatus.ERROR, e, e.getMessage());
    } finally {
      if (started) {
        if (succeeded) {
          ModelerCore.commitTxn();
        } else {
          ModelerCore.rollbackTxn();
        }
      }
    }
  }
  /**
   * ライブラリリスト.
   *
   * @param refresh リフレッシュ
   * @param shell シェル
   * @return ライブラリリスト
   */
  public static LibraryList getLibraryList(boolean refresh) {

    if (!refresh && H5WizardPlugin.getInstance().getLibraryList() != null) {
      return H5WizardPlugin.getInstance().getLibraryList();
    }

    // クリアしておく
    H5WizardPlugin.getInstance().setLibraryList(null);
    H5WizardPlugin.getInstance().getSelectedLibrarySet().clear();

    ResultStatus resultStatus = new ResultStatus();

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);

    // サイトを読み込む.
    for (String urlStr :
        new String[] {
          PluginConstant.URL_LIBRARY_LIST,
          PluginConstant.URL_LIBRARY_LIST_MIRROR,
          LOCAL_LIBRARIES_XML
        }) {
      if (StringUtils.isNotEmpty(urlStr)) {
        InputStream is = null;
        DownloadModule downloadModule = new DownloadModule();
        try {

          //					IConnectMethod method = ConnectMethodFactory.getMethod(urlStr, true);
          //					method.setConnectionTimeout(PluginConstant.URL_LIBRARY_LIST_CONNECTION_TIMEOUT);
          //					method.setProxy(downloadModule.getProxyService());
          //					is = method.getInputStream();
          //					if (is == null) {
          //						resultStatus.log(Messages.SE0046, urlStr);
          //					} else {
          //						LibraryFileParser parser = LibraryFileParserFactory.createParser(is);
          //						LibraryList libraryList = parser.getLibraryList();
          //						libraryList.setLastModified(method.getLastModified());
          //						libraryList.setSource(urlStr);
          //						H5WizardPlugin.getInstance().setLibraryList(libraryList); // キャッシュさせておく.
          //						return libraryList;
          //					}
          //				} catch (ParseException e) {
          //					resultStatus.log(e, Messages.SE0046, urlStr);
          //				} catch (MalformedURLException e) {
          //					resultStatus.log(e, Messages.SE0046, urlStr);
          //				} catch (IOException e) {
          //					resultStatus.log(e, Messages.SE0046, urlStr);

          // 進捗表示の場合
          final IRunnableWithProgress runnable =
              getSiteDownLoad(resultStatus, urlStr, downloadModule);

          try {
            dialog.run(true, false, runnable);
            if (resultStatus.isSuccess()) {
              return H5WizardPlugin.getInstance().getLibraryList();
            }
          } catch (InvocationTargetException e) {
            resultStatus.log(e, Messages.SE0046, urlStr);
          } catch (InterruptedException e) {
            resultStatus.log(e, Messages.SE0046, urlStr);
          }
        } finally {
          downloadModule.close();
          IOUtils.closeQuietly(is);
        }
      }
    }

    //		// ローカルのリソースを利用する.
    //		InputStream is = null;
    //		try {
    //			URLConnection connection =
    // RemoteContentManager.class.getResource(LOCAL_LIBRARIES_XML).openConnection();
    //			is = connection.getInputStream();
    //			if (is == null) {
    //				resultStatus.log(Messages.SE0046, LOCAL_LIBRARIES_XML);
    //			} else {
    //				LibraryFileParser parser = LibraryFileParserFactory.createParser(is);
    //				LibraryList libraryList = parser.getLibraryList();
    //				if (connection.getLastModified() > 0) {
    //					libraryList.setLastModified(new Date(connection.getLastModified()));
    //				}
    //				libraryList.setSource(null);
    //				H5WizardPlugin.getInstance().setLibraryList(libraryList); // キャッシュさせておく.
    //				return libraryList;
    //			}
    //		} catch (ParseException e) {
    //			resultStatus.log(e, Messages.SE0046, LOCAL_LIBRARIES_XML);
    //		} catch (IOException e) {
    //			resultStatus.log(e, Messages.SE0046, LOCAL_LIBRARIES_XML);
    //		} finally {
    //			IOUtils.closeQuietly(is);
    //		}

    if (!resultStatus.isSuccess()) {
      // エラーを表示する.
      resultStatus.falureDialog(Messages.PI0139, Messages.PI0140);
    }

    return null;
  }