private void clearFieldsConfirm() {
   if (BgcPlugin.openConfirm(
       Messages.PatientLabelEntryForm_reset_confirm_title,
       Messages.PatientLabelEntryForm_reset_confirm_msg)) {
     clearFields();
   }
 }
 @Override
 public void reload() {
   if (rootNode != null) {
     rootNode.removeAll();
     try {
       createNodes();
     } catch (Exception e) {
       logger.error(Messages.SpecimenTransitView_nodes_error_title, e);
     }
     for (AbstractAdapterBase adaper : rootNode.getChildren()) {
       adaper.rebuild();
     }
   }
   try {
     setSearchFieldsEnablement(
         SessionManager.getAppService()
                 .isAllowed(
                     new DispatchReadPermission(
                         SessionManager.getUser().getCurrentWorkingCenter().getWrappedObject()))
             || SessionManager.getAppService()
                 .isAllowed(
                     new OriginInfoReadPermission(
                         SessionManager.getUser().getCurrentWorkingCenter().getWrappedObject())));
   } catch (ApplicationException e) {
     BgcPlugin.openAccessDeniedErrorMessage();
   }
   super.reload();
 }
 @Override
 public void dispose() {
   if (loginProvider != null) {
     BgcPlugin.getSessionStateSourceProvider().removeSourceProviderListener(loginProvider);
     loginProvider = null;
   }
   super.dispose();
 }
  @Override
  public boolean print() {
    PrintOperation printOperation = null;
    BarcodeViewGuiData guiData = null;
    try {
      guiData = new BarcodeViewGuiData();

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

      // print operation
      printOperation = new PrintOperation(guiData, patientNumbers);

      try {
        new ProgressMonitorDialog(shell).run(true, true, printOperation);
      } catch (InvocationTargetException e1) {
        printOperation.saveFailed();
        printOperation.setError(
            Messages.PatientLabelEntryForm_print_error_title,
            "InvocationTargetException: " //$NON-NLS-1$
                + e1.getCause().getMessage());
      }

      if (printOperation.isSuccessful()) {
        updateSavePreferences();
        clearFieldsConfirm();
        return true;
      }

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

    } catch (BiobankServerException e) {
      BgcPlugin.openAsyncError(Messages.PatientLabelEntryForm_specimenid_error_msg, e.getMessage());
    } catch (ApplicationException e) {
      BgcPlugin.openAsyncError(Messages.PatientLabelEntryForm_server_error_msg, e.getMessage());
    } catch (CBSRGuiVerificationException e1) {
      BgcPlugin.openAsyncError(
          Messages.PatientLabelEntryForm_validation_error_msg, e1.getMessage());
    } catch (InterruptedException e2) {
      // do nothing
    }
    return false;
  }
 @Override
 public boolean isEnabled() {
   if (allowed == null)
     try {
       allowed = SessionManager.getAppService().isAllowed(new UserManagerPermission());
     } catch (ApplicationException e) {
       BgcPlugin.openAsyncError("Unable to Load User Management Data", e.getMessage());
     }
   return allowed;
 }
 @Override
 public void init() {
   try {
     this.isDeletable =
         SessionManager.getAppService().isAllowed(new ResearchGroupDeletePermission(rg.id));
     this.isReadable =
         SessionManager.getAppService().isAllowed(new ResearchGroupReadPermission(rg.id));
     this.isEditable =
         SessionManager.getAppService().isAllowed(new ResearchGroupUpdatePermission(rg.id));
   } catch (ApplicationException e) {
     BgcPlugin.openAsyncError("Permission Error", "Unable to retrieve user permissions");
   }
 }
  @Override
  protected void createFormContent() throws Exception {
    super.createFormContent();
    form.setText(Messages.PatientLabelEntryForm_form_title);
    form.setMessage(Messages.PatientLabelEntryForm_form_description, IMessageProvider.NONE);
    page.setLayout(new GridLayout(1, false));

    BgcSessionState sessionSourceProvider = BgcPlugin.getSessionStateSourceProvider();

    loggedIn =
        sessionSourceProvider
            .getCurrentState()
            .get(BgcSessionState.SESSION_STATE_SOURCE_NAME)
            .equals(BgcSessionState.LOGGED_IN);

    loadPreferenceStore();

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

    createTopSection();
    createPerLabelInfo();
    createPerSheetInfo();
    createActionButtonsGroup();

    if (loginProvider != null) {
      sessionSourceProvider.removeSourceProviderListener(loginProvider);
      loginProvider = null;
    }

    loginProvider =
        new ISourceProviderListener() {
          @Override
          public void sourceChanged(int sourcePriority, String sourceName, Object sourceValue) {
            if (sourceValue != null) {
              loggedIn = sourceValue.equals(BgcSessionState.LOGGED_IN);
              updateForm();
            }
          }

          @Override
          public void sourceChanged(
              int sourcePriority, @SuppressWarnings("rawtypes") Map sourceValuesByName) {
            // do nothing for now
          }
        };
    sessionSourceProvider.addSourceProviderListener(loginProvider);

    templateStore = null;
    updateForm();
  }
 @Override
 protected void internalSearch() {
   try {
     List<? extends ModelWrapper<?>> searchedObject = search();
     if (searchedObject == null || searchedObject.size() == 0) {
       String msg;
       if (radioWaybill.getSelection()) {
         msg =
             NLS.bind(Messages.SpecimenTransitView_notfound_waybill_error_msg, treeText.getText());
       } else {
         msg =
             NLS.bind(
                 Messages.SpecimenTransitView_notfound_date_error_msg,
                 DateFormatter.formatAsDate(dateWidget.getDate()));
       }
       BgcPlugin.openMessage(Messages.SpecimenTransitView_notfound_error_title, msg);
     } else {
       showSearchedObjectsInTree(searchedObject, true);
       getTreeViewer().expandToLevel(searchedNode, 2);
     }
   } catch (Exception e) {
     BgcPlugin.openError(Messages.SpecimenTransitView_search_error_msg, e);
   }
 }
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
      BiobankApplicationService service = SessionManager.getAppService();
      ManagerContext context =
          service.doAction(new ManagerContextGetAction(new ManagerContextGetInput())).getContext();

      new UserManagementDialog(
              PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), context)
          .open();
    } catch (ApplicationException e) {
      BgcPlugin.openAsyncError("Unable to Load User Management Data", e.getMessage());
    }

    return null;
  }
  @SuppressWarnings("nls")
  @Override
  public void widgetSelected(SelectionEvent e) {
    if (e.getSource() != selectScannerBtn) return;

    ScanLibResult scanlibResult = ScanLib.getInstance().selectSourceAsDefault();

    if (scanlibResult.getResultCode() != ScanLibResult.Result.SUCCESS) {
      return;
    }

    ScanLibResult scannerCapResult = ScanLib.getInstance().getScannerCapability();
    int scannerCap = scannerCapResult.getValue();

    if (scanlibResult.getResultCode() != ScanLibResult.Result.SUCCESS) {
      // just stay with the last selected source
      if ((scannerCap & ScanLib.CAP_IS_SCANNER) != 0) {
        return;
      }
      setEnableAllWidgets(false);
      BgcPlugin.openError(i18n.tr("Scanning Source Error"), scanlibResult.getMessage());
      return;
    }

    IPreferenceStore prefs = ScannerConfigPlugin.getDefault().getPreferenceStore();

    String drvSetting = null;
    boolean[] drvRadioSettings = new boolean[] {false, false};

    if ((scannerCap & ScanLib.CAP_IS_WIA) != 0) {
      drvSetting = PreferenceConstants.SCANNER_DRV_TYPE_WIA;
      drvRadioSettings[1] = true;
    } else {
      drvSetting = PreferenceConstants.SCANNER_DRV_TYPE_TWAIN;
      drvRadioSettings[0] = true;
    }

    prefs.setValue(PreferenceConstants.SCANNER_DRV_TYPE, drvSetting);
    driverTypeRadio.setSelectionArray(drvRadioSettings);
    driverTypeRadio.doLoad();
    setEnableAllWidgets(true);
  }
  /**
   * Loads the Template from templateCombo.
   *
   * <p>A new template is loaded for each selection change in templateCombo.
   */
  private void loadSelectedTemplate() {
    if (templateCombo.getSelectionIndex() >= 0) {
      try {

        String comboSelectedTemplate = templateCombo.getItem(templateCombo.getSelectionIndex());

        // already loaded
        if ((loadedTemplate == null) || !loadedTemplate.getName().equals(comboSelectedTemplate)) {
          loadedTemplate = templateStore.getTemplate(comboSelectedTemplate);
        }

      } catch (Exception ee) {
        BgcPlugin.openAsyncError(
            Messages.PatientLabelEntryForm_verification_error_title,
            NLS.bind(Messages.PatientLabelEntryForm_verification_error_msg, ee.getMessage()));
      }

      if (loadedTemplate != null) printerText.setText(loadedTemplate.getPrinterName());
    }
  }
  private void updateForm() {
    try {
      if (loggedIn) {
        if (templateStore == null) {
          templateStore = new TemplateStore();
        }
        setEnable(true);

        // remove and reload template combo
        templateCombo.removeAll();
        for (String templateName : templateStore.getTemplateNames()) {
          templateCombo.add(templateName);
        }

        if (templateCombo.getItemCount() > 0) templateCombo.select(0);

        for (int i = 0; i < templateCombo.getItemCount(); i++) {
          if (templateCombo
              .getItem(i)
              .equals(perferenceStore.getString(PreferenceConstants.TEMPLATE_NAME))) {
            templateCombo.select(i);
            break;
          }
        }
        templateCombo.redraw();

        loadSelectedTemplate();

      } else {
        setEnable(false);
        templateCombo.removeAll();
        templateCombo.redraw();
      }
    } catch (ApplicationException e) {
      BgcPlugin.openAsyncError(
          "Database Error", //$NON-NLS-1$
          "Error while updating form",
          e); //$NON-NLS-1$
    }
  }
 @Override
 protected void showSearchedObjectsInTree(
     List<? extends ModelWrapper<?>> searchedObjects, boolean doubleClick) {
   for (ModelWrapper<?> searchedObject : searchedObjects) {
     List<AbstractAdapterBase> nodeRes =
         rootNode.search(searchedObject.getClass(), searchedObject.getId());
     if (nodeRes.size() == 0) {
       searchedNode.addSearchObject(searchedObject, searchedObject.getId());
       SpecimenTransitView.addToNode(searchedNode, searchedObject);
     }
   }
   if (searchedObjects.size() == 1) {
     ModelWrapper<?> searchedWrap = searchedObjects.get(0);
     List<AbstractAdapterBase> nodeRes =
         rootNode.search(searchedWrap.getClass(), searchedWrap.getId());
     if (nodeRes.size() > 0) nodeRes.get(0).performDoubleClick();
   } else {
     searchedNode.performExpand();
     BgcPlugin.openMessage(
         Messages.SpecimenTransitView_res_dialog_title,
         NLS.bind(Messages.SpecimenTransitView_found_multiple_msg, searchedObjects.size()));
   }
 }
        @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());
          }
        }
  @Override
  public void performExpand() {
    List<ModelWrapper<?>> alreadyHasListener = new ArrayList<ModelWrapper<?>>();
    try {
      for (AbstractAdapterBase child : getChildren()) {
        if (child instanceof AdapterBase) {
          ModelWrapper<?> childWrapper = ((AdapterBase) child).getModelObject();
          if (childWrapper != null) {
            childWrapper.reload();
          }
        }
        List<AbstractAdapterBase> subChildren =
            new ArrayList<AbstractAdapterBase>(child.getChildren());
        List<AbstractAdapterBase> toRemove = new ArrayList<AbstractAdapterBase>();
        for (AbstractAdapterBase subChild : subChildren) {
          ModelWrapper<?> wrapper = null;
          if (subChild instanceof AdapterBase) {
            Object subChildObj = ((AdapterBase) subChild).getModelObject();
            if (subChildObj instanceof ModelWrapper) {
              wrapper = (ModelWrapper<?>) subChildObj;
              // wrapper.reload();
              // FIXME: using reload here breaks a lot of stuff,
              // why?
            }
          }
          Integer subChildId = subChild.getId();
          if (!searchedObjectIds.contains(subChildId)) {
            toRemove.add(subChild);
          } else {
            // subChild.rebuild();
            if (wrapper != null) {
              alreadyHasListener.add(wrapper);
            }
          }
        }
        for (AbstractAdapterBase subChild : toRemove) child.removeChild(subChild);
      }
      // add searched objects is not yet there
      for (final Object o : searchedObjects) {
        if (o instanceof ModelWrapper) {
          ModelWrapper<?> w = (ModelWrapper<?>) o;
          if (!alreadyHasListener.contains(w)) {
            w.addWrapperListener(
                new WrapperListenerAdapter() {
                  @Override
                  public void deleted(WrapperEvent event) {
                    searchedObjects.remove(o);
                    performExpand();
                  }
                });
          }
        }
        addNode(o);
      }

      if (!keepDirectLeafChild) {
        // remove sub children without any children
        List<AbstractAdapterBase> children = new ArrayList<AbstractAdapterBase>(getChildren());
        for (AbstractAdapterBase child : children) {
          if (!(child instanceof DispatchAdapter) && child.getChildren().size() == 0) {
            removeChild(child);
          }
        }
      }
    } catch (final RemoteAccessException exp) {
      BgcPlugin.openRemoteAccessErrorMessage(exp);
    } catch (Exception e) {
      logger.error("Error while refreshing searched elements", e); // $NON-NLS-1$
    }
  }