Example usage for org.apache.wicket.ajax AjaxRequestTarget addChildren

List of usage examples for org.apache.wicket.ajax AjaxRequestTarget addChildren

Introduction

In this page you can find the example usage for org.apache.wicket.ajax AjaxRequestTarget addChildren.

Prototype

void addChildren(MarkupContainer parent, Class<?> childCriteria);

Source Link

Document

Visits all children of the specified parent container and adds them to the target if they are of same type as childCriteria

Usage

From source file:de.tudarmstadt.ukp.clarin.webanno.brat.annotation.component.AnnotationDetailEditorPanel.java

License:Apache License

public void actionAnnotate(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel, JCas jCas,
        boolean aIsForwarded)
        throws UIMAException, ClassNotFoundException, IOException, BratAnnotationException {
    if (aBModel.getSelectedAnnotationLayer() == null) {
        error("No layer is selected. First select a layer.");
        aTarget.addChildren(getPage(), FeedbackPanel.class);
        return;//from w  ww.java  2s  .c o m
    }

    if (aBModel.getSelectedAnnotationLayer().isReadonly()) {
        error("Layer is not editable.");
        aTarget.addChildren(getPage(), FeedbackPanel.class);
        return;
    }

    // Verify if input is valid according to tagset
    for (int i = 0; i < featureModels.size(); i++) {
        AnnotationFeature feature = featureModels.get(i).feature;
        if (CAS.TYPE_NAME_STRING.equals(feature.getType())) {
            String value = (String) featureModels.get(i).value;
            // Check if tag is necessary, set, and correct
            if (feature.getTagset() != null && !feature.getTagset().isCreateTag()
                    && !annotationService.existsTag(value, feature.getTagset())) {
                error("[" + value + "] is not in the tag list. Please choose form the existing tags");
                return;
            }
        }
    }

    TypeAdapter adapter = getAdapter(annotationService, aBModel.getSelectedAnnotationLayer());
    Selection selection = aBModel.getSelection();
    if (selection.getAnnotation().isNotSet()) {
        if (bModel.getSelection().isRelationAnno()) {
            AnnotationFS originFs = selectByAddr(jCas, selection.getOrigin());
            AnnotationFS targetFs = selectByAddr(jCas, selection.getTarget());
            if (adapter instanceof ArcAdapter) {
                Sentence sentence = selectSentenceAt(jCas, bModel.getSentenceBeginOffset(),
                        bModel.getSentenceEndOffset());
                int start = sentence.getBegin();
                int end = selectByAddr(jCas, Sentence.class, getLastSentenceAddressInDisplayWindow(jCas,
                        getAddr(sentence), bModel.getPreferences().getWindowSize())).getEnd();

                AnnotationFS arc = ((ArcAdapter) adapter).add(originFs, targetFs, jCas, start, end, null, null);
                selection.setAnnotation(new VID(getAddr(arc)));
            } else {
                selection.setAnnotation(
                        new VID(((ChainAdapter) adapter).addArc(jCas, originFs, targetFs, null, null)));
            }
            selection.setBegin(originFs.getBegin());
        } else if (adapter instanceof SpanAdapter) {
            for (FeatureModel fm : featureModels) {
                if (((SpanAdapter) adapter).getSpan(jCas, selection.getBegin(), selection.getEnd(), fm.feature,
                        null) != null) {
                    actionClear(aTarget, bModel);
                    throw new BratAnnotationException("Cannot create another annotation of layer [" + ""
                            + bModel.getSelectedAnnotationLayer().getUiName() + " at this"
                            + " location - stacking is not enabled for this layer.");
                }
            }
            selection.setAnnotation(new VID(
                    ((SpanAdapter) adapter).add(jCas, selection.getBegin(), selection.getEnd(), null, null)));
        } else {
            for (FeatureModel fm : featureModels) {
                if (((ChainAdapter) adapter).getSpan(jCas, selection.getBegin(), selection.getEnd(), fm.feature,
                        null) != null) {
                    actionClear(aTarget, bModel);
                    throw new BratAnnotationException("Cannot create another annotation of layer [" + ""
                            + bModel.getSelectedAnnotationLayer().getUiName() + " at this"
                            + " location - stacking is not enabled for this layer.");
                }
            }
            selection.setAnnotation(new VID(((ChainAdapter) adapter).addSpan(jCas, selection.getBegin(),
                    selection.getEnd(), null, null)));
        }
    }

    // Set feature values
    List<AnnotationFeature> features = new ArrayList<AnnotationFeature>();
    for (FeatureModel fm : featureModels) {
        features.add(fm.feature);

        // For string features with extensible tagsets, extend the tagset
        if (CAS.TYPE_NAME_STRING.equals(fm.feature.getType())) {
            String value = (String) fm.value;

            if (fm.feature.getTagset() != null && fm.feature.getTagset().isCreateTag()
                    && !annotationService.existsTag(value, fm.feature.getTagset())) {
                // Persist only if the feature value is actually set
                if (value != null) {
                    Tag selectedTag = new Tag();
                    selectedTag.setName(value);
                    selectedTag.setTagSet(fm.feature.getTagset());
                    annotationService.createTag(selectedTag, aBModel.getUser());
                }
            }
        }
        adapter.updateFeature(jCas, fm.feature, aBModel.getSelection().getAnnotation().getId(), fm.value);
    }

    // Update progress information
    int sentenceNumber = getSentenceNumber(jCas, aBModel.getSelection().getBegin());
    aBModel.setSentenceNumber(sentenceNumber);
    aBModel.getDocument().setSentenceAccessed(sentenceNumber);

    // persist changes
    repository.writeCas(aBModel.getMode(), aBModel.getDocument(), aBModel.getUser(), jCas);

    if (aBModel.getPreferences().isScrollPage()) {
        autoScroll(jCas, aBModel);
    }

    if (bModel.getSelection().isRelationAnno()) {
        aBModel.setRememberedArcLayer(aBModel.getSelectedAnnotationLayer());
        aBModel.setRememberedArcFeatures(featureModels);
    } else {
        aBModel.setRememberedSpanLayer(aBModel.getSelectedAnnotationLayer());
        aBModel.setRememberedSpanFeatures(featureModels);
    }

    aBModel.getSelection().setAnnotate(true);
    if (aBModel.getSelection().getAnnotation().isSet()) {
        String bratLabelText = TypeUtil.getBratLabelText(adapter,
                selectByAddr(jCas, aBModel.getSelection().getAnnotation().getId()), features);
        info(generateMessage(aBModel.getSelectedAnnotationLayer(), bratLabelText, false));
    }

    if (aBModel.isForwardAnnotation() && !aIsForwarded && featureModels.get(0).value != null) {
        onAutoForward(aTarget, aBModel);
    }
    onAnnotate(aTarget, aBModel, selection.getBegin(), selection.getEnd());
    onChange(aTarget, aBModel);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.brat.curation.component.CurationPanel.java

License:Apache License

public CurationPanel(String id, final IModel<CurationContainer> cCModel) {
    super(id, cCModel);
    // add container for list of sentences panel
    sentencesListView = new WebMarkupContainer("sentencesListView");
    sentencesListView.setOutputMarkupId(true);
    add(sentencesListView);// w  w  w.jav  a 2s.c o m

    // add container for the list of sentences where annotations exists crossing multiple
    // sentences
    // outside of the current page
    corssSentAnnoView = new WebMarkupContainer("corssSentAnnoView");
    corssSentAnnoView.setOutputMarkupId(true);
    add(corssSentAnnoView);

    bModel = getModelObject().getBratAnnotatorModel();

    LinkedList<CurationUserSegmentForAnnotationDocument> sentences = new LinkedList<CurationUserSegmentForAnnotationDocument>();
    CurationUserSegmentForAnnotationDocument curationUserSegmentForAnnotationDocument = new CurationUserSegmentForAnnotationDocument();
    if (bModel != null) {
        curationUserSegmentForAnnotationDocument
                .setAnnotationSelectionByUsernameAndAddress(annotationSelectionByUsernameAndAddress);
        curationUserSegmentForAnnotationDocument.setBratAnnotatorModel(bModel);
        sentences.add(curationUserSegmentForAnnotationDocument);
    }
    // update source list model only first time.
    sourceListModel = sourceListModel == null ? getModelObject().getCurationViews() : sourceListModel;

    suggestionViewPanel = new SuggestionViewPanel("suggestionViewPanel",
            new Model<LinkedList<CurationUserSegmentForAnnotationDocument>>(sentences)) {
        private static final long serialVersionUID = 2583509126979792202L;
        CurationContainer curationContainer = cCModel.getObject();

        @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);
                updatePanel(aTarget, curationContainer);
            } 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());
            }
        }
    };

    suggestionViewPanel.setOutputMarkupId(true);
    add(suggestionViewPanel);

    editor = 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);
            annotate = true;

            annotator.onChange(aTarget, aBModel);
        }

        @Override
        protected void onAutoForward(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) {
            try {
                annotator.autoForward(aTarget, getCas(aBModel));
            } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) {
                LOG.info("Error reading CAS " + e.getMessage());
                error("Error reading CAS " + e.getMessage());
                return;
            }
        }

        @Override
        protected void onConfigure() {
            super.onConfigure();
            setEnabled(bModel.getDocument() != null && !repository
                    .getSourceDocument(bModel.getDocument().getProject(), bModel.getDocument().getName())
                    .getState().equals(SourceDocumentState.CURATION_FINISHED));
        }
    };

    editor.setOutputMarkupId(true);
    add(editor);

    annotator = new BratAnnotator("mergeView", new Model<BratAnnotatorModel>(bModel), editor) {

        private static final long serialVersionUID = 7279648231521710155L;

        @Override
        public void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel bratAnnotatorModel) {
            aTarget.addChildren(getPage(), FeedbackPanel.class);
            try {
                updatePanel(aTarget, cCModel.getObject());
            } 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());
            }
        }
    };
    // reset sentenceAddress and lastSentenceAddress to the orginal once

    annotator.setOutputMarkupId(true);
    add(annotator);

    LoadableDetachableModel sentenceDiffModel = new LoadableDetachableModel() {

        @Override
        protected Object load() {
            int fSN = bModel.getFSN();
            int lSN = bModel.getLSN();

            List<String> crossSentAnnos = new ArrayList<>();
            if (SuggestionBuilder.crossSentenceLists != null) {
                for (int sn : SuggestionBuilder.crossSentenceLists.keySet()) {
                    if (sn >= fSN && sn <= lSN) {
                        List<Integer> cr = new ArrayList<>();
                        for (int c : SuggestionBuilder.crossSentenceLists.get(sn)) {
                            if (c < fSN || c > lSN) {
                                cr.add(c);
                            }
                        }
                        if (!cr.isEmpty()) {
                            crossSentAnnos.add(sn + "-->" + cr);
                        }
                    }
                }
            }

            return crossSentAnnos;
        }
    };

    crossSentAnnoList = new ListView<String>("crossSentAnnoList", sentenceDiffModel) {
        private static final long serialVersionUID = 8539162089561432091L;

        @Override
        protected void populateItem(ListItem<String> item) {
            String crossSentAnno = item.getModelObject();

            // ajax call when clicking on a sentence on the left side
            final AbstractDefaultAjaxBehavior click = new AbstractDefaultAjaxBehavior() {
                private static final long serialVersionUID = 5803814168152098822L;

                @Override
                protected void respond(AjaxRequestTarget aTarget) {
                    // Expand curation view
                }

            };

            // add subcomponents to the component
            item.add(click);
            Label crossSentAnnoItem = new AjaxLabel("crossAnnoSent", crossSentAnno, click);
            item.add(crossSentAnnoItem);
        }

    };
    crossSentAnnoList.setOutputMarkupId(true);
    corssSentAnnoView.add(crossSentAnnoList);

    LoadableDetachableModel sentencesListModel = new LoadableDetachableModel() {

        @Override
        protected Object load() {

            return getModelObject().getCurationViews();
        }
    };

    sentenceList = new ListView<SourceListView>("sentencesList", sentencesListModel) {
        private static final long serialVersionUID = 8539162089561432091L;

        @Override
        protected void populateItem(ListItem<SourceListView> item) {
            final SourceListView curationViewItem = item.getModelObject();

            // ajax call when clicking on a sentence on the left side
            final AbstractDefaultAjaxBehavior click = new AbstractDefaultAjaxBehavior() {
                private static final long serialVersionUID = 5803814168152098822L;

                @Override
                protected void respond(AjaxRequestTarget aTarget) {
                    curationView = curationViewItem;
                    fSn = 0;
                    try {
                        JCas jCas = repository.readCurationCas(bModel.getDocument());
                        updateCurationView(cCModel.getObject(), curationViewItem, aTarget, jCas);
                        updatePanel(aTarget, cCModel.getObject());
                        bModel.setSentenceNumber(curationViewItem.getSentenceNumber());

                    } 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());
                    }
                }

            };

            // add subcomponents to the component
            item.add(click);

            String cC = curationViewItem.getSentenceState().getValue();
            // mark current sentence in orange if disagree
            if (curationViewItem.getSentenceNumber() == bModel.getSentenceNumber()) {
                if (cC != null) {
                    item.add(AttributeModifier.append("class", "current-disagree"));
                }
            } else if (cC != null) {
                // disagree in range
                if (curationViewItem.getSentenceNumber() >= fSn
                        && curationViewItem.getSentenceNumber() <= lSn) {
                    item.add(AttributeModifier.append("class", "range-disagree"));
                } else {
                    item.add(AttributeModifier.append("class", "disagree"));
                }
            }
            // agree and in range
            else if (curationViewItem.getSentenceNumber() >= fSn
                    && curationViewItem.getSentenceNumber() <= lSn) {
                item.add(AttributeModifier.append("class", "range-agree"));
            } else {
                item.add(AttributeModifier.append("class", "agree"));
            }
            Label sentenceNumber = new AjaxLabel("sentenceNumber",
                    curationViewItem.getSentenceNumber().toString(), click);
            item.add(sentenceNumber);
        }
    };
    // add subcomponents to the component
    sentenceList.setOutputMarkupId(true);
    sentencesListView.add(sentenceList);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.brat.curation.component.model.BratSuggestionVisualizer.java

License:Apache License

public BratSuggestionVisualizer(String id, IModel<CurationUserSegmentForAnnotationDocument> aModel) {
    super(id, aModel);
    String username;/*from w ww.j a  v  a 2  s  . c o  m*/
    if (getModelObject().getBratAnnotatorModel().getMode().equals(Mode.AUTOMATION)
            || getModelObject().getBratAnnotatorModel().getMode().equals(Mode.CORRECTION)) {
        username = "Suggestion";
    } else {
        username = getModelObject().getUsername();
    }
    Label label = new Label("username", username);
    add(label);
    controller = new AbstractDefaultAjaxBehavior() {
        private static final long serialVersionUID = 1133593826878553307L;

        @Override
        protected void respond(AjaxRequestTarget aTarget) {
            try {
                onSelectAnnotationForMerge(aTarget);
            } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) {
                aTarget.addChildren(getPage(), FeedbackPanel.class);
                error(e.getMessage());
            }
        }

    };
    add(controller);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.monitoring.page.MonitoringPage.java

License:Apache License

private void updateAgreementTable(AjaxRequestTarget aTarget, boolean aClearCache) {
    try {//from  w  ww .  java2  s  . c o  m
        if (aClearCache) {
            cachedCASes = null;
        }
        agreementForm.agreementTable2.getDefaultModel().detach();
        if (aTarget != null) {
            aTarget.add(agreementForm.agreementTable2);
        }
    } catch (Throwable e) {
        error(ExceptionUtils.getRootCauseMessage(e));
        if (aTarget != null) {
            aTarget.addChildren(getPage(), FeedbackPanel.class);
        }
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.AnnotationPage.java

License:Apache License

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

        @Override/*from w  w w.j  av a  2  s  .  co m*/
        protected void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) {
            aTarget.addChildren(getPage(), FeedbackPanel.class);

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

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

            annotator.onChange(aTarget, aBModel);
        }

        @Override
        protected void onAutoForward(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) {
            try {
                annotator.autoForward(aTarget, getCas(aBModel));
            } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) {
                LOG.info("Error reading CAS " + e.getMessage());
                error("Error reading CAS " + e.getMessage());
                return;
            }
        }
    };

    editor.setOutputMarkupId(true);
    add(editor);

    annotator = new BratAnnotator("embedder1", new Model<BratAnnotatorModel>(bModel), editor) {

        private static final long serialVersionUID = 7279648231521710155L;

        @Override
        public void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBratAnnotatorModel) {
            bModel = aBratAnnotatorModel;
            aTarget.add(numberOfPages);
        }

        @Override
        public void renderHead(IHeaderResponse aResponse) {
            super.renderHead(aResponse);

            // If the page is reloaded in the browser and a document was already open, we need
            // to render it. We use the "later" commands here to avoid polluting the Javascript
            // header items with document data and because loading times are not that critical
            // on a reload.
            if (getModelObject().getProject() != null) {
                // We want to trigger a late rendering only on a page reload, but not on a
                // Ajax request.
                if (!aResponse.getResponse().getClass().getName().endsWith("AjaxResponse")) {
                    aResponse.render(OnLoadHeaderItem.forScript(bratInitLaterCommand()));
                    aResponse.render(OnLoadHeaderItem.forScript(bratRenderLaterCommand()));
                }
            }
        }
    };

    // This is an Annotation Operation, set model to ANNOTATION mode
    bModel.setMode(Mode.ANNOTATION);
    add(annotator);

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

    numberOfPages = new Label("numberOfPages", new Model<String>());
    numberOfPages.setOutputMarkupId(true);
    add(numberOfPages);

    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");
    openDocumentsModal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() {
        private static final long serialVersionUID = -5423095433535634321L;

        @Override
        public boolean onCloseButtonClicked(AjaxRequestTarget aTarget) {
            closeButtonClicked = true;
            return true;
        }
    });

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

        @Override
        public void onClick(AjaxRequestTarget aTarget) {
            editor.reset(aTarget);
            closeButtonClicked = false;
            openDocumentsModal.setContent(new OpenModalWindowPanel(openDocumentsModal.getContentId(), bModel,
                    openDocumentsModal, Mode.ANNOTATION) {

                private static final long serialVersionUID = -3434069761864809703L;

                @Override
                protected void onCancel(AjaxRequestTarget aTarget) {
                    closeButtonClicked = true;
                };
            });
            openDocumentsModal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
                private static final long serialVersionUID = -1746088901018629567L;

                @Override
                public void onClose(AjaxRequestTarget target) {
                    // A hack, the dialog opens for the first time, and if no document is
                    // selected window will be "blind down". Something in the brat js causes
                    // this!
                    if (bModel.getProject() == null || bModel.getDocument() == null) {
                        setResponsePage(WelcomePage.class);
                    }

                    // Dialog was cancelled rather that a document was selected.
                    if (closeButtonClicked) {
                        return;
                    }

                    loadDocumentAction(target);
                    String username = SecurityContextHolder.getContext().getAuthentication().getName();
                    User user = userRepository.get(username);
                    editor.setEnabled(
                            !FinishImage.isFinished(new Model<BratAnnotatorModel>(bModel), user, repository));

                }
            });
            // target.appendJavaScript("Wicket.Window.unloadConfirmation = false;");
            openDocumentsModal.show(aTarget);
        }
    });

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

        @Override
        protected void onChange(AjaxRequestTarget aTarget) {

            try {
                JCas jCas = getJCas();
                annotator.bratRender(aTarget, jCas);
                updateSentenceAddress(jCas, aTarget);
            } catch (UIMAException | ClassNotFoundException | IOException e) {
                LOG.info("Error reading CAS " + e.getMessage());
                error("Error reading CAS " + e.getMessage());
                return;
            }

        }
    });

    add(new ExportModalPanel("exportModalPanel", new Model<BratAnnotatorModel>(bModel)));
    // 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 aTarget) {
            editor.reset(aTarget);
            // 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);
                }
            }

            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) {
                aTarget.appendJavaScript("alert('This is the first document!')");
                return;
            }
            bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex - 1).getName());
            bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex - 1));

            loadDocumentAction(aTarget);
        }
    }.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 aTarget) {
            editor.reset(aTarget);
            // 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);
                }
            }

            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) {
                aTarget.appendJavaScript("alert('This is the last document!')");
                return;
            }
            bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex + 1).getName());
            bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex + 1));

            loadDocumentAction(aTarget);
        }
    }.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) {
            try {
                if (bModel.getDocument() != null) {
                    JCas jCas = getJCas();
                    int nextSentenceAddress = BratAjaxCasUtil.getNextPageFirstSentenceAddress(jCas,
                            bModel.getSentenceAddress(), bModel.getPreferences().getWindowSize());
                    if (bModel.getSentenceAddress() != nextSentenceAddress) {

                        updateSentenceNumber(jCas, nextSentenceAddress);

                        aTarget.addChildren(getPage(), FeedbackPanel.class);
                        annotator.bratRenderLater(aTarget);
                        gotoPageTextField.setModelObject(
                                BratAjaxCasUtil.getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1);
                        updateSentenceAddress(jCas, aTarget);
                    }

                    else {
                        aTarget.appendJavaScript("alert('This is last page!')");
                    }
                } else {
                    aTarget.appendJavaScript("alert('Please open a document first!')");
                }
            } catch (Exception e) {
                error(e.getMessage());
                aTarget.addChildren(getPage(), FeedbackPanel.class);
            }
        }
    }.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) {
            try {
                if (bModel.getDocument() != null) {

                    JCas jCas = getJCas();

                    int previousSentenceAddress = BratAjaxCasUtil.getPreviousDisplayWindowSentenceBeginAddress(
                            jCas, bModel.getSentenceAddress(), bModel.getPreferences().getWindowSize());
                    if (bModel.getSentenceAddress() != previousSentenceAddress) {

                        updateSentenceNumber(jCas, previousSentenceAddress);

                        aTarget.addChildren(getPage(), FeedbackPanel.class);
                        annotator.bratRenderLater(aTarget);
                        gotoPageTextField.setModelObject(
                                BratAjaxCasUtil.getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1);
                        updateSentenceAddress(jCas, aTarget);
                    } else {
                        aTarget.appendJavaScript("alert('This is First Page!')");
                    }
                } else {
                    aTarget.appendJavaScript("alert('Please open a document first!')");
                }
            } catch (Exception e) {
                error(e.getMessage());
                aTarget.addChildren(getPage(), FeedbackPanel.class);
            }
        }
    }.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) {
            try {
                if (bModel.getDocument() != null) {

                    JCas jCas = getJCas();

                    if (bModel.getFirstSentenceAddress() != bModel.getSentenceAddress()) {

                        updateSentenceNumber(jCas, bModel.getFirstSentenceAddress());

                        aTarget.addChildren(getPage(), FeedbackPanel.class);
                        annotator.bratRenderLater(aTarget);
                        gotoPageTextField.setModelObject(
                                BratAjaxCasUtil.getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1);
                        updateSentenceAddress(jCas, aTarget);
                    } else {
                        aTarget.appendJavaScript("alert('This is first page!')");
                    }
                } else {
                    aTarget.appendJavaScript("alert('Please open a document first!')");
                }
            } catch (Exception e) {
                error(e.getMessage());
                aTarget.addChildren(getPage(), FeedbackPanel.class);
            }
        }
    }.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) {
            try {
                if (bModel.getDocument() != null) {

                    JCas jCas = getJCas();

                    int lastDisplayWindowBeginingSentenceAddress = BratAjaxCasUtil
                            .getLastDisplayWindowFirstSentenceAddress(jCas,
                                    bModel.getPreferences().getWindowSize());
                    if (lastDisplayWindowBeginingSentenceAddress != bModel.getSentenceAddress()) {

                        updateSentenceNumber(jCas, lastDisplayWindowBeginingSentenceAddress);

                        aTarget.addChildren(getPage(), FeedbackPanel.class);
                        annotator.bratRenderLater(aTarget);
                        gotoPageTextField.setModelObject(
                                BratAjaxCasUtil.getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1);
                        updateSentenceAddress(jCas, aTarget);
                    } else {
                        aTarget.appendJavaScript("alert('This is last Page!')");
                    }
                } else {
                    aTarget.appendJavaScript("alert('Please open a document first!')");
                }
            } catch (Exception e) {
                error(e.getMessage());
                aTarget.addChildren(getPage(), FeedbackPanel.class);
            }
        }
    }.add(new InputBehavior(new KeyType[] { KeyType.End }, EventType.click)));

    add(new AjaxLink<Void>("toggleScriptDirection") {
        private static final long serialVersionUID = -4332566542278611728L;

        @Override
        public void onClick(AjaxRequestTarget aTarget) {
            if (ScriptDirection.LTR.equals(bModel.getScriptDirection())) {
                bModel.setScriptDirection(ScriptDirection.RTL);
            } else {
                bModel.setScriptDirection(ScriptDirection.LTR);
            }
            annotator.bratRenderLater(aTarget);
        }
    });
    add(new GuidelineModalPanel("guidelineModalPanel", 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) {
            try {
                if (gotoPageAddress == 0) {
                    aTarget.appendJavaScript("alert('The sentence number entered is not valid')");
                    return;
                }
                if (bModel.getSentenceAddress() != gotoPageAddress) {
                    JCas jCas = getJCas();

                    updateSentenceNumber(jCas, gotoPageAddress);

                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    annotator.bratRenderLater(aTarget);
                    aTarget.add(numberOfPages);
                    gotoPageTextField.setModelObject(
                            BratAjaxCasUtil.getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1);
                    aTarget.add(gotoPageTextField);
                }
            } catch (Exception e) {
                error(e.getMessage());
                aTarget.addChildren(getPage(), FeedbackPanel.class);
            }
        }
    });
    gotoPageTextField.setType(Integer.class);
    gotoPageTextField.setMinimum(1);
    gotoPageTextField.setDefaultModelObject(1);
    add(gotoPageTextFieldForm.add(gotoPageTextField));

    gotoPageTextField.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        private static final long serialVersionUID = 56637289242712170L;

        @Override
        protected void onUpdate(AjaxRequestTarget aTarget) {
            try {
                if (gotoPageTextField.getModelObject() < 1) {
                    aTarget.appendJavaScript("alert('Page number shouldn't be less than 1')");
                } else {
                    updateSentenceAddress(getJCas(), aTarget);
                }
            } catch (Exception e) {
                error(e.getMessage());
                aTarget.addChildren(getPage(), FeedbackPanel.class);
            }
        }
    });

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

        @Override
        public void onClick(AjaxRequestTarget aTarget) {
            try {
                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;
                }
                if (bModel.getSentenceAddress() != gotoPageAddress) {
                    JCas jCas = getJCas();
                    updateSentenceNumber(jCas, gotoPageAddress);
                    updateSentenceAddress(jCas, aTarget);
                    annotator.bratRenderLater(aTarget);
                }
            } catch (Exception e) {
                error(e.getMessage());
                aTarget.addChildren(getPage(), FeedbackPanel.class);
            }
        }
    });

    finish = new FinishImage("finishImage", new Model<BratAnnotatorModel>(bModel));
    finish.setOutputMarkupId(true);

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

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.AnnotationPage.java

License:Apache License

private void loadDocumentAction(AjaxRequestTarget aTarget) {
    LOG.info("BEGIN LOAD_DOCUMENT_ACTION");

    // Update dynamic elements in action bar
    aTarget.add(finish);//from  w  ww.j a  v a 2s . c  o m
    aTarget.add(numberOfPages);
    aTarget.add(documentNamePanel);

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

    bModel.setUser(userRepository.get(username));

    try {
        // Check if there is an annotation document entry in the database. If there is none,
        // create one.
        AnnotationDocument annotationDocument = repository.createOrGetAnnotationDocument(bModel.getDocument(),
                user);

        // Read the CAS
        JCas jcas = repository.readAnnotationCas(annotationDocument);

        // Update the annotation document CAS
        repository.upgradeCas(jcas.getCas(), annotationDocument);

        // After creating an new CAS or upgrading the CAS, we need to save it
        repository.writeAnnotationCas(jcas.getCas().getJCas(), annotationDocument.getDocument(), user);

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

        // Load constraints
        bModel.setConstraints(loadConstraints(aTarget, bModel.getProject()));

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

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

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

        LOG.debug("Configured BratAnnotatorModel for user [" + bModel.getUser() + "] f:["
                + bModel.getFirstSentenceAddress() + "] l:[" + bModel.getLastSentenceAddress() + "] s:["
                + bModel.getSentenceAddress() + "]");

        gotoPageTextField.setModelObject(1);

        updateSentenceAddress(jcas, aTarget);

        // Wicket-level rendering of annotator because it becomes visible
        // after selecting a document
        aTarget.add(annotator);

        // brat-level initialization and rendering of document
        annotator.bratInit(aTarget);
        annotator.bratRender(aTarget, jcas);
    } catch (DataRetrievalFailureException e) {
        LOG.error("Error", e);
        aTarget.addChildren(getPage(), FeedbackPanel.class);
        error(e.getMessage());
    } catch (IOException e) {
        LOG.error("Error", e);
        aTarget.addChildren(getPage(), FeedbackPanel.class);
        error(e.getMessage());
    } catch (UIMAException e) {
        LOG.error("Error", e);
        aTarget.addChildren(getPage(), FeedbackPanel.class);
        error(ExceptionUtils.getRootCauseMessage(e));
    } catch (ClassNotFoundException e) {
        LOG.error("Error", e);
        aTarget.addChildren(getPage(), FeedbackPanel.class);
        error(e.getMessage());
    }

    LOG.info("END LOAD_DOCUMENT_ACTION");
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.AnnotationPage.java

License:Apache License

private ParsedConstraints loadConstraints(AjaxRequestTarget aTarget, Project aProject) throws IOException {
    ParsedConstraints merged = null;//from  w  w w.j  a  v  a  2s  .  c om

    for (ConstraintSet set : repository.listConstraintSets(aProject)) {
        try {
            String script = repository.readConstrainSet(set);
            ConstraintsGrammar parser = new ConstraintsGrammar(new StringReader(script));
            Parse p = parser.Parse();
            ParsedConstraints constraints = p.accept(new ParserVisitor());

            if (merged == null) {
                merged = constraints;
            } else {
                // Merge imports
                for (Entry<String, String> e : constraints.getImports().entrySet()) {
                    //Check if the value already points to some other feature in previous constraint file(s).
                    if (merged.getImports().containsKey(e.getKey())
                            && !e.getValue().equalsIgnoreCase(merged.getImports().get(e.getKey()))) {
                        //If detected, notify user with proper message and abort merging
                        StringBuffer errorMessage = new StringBuffer();
                        errorMessage.append("Conflict detected in imports for key \"");
                        errorMessage.append(e.getKey());
                        errorMessage.append("\", conflicting values are \"");
                        errorMessage.append(e.getValue());
                        errorMessage.append("\" & \"");
                        errorMessage.append(merged.getImports().get(e.getKey()));
                        errorMessage.append(
                                "\". Please contact Project Admin for correcting this. Constraints feature may not work.");
                        errorMessage.append("\nAborting Constraint rules merge!");
                        LOG.error(errorMessage.toString());
                        error(errorMessage.toString());
                        break;
                    }
                }
                merged.getImports().putAll(constraints.getImports());

                // Merge scopes
                for (Scope scope : constraints.getScopes()) {
                    Scope target = merged.getScopeByName(scope.getScopeName());
                    if (target == null) {
                        // Scope does not exist yet
                        merged.getScopes().add(scope);
                    } else {
                        // Scope already exists
                        target.getRules().addAll(scope.getRules());
                    }
                }
            }
        } catch (ParseException e) {
            LOG.error("Error", e);
            aTarget.addChildren(getPage(), FeedbackPanel.class);
            error(e.getMessage());
        }
    }

    return merged;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.page.automation.AutomationPage.java

License:Apache License

public AutomationPage() {
    bModel = new BratAnnotatorModel();
    bModel.setMode(Mode.AUTOMATION);//  w ww .j a  v  a 2s.  co m

    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, annotator, 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());
            }
            annotator.bratRenderLater(aTarget);
            aTarget.add(numberOfPages);
            update(aTarget);
        }
    };

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

    editor = 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 {
                annotator.bratRender(aTarget, getCas(aBModel));
            } catch (UIMAException | ClassNotFoundException | IOException e) {
                LOG.info("Error reading CAS " + e.getMessage());
                error("Error reading CAS " + e.getMessage());
                return;
            }

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

            annotator.onChange(aTarget, aBModel);
        }

        @Override
        protected void onAutoForward(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) {
            try {
                annotator.autoForward(aTarget, getCas(aBModel));
            } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) {
                LOG.info("Error reading CAS " + e.getMessage());
                error("Error reading CAS " + e.getMessage());
                return;
            }
        }

        @Override
        public void onAnnotate(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel, int aStart, int aEnd) {
            AnnotationLayer layer = aBModel.getSelectedAnnotationLayer();
            int address = aBModel.getSelection().getAnnotation().getId();
            try {
                AnnotationDocument annodoc = repository.createOrGetAnnotationDocument(aBModel.getDocument(),
                        aBModel.getUser());
                JCas jCas = repository.readAnnotationCas(annodoc);
                AnnotationFS fs = selectByAddr(jCas, address);

                for (AnnotationFeature f : annotationService.listAnnotationFeature(layer)) {
                    Type type = CasUtil.getType(fs.getCAS(), layer.getName());
                    Feature feat = type.getFeatureByBaseName(f.getName());
                    if (!automationService.existsMiraTemplate(f)) {
                        continue;
                    }
                    if (!automationService.getMiraTemplate(f).isAnnotateAndRepeat()) {
                        continue;
                    }
                    TagSet tagSet = f.getTagset();
                    boolean isRepeatabl = false;
                    // repeat only if the value is in the tagset
                    for (Tag tag : annotationService.listTags(tagSet)) {
                        if (fs.getFeatureValueAsString(feat) == null) {
                            break; // this is new annotation without values
                        }
                        if (fs.getFeatureValueAsString(feat).equals(tag.getName())) {
                            isRepeatabl = true;
                            break;
                        }
                    }
                    if (automationService.getMiraTemplate(f) != null && isRepeatabl) {

                        if (layer.getType().endsWith(WebAnnoConst.RELATION_TYPE)) {
                            AutomationUtil.repeateRelationAnnotation(aBModel, repository, annotationService, fs,
                                    f, fs.getFeatureValueAsString(feat));
                            update(aTarget);
                            break;
                        } else if (layer.getType().endsWith(WebAnnoConst.SPAN_TYPE)) {
                            AutomationUtil.repeateSpanAnnotation(aBModel, repository, annotationService, aStart,
                                    aEnd, f, fs.getFeatureValueAsString(feat));
                            update(aTarget);
                            break;
                        }

                    }
                }
            } 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());
            }
        }

        @Override
        public void onDelete(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel, AnnotationFS aFs) {
            AnnotationLayer layer = aBModel.getSelectedAnnotationLayer();
            for (AnnotationFeature f : annotationService.listAnnotationFeature(layer)) {
                if (!automationService.existsMiraTemplate(f)) {
                    continue;
                }
                if (!automationService.getMiraTemplate(f).isAnnotateAndRepeat()) {
                    continue;
                }
                try {
                    Type type = CasUtil.getType(aFs.getCAS(), layer.getName());
                    Feature feat = type.getFeatureByBaseName(f.getName());
                    if (layer.getType().endsWith(WebAnnoConst.RELATION_TYPE)) {
                        AutomationUtil.deleteRelationAnnotation(aBModel, repository, annotationService, aFs, f,
                                aFs.getFeatureValueAsString(feat));
                    } else {
                        AutomationUtil.deleteSpanAnnotation(aBModel, repository, annotationService,
                                aFs.getBegin(), aFs.getEnd(), f, aFs.getFeatureValueAsString(feat));
                    }
                    update(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());
                }
            }

        }
    };

    editor.setOutputMarkupId(true);
    add(editor);

    annotator = new BratAnnotator("mergeView", new Model<BratAnnotatorModel>(bModel), editor) {
        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);
        }
    };
    // reset sentenceAddress and lastSentenceAddress to the orginal once

    annotator.setOutputMarkupId(true);
    add(annotator);

    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) {
            editor.reset(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();

                        loadDocumentAction();
                        setCurationSegmentBeginEnd();
                        update(target);
                        User user = userRepository.get(username);
                        editor.setEnabled(!FinishImage.isFinished(new Model<BratAnnotatorModel>(bModel), user,
                                repository));

                    } 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),
            editor) {
        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) {

                    updateSentenceNumber(mergeJCas, gotoPageAddress);

                    SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                            userRepository);
                    curationContainer = builder.buildCurationContainer(bModel);
                    setCurationSegmentBeginEnd();
                    curationContainer.setBratAnnotatorModel(bModel);
                    update(aTarget);
                    annotator.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) {

                    updateSentenceNumber(mergeJCas, gotoPageAddress);

                    SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                            userRepository);
                    curationContainer = builder.buildCurationContainer(bModel);
                    setCurationSegmentBeginEnd();
                    curationContainer.setBratAnnotatorModel(bModel);
                    update(aTarget);
                    annotator.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 aTarget) {
            editor.reset(aTarget);
            aTarget.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) {
                aTarget.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(aTarget);

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

                finish.setModelObject(bModel);
                aTarget.add(finish.setOutputMarkupId(true));
                aTarget.add(numberOfPages);
                aTarget.add(documentNamePanel);
                annotator.bratRenderLater(aTarget);
            }
        }
    }.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 aTarget) {
            editor.reset(aTarget);
            aTarget.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) {
                aTarget.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(aTarget);

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

            finish.setModelObject(bModel);
            aTarget.add(finish.setOutputMarkupId(true));
            aTarget.add(numberOfPages);
            aTarget.add(documentNamePanel);
            annotator.bratRenderLater(aTarget);
        }
    }.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) {
                        updateSentenceNumber(mergeJCas, nextSentenceAddress);

                        SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                                userRepository);
                        curationContainer = builder.buildCurationContainer(bModel);
                        setCurationSegmentBeginEnd();
                        curationContainer.setBratAnnotatorModel(bModel);
                        update(aTarget);
                        annotator.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) {
                        updateSentenceNumber(mergeJCas, previousSentenceAddress);

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

                        curationContainer = builder.buildCurationContainer(bModel);
                        setCurationSegmentBeginEnd();
                        curationContainer.setBratAnnotatorModel(bModel);
                        update(aTarget);
                        annotator.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) {
                        updateSentenceNumber(mergeJCas, firstAddress);

                        SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                                userRepository);
                        curationContainer = builder.buildCurationContainer(bModel);
                        setCurationSegmentBeginEnd();
                        curationContainer.setBratAnnotatorModel(bModel);
                        update(aTarget);
                        annotator.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()) {
                        updateSentenceNumber(mergeJCas, lastDisplayWindowBeginingSentenceAddress);

                        SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                                userRepository);
                        curationContainer = builder.buildCurationContainer(bModel);
                        setCurationSegmentBeginEnd();
                        curationContainer.setBratAnnotatorModel(bModel);
                        update(aTarget);
                        annotator.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)));
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.page.correction.CorrectionPage.java

License:Apache License

public CorrectionPage() {
    bModel = new BratAnnotatorModel();
    bModel.setMode(Mode.CORRECTION);/*from w  w  w.j  a va2 s .  c o  m*/

    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, annotator, 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());
            }
            annotator.bratRenderLater(aTarget);
            aTarget.add(numberOfPages);
            update(aTarget);
        }
    };

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

    editor = 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 {
                annotator.bratRender(aTarget, getCas(aBModel));
            } catch (UIMAException | ClassNotFoundException | IOException e) {
                LOG.info("Error reading CAS " + e.getMessage());
                error("Error reading CAS " + e.getMessage());
                return;
            }

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

            annotator.onChange(aTarget, aBModel);

        }

        @Override
        protected void onAutoForward(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) {
            try {
                annotator.autoForward(aTarget, getCas(aBModel));
            } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) {
                LOG.info("Error reading CAS " + e.getMessage());
                error("Error reading CAS " + e.getMessage());
                return;
            }
        }
    };

    editor.setOutputMarkupId(true);
    add(editor);

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

        @Override
        public void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBratAnnotatorModel) {
            try {
                aTarget.addChildren(getPage(), FeedbackPanel.class);
                // info(bratAnnotatorModel.getMessage());
                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);
        }
    };
    // reset sentenceAddress and lastSentenceAddress to the orginal once

    annotator.setOutputMarkupId(true);
    add(annotator);

    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 project and document information at the top
    add(new AjaxLink<Void>("showOpenDocumentModal") {
        private static final long serialVersionUID = 7496156015186497496L;

        @Override
        public void onClick(AjaxRequestTarget aTarget) {
            editor.reset(aTarget);
            openDocumentsModal.setContent(new OpenModalWindowPanel(openDocumentsModal.getContentId(), bModel,
                    openDocumentsModal, Mode.CORRECTION));
            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());

                        loadDocumentAction();
                        setCurationSegmentBeginEnd();
                        update(target);

                        String username = SecurityContextHolder.getContext().getAuthentication().getName();
                        User user = userRepository.get(username);
                        editor.setEnabled(!FinishImage.isFinished(new Model<BratAnnotatorModel>(bModel), user,
                                repository));

                    } catch (UIMAException e) {
                        target.appendJavaScript("alert('" + e.getMessage() + "')");
                        setResponsePage(WelcomePage.class);
                    } catch (ClassNotFoundException e) {
                        target.appendJavaScript("alert('" + e.getMessage() + "')");
                        setResponsePage(WelcomePage.class);
                    } catch (IOException e) {
                        target.appendJavaScript("alert('" + e.getMessage() + "')");
                        setResponsePage(WelcomePage.class);
                    } catch (BratAnnotationException e) {
                        target.appendJavaScript("alert('" + e.getMessage() + "')");
                        setResponsePage(WelcomePage.class);
                    }
                    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),
            editor) {
        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) {
                    bModel.setSentenceAddress(gotoPageAddress);

                    Sentence sentence = selectByAddr(mergeJCas, Sentence.class, gotoPageAddress);
                    bModel.setSentenceBeginOffset(sentence.getBegin());
                    bModel.setSentenceEndOffset(sentence.getEnd());

                    SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                            userRepository);
                    curationContainer = builder.buildCurationContainer(bModel);
                    setCurationSegmentBeginEnd();
                    curationContainer.setBratAnnotatorModel(bModel);
                    update(aTarget);
                    annotator.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) {
                    bModel.setSentenceAddress(gotoPageAddress);

                    Sentence sentence = selectByAddr(mergeJCas, Sentence.class, gotoPageAddress);
                    bModel.setSentenceBeginOffset(sentence.getBegin());
                    bModel.setSentenceEndOffset(sentence.getEnd());

                    SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                            userRepository);
                    curationContainer = builder.buildCurationContainer(bModel);
                    setCurationSegmentBeginEnd();
                    curationContainer.setBratAnnotatorModel(bModel);
                    update(aTarget);
                    annotator.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 aTarget) {
            editor.reset(aTarget);
            aTarget.addChildren(getPage(), FeedbackPanel.class);
            // List of all Source Documents in the project
            List<SourceDocument> listOfSourceDocuements = repository.listSourceDocuments(bModel.getProject());

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

            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);
                }
            }

            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) {
                aTarget.appendJavaScript("alert('This is the first document!')");
            } else {
                bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex - 1).getName());
                bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex - 1));

                try {
                    loadDocumentAction();
                    setCurationSegmentBeginEnd();
                    update(aTarget);

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

                finish.setModelObject(bModel);
                aTarget.add(finish.setOutputMarkupId(true));
                aTarget.add(documentNamePanel);
                annotator.bratRenderLater(aTarget);
            }
        }
    }.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 aTarget) {
            editor.reset(aTarget);
            aTarget.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);
                }
            }

            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) {
                aTarget.appendJavaScript("alert('This is the last document!')");
                return;
            }
            bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex + 1).getName());
            bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex + 1));

            try {
                loadDocumentAction();
                setCurationSegmentBeginEnd();
                update(aTarget);

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

            finish.setModelObject(bModel);
            aTarget.add(finish.setOutputMarkupId(true));
            aTarget.add(documentNamePanel);
            annotator.bratRenderLater(aTarget);
        }
    }.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) {
                        bModel.setSentenceAddress(nextSentenceAddress);

                        Sentence sentence = selectByAddr(mergeJCas, Sentence.class, nextSentenceAddress);
                        bModel.setSentenceBeginOffset(sentence.getBegin());
                        bModel.setSentenceEndOffset(sentence.getEnd());

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

                    else {
                        aTarget.appendJavaScript("alert('This is last page!')");
                    }
                } catch (UIMAException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(ExceptionUtils.getRootCause(e));
                } catch (ClassNotFoundException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (IOException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (BratAnnotationException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (Exception e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    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) {
                        bModel.setSentenceAddress(previousSentenceAddress);

                        Sentence sentence = selectByAddr(mergeJCas, Sentence.class, previousSentenceAddress);
                        bModel.setSentenceBeginOffset(sentence.getBegin());
                        bModel.setSentenceEndOffset(sentence.getEnd());

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

                        curationContainer = builder.buildCurationContainer(bModel);
                        setCurationSegmentBeginEnd();
                        curationContainer.setBratAnnotatorModel(bModel);
                        update(aTarget);
                        annotator.bratRenderLater(aTarget);
                    } else {
                        aTarget.appendJavaScript("alert('This is First Page!')");
                    }
                } catch (UIMAException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(ExceptionUtils.getRootCause(e));
                } catch (ClassNotFoundException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (IOException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (BratAnnotationException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (Exception e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    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) {
                        bModel.setSentenceAddress(firstAddress);

                        Sentence sentence = selectByAddr(mergeJCas, Sentence.class, firstAddress);
                        bModel.setSentenceBeginOffset(sentence.getBegin());
                        bModel.setSentenceEndOffset(sentence.getEnd());

                        SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                                userRepository);
                        curationContainer = builder.buildCurationContainer(bModel);
                        setCurationSegmentBeginEnd();
                        curationContainer.setBratAnnotatorModel(bModel);
                        update(aTarget);
                        annotator.bratRenderLater(aTarget);
                    } else {
                        aTarget.appendJavaScript("alert('This is first page!')");
                    }
                } catch (UIMAException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(ExceptionUtils.getRootCause(e));
                } catch (ClassNotFoundException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (IOException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (BratAnnotationException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (Exception e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    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()) {
                        bModel.setSentenceAddress(lastDisplayWindowBeginingSentenceAddress);

                        Sentence sentence = selectByAddr(mergeJCas, Sentence.class,
                                lastDisplayWindowBeginingSentenceAddress);
                        bModel.setSentenceBeginOffset(sentence.getBegin());
                        bModel.setSentenceEndOffset(sentence.getEnd());

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

                    } else {
                        aTarget.appendJavaScript("alert('This is last Page!')");
                    }
                } catch (UIMAException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(ExceptionUtils.getRootCause(e));
                } catch (ClassNotFoundException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (IOException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (BratAnnotationException e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    error(e.getMessage());
                } catch (Exception e) {
                    aTarget.addChildren(getPage(), FeedbackPanel.class);
                    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)));
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.page.curation.CurationPage.java

License:Apache License

private ParsedConstraints loadConstraints(AjaxRequestTarget aTarget, Project aProject) throws IOException {
    ParsedConstraints merged = null;//from www .j ava2  s.  c om

    for (ConstraintSet set : repository.listConstraintSets(aProject)) {
        try {
            String script = repository.readConstrainSet(set);
            ConstraintsGrammar parser = new ConstraintsGrammar(new StringReader(script));
            Parse p = parser.Parse();
            ParsedConstraints constraints = p.accept(new ParserVisitor());

            if (merged == null) {
                merged = constraints;
            } else {
                // Merge imports
                for (Entry<String, String> e : constraints.getImports().entrySet()) {
                    // Check if the value already points to some other feature in previous
                    // constraint file(s).
                    if (merged.getImports().containsKey(e.getKey())
                            && !e.getValue().equalsIgnoreCase(merged.getImports().get(e.getKey()))) {
                        // If detected, notify user with proper message and abort merging
                        StringBuffer errorMessage = new StringBuffer();
                        errorMessage.append("Conflict detected in imports for key \"");
                        errorMessage.append(e.getKey());
                        errorMessage.append("\", conflicting values are \"");
                        errorMessage.append(e.getValue());
                        errorMessage.append("\" & \"");
                        errorMessage.append(merged.getImports().get(e.getKey()));
                        errorMessage.append(
                                "\". Please contact Project Admin for correcting this. Constraints feature may not work.");
                        errorMessage.append("\nAborting Constraint rules merge!");
                        //                            LOG.error(errorMessage.toString());
                        error(errorMessage.toString());
                        break;
                    }
                }
                merged.getImports().putAll(constraints.getImports());

                // Merge scopes
                for (Scope scope : constraints.getScopes()) {
                    Scope target = merged.getScopeByName(scope.getScopeName());
                    if (target == null) {
                        // Scope does not exist yet
                        merged.getScopes().add(scope);
                    } else {
                        // Scope already exists
                        target.getRules().addAll(scope.getRules());
                    }
                }
            }
        } catch (ParseException e) {
            //                LOG.error("Error", e);
            aTarget.addChildren(getPage(), FeedbackPanel.class);
            error(e.getMessage());
        }
    }

    return merged;
}