Example usage for java.util List removeAll

List of usage examples for java.util List removeAll

Introduction

In this page you can find the example usage for java.util List removeAll.

Prototype

boolean removeAll(Collection<?> c);

Source Link

Document

Removes from this list all of its elements that are contained in the specified collection (optional operation).

Usage

From source file:com.manydesigns.portofino.pageactions.crud.AbstractCrudAction.java

protected void deleteOldBlobs(List<Blob> blobsBefore, List<Blob> blobsAfter) {
    List<Blob> toDelete = new ArrayList<Blob>(blobsBefore);
    toDelete.removeAll(blobsAfter);
    for (Blob blob : toDelete) {
        try {/*from www  .java 2s. c o m*/
            getBlobManager().delete(blob);
        } catch (IOException e) {
            logger.warn("Could not delete blob: " + blob.getCode(), e);
        }
    }
}

From source file:eu.europa.ec.markt.tlmanager.core.validation.Validation.java

/**
 * 5.5.4 Service current status//from  ww  w.j  a va2s  . com
 Presence: This field shall be present.
 Description: It specifies the identifier of the current status of the service.
 Format: An identifier expressed as an URI.
 Value:  In the context of EU Member States,
 to the exception of the "NationalRootCA-QC" service type, the identifier of the status of all
 the services shall be one of the following URIs as defined in clause D.5:
 - Under Supervision:
 "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/undersupervision"
 - Supervision of Service in Cessation:
 "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionincessation"
 - Supervision Ceased:
 "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionceased"
 - Supervision Revoked:
 "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/supervisionrevoked"
 - Accredited:
 "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accredited"
 - Accreditation Ceased:
 "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accreditationceased"
 - Accreditation Revoked:
 "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/accreditationrevoked"
 with regards to the "NationalRootCA-QC" service type (as defined in clause 5.5.1), the
 identifier of the status of such services shall be one of the following URIs as defined in
 clause D.5:
 - Set by national law:
 "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/setbynationallaw"
 - Deprecated by national law:
 "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/deprecatedbynationallaw"
 */
void checkRuleTspServiceCurrentStatus() {
    final QName name = QNames._ServiceStatus_QNAME;
    final String schemeTerritory = tsl.getSchemeInformation().getSchemeTerritory();
    if (Configuration.getInstance().getCountryCodes().isCodeInList(schemeTerritory)) {
        // In EU
        if (services != null) {
            final String nationalRootCaQc = "http://uri.etsi.org/TrstSvc/Svctype/NationalRootCA-QC";
            final String setByNationalLaw = "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/setbynationallaw";
            final String deprecatedByNationalLaw = "http://uri.etsi.org/TrstSvc/TrustedList/Svcstatus/deprecatedbynationallaw";
            final List<String> allowedForNationalRootCAQC = new ArrayList<String>();
            allowedForNationalRootCAQC.add(setByNationalLaw);
            allowedForNationalRootCAQC.add(deprecatedByNationalLaw);

            final List<String> tslServiceStatuses = Arrays
                    .asList(Configuration.getInstance().getTL().getTslServiceStatus());
            tslServiceStatuses.removeAll(allowedForNationalRootCAQC);
            for (TSPServiceType service : services) {
                TSPServiceInformationType serviceInfo = service.getServiceInformation();
                final String serviceStatus = serviceInfo.getServiceStatus();
                final String serviceTypeIdentifier = serviceInfo.getServiceTypeIdentifier();
                if (!nationalRootCaQc.equals(serviceTypeIdentifier)) {
                    if (!tslServiceStatuses.contains(serviceStatus)) {
                        logger.error(name + uiKeys.getString("Validation.rule.serviceCurrentStatus.notAllowed"),
                                service);
                    }
                } else {
                    if (!allowedForNationalRootCAQC.contains(serviceStatus)) {
                        logger.error(name + uiKeys.getString("Validation.rule.serviceCurrentStatus.notAllowed"),
                                service);
                    }
                }
            }
        }
    }
}

From source file:eu.clarin.cmdi.vlo.importer.MetadataImporter.java

/**
 * Retrieve all files with VALID_CMDI_EXTENSIONS from all DataRoot entries
 * and starts processing for every single file
 *
 * @throws MalformedURLException/*from  w ww .j  a  v a 2  s . c  o m*/
 */
void startImport() throws MalformedURLException {

    initSolrServer();
    List<DataRoot> dataRoots = checkDataRoots();
    dataRoots = filterDataRootsWithCLArgs(dataRoots);

    long start = System.currentTimeMillis();
    try {
        // Delete the whole Solr db
        if (config.getDeleteAllFirst()) {
            LOG.info("Deleting original data...");
            solrServer.deleteByQuery("*:*");
            solrServer.commit();
            LOG.info("Deleting original data done.");
        }

        // Import the specified data roots
        for (DataRoot dataRoot : dataRoots) {
            LOG.info("Start of processing: " + dataRoot.getOriginName());
            if (dataRoot.deleteFirst()) {
                LOG.info("Deleting data for data provider: " + dataRoot.getOriginName());
                solrServer.deleteByQuery(FacetConstants.FIELD_DATA_PROVIDER + ":"
                        + ClientUtils.escapeQueryChars(dataRoot.getOriginName()));
                LOG.info("Deleting data of provider done.");
            }
            CMDIDataProcessor processor = new CMDIParserVTDXML(POST_PROCESSORS, config, false);
            List<List<File>> centreFilesList = getFilesFromDataRoot(dataRoot.getRootFile());
            // import files from every endpoint
            for (List<File> centreFiles : centreFilesList) {
                LOG.info("Processing directory: {}", centreFiles.get(0).getParent());

                // identify mdSelfLinks and remove too large files from center file list
                LOG.info("Extracting mdSelfLinks");
                Set<String> mdSelfLinkSet = new HashSet<>();
                Set<File> ignoredFileSet = new HashSet<>();
                for (File file : centreFiles) {
                    if (config.getMaxFileSize() > 0 && file.length() > config.getMaxFileSize()) {
                        LOG.info("Skipping " + file.getAbsolutePath() + " because it is too large.");
                        nrOfFilesTooLarge++;
                        ignoredFileSet.add(file);
                    } else {
                        String mdSelfLink = null;
                        try {
                            mdSelfLink = processor.extractMdSelfLink(file);
                        } catch (Exception e) {
                            LOG.error("error in file: {}", file, e);
                            nrOfFilesWithError++;
                        }
                        if (mdSelfLink != null) {
                            mdSelfLinkSet.add(StringUtils.normalizeIdString(mdSelfLink));
                        }
                    }
                }
                centreFiles.removeAll(ignoredFileSet);

                // inform structure graph about MdSelfLinks of all files in this collection
                ResourceStructureGraph.setOccurringMdSelfLinks(mdSelfLinkSet);
                LOG.info("...extracted {} mdSelfLinks", mdSelfLinkSet.size());

                // process every file in this collection
                for (File file : centreFiles) {
                    LOG.debug("PROCESSING FILE: {}", file.getAbsolutePath());
                    processCmdi(file, dataRoot, processor);
                }
                if (!docs.isEmpty()) {
                    sendDocs();
                }
                solrServer.commit();
                if (config.isProcessHierarchies()) {
                    updateDocumentHierarchy();
                }
            }
            updateDaysSinceLastImport(dataRoot);
            LOG.info("End of processing: " + dataRoot.getOriginName());
        }

        // delete outdated entries (based on maxDaysInSolr parameter)
        if (config.getMaxDaysInSolr() > 0 && config.getDeleteAllFirst() == false) {
            LOG.info("Deleting old files that were not seen for more than " + config.getMaxDaysInSolr()
                    + " days...");
            solrServer.deleteByQuery(
                    FacetConstants.FIELD_LAST_SEEN + ":[* TO NOW-" + config.getMaxDaysInSolr() + "DAYS]");
            LOG.info("Deleting old files done.");
        }
    } catch (SolrServerException e) {
        LOG.error("error updating files:\n", e);
        LOG.error("Also see vlo_solr server logs for more information");
    } catch (IOException e) {
        LOG.error("error updating files:\n", e);
    } finally {
        try {
            if (solrServer != null) {
                solrServer.commit();
                buildSuggesterIndex();
            }
        } catch (SolrServerException | IOException e) {
            LOG.error("cannot commit:\n", e);
        }
    }
    long took = (System.currentTimeMillis() - start) / 1000;
    LOG.info("Found " + nrOfFilesWithoutId
            + " file(s) without an id. (id is generated based on fileName but that may not be unique)");
    LOG.info("Found " + nrOfFilesWithError + " file(s) with errors.");
    LOG.info("Found " + nrOfFilesTooLarge + " file(s) too large.");
    LOG.info("Update of " + nrOFDocumentsSend + " took " + took + " secs. Total nr of files analyzed "
            + nrOfFilesAnalyzed);
    solrServer.shutdown();
}

From source file:de.innovationgate.utils.WGUtils.java

/**
 * Updates a list with the state represented by another list, with as less
 * changes as possible. Elements that are new in newCol will get added to
 * list. Elements that do not exist in newCol but exist in list will get
 * removed from list. Elements that both, list and newCol, contain will
 * remain. This method can be used to update lists that are stored via
 * hibernate. Just replacing the old list with a new one would result in
 * hibernate removing all rows from the table and re-insert all values anew.
 * If lists are updated with this method, hibernate can focus on the real
 * removements and added elements without touching unmodified values.
 * WARNING: Only use this when the sorting order of the list is of no
 * importance!/* ww  w .j a  v a 2s  .c  o m*/
 * 
 * @param list
 * @param newCol
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void updateList(List list, Collection newCol) {
    List newList = new ArrayList(newCol);
    list.retainAll(newList);
    newList.removeAll(list);
    list.addAll(newList);
}

From source file:com.moviejukebox.model.Library.java

protected static void compressSetMovies(List<Movie> movies, Index index, Map<String, Movie> masters,
        String indexName, String subIndexName) {
    // Construct an index that includes only the intersection of movies and index
    Index inMovies = new Index();
    for (Map.Entry<String, List<Movie>> indexEntry : index.entrySet()) {
        for (Movie m : indexEntry.getValue()) {
            if (movies.contains(m)) {
                inMovies.addMovie(indexEntry.getKey(), m);
            }/*from  w w  w .  j  a  va 2s  . c  om*/
        }
    }

    // Now, for each list of movies in in_movies, if the list has more than the minSetCount movies
    // remove them all from the movies list, and insert the corresponding master
    for (Map.Entry<String, List<Movie>> inMoviesEntry : inMovies.entrySet()) {
        List<Movie> lm = inMoviesEntry.getValue();
        if (lm.size() >= minSetCount
                && (!setsRequireAll || lm.size() == index.get(inMoviesEntry.getKey()).size())) {
            boolean tvSet = keepTVExplodeSet && lm.get(0).isTVShow();
            boolean explodeSet = CATEGORIES_EXPLODE_SET.contains(indexName)
                    || (indexName.equalsIgnoreCase(INDEX_OTHER)
                            && CATEGORIES_EXPLODE_SET.contains(subIndexName));
            if (!beforeSortExplodeSet || !explodeSet || tvSet) {
                movies.removeAll(lm);
            }
            if (!beforeSortExplodeSet || !explodeSet || tvSet || !removeExplodeSet) {
                movies.add(masters.get(inMoviesEntry.getKey()));
            }
        }
    }
}

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

@SuppressWarnings("deprecation")
public CurationPage() {
    bratAnnotatorModel = new BratAnnotatorModel();
    bratAnnotatorModel.setMode(Mode.CURATION);
    reMerge = new ReMergeCasModel();

    curationContainer = new CurationContainer();
    curationContainer.setBratAnnotatorModel(bratAnnotatorModel);
    curationPanel = new CurationPanel("curationPanel", curationContainer);
    curationPanel.setOutputMarkupId(true);
    add(curationPanel);/*w  w  w .  ja  v a  2 s.co m*/

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

    add(numberOfPages = (Label) new Label("numberOfPages", new LoadableDetachableModel<String>() {

        private static final long serialVersionUID = 1L;

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

                JCas mergeJCas = null;
                try {
                    mergeJCas = repository.readCurationCas(bratAnnotatorModel.getDocument());

                    totalNumberOfSentence = getNumberOfPages(mergeJCas);

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

                    return "showing " + firstSentenceNumber + "-" + lastSentenceNumber + " of "
                            + totalNumberOfSentence + " sentences";
                } catch (UIMAException e) {
                    return "";
                } catch (ClassNotFoundException 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) {
            openDocumentsModal.setContent(new OpenModalWindowPanel(openDocumentsModal.getContentId(),
                    bratAnnotatorModel, openDocumentsModal, Mode.CURATION));
            openDocumentsModal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
                private static final long serialVersionUID = -1746088901018629567L;

                @Override
                public void onClose(AjaxRequestTarget target) {
                    String username = SecurityContextHolder.getContext().getAuthentication().getName();

                    if (bratAnnotatorModel.getDocument() == null) {
                        setResponsePage(WelcomePage.class);
                        return;
                    }

                    User user = userRepository.get(username);
                    // Update source document state to
                    // CURRATION_INPROGRESS, if it was not
                    // ANNOTATION_FINISHED
                    if (!bratAnnotatorModel.getDocument().getState()
                            .equals(SourceDocumentState.CURATION_FINISHED)) {

                        bratAnnotatorModel.getDocument().setState(SourceDocumentState.CURATION_IN_PROGRESS);
                    }

                    try {
                        repository.createSourceDocument(bratAnnotatorModel.getDocument(), user);
                        repository.upgradeCasAndSave(bratAnnotatorModel.getDocument(), Mode.CURATION, username);

                        loadDocumentAction(target);
                    } catch (IOException e) {
                        target.add(getFeedbackPanel());
                        error(e.getCause().getMessage());
                    }
                }
            });
            openDocumentsModal.show(aTarget);
        }
    });

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

        @Override
        protected void onChange(AjaxRequestTarget aTarget) {
            SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService, userRepository);
            try {

                aTarget.add(getFeedbackPanel());
                curationContainer = builder.buildCurationContainer(bratAnnotatorModel);
                curationContainer.setBratAnnotatorModel(bratAnnotatorModel);

                updatePanel(curationContainer, aTarget);
                aTarget.add(numberOfPages);
                aTarget.appendJavaScript("Wicket.Window.unloadConfirmation=false;window.location.reload()");

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

    // 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) {
            // List of all Source Documents in the project
            List<SourceDocument> listOfSourceDocuements = repository
                    .listSourceDocuments(bratAnnotatorModel.getProject());

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

            List<SourceDocument> sourceDocumentsinIgnorState = new ArrayList<SourceDocument>();
            for (SourceDocument sourceDocument : listOfSourceDocuements) {
                if (!repository.existFinishedDocument(sourceDocument, user, bratAnnotatorModel.getProject())) {
                    sourceDocumentsinIgnorState.add(sourceDocument);
                }
            }

            listOfSourceDocuements.removeAll(sourceDocumentsinIgnorState);

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

            // If the first the document
            if (currentDocumentIndex == 0) {
                aTarget.appendJavaScript("alert('This is the first document!')");
            } else {
                bratAnnotatorModel
                        .setDocumentName(listOfSourceDocuements.get(currentDocumentIndex - 1).getName());
                bratAnnotatorModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex - 1));
                try {
                    repository.upgradeCasAndSave(bratAnnotatorModel.getDocument(), Mode.CURATION,
                            bratAnnotatorModel.getUser().getUsername());

                    loadDocumentAction(aTarget);
                } catch (IOException e) {
                    aTarget.add(getFeedbackPanel());
                    error(e.getCause().getMessage());
                }
            }
        }
    }.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) {
            // List of all Source Documents in the project
            List<SourceDocument> listOfSourceDocuements = repository
                    .listSourceDocuments(bratAnnotatorModel.getProject());

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

            List<SourceDocument> sourceDocumentsinIgnorState = new ArrayList<SourceDocument>();
            for (SourceDocument sourceDocument : listOfSourceDocuements) {
                if (!repository.existFinishedDocument(sourceDocument, user, bratAnnotatorModel.getProject())) {
                    sourceDocumentsinIgnorState.add(sourceDocument);
                }
            }

            listOfSourceDocuements.removeAll(sourceDocumentsinIgnorState);

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

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

                try {
                    aTarget.add(getFeedbackPanel());
                    repository.upgradeCasAndSave(bratAnnotatorModel.getDocument(), Mode.CURATION,
                            bratAnnotatorModel.getUser().getUsername());

                    loadDocumentAction(aTarget);
                } catch (IOException e) {
                    aTarget.add(getFeedbackPanel());
                    error(e.getCause().getMessage());
                }
            }
        }
    }.add(new InputBehavior(new KeyType[] { KeyType.Shift, KeyType.Page_down }, EventType.click)));

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

    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.add(getFeedbackPanel());
                mergeJCas = repository.readCurationCas(bratAnnotatorModel.getDocument());
                if (bratAnnotatorModel.getSentenceAddress() != gotoPageAddress) {
                    bratAnnotatorModel.setSentenceAddress(gotoPageAddress);

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

                    SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                            userRepository);
                    curationContainer = builder.buildCurationContainer(bratAnnotatorModel);
                    curationContainer.setBratAnnotatorModel(bratAnnotatorModel);

                    updatePanel(curationContainer, aTarget);
                    aTarget.add(numberOfPages);
                    aTarget.appendJavaScript("Wicket.Window.unloadConfirmation=false;window.location.reload()");
                }
            } catch (UIMAException e) {
                error(ExceptionUtils.getRootCauseMessage(e));
            } catch (ClassNotFoundException e) {
                error(e.getMessage());
            } catch (IOException e) {
                error(e.getMessage());
            } catch (BratAnnotationException e) {
                error(e.getMessage());
            }
        }
    });

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

        @Override
        protected void onUpdate(AjaxRequestTarget aTarget) {
            JCas mergeJCas = null;
            try {
                aTarget.add(getFeedbackPanel());
                mergeJCas = repository.readCurationCas(bratAnnotatorModel.getDocument());
                gotoPageAddress = getSentenceAddress(mergeJCas, gotoPageTextField.getModelObject());

            } catch (UIMAException e) {
                error(ExceptionUtils.getRootCause(e));
            } catch (ClassNotFoundException e) {
                error(e.getMessage());
            } 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 (bratAnnotatorModel.getDocument() == null) {
                aTarget.appendJavaScript("alert('Please open a document first!')");
                return;
            }

            JCas mergeJCas = null;
            try {
                aTarget.add(getFeedbackPanel());
                mergeJCas = repository.readCurationCas(bratAnnotatorModel.getDocument());
                if (bratAnnotatorModel.getSentenceAddress() != gotoPageAddress) {
                    bratAnnotatorModel.setSentenceAddress(gotoPageAddress);

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

                    SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                            userRepository);
                    curationContainer = builder.buildCurationContainer(bratAnnotatorModel);
                    curationContainer.setBratAnnotatorModel(bratAnnotatorModel);

                    updatePanel(curationContainer, aTarget);
                    aTarget.add(numberOfPages);
                    aTarget.appendJavaScript("Wicket.Window.unloadConfirmation=false;window.location.reload()");
                }
            } catch (UIMAException e) {
                error(ExceptionUtils.getRootCauseMessage(e));
            } catch (ClassNotFoundException e) {
                error(e.getMessage());
            } catch (IOException e) {
                error(e.getMessage());
            } catch (BratAnnotationException e) {
                error(e.getMessage());
            }
        }
    });

    finish = new WebMarkupContainer("finishImage");
    finish.setOutputMarkupId(true);
    finish.add(new AttributeModifier("src", true, new LoadableDetachableModel<String>() {
        private static final long serialVersionUID = 1562727305401900776L;

        @Override
        protected String load() {

            if (bratAnnotatorModel.getProject() != null && bratAnnotatorModel.getDocument() != null) {
                if (repository
                        .getSourceDocument(bratAnnotatorModel.getDocument().getProject(),
                                bratAnnotatorModel.getDocument().getName())
                        .getState().equals(SourceDocumentState.CURATION_FINISHED)) {
                    return "images/accept.png";
                } else {
                    return "images/inprogress.png";
                }
            } else {
                return "images/inprogress.png";
            }

        }
    }));

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

    finishCurationModal.setInitialWidth(700);
    finishCurationModal.setInitialHeight(50);
    finishCurationModal.setResizable(true);
    finishCurationModal.setWidthUnit("px");
    finishCurationModal.setHeightUnit("px");

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

        @Override
        public void onClick(AjaxRequestTarget target) {
            if (bratAnnotatorModel.getDocument() != null && bratAnnotatorModel.getDocument().getState()
                    .equals(SourceDocumentState.CURATION_FINISHED)) {
                finishCurationModal.setTitle(
                        "Curation was finished. Are you sure you want to re-open document for curation?");
            } else {
                finishCurationModal.setTitle("Are you sure you want to finish curating?");
            }
            finishCurationModal.setContent(new YesNoFinishModalPanel(finishCurationModal.getContentId(),
                    bratAnnotatorModel, finishCurationModal, Mode.CURATION));
            finishCurationModal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
                private static final long serialVersionUID = -1746088901018629567L;

                @Override
                public void onClose(AjaxRequestTarget target) {
                    target.add(finish);
                    target.appendJavaScript("Wicket.Window.unloadConfirmation=false;window.location.reload()");
                }
            });
            finishCurationModal.show(target);
        }
    });

    showFinishCurationModal.add(finish);

    add(new GuidelineModalPanel("guidelineModalPanel", new Model<BratAnnotatorModel>(bratAnnotatorModel)));

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

    reCreateMergeCas.setInitialWidth(400);
    reCreateMergeCas.setInitialHeight(50);
    reCreateMergeCas.setResizable(true);
    reCreateMergeCas.setWidthUnit("px");
    reCreateMergeCas.setHeightUnit("px");
    reCreateMergeCas.setTitle("are you sure? all curation annotations for this document will be lost");

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

        @Override
        public void onClick(AjaxRequestTarget target) {
            reCreateMergeCas.setContent(
                    new ReCreateMergeCASModalPanel(reCreateMergeCas.getContentId(), reCreateMergeCas, reMerge));
            reCreateMergeCas.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {

                private static final long serialVersionUID = 4816615910398625993L;

                @Override
                public void onClose(AjaxRequestTarget aTarget) {
                    if (reMerge.isReMerege()) {
                        try {
                            aTarget.add(getFeedbackPanel());
                            repository.removeCurationDocumentContent(bratAnnotatorModel.getDocument(),
                                    bratAnnotatorModel.getUser().getUsername());
                            loadDocumentAction(aTarget);

                            aTarget.appendJavaScript("alert('remerege finished!')");
                        } catch (IOException e) {
                            aTarget.add(getFeedbackPanel());
                            error(e.getCause().getMessage());
                        }
                    }
                }
            });
            reCreateMergeCas.show(target);
        }

        @Override
        public boolean isEnabled() {
            return bratAnnotatorModel.getDocument() != null && !bratAnnotatorModel.getDocument().getState()
                    .equals(SourceDocumentState.CURATION_FINISHED);
        }
    });
    // 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 (bratAnnotatorModel.getDocument() != null) {
                JCas mergeJCas = null;
                try {
                    mergeJCas = repository.readCurationCas(bratAnnotatorModel.getDocument());
                    int nextSentenceAddress = getNextPageFirstSentenceAddress(mergeJCas,
                            bratAnnotatorModel.getSentenceAddress(),
                            bratAnnotatorModel.getPreferences().getWindowSize());
                    if (bratAnnotatorModel.getSentenceAddress() != nextSentenceAddress) {
                        aTarget.add(getFeedbackPanel());
                        bratAnnotatorModel.setSentenceAddress(nextSentenceAddress);

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

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

                        curationContainer = builder.buildCurationContainer(bratAnnotatorModel);

                        curationContainer.setBratAnnotatorModel(bratAnnotatorModel);

                        updatePanel(curationContainer, aTarget);
                        aTarget.add(numberOfPages);
                        aTarget.appendJavaScript(
                                "Wicket.Window.unloadConfirmation=false;window.location.reload()");
                    }

                    else {
                        aTarget.appendJavaScript("alert('This is last page!')");
                    }
                } catch (UIMAException e) {
                    error(ExceptionUtils.getRootCauseMessage(e));
                } catch (ClassNotFoundException e) {
                    error(e.getMessage());
                } catch (IOException e) {
                    error(e.getMessage());
                } catch (BratAnnotationException e) {
                    error(e.getMessage());
                }
            } 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 (bratAnnotatorModel.getDocument() != null) {

                JCas mergeJCas = null;
                try {
                    aTarget.add(getFeedbackPanel());
                    mergeJCas = repository.readCurationCas(bratAnnotatorModel.getDocument());
                    int previousSentenceAddress = BratAjaxCasUtil.getPreviousDisplayWindowSentenceBeginAddress(
                            mergeJCas, bratAnnotatorModel.getSentenceAddress(),
                            bratAnnotatorModel.getPreferences().getWindowSize());
                    if (bratAnnotatorModel.getSentenceAddress() != previousSentenceAddress) {
                        bratAnnotatorModel.setSentenceAddress(previousSentenceAddress);

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

                        SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                                userRepository);
                        curationContainer = builder.buildCurationContainer(bratAnnotatorModel);
                        curationContainer.setBratAnnotatorModel(bratAnnotatorModel);

                        updatePanel(curationContainer, aTarget);
                        aTarget.add(numberOfPages);
                        aTarget.appendJavaScript(
                                "Wicket.Window.unloadConfirmation=false;window.location.reload()");
                    } else {
                        aTarget.appendJavaScript("alert('This is First Page!')");
                    }
                } catch (UIMAException e) {
                    error(ExceptionUtils.getRootCauseMessage(e));
                } catch (ClassNotFoundException e) {
                    error(e.getMessage());
                } catch (IOException e) {
                    error(e.getMessage());
                } catch (BratAnnotationException e) {
                    error(e.getMessage());
                }
            } 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 (bratAnnotatorModel.getDocument() != null) {
                JCas mergeJCas = null;
                try {
                    aTarget.add(getFeedbackPanel());
                    mergeJCas = repository.readCurationCas(bratAnnotatorModel.getDocument());

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

                    if (firstAddress != address) {
                        bratAnnotatorModel.setSentenceAddress(firstAddress);

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

                        SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                                userRepository);
                        curationContainer = builder.buildCurationContainer(bratAnnotatorModel);
                        curationContainer.setBratAnnotatorModel(bratAnnotatorModel);

                        updatePanel(curationContainer, aTarget);
                        aTarget.add(numberOfPages);
                        aTarget.appendJavaScript(
                                "Wicket.Window.unloadConfirmation=false;window.location.reload()");

                    } else {
                        aTarget.appendJavaScript("alert('This is first page!')");
                    }
                } catch (UIMAException e) {
                    error(ExceptionUtils.getRootCauseMessage(e));
                } catch (ClassNotFoundException e) {
                    error(e.getMessage());
                } catch (IOException e) {
                    error(e.getMessage());
                } catch (BratAnnotationException e) {
                    error(e.getMessage());
                }
            } 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 (bratAnnotatorModel.getDocument() != null) {
                JCas mergeJCas = null;
                try {
                    aTarget.add(getFeedbackPanel());
                    mergeJCas = repository.readCurationCas(bratAnnotatorModel.getDocument());
                    int lastDisplayWindowBeginingSentenceAddress = BratAjaxCasUtil
                            .getLastDisplayWindowFirstSentenceAddress(mergeJCas,
                                    bratAnnotatorModel.getPreferences().getWindowSize());
                    if (lastDisplayWindowBeginingSentenceAddress != bratAnnotatorModel.getSentenceAddress()) {
                        bratAnnotatorModel.setSentenceAddress(lastDisplayWindowBeginingSentenceAddress);

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

                        SuggestionBuilder builder = new SuggestionBuilder(repository, annotationService,
                                userRepository);
                        curationContainer = builder.buildCurationContainer(bratAnnotatorModel);
                        curationContainer.setBratAnnotatorModel(bratAnnotatorModel);

                        updatePanel(curationContainer, aTarget);
                        aTarget.add(numberOfPages);
                        aTarget.appendJavaScript(
                                "Wicket.Window.unloadConfirmation=false;window.location.reload()");

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

From source file:net.nifheim.beelzebu.coins.common.utils.FileManager.java

private void updateMessages() {
    try {//from w  w  w .  ja v  a  2 s  . co  m
        List<String> lines = FileUtils.readLines(messagesFiles.get("default"), Charsets.UTF_8);
        int index;
        if (core.getMessages("").getInt("version") == 6) {
            index = lines.indexOf("version: 6");
            lines.set(index, "version: 7");
            index = lines.indexOf("Multipliers:");
            lines.remove(index);
            index = lines.indexOf("  Menu:");
            lines.add(index, "Multipliers:");
            core.log("Updated messages.yml file to v7");
        }
        if (core.getMessages("").getInt("version") == 7) {
            index = lines.indexOf("version: 7");
            lines.set(index, "version: 8");
            index = lines.indexOf("  Menu:") + 2;
            lines.addAll(index,
                    Arrays.asList("    Confirm:", "      Title: '&8Are you sure?'", "      Accept: '&aYES!'",
                            "      Decline: '&cNope'", "    Multipliers:",
                            "      Name: '&6Multiplier &cx%amount%'", "      Lore:", "      - ''",
                            "      - '&7Amount: &c%amount%'", "      - '&7Server: &c%server%'",
                            "      - '&7Minutes: &c%minutes%'", "      - ''", "      - '&7ID: &c#%id%'",
                            "    No Multipliers:", "      Name: '&cYou don''t have any multiplier :('",
                            "      Lore:", "      - ''", "      - '&7You can buy multipliers in our store'",
                            "      - '&6&nstore.servername.net'"));
            core.log("Updated messages.yml file to v8");
        }
        if (core.getMessages("").getInt("version") == 8) {
            index = lines.indexOf("version: 8");
            lines.set(index, "version: 9");
            lines.removeAll(Arrays.asList("# Coins messages file.",
                    "# If you need support or find a bug open a issuse in",
                    "# the official github repo https://github.com/Beelzebu/Coins/issuses/", "",
                    "# The version of this file, don't edit!"));
            lines.addAll(0,
                    Arrays.asList("# Coins messages file.",
                            "# If you need support or find a bug open a issuse in",
                            "# the official github repo https://github.com/Beelzebu/Coins/issuses/", "",
                            "# The version of this file, is used to auto update this file, don't change it",
                            "# unless you know what you do."));
            core.log("Updated messages.yml file to v9");
        }
        if (core.getMessages("").getInt("version") == 9) {
            index = lines.indexOf("version: 9");
            lines.set(index, "version: 10");
            index = lines.indexOf(
                    "  Multiplier Create: '" + core.getMessages("").getString("Help.Multiplier Create") + "'")
                    + 1;
            lines.add(index,
                    "  Multiplier Set: '%prefix% &cPlease use &f/coins multiplier set <amount> <enabler> <minutes> (server)'");
            lines.addAll(Arrays.asList("  Set:",
                    "  - '%prefix% A multiplier with the following data was set for %server%'",
                    "  - '  &7Enabler: &c%enabler%'", "  - '  &7Amount: &c%amount%'",
                    "  - '  &7Minutes: &c%minutes%'"));
            core.log("Updated messages.yml file to v10");
        }
        FileUtils.writeLines(messagesFiles.get("default"), lines);
    } catch (IOException ex) {
        core.log("An unexpected error occurred while updating the messages.yml file.");
        core.debug(ex.getMessage());
    }
    try {
        List<String> lines = FileUtils.readLines(messagesFiles.get("es"), Charsets.UTF_8);
        int index;
        if (core.getMessages("es").getInt("version") == 6) {
            index = lines.indexOf("version: 6");
            lines.set(index, "version: 7");
            index = lines.indexOf("Multipliers:");
            lines.remove(index);
            index = lines.indexOf("  Menu:");
            lines.add(index, "Multipliers:");
            core.log("Updated messages_es.yml file to v7");
        }
        if (core.getMessages("es").getInt("version") == 7) {
            index = lines.indexOf("version: 7");
            lines.set(index, "version: 8");
            index = lines.indexOf("  Menu:") + 2;
            lines.addAll(index, Arrays.asList("    Confirm:", "      Title: '&8Ests seguro?'",
                    "      Accept: '&aSI!'", "      Decline: '&cNo'", "    Multipliers:",
                    "      Name: '&6Multiplicador &cx%amount%'", "      Lore:", "      - ''",
                    "      - '&7Cantidad: &c%amount%'", "      - '&7Servidor: &c%server%'",
                    "      - '&7Minutos: &c%minutes%'", "      - ''", "      - '&7ID: &c#%id%'",
                    "    No Multipliers:", "      Name: '&cNo tienes ningn multiplicador :('", "      Lore:",
                    "      - ''", "      - '&7Puedes comprar multiplicadores en nuestra tienda'",
                    "      - '&6&nstore.servername.net'"));
            core.log("Updated messages_es.yml file to v8");
        }
        index = lines.indexOf("      - '&6&nstore.servername.net'\"");
        if (index != -1) {
            lines.set(index, "      - '&6&nstore.servername.net'");
        }
        if (core.getMessages("es").getInt("version") == 8) {
            index = lines.indexOf("version: 8");
            lines.set(index, "version: 9");
            lines.removeAll(Arrays.asList("# Coins messages file.",
                    "# If you need support or find a bug open a issuse in",
                    "# the official github repo https://github.com/Beelzebu/Coins/issuses/", "",
                    "# The version of this file, don't edit!"));
            lines.addAll(0, Arrays.asList("# Coins messages file.",
                    "# Si necesitas soporte o encuentras un error por favor abre un ticket en el",
                    "# repositorio oficial de github https://github.com/Beelzebu/Coins/issuses/", "",
                    "# La versin de este archivo, es usado para actualizarlo automticamente, no lo cambies",
                    "# a menos que sepas lo que haces."));
            core.log("Updated messages_es.yml file to v9");
        }
        if (core.getMessages("es").getInt("version") == 9) {
            index = lines.indexOf("version: 9");
            lines.set(index, "version: 10");
            index = lines.indexOf(
                    "  Multiplier Create: '" + core.getMessages("es").getString("Help.Multiplier Create") + "'")
                    + 1;
            lines.add(index,
                    "  Multiplier Set: '%prefix% &cPor favor usa &f/coins multiplier set <cantidad> <activador> <minutos> (server)'");
            lines.addAll(Arrays.asList("  Set:",
                    "  - '%prefix% Un multiplicador con la siguiente informacin fue establecido en %server%'",
                    "  - '  &7Activador: &c%enabler%'", "  - '  &7Cantidad: &c%amount%'",
                    "  - '  &7Minutos: &c%minutes%'"));
            core.log("Updated messages_es.yml file to v10");
        }
        if (lines.get(0).startsWith("  Multiplier Set:")) {
            lines.remove(0);
            index = lines.indexOf(
                    "  Multiplier Create: '" + core.getMessages("es").getString("Help.Multiplier Create") + "'")
                    + 1;
            lines.add(index,
                    "  Multiplier Set: '%prefix% &cPor favor usa &f/coins multiplier set <cantidad> <activador> <minutos> (server)'");
        }
        FileUtils.writeLines(messagesFiles.get("es"), lines);
    } catch (IOException ex) {
        core.log("An unexpected error occurred while updating the messages_es.yml file.");
        core.debug(ex.getMessage());
    }
}