Esempio n. 1
0
  private void update(AjaxRequestTarget target) {
    JCas jCas = null;
    try {
      CuratorUtil.updatePanel(
          target,
          automateView,
          curationContainer,
          mergeVisualizer,
          repository,
          annotationSelectionByUsernameAndAddress,
          curationSegment,
          annotationService,
          userRepository);

      jCas = repository.readCorrectionCas(bModel.getDocument());
    } catch (UIMAException e) {
      error(ExceptionUtils.getRootCauseMessage(e));
    } catch (ClassNotFoundException e) {
      error(e.getMessage());
    } catch (IOException e) {
      error(e.getMessage());
    } catch (BratAnnotationException e) {
      error(e.getMessage());
    }

    gotoPageTextField.setModelObject(getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1);
    gotoPageAddress = getSentenceAddress(jCas, gotoPageTextField.getModelObject());

    target.add(gotoPageTextField);
    target.add(automateView);
    target.add(numberOfPages);
  }
Esempio n. 2
0
  public void updatePanel(AjaxRequestTarget aTarget, CurationContainer aCC)
      throws UIMAException, ClassNotFoundException, IOException, BratAnnotationException {
    JCas jCas = repository.readCurationCas(bModel.getDocument());

    final int sentenceAddress =
        getAddr(
            selectSentenceAt(jCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset()));
    bModel.setSentenceAddress(sentenceAddress);

    final Sentence sentence = selectByAddr(jCas, Sentence.class, sentenceAddress);
    List<Sentence> followingSentences =
        selectFollowing(jCas, Sentence.class, sentence, bModel.getPreferences().getWindowSize());
    // Check also, when getting the last sentence address in the display window, if this is the
    // last sentence or the ONLY sentence in the document
    Sentence lastSentenceAddressInDisplayWindow =
        followingSentences.size() == 0
            ? sentence
            : followingSentences.get(followingSentences.size() - 1);
    if (curationView == null) {
      curationView = new SourceListView();
    }
    curationView.setCurationBegin(sentence.getBegin());
    curationView.setCurationEnd(lastSentenceAddressInDisplayWindow.getEnd());

    int ws = bModel.getPreferences().getWindowSize();
    Sentence fs =
        BratAjaxCasUtil.selectSentenceAt(
            jCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset());
    int l = BratAjaxCasUtil.getLastSentenceAddressInDisplayWindow(jCas, getAddr(fs), ws);
    Sentence ls = (Sentence) selectByAddr(jCas, FeatureStructure.class, l);
    fSn = BratAjaxCasUtil.getSentenceNumber(jCas, fs.getBegin());
    lSn = BratAjaxCasUtil.getSentenceNumber(jCas, ls.getBegin());

    sentencesListView.addOrReplace(sentenceList);
    aTarget.add(sentencesListView);

    /*
     * corssSentAnnoView.addOrReplace(crossSentAnnoList); aTarget.add(corssSentAnnoView);
     */
    aTarget.add(suggestionViewPanel);
    if (annotate) {
      annotator.bratRender(aTarget, editor.getCas(bModel));
      annotator.bratSetHighlight(aTarget, bModel.getSelection().getAnnotation());

    } else {
      annotator.bratRenderLater(aTarget);
    }
    annotate = false;
    CuratorUtil.updatePanel(
        aTarget,
        suggestionViewPanel,
        aCC,
        annotator,
        repository,
        annotationSelectionByUsernameAndAddress,
        curationView,
        annotationService,
        userRepository);
  }
Esempio n. 3
0
  @Override
  public void renderHead(IHeaderResponse response) {
    super.renderHead(response);

    if (firstLoad) {
      firstLoad = false;
    } else if (bModel.getProject() != null) {
      // mergeVisualizer.setModelObject(bratAnnotatorModel);
      annotator.setCollection("#" + bModel.getProject().getName() + "/");
      annotator.bratInitRenderLater(response);
    }
  }
  public static void savePreference(BratAnnotatorModel aBModel, RepositoryService aRepository)
      throws FileNotFoundException, IOException {
    AnnotationPreference preference = aBModel.getPreferences();
    ArrayList<Long> layers = new ArrayList<Long>();

    for (AnnotationLayer layer : aBModel.getAnnotationLayers()) {
      layers.add(layer.getId());
    }
    preference.setAnnotationLayers(layers);

    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    aRepository.saveUserSettings(username, aBModel.getProject(), aBModel.getMode(), preference);
  }
Esempio n. 5
0
  /** for the first time the page is accessed, open the <b>open document dialog</b> */
  @Override
  public void renderHead(IHeaderResponse response) {
    super.renderHead(response);

    String jQueryString = "";
    if (firstLoad) {
      jQueryString += "jQuery('#showOpenDocumentModal').trigger('click');";
      firstLoad = false;
    }
    response.render(OnLoadHeaderItem.forScript(jQueryString));
    if (bModel.getProject() != null) {

      mergeVisualizer.setModelObject(bModel);
      mergeVisualizer.setCollection("#" + bModel.getProject().getName() + "/");
      mergeVisualizer.bratInitRenderLater(response);
    }
  }
  /**
   * Set annotation preferences of users for a given project such as window size, annotation
   * layers,... reading from the file system.
   *
   * @param aUsername The {@link User} for whom we need to read the preference (preferences are
   *     stored per user)
   * @param aRepositoryService the repository service.
   * @param aAnnotationService the annotation service.
   * @param aBModel The {@link BratAnnotatorModel} that will be populated with preferences from the
   *     file
   * @param aMode the mode.
   * @throws BeansException hum?
   * @throws IOException hum?
   */
  public static void setAnnotationPreference(
      String aUsername,
      RepositoryService aRepositoryService,
      AnnotationService aAnnotationService,
      BratAnnotatorModel aBModel,
      Mode aMode)
      throws BeansException, IOException {
    AnnotationPreference preference = new AnnotationPreference();
    BeanWrapper wrapper = new BeanWrapperImpl(preference);
    // get annotation preference from file system
    try {
      Properties props = aRepositoryService.loadUserSettings(aUsername, aBModel.getProject());
      for (Entry<Object, Object> entry : props.entrySet()) {
        String property = entry.getKey().toString();
        int index = property.lastIndexOf(".");
        String propertyName = property.substring(index + 1);
        String mode = property.substring(0, index);
        if (wrapper.isWritableProperty(propertyName) && mode.equals(aMode.getName())) {
          if (AnnotationPreference.class.getDeclaredField(propertyName).getGenericType()
              instanceof ParameterizedType) {
            List<String> value =
                Arrays.asList(
                    StringUtils.replaceChars(entry.getValue().toString(), "[]", "").split(","));
            if (!value.get(0).equals("")) {
              wrapper.setPropertyValue(propertyName, value);
            }
          } else {
            wrapper.setPropertyValue(propertyName, entry.getValue());
          }
        }
      }
      aBModel.setPreferences(preference);

      // Get tagset using the id, from the properties file
      aBModel.getAnnotationLayers().clear();
      if (preference.getAnnotationLayers() != null) {
        for (Long id : preference.getAnnotationLayers()) {
          aBModel.getAnnotationLayers().add(aAnnotationService.getLayer(id));
        }
      } else {
        // If no layer preferences are defined, then just assume all layers are enabled
        List<AnnotationLayer> layers = aAnnotationService.listAnnotationLayer(aBModel.getProject());
        aBModel.setAnnotationLayers(layers);
      }
    }
    // no preference found
    catch (Exception e) {
      // If no layer preferences are defined, then just assume all layers are enabled
      List<AnnotationLayer> layers = aAnnotationService.listAnnotationLayer(aBModel.getProject());
      aBModel.setAnnotationLayers(layers);
    }
  }
Esempio n. 7
0
  private void setCurationSegmentBeginEnd()
      throws UIMAException, ClassNotFoundException, IOException {
    JCas jCas = repository.readAnnotationCas(bModel.getDocument(), bModel.getUser());

    final int sentenceAddress =
        getAddr(
            selectSentenceAt(jCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset()));

    final Sentence sentence = selectByAddr(jCas, Sentence.class, sentenceAddress);
    List<Sentence> followingSentences =
        selectFollowing(jCas, Sentence.class, sentence, bModel.getPreferences().getWindowSize());
    // Check also, when getting the last sentence address in the display window, if this is the
    // last sentence or the ONLY sentence in the document
    Sentence lastSentenceAddressInDisplayWindow =
        followingSentences.size() == 0
            ? sentence
            : followingSentences.get(followingSentences.size() - 1);
    curationSegment.setBegin(sentence.getBegin());
    curationSegment.setEnd(lastSentenceAddressInDisplayWindow.getEnd());
  }
 private JCas createCorrectionCas(
     JCas mergeJCas,
     BratAnnotatorModel aBratAnnotatorModel,
     AnnotationDocument randomAnnotationDocument)
     throws UIMAException, ClassNotFoundException, IOException {
   User userLoggedIn =
       userRepository.get(SecurityContextHolder.getContext().getAuthentication().getName());
   mergeJCas = repository.readAnnotationCas(aBratAnnotatorModel.getDocument(), userLoggedIn);
   repository.writeCorrectionCas(mergeJCas, randomAnnotationDocument.getDocument(), userLoggedIn);
   return mergeJCas;
 }
Esempio n. 9
0
  private void ubdateSentenceNumber(JCas aJCas, int aAddress) {
    bModel.setSentenceAddress(aAddress);
    Sentence sentence = selectByAddr(aJCas, Sentence.class, aAddress);
    bModel.setSentenceBeginOffset(sentence.getBegin());
    bModel.setSentenceEndOffset(sentence.getEnd());
    bModel.setSentenceNumber(BratAjaxCasUtil.getSentenceNumber(aJCas, sentence.getBegin()));

    Sentence firstSentence =
        selectSentenceAt(aJCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset());
    int lastAddressInPage =
        getLastSentenceAddressInDisplayWindow(
            aJCas, getAddr(firstSentence), bModel.getPreferences().getWindowSize());
    // the last sentence address in the display window
    Sentence lastSentenceInPage =
        (Sentence) selectByAddr(aJCas, FeatureStructure.class, lastAddressInPage);
    bModel.setFSN(BratAjaxCasUtil.getSentenceNumber(aJCas, firstSentence.getBegin()));
    bModel.setLSN(BratAjaxCasUtil.getSentenceNumber(aJCas, lastSentenceInPage.getBegin()));
  }
Esempio n. 10
0
  /**
   * Puts JCases into a list and get a random annotation document that will be used as a base for
   * the diff.
   *
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws UIMAException
   */
  private void updateSegment(
      BratAnnotatorModel aBratAnnotatorModel,
      Map<Integer, Integer> segmentBeginEnd,
      Map<Integer, Integer> segmentNumber,
      Map<String, Map<Integer, Integer>> segmentAdress,
      JCas jCas,
      String username,
      int aWinSize)
      throws UIMAException, ClassNotFoundException, IOException {
    Sentence firstSentence =
        selectSentenceAt(
            jCas,
            aBratAnnotatorModel.getSentenceBeginOffset(),
            aBratAnnotatorModel.getSentenceEndOffset());
    Sentence lastSentence =
        selectByAddr(
            jCas,
            Sentence.class,
            getLastSentenceAddressInDisplayWindow(jCas, getAddr(firstSentence), aWinSize));

    begin = firstSentence.getBegin();
    end = lastSentence.getEnd();
    sentenceNumber = getFirstSentenceNumber(jCas, getAddr(firstSentence));
    segmentAdress.put(username, new HashMap<Integer, Integer>());

    for (Sentence sentence : selectCovered(jCas, Sentence.class, begin, end)) {
      sentenceNumber += 1;
      segmentBeginEnd.put(sentence.getBegin(), sentence.getEnd());
      segmentNumber.put(sentence.getBegin(), sentenceNumber);
      segmentAdress.get(username).put(sentence.getBegin(), getAddr(sentence));
    }

    /*
     * if (segmentBeginEnd.isEmpty()) { for (Sentence sentence : selectCovered(mergeJCas,
     * Sentence.class, begin, end)) {
     *
     * } }
     */
  }
Esempio n. 11
0
  /**
   * Fetches the CAS that the user will be able to edit. In AUTOMATION/CORRECTION mode, this is the
   * CAS for the CORRECTION_USER and in CURATION mode it is the CAS for the CURATION user.
   *
   * @param aBratAnnotatorModel the model.
   * @param aDocument the source document.
   * @param jCases the JCases.
   * @param randomAnnotationDocument an annotation document.
   * @return the JCas.
   * @throws UIMAException hum?
   * @throws ClassNotFoundException hum?
   * @throws IOException if an I/O error occurs.
   * @throws BratAnnotationException hum?
   */
  public JCas getMergeCas(
      BratAnnotatorModel aBratAnnotatorModel,
      SourceDocument aDocument,
      Map<String, JCas> jCases,
      AnnotationDocument randomAnnotationDocument)
      throws UIMAException, ClassNotFoundException, IOException, BratAnnotationException {
    JCas mergeJCas = null;
    try {
      if (aBratAnnotatorModel.getMode().equals(Mode.AUTOMATION)
          || aBratAnnotatorModel.getMode().equals(Mode.CORRECTION)) {
        // Upgrading should be an explicit action during the opening of a document at the
        // end
        // of the open dialog - it must not happen during editing because the CAS addresses
        // are used as IDs in the UI
        // repository.upgradeCasAndSave(aDocument, aBratAnnotatorModel.getMode(),
        // aBratAnnotatorModel.getUser().getUsername());
        mergeJCas = repository.readCorrectionCas(aDocument);
      } else {
        // Upgrading should be an explicit action during the opening of a document at the
        // end
        // of the open dialog - it must not happen during editing because the CAS addresses
        // are used as IDs in the UI
        // repository.upgradeCasAndSave(aDocument, aBratAnnotatorModel.getMode(),
        // aBratAnnotatorModel.getUser().getUsername());
        mergeJCas = repository.readCurationCas(aDocument);
      }
    }
    // Create jcas, if it could not be loaded from the file system
    catch (Exception e) {

      if (aBratAnnotatorModel.getMode().equals(Mode.AUTOMATION)
          || aBratAnnotatorModel.getMode().equals(Mode.CORRECTION)) {
        mergeJCas = createCorrectionCas(mergeJCas, aBratAnnotatorModel, randomAnnotationDocument);
      } else {
        mergeJCas =
            createCurationCas(
                aBratAnnotatorModel.getProject(),
                randomAnnotationDocument,
                jCases,
                aBratAnnotatorModel.getAnnotationLayers());
      }
    }
    return mergeJCas;
  }
Esempio n. 12
0
  public AutomationPage() {
    bModel = new BratAnnotatorModel();
    bModel.setMode(Mode.AUTOMATION);

    LinkedList<CurationUserSegmentForAnnotationDocument> sentences =
        new LinkedList<CurationUserSegmentForAnnotationDocument>();
    CurationUserSegmentForAnnotationDocument curationUserSegmentForAnnotationDocument =
        new CurationUserSegmentForAnnotationDocument();
    if (bModel.getDocument() != null) {
      curationUserSegmentForAnnotationDocument.setAnnotationSelectionByUsernameAndAddress(
          annotationSelectionByUsernameAndAddress);
      curationUserSegmentForAnnotationDocument.setBratAnnotatorModel(bModel);
      sentences.add(curationUserSegmentForAnnotationDocument);
    }
    automateView =
        new SuggestionViewPanel(
            "automateView",
            new Model<LinkedList<CurationUserSegmentForAnnotationDocument>>(sentences)) {
          private static final long serialVersionUID = 2583509126979792202L;

          @Override
          public void onChange(AjaxRequestTarget aTarget) {
            try {
              // update begin/end of the curationsegment based on bratAnnotatorModel changes
              // (like sentence change in auto-scroll mode,....
              aTarget.addChildren(getPage(), FeedbackPanel.class);
              curationContainer.setBratAnnotatorModel(bModel);
              setCurationSegmentBeginEnd();

              CuratorUtil.updatePanel(
                  aTarget,
                  this,
                  curationContainer,
                  mergeVisualizer,
                  repository,
                  annotationSelectionByUsernameAndAddress,
                  curationSegment,
                  annotationService,
                  userRepository);
            } catch (UIMAException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (ClassNotFoundException e) {
              error(e.getMessage());
            } catch (IOException e) {
              error(e.getMessage());
            } catch (BratAnnotationException e) {
              error(e.getMessage());
            }
            mergeVisualizer.bratRenderLater(aTarget);
            aTarget.add(numberOfPages);
            update(aTarget);
          }
        };

    automateView.setOutputMarkupId(true);
    add(automateView);

    annotationDetailEditorPanel =
        new AnnotationDetailEditorPanel(
            "annotationDetailEditorPanel", new Model<BratAnnotatorModel>(bModel)) {
          private static final long serialVersionUID = 2857345299480098279L;

          @Override
          protected void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) {
            aTarget.addChildren(getPage(), FeedbackPanel.class);

            try {
              mergeVisualizer.bratRender(aTarget, getCas(aBModel));
            } catch (UIMAException | ClassNotFoundException | IOException e) {
              LOG.info("Error reading CAS " + e.getMessage());
              error("Error reading CAS " + e.getMessage());
              return;
            }

            mergeVisualizer.bratRenderHighlight(aTarget, aBModel.getSelection().getAnnotation());

            mergeVisualizer.onChange(aTarget, aBModel);
            mergeVisualizer.onAnnotate(
                aTarget,
                aBModel,
                aBModel.getSelection().getBegin(),
                aBModel.getSelection().getEnd());
            if (!aBModel.getSelection().isAnnotate()) {
              mergeVisualizer.onDelete(
                  aTarget,
                  aBModel,
                  aBModel.getSelection().getBegin(),
                  aBModel.getSelection().getEnd());
            }
          }
        };

    annotationDetailEditorPanel.setOutputMarkupId(true);
    add(annotationDetailEditorPanel);

    mergeVisualizer =
        new BratAnnotator(
            "mergeView", new Model<BratAnnotatorModel>(bModel), annotationDetailEditorPanel) {
          private static final long serialVersionUID = 7279648231521710155L;

          @Override
          public void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBratAnnotatorModel) {
            try {
              aTarget.addChildren(getPage(), FeedbackPanel.class);
              // info(bratAnnotatorModel.getMessage());
              aTarget.addChildren(getPage(), FeedbackPanel.class);
              bModel = aBratAnnotatorModel;
              SuggestionBuilder builder =
                  new SuggestionBuilder(repository, annotationService, userRepository);
              curationContainer = builder.buildCurationContainer(bModel);
              setCurationSegmentBeginEnd();
              curationContainer.setBratAnnotatorModel(bModel);

              CuratorUtil.updatePanel(
                  aTarget,
                  automateView,
                  curationContainer,
                  this,
                  repository,
                  annotationSelectionByUsernameAndAddress,
                  curationSegment,
                  annotationService,
                  userRepository);
              aTarget.add(automateView);
              aTarget.add(numberOfPages);
            } catch (UIMAException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (ClassNotFoundException e) {
              error(e.getMessage());
            } catch (IOException e) {
              error(e.getMessage());
            } catch (BratAnnotationException e) {
              error(e.getMessage());
            }
            update(aTarget);
          }

          @Override
          public void onAnnotate(
              AjaxRequestTarget aTarget,
              BratAnnotatorModel aBratAnnotatorModel,
              int aStart,
              int aEnd) {
            MiraTemplate template;
            Set<AnnotationFeature> features = bModel.getRememberedSpanFeatures().keySet();
            AnnotationFeature autoFeature = null;
            for (AnnotationFeature feature : features) {
              autoFeature = feature;
              break;
            }
            try {
              template = automationService.getMiraTemplate(autoFeature);
              if (!template.isAnnotateAndPredict()) {
                return;
              }
              /*
               * Tag tag = annotationService.getTag(bratAnnotatorModel
               * .getRememberedSpanFeatures().get(autoFeature), autoFeature.getTagset());
               */
              AutomationUtil.repeateAnnotation(
                  bModel,
                  repository,
                  userRepository,
                  annotationService,
                  automationService,
                  aStart,
                  aEnd,
                  autoFeature);
            } catch (UIMAException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (ClassNotFoundException e) {
              error(e.getMessage());
            } catch (IOException e) {
              error(e.getMessage());
            } catch (BratAnnotationException e) {
              error(e.getMessage());
            } catch (NoResultException e) { // no automation layer is configured yet.
              template = null;
              return;
            }
            update(aTarget);
          }

          @Override
          public void onDelete(
              AjaxRequestTarget aTarget,
              BratAnnotatorModel aBratAnnotatorModel,
              int aStart,
              int aEnd) {
            MiraTemplate template;
            Set<AnnotationFeature> features = bModel.getRememberedSpanFeatures().keySet();
            AnnotationFeature autoFeature = null;
            for (AnnotationFeature feature : features) {
              autoFeature = feature;
              break;
            }
            if (autoFeature == null) {
              return;
            }
            try {
              template = automationService.getMiraTemplate(autoFeature);
              if (!template.isAnnotateAndPredict()) {
                return;
              }
              /*
               * Tag tag = annotationService.getTag(bratAnnotatorModel
               * .getRememberedSpanFeatures().get(autoFeature), autoFeature.getTagset());
               */
              AutomationUtil.deleteAnnotation(
                  bModel,
                  repository,
                  annotationService,
                  automationService,
                  userRepository,
                  aStart,
                  aEnd,
                  autoFeature);
            } catch (UIMAException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (ClassNotFoundException e) {
              error(e.getMessage());
            } catch (IOException e) {
              error(e.getMessage());
            } catch (BratAnnotationException e) {
              error(e.getMessage());
            } catch (NoResultException e) { // no automation layer is configured yet.
              template = null;
              return;
            }
            update(aTarget);
          }
        };
    // reset sentenceAddress and lastSentenceAddress to the orginal once

    mergeVisualizer.setOutputMarkupId(true);
    add(mergeVisualizer);

    curationContainer = new CurationContainer();
    curationContainer.setBratAnnotatorModel(bModel);

    add(
        documentNamePanel =
            new DocumentNamePanel("documentNamePanel", new Model<BratAnnotatorModel>(bModel)));

    add(
        numberOfPages =
            (Label)
                new Label(
                        "numberOfPages",
                        new LoadableDetachableModel<String>() {
                          private static final long serialVersionUID = 891566759811286173L;

                          @Override
                          protected String load() {
                            if (bModel.getDocument() != null) {

                              JCas mergeJCas = null;
                              try {

                                mergeJCas = repository.readCorrectionCas(bModel.getDocument());

                                totalNumberOfSentence = getNumberOfPages(mergeJCas);

                                // If only one page, start displaying from sentence 1
                                /*
                                 * if (totalNumberOfSentence == 1) {
                                 * bratAnnotatorModel.setSentenceAddress(bratAnnotatorModel
                                 * .getFirstSentenceAddress()); }
                                 */
                                int address =
                                    getAddr(
                                        selectSentenceAt(
                                            mergeJCas,
                                            bModel.getSentenceBeginOffset(),
                                            bModel.getSentenceEndOffset()));
                                sentenceNumber = getFirstSentenceNumber(mergeJCas, address);
                                int firstSentenceNumber = sentenceNumber + 1;
                                int lastSentenceNumber;
                                if (firstSentenceNumber
                                        + bModel.getPreferences().getWindowSize()
                                        - 1
                                    < totalNumberOfSentence) {
                                  lastSentenceNumber =
                                      firstSentenceNumber
                                          + bModel.getPreferences().getWindowSize()
                                          - 1;
                                } else {
                                  lastSentenceNumber = totalNumberOfSentence;
                                }

                                return "showing "
                                    + firstSentenceNumber
                                    + "-"
                                    + lastSentenceNumber
                                    + " of "
                                    + totalNumberOfSentence
                                    + " sentences";
                              } catch (UIMAException e) {
                                return "";
                              } catch (DataRetrievalFailureException e) {
                                return "";
                              } catch (ClassNotFoundException e) {
                                return "";
                              } catch (FileNotFoundException e) {
                                return "";
                              } catch (IOException e) {
                                return "";
                              }

                            } else {
                              return ""; // no document yet selected
                            }
                          }
                        })
                    .setOutputMarkupId(true));

    final ModalWindow openDocumentsModal;
    add(openDocumentsModal = new ModalWindow("openDocumentsModal"));
    openDocumentsModal.setOutputMarkupId(true);

    openDocumentsModal.setInitialWidth(500);
    openDocumentsModal.setInitialHeight(300);
    openDocumentsModal.setResizable(true);
    openDocumentsModal.setWidthUnit("px");
    openDocumentsModal.setHeightUnit("px");
    openDocumentsModal.setTitle("Open document");

    add(
        new AjaxLink<Void>("showOpenDocumentModal") {
          private static final long serialVersionUID = 7496156015186497496L;

          @Override
          public void onClick(AjaxRequestTarget aTarget) {
            openDocumentsModal.setContent(
                new OpenModalWindowPanel(
                    openDocumentsModal.getContentId(),
                    bModel,
                    openDocumentsModal,
                    Mode.AUTOMATION));
            openDocumentsModal.setWindowClosedCallback(
                new ModalWindow.WindowClosedCallback() {
                  private static final long serialVersionUID = -1746088901018629567L;

                  @Override
                  public void onClose(AjaxRequestTarget target) {
                    if (bModel.getDocument() == null) {
                      setResponsePage(WelcomePage.class);
                      return;
                    }

                    try {
                      target.addChildren(getPage(), FeedbackPanel.class);
                      bModel.setDocument(bModel.getDocument());
                      bModel.setProject(bModel.getProject());

                      String username =
                          SecurityContextHolder.getContext().getAuthentication().getName();

                      repository.upgradeCasAndSave(bModel.getDocument(), Mode.AUTOMATION, username);
                      loadDocumentAction();
                      setCurationSegmentBeginEnd();
                      update(target);

                    } catch (UIMAException e) {
                      target.addChildren(getPage(), FeedbackPanel.class);
                      error(ExceptionUtils.getRootCause(e));
                    } catch (ClassNotFoundException e) {
                      target.addChildren(getPage(), FeedbackPanel.class);
                      error(e.getMessage());
                    } catch (IOException e) {
                      target.addChildren(getPage(), FeedbackPanel.class);
                      error(e.getMessage());
                    } catch (BratAnnotationException e) {
                      error(e.getMessage());
                    }
                    finish.setModelObject(bModel);
                    target.add(finish.setOutputMarkupId(true));
                    target.appendJavaScript(
                        "Wicket.Window.unloadConfirmation=false;window.location.reload()");
                    target.add(documentNamePanel.setOutputMarkupId(true));
                    target.add(numberOfPages);
                  }
                });
            openDocumentsModal.show(aTarget);
          }
        });

    add(
        new AnnotationLayersModalPanel(
            "annotationLayersModalPanel", new Model<BratAnnotatorModel>(bModel)) {
          private static final long serialVersionUID = -4657965743173979437L;

          @Override
          protected void onChange(AjaxRequestTarget aTarget) {
            curationContainer.setBratAnnotatorModel(bModel);
            try {
              aTarget.addChildren(getPage(), FeedbackPanel.class);
              setCurationSegmentBeginEnd();
            } catch (UIMAException e) {
              error(ExceptionUtils.getRootCauseMessage(e));
            } catch (ClassNotFoundException e) {
              error(e.getMessage());
            } catch (IOException e) {
              error(e.getMessage());
            }
            update(aTarget);
            // mergeVisualizer.reloadContent(aTarget);
            aTarget.appendJavaScript(
                "Wicket.Window.unloadConfirmation = false;window.location.reload()");
          }
        });

    add(new ExportModalPanel("exportModalPanel", new Model<BratAnnotatorModel>(bModel)));

    gotoPageTextField =
        (NumberTextField<Integer>)
            new NumberTextField<Integer>("gotoPageText", new Model<Integer>(0));
    Form<Void> gotoPageTextFieldForm = new Form<Void>("gotoPageTextFieldForm");
    gotoPageTextFieldForm.add(
        new AjaxFormSubmitBehavior(gotoPageTextFieldForm, "onsubmit") {
          private static final long serialVersionUID = -4549805321484461545L;

          @Override
          protected void onSubmit(AjaxRequestTarget aTarget) {
            if (gotoPageAddress == 0) {
              aTarget.appendJavaScript("alert('The sentence number entered is not valid')");
              return;
            }
            JCas mergeJCas = null;
            try {
              aTarget.addChildren(getPage(), FeedbackPanel.class);
              mergeJCas = repository.readCorrectionCas(bModel.getDocument());
              if (bModel.getSentenceAddress() != gotoPageAddress) {

                ubdateSentenceNumber(mergeJCas, gotoPageAddress);

                SuggestionBuilder builder =
                    new SuggestionBuilder(repository, annotationService, userRepository);
                curationContainer = builder.buildCurationContainer(bModel);
                setCurationSegmentBeginEnd();
                curationContainer.setBratAnnotatorModel(bModel);
                update(aTarget);
                mergeVisualizer.bratRenderLater(aTarget);
              }
            } catch (UIMAException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (ClassNotFoundException e) {
              error(e.getMessage());
            } catch (IOException e) {
              error(e.getMessage());
            } catch (BratAnnotationException e) {
              error(e.getMessage());
            }
          }
        });

    gotoPageTextField.setType(Integer.class);
    gotoPageTextField.setMinimum(1);
    gotoPageTextField.setDefaultModelObject(1);
    add(gotoPageTextFieldForm.add(gotoPageTextField));
    gotoPageTextField.add(
        new AjaxFormComponentUpdatingBehavior("onchange") {
          private static final long serialVersionUID = -3853194405966729661L;

          @Override
          protected void onUpdate(AjaxRequestTarget target) {
            JCas mergeJCas = null;
            try {
              mergeJCas = repository.readCorrectionCas(bModel.getDocument());
              gotoPageAddress = getSentenceAddress(mergeJCas, gotoPageTextField.getModelObject());
            } catch (UIMAException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (ClassNotFoundException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (IOException e) {
              error(e.getMessage());
            }
          }
        });

    add(
        new AjaxLink<Void>("gotoPageLink") {
          private static final long serialVersionUID = 7496156015186497496L;

          @Override
          public void onClick(AjaxRequestTarget aTarget) {

            if (gotoPageAddress == 0) {
              aTarget.appendJavaScript("alert('The sentence number entered is not valid')");
              return;
            }
            if (bModel.getDocument() == null) {
              aTarget.appendJavaScript("alert('Please open a document first!')");
              return;
            }
            JCas mergeJCas = null;
            try {
              aTarget.addChildren(getPage(), FeedbackPanel.class);
              mergeJCas = repository.readCorrectionCas(bModel.getDocument());
              if (bModel.getSentenceAddress() != gotoPageAddress) {

                ubdateSentenceNumber(mergeJCas, gotoPageAddress);

                SuggestionBuilder builder =
                    new SuggestionBuilder(repository, annotationService, userRepository);
                curationContainer = builder.buildCurationContainer(bModel);
                setCurationSegmentBeginEnd();
                curationContainer.setBratAnnotatorModel(bModel);
                update(aTarget);
                mergeVisualizer.bratRenderLater(aTarget);
              }
            } catch (UIMAException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (ClassNotFoundException e) {
              error(e.getMessage());
            } catch (IOException e) {
              error(e.getMessage());
            } catch (BratAnnotationException e) {
              error(e.getMessage());
            }
          }
        });

    finish =
        new FinishImage(
            "finishImage",
            new LoadableDetachableModel<BratAnnotatorModel>() {
              private static final long serialVersionUID = -2737326878793568454L;

              @Override
              protected BratAnnotatorModel load() {
                return bModel;
              }
            });

    add(
        new FinishLink("showYesNoModalPanel", new Model<BratAnnotatorModel>(bModel), finish) {
          private static final long serialVersionUID = -4657965743173979437L;
        });

    // Show the previous document, if exist
    add(
        new AjaxLink<Void>("showPreviousDocument") {
          private static final long serialVersionUID = 7496156015186497496L;

          /**
           * Get the current beginning sentence address and add on it the size of the display window
           */
          @Override
          public void onClick(AjaxRequestTarget target) {
            target.addChildren(getPage(), FeedbackPanel.class);
            // List of all Source Documents in the project
            List<SourceDocument> listOfSourceDocuements =
                repository.listSourceDocuments(bModel.getProject());

            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            User user = userRepository.get(username);

            List<SourceDocument> sourceDocumentsinIgnorState = new ArrayList<SourceDocument>();
            for (SourceDocument sourceDocument : listOfSourceDocuements) {
              if (repository.existsAnnotationDocument(sourceDocument, user)
                  && repository
                      .getAnnotationDocument(sourceDocument, user)
                      .getState()
                      .equals(AnnotationDocumentState.IGNORE)) {
                sourceDocumentsinIgnorState.add(sourceDocument);
              } else if (sourceDocument.isTrainingDocument()) {
                sourceDocumentsinIgnorState.add(sourceDocument);
              }
            }

            listOfSourceDocuements.removeAll(sourceDocumentsinIgnorState);

            // Index of the current source document in the list
            int currentDocumentIndex = listOfSourceDocuements.indexOf(bModel.getDocument());

            // If the first the document
            if (currentDocumentIndex == 0) {
              target.appendJavaScript("alert('This is the first document!')");
            } else {
              bModel.setDocumentName(
                  listOfSourceDocuements.get(currentDocumentIndex - 1).getName());
              bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex - 1));

              try {
                repository.upgradeCasAndSave(
                    bModel.getDocument(), Mode.AUTOMATION, bModel.getUser().getUsername());
                loadDocumentAction();
                setCurationSegmentBeginEnd();
                update(target);

              } catch (UIMAException e) {
                error(ExceptionUtils.getRootCause(e));
              } catch (ClassNotFoundException e) {
                error(ExceptionUtils.getRootCause(e));
              } catch (IOException e) {
                error(ExceptionUtils.getRootCause(e));
              } catch (BratAnnotationException e) {
                target.addChildren(getPage(), FeedbackPanel.class);
                error(e.getMessage());
              }

              finish.setModelObject(bModel);
              target.add(finish.setOutputMarkupId(true));
              target.add(numberOfPages);
              target.add(documentNamePanel);
              mergeVisualizer.bratRenderLater(target);
            }
          }
        }.add(new InputBehavior(new KeyType[] {KeyType.Shift, KeyType.Page_up}, EventType.click)));

    // Show the next document if exist
    add(
        new AjaxLink<Void>("showNextDocument") {
          private static final long serialVersionUID = 7496156015186497496L;

          /**
           * Get the current beginning sentence address and add on it the size of the display window
           */
          @Override
          public void onClick(AjaxRequestTarget target) {
            target.addChildren(getPage(), FeedbackPanel.class);
            // List of all Source Documents in the project
            List<SourceDocument> listOfSourceDocuements =
                repository.listSourceDocuments(bModel.getProject());

            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            User user = userRepository.get(username);

            List<SourceDocument> sourceDocumentsinIgnorState = new ArrayList<SourceDocument>();
            for (SourceDocument sourceDocument : listOfSourceDocuements) {
              if (repository.existsAnnotationDocument(sourceDocument, user)
                  && repository
                      .getAnnotationDocument(sourceDocument, user)
                      .getState()
                      .equals(AnnotationDocumentState.IGNORE)) {
                sourceDocumentsinIgnorState.add(sourceDocument);
              } else if (sourceDocument.isTrainingDocument()) {
                sourceDocumentsinIgnorState.add(sourceDocument);
              }
            }

            listOfSourceDocuements.removeAll(sourceDocumentsinIgnorState);

            // Index of the current source document in the list
            int currentDocumentIndex = listOfSourceDocuements.indexOf(bModel.getDocument());

            // If the first document
            if (currentDocumentIndex == listOfSourceDocuements.size() - 1) {
              target.appendJavaScript("alert('This is the last document!')");
              return;
            }
            bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex + 1).getName());
            bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex + 1));

            try {
              repository.upgradeCasAndSave(
                  bModel.getDocument(), Mode.AUTOMATION, bModel.getUser().getUsername());
              loadDocumentAction();
              setCurationSegmentBeginEnd();
              update(target);

            } catch (UIMAException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (ClassNotFoundException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (IOException e) {
              error(ExceptionUtils.getRootCause(e));
            } catch (BratAnnotationException e) {
              target.addChildren(getPage(), FeedbackPanel.class);
              error(e.getMessage());
            }

            finish.setModelObject(bModel);
            target.add(finish.setOutputMarkupId(true));
            target.add(numberOfPages);
            target.add(documentNamePanel);
            mergeVisualizer.bratRenderLater(target);
          }
        }.add(
            new InputBehavior(new KeyType[] {KeyType.Shift, KeyType.Page_down}, EventType.click)));

    // Show the next page of this document
    add(
        new AjaxLink<Void>("showNext") {
          private static final long serialVersionUID = 7496156015186497496L;

          /**
           * Get the current beginning sentence address and add on it the size of the display window
           */
          @Override
          public void onClick(AjaxRequestTarget aTarget) {
            if (bModel.getDocument() != null) {
              JCas mergeJCas = null;
              try {
                aTarget.addChildren(getPage(), FeedbackPanel.class);
                mergeJCas = repository.readCorrectionCas(bModel.getDocument());
                int address =
                    getAddr(
                        selectSentenceAt(
                            mergeJCas,
                            bModel.getSentenceBeginOffset(),
                            bModel.getSentenceEndOffset()));
                int nextSentenceAddress =
                    getNextPageFirstSentenceAddress(
                        mergeJCas, address, bModel.getPreferences().getWindowSize());
                if (address != nextSentenceAddress) {
                  ubdateSentenceNumber(mergeJCas, nextSentenceAddress);

                  SuggestionBuilder builder =
                      new SuggestionBuilder(repository, annotationService, userRepository);
                  curationContainer = builder.buildCurationContainer(bModel);
                  setCurationSegmentBeginEnd();
                  curationContainer.setBratAnnotatorModel(bModel);
                  update(aTarget);
                  mergeVisualizer.bratRenderLater(aTarget);
                } else {
                  aTarget.appendJavaScript("alert('This is last page!')");
                }
              } catch (UIMAException e) {
                error(ExceptionUtils.getRootCause(e));
              } catch (ClassNotFoundException e) {
                error(e.getMessage());
              } catch (IOException e) {
                error(e.getMessage());
              } catch (BratAnnotationException e) {
                error(e.getMessage());
              }
            } else {
              aTarget.appendJavaScript("alert('Please open a document first!')");
            }
          }
        }.add(new InputBehavior(new KeyType[] {KeyType.Page_down}, EventType.click)));

    // SHow the previous page of this document
    add(
        new AjaxLink<Void>("showPrevious") {
          private static final long serialVersionUID = 7496156015186497496L;

          @Override
          public void onClick(AjaxRequestTarget aTarget) {
            if (bModel.getDocument() != null) {

              JCas mergeJCas = null;
              try {
                aTarget.addChildren(getPage(), FeedbackPanel.class);
                mergeJCas = repository.readCorrectionCas(bModel.getDocument());
                int previousSentenceAddress =
                    BratAjaxCasUtil.getPreviousDisplayWindowSentenceBeginAddress(
                        mergeJCas,
                        bModel.getSentenceAddress(),
                        bModel.getPreferences().getWindowSize());
                if (bModel.getSentenceAddress() != previousSentenceAddress) {
                  ubdateSentenceNumber(mergeJCas, previousSentenceAddress);

                  SuggestionBuilder builder =
                      new SuggestionBuilder(repository, annotationService, userRepository);

                  curationContainer = builder.buildCurationContainer(bModel);
                  setCurationSegmentBeginEnd();
                  curationContainer.setBratAnnotatorModel(bModel);
                  update(aTarget);
                  mergeVisualizer.bratRenderLater(aTarget);
                } else {
                  aTarget.appendJavaScript("alert('This is First Page!')");
                }
              } catch (UIMAException e) {
                error(ExceptionUtils.getRootCause(e));
              } catch (ClassNotFoundException e) {
                error(e.getMessage());
              } catch (IOException e) {;
                error(e.getMessage());
              } catch (BratAnnotationException e) {
                error(e.getMessage());
              }
            } else {
              aTarget.appendJavaScript("alert('Please open a document first!')");
            }
          }
        }.add(new InputBehavior(new KeyType[] {KeyType.Page_up}, EventType.click)));

    add(
        new AjaxLink<Void>("showFirst") {
          private static final long serialVersionUID = 7496156015186497496L;

          @Override
          public void onClick(AjaxRequestTarget aTarget) {
            if (bModel.getDocument() != null) {
              JCas mergeJCas = null;
              try {
                aTarget.addChildren(getPage(), FeedbackPanel.class);
                mergeJCas = repository.readCorrectionCas(bModel.getDocument());

                int address =
                    getAddr(
                        selectSentenceAt(
                            mergeJCas,
                            bModel.getSentenceBeginOffset(),
                            bModel.getSentenceEndOffset()));
                int firstAddress = getFirstSentenceAddress(mergeJCas);

                if (firstAddress != address) {
                  ubdateSentenceNumber(mergeJCas, firstAddress);

                  SuggestionBuilder builder =
                      new SuggestionBuilder(repository, annotationService, userRepository);
                  curationContainer = builder.buildCurationContainer(bModel);
                  setCurationSegmentBeginEnd();
                  curationContainer.setBratAnnotatorModel(bModel);
                  update(aTarget);
                  mergeVisualizer.bratRenderLater(aTarget);
                } else {
                  aTarget.appendJavaScript("alert('This is first page!')");
                }
              } catch (UIMAException e) {
                error(ExceptionUtils.getRootCause(e));
              } catch (ClassNotFoundException e) {
                error(e.getMessage());
              } catch (IOException e) {
                error(e.getMessage());
              } catch (BratAnnotationException e) {
                error(e.getMessage());
              }
            } else {
              aTarget.appendJavaScript("alert('Please open a document first!')");
            }
          }
        }.add(new InputBehavior(new KeyType[] {KeyType.Home}, EventType.click)));

    add(
        new AjaxLink<Void>("showLast") {
          private static final long serialVersionUID = 7496156015186497496L;

          @Override
          public void onClick(AjaxRequestTarget aTarget) {
            if (bModel.getDocument() != null) {
              JCas mergeJCas = null;
              try {
                aTarget.addChildren(getPage(), FeedbackPanel.class);
                mergeJCas = repository.readCorrectionCas(bModel.getDocument());
                int lastDisplayWindowBeginingSentenceAddress =
                    BratAjaxCasUtil.getLastDisplayWindowFirstSentenceAddress(
                        mergeJCas, bModel.getPreferences().getWindowSize());
                if (lastDisplayWindowBeginingSentenceAddress != bModel.getSentenceAddress()) {
                  ubdateSentenceNumber(mergeJCas, lastDisplayWindowBeginingSentenceAddress);

                  SuggestionBuilder builder =
                      new SuggestionBuilder(repository, annotationService, userRepository);
                  curationContainer = builder.buildCurationContainer(bModel);
                  setCurationSegmentBeginEnd();
                  curationContainer.setBratAnnotatorModel(bModel);
                  update(aTarget);
                  mergeVisualizer.bratRenderLater(aTarget);

                } else {
                  aTarget.appendJavaScript("alert('This is last Page!')");
                }
              } catch (UIMAException e) {
                error(ExceptionUtils.getRootCause(e));
              } catch (ClassNotFoundException e) {
                error(e.getMessage());
              } catch (IOException e) {
                error(e.getMessage());
              } catch (BratAnnotationException e) {
                error(e.getMessage());
              }
            } else {
              aTarget.appendJavaScript("alert('Please open a document first!')");
            }
          }
        }.add(new InputBehavior(new KeyType[] {KeyType.End}, EventType.click)));

    add(new GuidelineModalPanel("guidelineModalPanel", new Model<BratAnnotatorModel>(bModel)));
  }
Esempio n. 13
0
  private void loadDocumentAction()
      throws UIMAException, ClassNotFoundException, IOException, BratAnnotationException {
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    User logedInUser =
        userRepository.get(SecurityContextHolder.getContext().getAuthentication().getName());

    bModel.setUser(logedInUser);

    JCas jCas = null;
    try {
      AnnotationDocument logedInUserAnnotationDocument =
          repository.getAnnotationDocument(bModel.getDocument(), logedInUser);
      jCas = repository.readAnnotationCas(logedInUserAnnotationDocument);
    } catch (IOException e) {
      throw e;
    }
    // Get information to be populated to bratAnnotatorModel from the JCAS of the logged in user
    //
    catch (DataRetrievalFailureException e) {

      jCas = repository.readAnnotationCas(bModel.getDocument(), logedInUser);
      // This is the auto annotation, save it under CORRECTION_USER, Only if it is not created
      // by another annotater
      if (!repository.existsCorrectionCas(bModel.getDocument())) {
        repository.writeCorrectionCas(jCas, bModel.getDocument(), logedInUser);
      }
    } catch (NoResultException e) {
      jCas = repository.readAnnotationCas(bModel.getDocument(), logedInUser);
      // This is the auto annotation, save it under CORRECTION_USER, Only if it is not created
      // by another annotater
      if (!repository.existsCorrectionCas(bModel.getDocument())) {
        repository.writeCorrectionCas(jCas, bModel.getDocument(), logedInUser);
      }
    }

    // (Re)initialize brat model after potential creating / upgrading CAS
    bModel.initForDocument(jCas);

    // Load user preferences
    PreferencesUtil.setAnnotationPreference(
        username, repository, annotationService, bModel, Mode.AUTOMATION);

    // if project is changed, reset some project specific settings
    if (currentprojectId != bModel.getProject().getId()) {
      bModel.initForProject();
    }

    currentprojectId = bModel.getProject().getId();
    currentDocumentId = bModel.getDocument().getId();

    LOG.debug(
        "Configured BratAnnotatorModel for user ["
            + bModel.getUser()
            + "] f:["
            + bModel.getFirstSentenceAddress()
            + "] l:["
            + bModel.getLastSentenceAddress()
            + "] s:["
            + bModel.getSentenceAddress()
            + "]");
  }
Esempio n. 14
0
  public CurationContainer buildCurationContainer(BratAnnotatorModel aBModel)
      throws UIMAException, ClassNotFoundException, IOException, BratAnnotationException {
    CurationContainer curationContainer = new CurationContainer();
    // initialize Variables
    SourceDocument sourceDocument = aBModel.getDocument();
    Map<Integer, Integer> segmentBeginEnd = new HashMap<Integer, Integer>();
    Map<Integer, Integer> segmentNumber = new HashMap<Integer, Integer>();
    Map<String, Map<Integer, Integer>> segmentAdress = new HashMap<String, Map<Integer, Integer>>();
    // get annotation documents

    List<AnnotationDocument> finishedAnnotationDocuments = new ArrayList<AnnotationDocument>();

    for (AnnotationDocument annotationDocument :
        repository.listAnnotationDocuments(aBModel.getDocument())) {
      if (annotationDocument.getState().equals(AnnotationDocumentState.FINISHED)) {
        finishedAnnotationDocuments.add(annotationDocument);
      }
    }

    Map<String, JCas> jCases = new HashMap<String, JCas>();

    AnnotationDocument randomAnnotationDocument = null;
    JCas mergeJCas;

    // get the correction/automation JCas for the logged in user
    if (aBModel.getMode().equals(Mode.AUTOMATION) || aBModel.getMode().equals(Mode.CORRECTION)) {
      jCases = listJcasesforCorrection(randomAnnotationDocument, sourceDocument, aBModel.getMode());
      mergeJCas = getMergeCas(aBModel, sourceDocument, jCases, randomAnnotationDocument);
      String username = jCases.keySet().iterator().next();
      updateSegment(
          aBModel,
          segmentBeginEnd,
          segmentNumber,
          segmentAdress,
          jCases.get(username),
          username,
          aBModel.getPreferences().getWindowSize());

    } else {

      jCases =
          listJcasesforCuration(
              finishedAnnotationDocuments, randomAnnotationDocument, aBModel.getMode());
      mergeJCas = getMergeCas(aBModel, sourceDocument, jCases, randomAnnotationDocument);
      updateSegment(
          aBModel,
          segmentBeginEnd,
          segmentNumber,
          segmentAdress,
          mergeJCas,
          CurationPanel.CURATION_USER,
          aBModel.getPreferences().getCurationWindowSize());
    }

    List<Type> entryTypes = null;

    segmentAdress.put(CurationPanel.CURATION_USER, new HashMap<Integer, Integer>());
    for (Sentence sentence : selectCovered(mergeJCas, Sentence.class, begin, end)) {
      segmentAdress.get(CurationPanel.CURATION_USER).put(sentence.getBegin(), getAddr(sentence));
    }

    if (entryTypes == null) {
      entryTypes = getEntryTypes(mergeJCas, aBModel.getAnnotationLayers(), annotationService);
    }

    // for cross-sentences annotation, update the end of the segment
    if (firstload) {
      updateCrossSentAnnoList(segmentBeginEnd, jCases, entryTypes);
      firstload = false;
    }

    for (Integer begin : segmentBeginEnd.keySet()) {
      Integer end = segmentBeginEnd.get(begin);

      DiffResult diff =
          CasDiff2.doDiffSingle(
              annotationService, aBModel.getProject(), entryTypes, jCases, begin, end);
      SourceListView curationSegment = new SourceListView();
      curationSegment.setBegin(begin);
      curationSegment.setEnd(end);
      if (diff.hasDifferences() || !diff.getIncompleteConfigurationSets().isEmpty()) {
        curationSegment.setSentenceState(SentenceState.DISAGREE);
      } else {
        curationSegment.setSentenceState(SentenceState.AGREE);
      }
      curationSegment.setSentenceNumber(segmentNumber.get(begin));

      for (String username : segmentAdress.keySet()) {
        curationSegment.getSentenceAddress().put(username, segmentAdress.get(username).get(begin));
      }
      curationContainer.getCurationViewByBegin().put(begin, curationSegment);
    }
    return curationContainer;
  }
Esempio n. 15
0
  /**
   * Add annotations from the CAS, which is controlled by the window size, to the brat response
   * {@link GetDocumentResponse}
   *
   * @param aJcas The JCAS object containing annotations
   * @param aResponse A brat response containing annotations in brat protocol
   * @param aBratAnnotatorModel Data model for brat annotations
   * @param aColoringStrategy the coloring strategy to render this layer (ignored)
   */
  @Override
  public void render(
      JCas aJcas,
      List<AnnotationFeature> aFeatures,
      GetDocumentResponse aResponse,
      BratAnnotatorModel aBratAnnotatorModel,
      ColoringStrategy aColoringStrategy) {
    // Get begin and end offsets of window content
    int windowBegin =
        BratAjaxCasUtil.selectByAddr(
                aJcas, Sentence.class, aBratAnnotatorModel.getSentenceAddress())
            .getBegin();
    int windowEnd =
        BratAjaxCasUtil.selectByAddr(
                aJcas,
                Sentence.class,
                BratAjaxCasUtil.getLastSentenceAddressInDisplayWindow(
                    aJcas,
                    aBratAnnotatorModel.getSentenceAddress(),
                    aBratAnnotatorModel.getPreferences().getWindowSize()))
            .getEnd();

    // Find the features for the arc and span labels - it is possible that we do not find a
    // feature for arc/span labels because they may have been disabled.
    AnnotationFeature spanLabelFeature = null;
    AnnotationFeature arcLabelFeature = null;
    for (AnnotationFeature f : aFeatures) {
      if (WebAnnoConst.COREFERENCE_TYPE_FEATURE.equals(f.getName())) {
        spanLabelFeature = f;
      }
      if (WebAnnoConst.COREFERENCE_RELATION_FEATURE.equals(f.getName())) {
        arcLabelFeature = f;
      }
    }
    // At this point arc and span feature labels must have been found! If not, the later code
    // will crash.

    Type chainType = getAnnotationType(aJcas.getCas());
    Feature chainFirst = chainType.getFeatureByBaseName(chainFirstFeatureName);

    int colorIndex = 0;
    // Iterate over the chains
    for (FeatureStructure chainFs : selectFS(aJcas.getCas(), chainType)) {
      AnnotationFS linkFs = (AnnotationFS) chainFs.getFeatureValue(chainFirst);
      AnnotationFS prevLinkFs = null;

      // Every chain is supposed to have a different color
      String color =
          ColoringStrategy.PALETTE_NORMAL_FILTERED[
              colorIndex % ColoringStrategy.PALETTE_NORMAL_FILTERED.length];
      // The color index is updated even for chains that have no visible links in the current
      // window because we would like the chain color to be independent of visibility. In
      // particular the color of a chain should not change when switching pages/scrolling.
      colorIndex++;

      // Iterate over the links of the chain
      while (linkFs != null) {
        Feature linkNext = linkFs.getType().getFeatureByBaseName(linkNextFeatureName);
        AnnotationFS nextLinkFs = (AnnotationFS) linkFs.getFeatureValue(linkNext);

        // Is link after window? If yes, we can skip the rest of the chain
        if (linkFs.getBegin() >= windowEnd) {
          break; // Go to next chain
        }

        // Is link before window? We only need links that being within the window and that
        // end within the window
        if (!(linkFs.getBegin() >= windowBegin) && (linkFs.getEnd() <= windowEnd)) {
          // prevLinkFs remains null until we enter the window
          linkFs = nextLinkFs;
          continue; // Go to next link
        }

        String bratTypeName = TypeUtil.getBratTypeName(this);

        // Render span
        {
          String bratLabelText =
              TypeUtil.getBratLabelText(
                  this,
                  linkFs,
                  (spanLabelFeature != null) ? asList(spanLabelFeature) : Collections.EMPTY_LIST);
          Offsets offsets =
              new Offsets(linkFs.getBegin() - windowBegin, linkFs.getEnd() - windowBegin);

          aResponse.addEntity(
              new Entity(
                  BratAjaxCasUtil.getAddr(linkFs), bratTypeName, offsets, bratLabelText, color));
        }

        // Render arc (we do this on prevLinkFs because then we easily know that the current
        // and last link are within the window ;)
        if (prevLinkFs != null) {
          String bratLabelText = null;

          if (linkedListBehavior && arcLabelFeature != null) {
            // Render arc label
            bratLabelText = TypeUtil.getBratLabelText(this, prevLinkFs, asList(arcLabelFeature));
          } else {
            // Render only chain type
            bratLabelText = TypeUtil.getBratLabelText(this, prevLinkFs, Collections.EMPTY_LIST);
          }

          List<Argument> argumentList =
              asList(
                  new Argument("Arg1", BratAjaxCasUtil.getAddr(prevLinkFs)),
                  new Argument("Arg2", BratAjaxCasUtil.getAddr(linkFs)));

          aResponse.addRelation(
              new Relation(
                  BratAjaxCasUtil.getAddr(prevLinkFs),
                  bratTypeName,
                  argumentList,
                  bratLabelText,
                  color));
        }

        //                if (BratAjaxCasUtil.isSame(linkFs, nextLinkFs)) {
        //                    log.error("Loop in CAS detected, aborting rendering of chains");
        //                    break;
        //                }

        prevLinkFs = linkFs;
        linkFs = nextLinkFs;
      }
    }
  }
Esempio n. 16
0
  private void updateCurationView(
      final CurationContainer curationContainer,
      final SourceListView curationViewItem,
      AjaxRequestTarget aTarget,
      JCas jCas) {
    int currentSentAddress =
        BratAjaxCasUtil.getCurrentSentence(
                jCas, curationViewItem.getBegin(), curationViewItem.getEnd())
            .getAddress();
    bModel.setSentenceAddress(
        BratAjaxCasUtil.getSentenceBeginAddress(
            jCas,
            currentSentAddress,
            curationViewItem.getBegin(),
            bModel.getProject(),
            bModel.getDocument(),
            bModel.getPreferences().getWindowSize()));

    Sentence sentence = selectByAddr(jCas, Sentence.class, bModel.getSentenceAddress());
    bModel.setSentenceBeginOffset(sentence.getBegin());
    bModel.setSentenceEndOffset(sentence.getEnd());

    Sentence firstSentence =
        selectSentenceAt(jCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset());
    int lastAddressInPage =
        getLastSentenceAddressInDisplayWindow(
            jCas, getAddr(firstSentence), bModel.getPreferences().getWindowSize());
    // the last sentence address in the display window
    Sentence lastSentenceInPage =
        (Sentence) selectByAddr(jCas, FeatureStructure.class, lastAddressInPage);
    bModel.setFSN(BratAjaxCasUtil.getSentenceNumber(jCas, firstSentence.getBegin()));
    bModel.setLSN(BratAjaxCasUtil.getSentenceNumber(jCas, lastSentenceInPage.getBegin()));

    curationContainer.setBratAnnotatorModel(bModel);
    onChange(aTarget);
  }