Example usage for org.apache.wicket.ajax.markup.html AjaxLink add

List of usage examples for org.apache.wicket.ajax.markup.html AjaxLink add

Introduction

In this page you can find the example usage for org.apache.wicket.ajax.markup.html AjaxLink add.

Prototype

public MarkupContainer add(final Component... children) 

Source Link

Document

Adds the child component(s) to this container.

Usage

From source file:org.patientview.radar.web.panels.alport.MedicinePanel.java

License:Open Source License

private WebMarkupContainer createMedicineList() {
    final WebMarkupContainer medicinesContainer = new WebMarkupContainer("medicinesContainer");
    medicinesContainer.setOutputMarkupId(true);
    medicinesContainer.setOutputMarkupPlaceholderTag(true);

    final IModel<List<Medicine>> medicinesModel = new AbstractReadOnlyModel<List<Medicine>>() {
        @Override/*from   w  ww. j  a va 2  s  . c om*/
        public List<Medicine> getObject() {
            return medicineManager.getMedicines(patient, diseaseGroup);
        }
    };

    ListView<Medicine> medicines = new ListView<Medicine>("medicines", medicinesModel) {
        @Override
        protected void populateItem(ListItem<Medicine> item) {
            final Medicine medicine = item.getModelObject();

            item.add(new Label("name", medicine.getName()));
            item.add(new Label("dose", medicine.getDose()));
            item.add(DateLabel.forDatePattern("startDate", new PropertyModel<Date>(medicine, "startDate"),
                    RadarApplication.DATE_PATTERN));
            item.add(DateLabel.forDatePattern("endDate", new PropertyModel<Date>(medicine, "endDate"),
                    RadarApplication.DATE_PATTERN));

            AjaxLink ajaxLink = new AjaxLink("deleteLink") {
                @Override
                public void onClick(AjaxRequestTarget ajaxRequestTarget) {
                    medicineManager.delete(medicine);
                    ajaxRequestTarget.add(medicinesContainer);
                }
            };
            ajaxLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());
            item.add(ajaxLink);

            AjaxLink ajaxEditLink = new AjaxLink("editLink") {
                @Override
                public void onClick(AjaxRequestTarget ajaxRequestTarget) {
                    editMedicineIModel.setObject(medicine);
                    ajaxRequestTarget.add(editMedicineForm);
                    ajaxRequestTarget.add(editMedicineContainer);
                }
            };
            item.add(ajaxEditLink);
        }
    };

    medicinesContainer.add(medicines);

    return medicinesContainer;
}

From source file:org.patientview.radar.web.panels.followup.RrtTherapyPanel.java

License:Open Source License

public RrtTherapyPanel(String id, final IModel<Long> radarNumberModel) {
    super(id);//  w w  w  .j a  v a 2  s . c o m
    setOutputMarkupId(true);
    setOutputMarkupPlaceholderTag(true);

    // General details
    TextField radarNumber = new TextField("radarNumber", radarNumberModel);
    radarNumber.setEnabled(false);
    add(radarNumber);

    add(new TextField("hospitalNumber",
            RadarModelFactory.getHospitalNumberModel(radarNumberModel, patientManager)));

    add(new TextField("diagnosis", new PropertyModel(
            RadarModelFactory.getDiagnosisCodeModel(radarNumberModel, diagnosisManager), "abbreviation")));

    add(new TextField("firstName", RadarModelFactory.getFirstNameModel(radarNumberModel, patientManager)));
    add(new TextField("surname", RadarModelFactory.getSurnameModel(radarNumberModel, patientManager)));
    add(new DateTextField("dob", RadarModelFactory.getDobModel(radarNumberModel, patientManager),
            RadarApplication.DATE_PATTERN));

    final IModel<Date> esrfDateModel = new LoadableDetachableModel<Date>() {
        @Override
        protected Date load() {
            Diagnosis diagnosis = RadarModelFactory.getDiagnosisModel(radarNumberModel, diagnosisManager)
                    .getObject();
            if (diagnosis != null) {
                return diagnosis.getEsrfDate();
            }
            return null;
        }
    };
    add(new DateLabel("esrfDate", esrfDateModel,
            new PatternDateConverter(RadarApplication.DATE_PATTERN, true)) {
        @Override
        public boolean isVisible() {
            return esrfDateModel.getObject() != null;
        }
    });
    add(new WebMarkupContainer("esrfNotEnteredContainer") {
        @Override
        public boolean isVisible() {
            return esrfDateModel.getObject() == null;
        }
    });

    // Reusable panel for the dialysis table
    add(new DialysisTablePanel("dialysisContainer", radarNumberModel));

    final IModel transplantListModel = new AbstractReadOnlyModel<List>() {
        @Override
        public List getObject() {

            if (radarNumberModel.getObject() != null) {
                return transplantManager.getTransplantsByRadarNumber(radarNumberModel.getObject());
            }
            return Collections.emptyList();

        }
    };

    final IModel editTransplantModel = new Model<Transplant>();
    final List<Component> addTransplantFormComponentsToUpdate = new ArrayList<Component>();
    final List<Component> editTransplantFormComponentsToUpdate = new ArrayList<Component>();

    final WebMarkupContainer transplantsContainer = new WebMarkupContainer("transplantsContainer");
    add(transplantsContainer);
    transplantsContainer.setOutputMarkupPlaceholderTag(true);
    transplantsContainer.setOutputMarkupId(true);

    // Container for edit transplants
    final MarkupContainer editTransplantContainer = new WebMarkupContainer("editTransplantContainer") {
        @Override
        public boolean isVisible() {
            return editTransplantModel.getObject() != null;
        }
    };

    editTransplantContainer.setOutputMarkupPlaceholderTag(true);
    editTransplantContainer.setOutputMarkupPlaceholderTag(true);
    add(editTransplantContainer);

    final IModel<Transplant.RejectData> addRejectModel = new CompoundPropertyModel<Transplant.RejectData>(
            new Model<Transplant.RejectData>());
    // Container for reject transplants
    final MarkupContainer rejectDataContainer = new WebMarkupContainer("rejectDataContainer") {
        @Override
        public boolean isVisible() {
            return addRejectModel.getObject() != null;
        }
    };
    rejectDataContainer.setOutputMarkupPlaceholderTag(true);
    rejectDataContainer.setOutputMarkupId(true);

    add(rejectDataContainer);

    // Transplants table
    transplantsContainer.add(new ListView<Transplant>("transplants", transplantListModel) {
        @Override
        protected void populateItem(final ListItem<Transplant> item) {
            item.setModel(new CompoundPropertyModel<Transplant>(item.getModelObject()));
            item.add(DateLabel.forDatePattern("date", RadarApplication.DATE_PATTERN));
            item.add(new Label("modality.description"));
            item.add(new Label("recurr", new AbstractReadOnlyModel<Object>() {
                @Override
                public Object getObject() {
                    return Boolean.TRUE.equals(item.getModelObject().getRecurr()) ? "yes" : "no";
                }
            }));
            item.add(DateLabel.forDatePattern("dateRecurr", RadarApplication.DATE_PATTERN));
            item.add(DateLabel.forDatePattern("dateFailureRejectData.failureDate",
                    RadarApplication.DATE_PATTERN));

            IModel rejectDataListModel = new AbstractReadOnlyModel<List>() {
                @Override
                public List getObject() {
                    return transplantManager.getRejectDataByTransplantNumber(item.getModelObject().getId());
                }
            };
            final WebMarkupContainer rejectDataListContainer = new WebMarkupContainer(
                    "rejectDataListContainer");
            rejectDataListContainer.setOutputMarkupId(true);
            rejectDataContainer.setOutputMarkupPlaceholderTag(true);
            rejectDataListContainer
                    .add(new ListView<Transplant.RejectData>("rejectDataList", rejectDataListModel) {
                        @Override
                        protected void populateItem(final ListItem<Transplant.RejectData> rejectDataListItem) {
                            rejectDataListItem.setModel(new CompoundPropertyModel<Transplant.RejectData>(
                                    rejectDataListItem.getModelObject()));
                            rejectDataListItem.add(
                                    DateLabel.forDatePattern("rejectedDate", RadarApplication.DATE_PATTERN));
                            rejectDataListItem
                                    .add(DateLabel.forDatePattern("biopsyDate", RadarApplication.DATE_PATTERN));
                            AjaxLink ajaxDeleteLink = new AjaxLink("deleteLink") {
                                @Override
                                public void onClick(AjaxRequestTarget target) {
                                    transplantManager.deleteRejectData(rejectDataListItem.getModelObject());
                                    target.add(rejectDataListContainer);
                                }
                            };
                            rejectDataListItem.add(ajaxDeleteLink);
                            ajaxDeleteLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());

                            AuthenticatedWebSession session = RadarSecuredSession.get();
                            if (session.isSignedIn()) {
                                if (session.getRoles().hasRole(User.ROLE_PATIENT)) {
                                    ajaxDeleteLink.setVisible(false);
                                }
                            }

                        }
                    });

            item.add(rejectDataListContainer);

            // Delete, edit and add reject buttons
            AjaxLink ajaxDeleteLink = new AjaxLink("deleteLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    Transplant transplant = item.getModelObject();
                    transplantManager.deleteTransplant(transplant);
                    target.add(addTransplantFormComponentsToUpdate
                            .toArray(new Component[addTransplantFormComponentsToUpdate.size()]));
                    target.add(transplantsContainer);
                }
            };
            item.add(ajaxDeleteLink);
            ajaxDeleteLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());
            AjaxLink ajaxEditLink = new AjaxLink("editLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    editTransplantModel.setObject(item.getModelObject());
                    target.add(editTransplantContainer);
                }
            };
            item.add(ajaxEditLink);
            AjaxLink ajaxAddRejectLink = new AjaxLink("addRejectLink") {
                {
                    if (item.getModelObject().getDateFailureRejectData() != null) {
                        if (item.getModelObject().getDateFailureRejectData().getFailureDate() != null) {
                            setVisible(false);
                        }
                    }
                }

                @Override
                public void onClick(AjaxRequestTarget target) {
                    Transplant.RejectData rejectData = new Transplant.RejectData();
                    rejectData.setTransplantId(item.getModelObject().getId());
                    addRejectModel.setObject(rejectData);
                    target.add(rejectDataContainer);
                }
            };
            item.add(ajaxAddRejectLink);

            AuthenticatedWebSession session = RadarSecuredSession.get();
            if (session.isSignedIn()) {
                if (session.getRoles().hasRole(User.ROLE_PATIENT)) {
                    ajaxDeleteLink.setVisible(false);
                    ajaxEditLink.setVisible(false);
                    ajaxAddRejectLink.setVisible(false);
                }
            }
        }
    });

    final List<Component> rejectDataComponentsToUpdate = new ArrayList<Component>();
    // Form for adding reject data - model probably needs changing
    Form<Transplant.RejectData> rejectDataForm = new Form<Transplant.RejectData>("form", addRejectModel);
    rejectDataForm.add(new RadarDateTextField("rejectedDate", rejectDataForm, rejectDataComponentsToUpdate));
    rejectDataForm.add(new RadarDateTextField("biopsyDate", rejectDataForm, rejectDataComponentsToUpdate));
    rejectDataForm.add(new AjaxSubmitLink("add") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(rejectDataContainer);
            target.add(transplantsContainer);
            target.add(
                    rejectDataComponentsToUpdate.toArray(new Component[rejectDataComponentsToUpdate.size()]));
            try {
                transplantManager.saveRejectDataWithValidation((Transplant.RejectData) form.getModelObject());
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;

            }
            addRejectModel.setObject(null);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(
                    rejectDataComponentsToUpdate.toArray(new Component[rejectDataComponentsToUpdate.size()]));
        }
    });
    rejectDataForm.add(new AjaxLink("cancel") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            addRejectModel.setObject(null);
            target.add(rejectDataContainer);
        }
    });
    rejectDataForm.add(DateLabel.forDatePattern("transplantDate", new Model<Date>(), "dd/MM/yyyy"));
    rejectDataContainer.add(rejectDataForm);
    rejectDataForm.add(new FeedbackPanel("dateRejectFeedback", new IFeedbackMessageFilter() {
        public boolean accept(FeedbackMessage feedbackMessage) {
            List<String> acceptedErrorMessages = new ArrayList<String>();
            acceptedErrorMessages.addAll(TransplantManager.REJECT_DATA_ERROR_MESSAGES);
            return acceptedErrorMessages.contains(feedbackMessage.getMessage());
        }
    }));

    // Edit transplant form
    Form<Transplant> editTransplantForm = new TransplantForm("form",
            new CompoundPropertyModel<Transplant>(editTransplantModel), editTransplantFormComponentsToUpdate);
    editTransplantContainer.add(editTransplantForm);

    editTransplantForm.add(new AjaxSubmitLink("saveTop") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(editTransplantContainer);
            target.add(transplantsContainer);

            try {
                transplantManager.saveTransplant((Transplant) form.getModelObject());
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }

            editTransplantModel.setObject(null);

        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(editTransplantFormComponentsToUpdate
                    .toArray(new Component[editTransplantFormComponentsToUpdate.size()]));
        }
    });

    editTransplantForm.add(new AjaxLink("cancelTop") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editTransplantModel.setObject(null);
            target.add(editTransplantContainer);
        }
    });

    editTransplantForm.add(new AjaxSubmitLink("saveBottom") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(editTransplantContainer);
            target.add(transplantsContainer);

            try {
                transplantManager.saveTransplant((Transplant) form.getModelObject());
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }

            editTransplantModel.setObject(null);

        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(editTransplantFormComponentsToUpdate
                    .toArray(new Component[editTransplantFormComponentsToUpdate.size()]));
        }
    });

    editTransplantForm.add(new AjaxLink("cancelBottom") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editTransplantModel.setObject(null);
            target.add(editTransplantContainer);
        }
    });

    // Add transplant form
    Form<Transplant> addTransplantForm = new TransplantForm("addTransplantForm",
            new CompoundPropertyModel<Transplant>(new Transplant()), addTransplantFormComponentsToUpdate);
    addTransplantForm.add(new AjaxSubmitLink("add") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            target.add(form);
            Transplant transplant = (Transplant) form.getModelObject();
            transplant.setRadarNumber(radarNumberModel.getObject());
            try {
                transplantManager.saveTransplant(transplant);
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }
            form.getModel().setObject(new Transplant());
            transplantsContainer.setVisible(true);
            target.add(transplantsContainer);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(addTransplantFormComponentsToUpdate
                    .toArray(new Component[addTransplantFormComponentsToUpdate.size()]));
        }
    });
    addTransplantForm.setOutputMarkupId(true);
    addTransplantForm.setOutputMarkupPlaceholderTag(true);
    add(addTransplantForm);

}

From source file:org.patientview.radar.web.panels.PlasmaPheresisPanel.java

License:Open Source License

public PlasmaPheresisPanel(String id, final IModel<Long> radarNumberModel) {

    super(id);//from   w  w  w. jav  a 2s .c  o m
    final WebMarkupContainer plasmapheresisContainer = new WebMarkupContainer("plasmapheresisContainer");

    plasmapheresisContainer.setOutputMarkupId(true);
    plasmapheresisContainer.setOutputMarkupPlaceholderTag(true);
    add(plasmapheresisContainer);

    final List<Component> addPlasmapheresisComponentsToUpdate = new ArrayList<Component>();
    final List<Component> editPlasmapheresisComponentsToUpdate = new ArrayList<Component>();

    final IModel plasmapheresisListModel = new AbstractReadOnlyModel<List>() {
        @Override
        public List getObject() {

            if (radarNumberModel.getObject() != null) {
                return plasmapheresisManager.getPlasmapheresisByRadarNumber(radarNumberModel.getObject());
            }
            return Collections.emptyList();
        }
    };

    final IModel editPlasmapheresisModel = new Model<Plasmapheresis>();
    final MarkupContainer editPlasmapheresisContainer = new WebMarkupContainer("editPlasmapheresisContainer") {
        @Override
        public boolean isVisible() {
            return editPlasmapheresisModel.getObject() != null;
        }
    };
    editPlasmapheresisContainer.setOutputMarkupPlaceholderTag(true);
    editPlasmapheresisContainer.setOutputMarkupId(true);

    ListView<Plasmapheresis> plasmapheresisListViewlistView = new ListView<Plasmapheresis>("plasmapheresis",
            plasmapheresisListModel) {
        @Override
        protected void populateItem(final ListItem<Plasmapheresis> item) {
            item.setModel(new CompoundPropertyModel<Plasmapheresis>(item.getModelObject()));
            item.add(DateLabel.forDatePattern("startDate", RadarApplication.DATE_PATTERN));
            item.add(DateLabel.forDatePattern("endDate", RadarApplication.DATE_PATTERN));
            item.add(new Label("plasmapheresisExchanges.name"));
            item.add(new Label("response.label"));
            AjaxLink ajaxDeleteLink = new AjaxLink("deleteLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    Plasmapheresis plasmapheresis = item.getModelObject();
                    plasmapheresisManager.deletePlasmaPheresis(plasmapheresis);
                    target.add(addPlasmapheresisComponentsToUpdate
                            .toArray(new Component[addPlasmapheresisComponentsToUpdate.size()]));
                    target.add(plasmapheresisContainer);
                }
            };
            item.add(ajaxDeleteLink);
            ajaxDeleteLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());
            AjaxLink ajaxEditLink = new AjaxLink("editLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    editPlasmapheresisModel.setObject(item.getModelObject());
                    target.add(editPlasmapheresisContainer);
                }
            };
            item.add(ajaxEditLink);

            AuthenticatedWebSession session = RadarSecuredSession.get();
            if (session.isSignedIn()) {
                if (session.getRoles().hasRole(User.ROLE_PATIENT)) {
                    ajaxDeleteLink.setVisible(false);
                    ajaxEditLink.setVisible(false);
                }
            }
        }
    };
    plasmapheresisContainer.add(plasmapheresisListViewlistView);

    // Add the form
    PlasmapheresisForm editPlasmapheresisForm = new PlasmapheresisForm("editPlasmapheresisForm",
            new CompoundPropertyModel<Plasmapheresis>(editPlasmapheresisModel),
            editPlasmapheresisComponentsToUpdate);

    editPlasmapheresisForm.add(new AjaxSubmitLink("saveTop") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(editPlasmapheresisContainer);
            target.add(plasmapheresisContainer);
            try {
                plasmapheresisManager.savePlasmapheresis((Plasmapheresis) form.getModelObject());
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }
            form.getModel().setObject(null);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(editPlasmapheresisComponentsToUpdate
                    .toArray(new Component[editPlasmapheresisComponentsToUpdate.size()]));
        }
    });

    editPlasmapheresisForm.add(new AjaxLink("cancelTop") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editPlasmapheresisModel.setObject(null);
            target.add(editPlasmapheresisContainer);
        }
    });

    editPlasmapheresisForm.add(new AjaxSubmitLink("saveBottom") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(editPlasmapheresisContainer);
            target.add(plasmapheresisContainer);
            try {
                plasmapheresisManager.savePlasmapheresis((Plasmapheresis) form.getModelObject());
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }
            form.getModel().setObject(null);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(editPlasmapheresisComponentsToUpdate
                    .toArray(new Component[editPlasmapheresisComponentsToUpdate.size()]));
        }
    });
    editPlasmapheresisForm.add(new AjaxLink("cancelBottom") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editPlasmapheresisModel.setObject(null);
            target.add(editPlasmapheresisContainer);
        }
    });

    editPlasmapheresisContainer.add(editPlasmapheresisForm);
    add(editPlasmapheresisContainer);

    // Add the add plasmapheresis form
    PlasmapheresisForm addPlasmapheresisForm = new PlasmapheresisForm("addPlasmapheresisForm",
            new CompoundPropertyModel<Plasmapheresis>(new Plasmapheresis()),
            addPlasmapheresisComponentsToUpdate);

    addPlasmapheresisForm.add(new AjaxSubmitLink("save") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            target.add(addPlasmapheresisComponentsToUpdate
                    .toArray(new Component[addPlasmapheresisComponentsToUpdate.size()]));
            target.add(plasmapheresisContainer);

            Plasmapheresis plasmapheresis = (Plasmapheresis) form.getModelObject();
            plasmapheresis.setRadarNumber(radarNumberModel.getObject());
            try {
                plasmapheresisManager.savePlasmapheresis(plasmapheresis);
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }

            form.getModel().setObject(new Plasmapheresis());
            plasmapheresisContainer.setVisible(true);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(addPlasmapheresisComponentsToUpdate
                    .toArray(new Component[addPlasmapheresisComponentsToUpdate.size()]));
        }
    });
    add(addPlasmapheresisForm);
}

From source file:org.patientview.radar.web.panels.RelapsePanel.java

License:Open Source License

public RelapsePanel(String id, final IModel<Long> radarNumberModel) {
    super(id);//from   w  ww .  jav a2s  .  c  o m
    setOutputMarkupId(true);
    setOutputMarkupPlaceholderTag(true);

    final IModel<Boolean> relapseListVisibilityModel = new Model<Boolean>(false);
    if (radarNumberModel.getObject() != null) {
        relapseListVisibilityModel
                .setObject(!relapseManager.getRelapsesByRadarNumber(radarNumberModel.getObject()).isEmpty());
    }

    final WebMarkupContainer relapseListViewContainer = new WebMarkupContainer("relapseListViewContainer") {
        @Override
        public boolean isVisible() {
            return relapseListVisibilityModel.getObject();
        }
    };

    relapseListViewContainer.setOutputMarkupId(true);
    relapseListViewContainer.setOutputMarkupPlaceholderTag(true);
    add(relapseListViewContainer);

    final List<Component> addRelapseComponentsToUpdate = new ArrayList<Component>();
    final List<Component> editRelapseComponentsToUpdate = new ArrayList<Component>();

    final IModel relapseListModel = new AbstractReadOnlyModel<List>() {
        @Override
        public List getObject() {

            if (radarNumberModel.getObject() != null) {
                return relapseManager.getRelapsesByRadarNumber(radarNumberModel.getObject());
            }
            return Collections.emptyList();
        }
    };

    //
    final IModel editRelapseModel = new Model<Relapse>();
    final MarkupContainer editRelapseContainer = new WebMarkupContainer("editRelapseContainer") {
        @Override
        public boolean isVisible() {
            return editRelapseModel.getObject() != null;
        }
    };
    editRelapseContainer.setOutputMarkupPlaceholderTag(true);
    editRelapseContainer.setOutputMarkupId(true);

    ListView<Relapse> relapseListView = new ListView<Relapse>("relapseListView", relapseListModel) {
        @Override
        protected void populateItem(final ListItem<Relapse> item) {
            item.setModel(new CompoundPropertyModel<Relapse>(item.getModelObject()));
            item.add(DateLabel.forDatePattern("dateOfRelapse", RadarApplication.DATE_PATTERN));
            item.add(new Label("transplantedNative.label"));
            item.add(new Label("viralTrigger"));
            item.add(new Label("immunisationTrigger"));
            item.add(new Label("otherTrigger"));
            item.add(new Label("drug1"));
            item.add(new Label("drug2"));
            item.add(new Label("drug3"));
            item.add(new Label("remissionAchieved.label"));
            item.add(DateLabel.forDatePattern("dateOfRemission", RadarApplication.DATE_PATTERN));

            AjaxLink ajaxDeleteLink = new AjaxLink("delete") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    Relapse relapse = item.getModelObject();
                    relapseManager.deleteRelapse(relapse);
                    target.add(addRelapseComponentsToUpdate
                            .toArray(new Component[addRelapseComponentsToUpdate.size()]));
                    target.add(relapseListViewContainer);
                    relapseListVisibilityModel.setObject(
                            !relapseManager.getRelapsesByRadarNumber(radarNumberModel.getObject()).isEmpty());
                }
            };
            item.add(ajaxDeleteLink);
            ajaxDeleteLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());
            AjaxLink ajaxEditLink = new AjaxLink("edit") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    editRelapseModel.setObject(item.getModelObject());
                    target.add(editRelapseContainer);
                }
            };
            item.add(ajaxEditLink);
            AuthenticatedWebSession session = RadarSecuredSession.get();
            if (session.isSignedIn()) {
                if (session.getRoles().hasRole(User.ROLE_PATIENT)) {
                    ajaxDeleteLink.setVisible(false);
                    ajaxEditLink.setVisible(false);
                }
            }
        }
    };
    relapseListViewContainer.add(relapseListView);

    // General details
    TextField<Long> radarNumber = new TextField<Long>("radarNumber", radarNumberModel);
    radarNumber.setEnabled(false);
    add(radarNumber);

    add(new TextField("hospitalNumber",
            RadarModelFactory.getHospitalNumberModel(radarNumberModel, patientManager)));

    add(new TextField("diagnosis", new PropertyModel(
            RadarModelFactory.getDiagnosisCodeModel(radarNumberModel, diagnosisManager), "abbreviation")));

    add(new TextField("firstName", RadarModelFactory.getFirstNameModel(radarNumberModel, patientManager)));
    add(new TextField("surname", RadarModelFactory.getSurnameModel(radarNumberModel, patientManager)));
    add(new DateTextField("dob", RadarModelFactory.getDobModel(radarNumberModel, patientManager),
            RadarApplication.DATE_PATTERN));

    RelapseForm editRelapseForm = new RelapseForm("editRelapseForm",
            new CompoundPropertyModel<Relapse>(editRelapseModel), editRelapseComponentsToUpdate);

    editRelapseForm.add(new AjaxSubmitLink("saveTop") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            relapseManager.saveRelapse((Relapse) form.getModelObject());
            form.getModel().setObject(null);
            target.add(editRelapseContainer);
            target.add(relapseListViewContainer);
            target.add(form);
            target.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(
                    editRelapseComponentsToUpdate.toArray(new Component[editRelapseComponentsToUpdate.size()]));
        }
    });

    editRelapseForm.add(new AjaxLink("cancelTop") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editRelapseModel.setObject(null);
            target.add(editRelapseContainer);
        }
    });

    editRelapseForm.add(new AjaxSubmitLink("saveBottom") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            relapseManager.saveRelapse((Relapse) form.getModelObject());
            form.getModel().setObject(null);
            target.add(editRelapseContainer);
            target.add(relapseListViewContainer);
            target.add(form);
            target.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(
                    editRelapseComponentsToUpdate.toArray(new Component[editRelapseComponentsToUpdate.size()]));
        }
    });

    editRelapseForm.add(new AjaxLink("cancelBottom") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editRelapseModel.setObject(null);
            target.add(editRelapseContainer);
        }
    });

    editRelapseContainer.add(editRelapseForm);
    add(editRelapseContainer);

    WebMarkupContainer addRelapseFormContainer = new WebMarkupContainer("addRelapseFormContainer");

    Form<Relapse> addRelapseform = new RelapseForm("addRelapseForm",
            new CompoundPropertyModel<Relapse>(new Relapse()), addRelapseComponentsToUpdate);

    addRelapseform.setOutputMarkupId(true);
    addRelapseform.setOutputMarkupPlaceholderTag(true);

    addRelapseform.add(new AjaxSubmitLink("submit") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            Relapse relapse = (Relapse) form.getModelObject();
            relapse.setRadarNumber(radarNumberModel.getObject());
            relapseManager.saveRelapse(relapse);
            target.add(
                    addRelapseComponentsToUpdate.toArray(new Component[addRelapseComponentsToUpdate.size()]));
            relapseListVisibilityModel.setObject(true);
            target.add(relapseListViewContainer);
            form.getModel().setObject(new Relapse());
            target.add(form);
        }

        @Override
        protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
            ajaxRequestTarget.add(
                    addRelapseComponentsToUpdate.toArray(new Component[addRelapseComponentsToUpdate.size()]));

        }
    });

    addRelapseFormContainer.add(addRelapseform);
    add(addRelapseFormContainer);

    PlasmaPheresisPanel plasmaPheresisPanel = new PlasmaPheresisPanel("plasmapheresisPanel", radarNumberModel);
    add(plasmaPheresisPanel);
}

From source file:org.patientview.radar.web.panels.subtabs.TreatmentPanel.java

License:Open Source License

public TreatmentPanel(String id, final IModel<Long> radarNumberModel, boolean firstVisit,
        IModel<Therapy> followingVisitTherapyModel, List<Component> followingVisitComponentsToUpdate) {
    super(id);/*from   ww  w .ja  v  a  2 s .  co m*/

    // Immunosuppression including Monoclonals

    final IModel immunosuppressionTreatmentListModel = new AbstractReadOnlyModel<List>() {
        @Override
        public List getObject() {

            if (radarNumberModel.getObject() != null) {
                return immunosuppressionManager
                        .getImmunosuppressionTreatmentByRadarNumber(radarNumberModel.getObject());
            }
            return Collections.emptyList();

        }
    };

    editImmunosuppressionTreatmentIModel = new Model<ImmunosuppressionTreatment>();

    final List<Component> addImmunoSuppressComponentsToUpdate = new ArrayList<Component>();
    final List<Component> editImmunoSuppressComponentsToUpdate = new ArrayList<Component>();

    final WebMarkupContainer immunosuppressionTreatmentsContainer = new WebMarkupContainer(
            "immunosuppressionTreatmentsContainer");

    // For showing edit from ajax call
    final MarkupContainer editContainer = new WebMarkupContainer("editContainer") {
        @Override
        public boolean isVisible() {
            return editImmunosuppressionTreatmentIModel.getObject() != null;
        }
    };
    editContainer.setOutputMarkupId(true);
    editContainer.setOutputMarkupPlaceholderTag(true);

    ListView<ImmunosuppressionTreatment> immunosuppressionTreatmentListView = new ListView<ImmunosuppressionTreatment>(
            "immunosuppressionTreatments", immunosuppressionTreatmentListModel) {
        @Override
        protected void populateItem(final ListItem<ImmunosuppressionTreatment> item) {
            item.setModel(new CompoundPropertyModel<ImmunosuppressionTreatment>(item.getModelObject()));
            item.add(DateLabel.forDatePattern("startDate", RadarApplication.DATE_PATTERN));
            item.add(DateLabel.forDatePattern("endDate", RadarApplication.DATE_PATTERN));
            item.add(new Label("immunosuppression.description"));
            item.add(new Label("cyclophosphamideTotalDose") {
                @Override
                public boolean isVisible() {
                    return item.getModelObject().getImmunosuppression().getId().equals(CYCLOPHOSPHAMIDE_ID);
                }
            });
            AjaxLink ajaxDeleteLink = new AjaxLink("deleteLink") {
                @Override
                public void onClick(AjaxRequestTarget ajaxRequestTarget) {
                    immunosuppressionManager.deleteImmunosuppressionTreatment(item.getModelObject());
                    ajaxRequestTarget.add(addImmunoSuppressComponentsToUpdate
                            .toArray(new Component[addImmunoSuppressComponentsToUpdate.size()]));
                    ajaxRequestTarget.add(immunosuppressionTreatmentsContainer);
                }
            };
            item.add(ajaxDeleteLink);
            ajaxDeleteLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());
            AjaxLink ajaxEditLink = new AjaxLink("editLink") {
                @Override
                public void onClick(AjaxRequestTarget ajaxRequestTarget) {
                    editImmunosuppressionTreatmentIModel.setObject(item.getModelObject());
                    ajaxRequestTarget.add(editContainer);
                }
            };
            item.add(ajaxEditLink);

            AuthenticatedWebSession session = RadarSecuredSession.get();
            if (session.isSignedIn()) {
                if (session.getRoles().hasRole(User.ROLE_PATIENT)) {
                    ajaxDeleteLink.setVisible(false);
                    ajaxEditLink.setVisible(false);
                }
            }

            immunosuppressionTreatmentsContainer.setVisible(true);
        }
    };

    immunosuppressionTreatmentsContainer.add(immunosuppressionTreatmentListView);
    add(immunosuppressionTreatmentsContainer);

    immunosuppressionTreatmentsContainer.setOutputMarkupId(true);
    immunosuppressionTreatmentsContainer.setOutputMarkupPlaceholderTag(true);

    // Construct the form
    final ImmunosuppressionTreatmentForm addImmunosuppressionForm = new ImmunosuppressionTreatmentForm(
            "addImmunosuppressionForm",
            new CompoundPropertyModel<ImmunosuppressionTreatment>(new ImmunosuppressionTreatment()),
            addImmunoSuppressComponentsToUpdate);

    ImmunosuppressionTreatmentForm editImmunosuppressionForm = new ImmunosuppressionTreatmentForm(
            "editImmunosuppressionForm",
            new CompoundPropertyModel<ImmunosuppressionTreatment>(editImmunosuppressionTreatmentIModel),
            editImmunoSuppressComponentsToUpdate);

    editImmunosuppressionForm.add(new AjaxSubmitLink("saveTop") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            target.add(editContainer);
            target.add(immunosuppressionTreatmentsContainer);
            try {
                immunosuppressionManager
                        .saveImmunosuppressionTreatment((ImmunosuppressionTreatment) form.getModelObject());
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }
            editImmunosuppressionTreatmentIModel.setObject(null);
            addImmunosuppressionForm.clearInput();
            target.add(addImmunosuppressionForm);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(editImmunoSuppressComponentsToUpdate
                    .toArray(new Component[editImmunoSuppressComponentsToUpdate.size()]));
        }
    });

    editImmunosuppressionForm.add(new AjaxLink("cancelTop") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editImmunosuppressionTreatmentIModel.setObject(null);
            target.add(editContainer);
        }
    });

    editImmunosuppressionForm.add(new AjaxSubmitLink("saveBottom") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            target.add(editContainer);
            target.add(immunosuppressionTreatmentsContainer);
            try {
                immunosuppressionManager
                        .saveImmunosuppressionTreatment((ImmunosuppressionTreatment) form.getModelObject());
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }
            editImmunosuppressionTreatmentIModel.setObject(null);
            addImmunosuppressionForm.clearInput();
            target.add(addImmunosuppressionForm);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(editImmunoSuppressComponentsToUpdate
                    .toArray(new Component[editImmunoSuppressComponentsToUpdate.size()]));
        }
    });

    editImmunosuppressionForm.add(new AjaxLink("cancelBottom") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editImmunosuppressionTreatmentIModel.setObject(null);
            target.add(editContainer);
        }
    });

    editContainer.add(editImmunosuppressionForm);

    add(editContainer);

    addImmunosuppressionForm.add(new AjaxSubmitLink("submit") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            target.add(immunosuppressionTreatmentsContainer);
            target.add(addImmunoSuppressComponentsToUpdate
                    .toArray(new Component[addImmunoSuppressComponentsToUpdate.size()]));
            ImmunosuppressionTreatment immunosuppressionTreatment = (ImmunosuppressionTreatment) form
                    .getModelObject();
            immunosuppressionTreatment.setRadarNumber(radarNumberModel.getObject());
            try {
                immunosuppressionManager.saveImmunosuppressionTreatment(immunosuppressionTreatment);
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }
            form.getModel().setObject(new ImmunosuppressionTreatment());
            immunosuppressionTreatmentsContainer.setVisible(true);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(addImmunoSuppressComponentsToUpdate
                    .toArray(new Component[addImmunoSuppressComponentsToUpdate.size()]));
        }
    });
    add(addImmunosuppressionForm);

    // Drugs
    final List<Component> therapyFormComponentsToUpdate = new ArrayList<Component>();

    final CompoundPropertyModel<Therapy> firstVisitTherapyFormModel = new CompoundPropertyModel<Therapy>(
            new LoadableDetachableModel<Therapy>() {
                @Override
                public Therapy load() {
                    Therapy therapyModelObject = null;

                    if (radarNumberModel.getObject() != null) {
                        therapyModelObject = therapyManager
                                .getFirstTherapyByRadarNumber(radarNumberModel.getObject());
                    }

                    if (therapyModelObject == null) {
                        therapyModelObject = new Therapy();
                        therapyModelObject.setSequenceNumber(1);
                    }
                    return therapyModelObject;
                }
            });

    CompoundPropertyModel<Therapy> therapyFormModel;
    if (firstVisit) {
        therapyFormModel = firstVisitTherapyFormModel;
    } else {
        therapyFormModel = new CompoundPropertyModel<Therapy>(followingVisitTherapyModel);
    }

    final Form<Therapy> therapyForm = new Form<Therapy>("therapyForm", therapyFormModel) {
        @Override
        protected void onSubmit() {
            Therapy therapy = getModelObject();
            therapy.setRadarNumber(radarNumberModel.getObject());
            therapyManager.saveTherapy(therapy);
        }
    };

    final IModel<Boolean> isSrnsModel = RadarModelFactory.getIsSrnsModel(radarNumberModel, diagnosisManager);
    IModel firstColumnLabelModel = new LoadableDetachableModel() {
        @Override
        protected Object load() {
            return isSrnsModel.getObject() ? "Prior to Referral" : "Drugs in the 4 weeks after Biopsy";
        }
    };
    Label successLabelTop = RadarComponentFactory.getSuccessMessageLabel("successMessageTop", therapyForm,
            therapyFormComponentsToUpdate);

    Label errorLabelTop = RadarComponentFactory.getErrorMessageLabel("errorMessageTop", therapyForm,
            therapyFormComponentsToUpdate);

    Label successLabelBottom = RadarComponentFactory.getSuccessMessageLabel("successMessageBottom", therapyForm,
            therapyFormComponentsToUpdate);

    Label errorLabelBottom = RadarComponentFactory.getErrorMessageLabel("errorMessageBottom", therapyForm,
            therapyFormComponentsToUpdate);

    RadarRequiredDateTextField treatmentRecordDate = new RadarRequiredDateTextField("treatmentRecordDate",
            therapyForm, therapyFormComponentsToUpdate);

    therapyForm.add(treatmentRecordDate);

    Label firstColumnLabel = new Label("firstColumnLabel", firstColumnLabelModel);
    therapyForm.add(firstColumnLabel);

    WebMarkupContainer currentContainer = new WebMarkupContainer("currentContainer") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    };
    therapyForm.add(currentContainer);

    WebMarkupContainer nsaidContainerParent = new WebMarkupContainer("nsaidContainerParent") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    };
    YesNoRadioGroupPanel nsaidContainer = new YesNoRadioGroupPanel("nsaidContainer", true,
            (CompoundPropertyModel) therapyFormModel, "nsaid");
    nsaidContainerParent.add(nsaidContainer);
    therapyForm.add(nsaidContainerParent);

    nsaidContainerParent.add(new YesNoRadioGroupPanel("nsaidPriorContainer", true,
            (CompoundPropertyModel) therapyFormModel, "nsaidPrior") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    });

    WebMarkupContainer diureticContainerParent = new WebMarkupContainer("diureticContainerParent") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    };
    YesNoRadioGroupPanel diureticContainer = new YesNoRadioGroupPanel("diureticContainer", true,
            (CompoundPropertyModel) therapyFormModel, "diuretic");

    diureticContainerParent.add(diureticContainer);
    therapyForm.add(diureticContainerParent);

    diureticContainerParent.add(new YesNoRadioGroupPanel("diureticPriorContainer", true,
            (CompoundPropertyModel) therapyFormModel, "diureticPrior") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    });

    boolean antihypertensiveToggleInit = (Boolean.FALSE
            .equals(therapyForm.getModelObject().getAntihypertensive())
            && Boolean.FALSE.equals(therapyForm.getModelObject().getAntihypertensivePrior()))
            || (therapyForm.getModelObject().getAntihypertensive() == null
                    && therapyForm.getModelObject().getAntihypertensivePrior() == null) ? false : true;
    final IModel<Boolean> antihypertensiveToggleModel = new Model<Boolean>(antihypertensiveToggleInit);

    AjaxFormChoiceComponentUpdatingBehavior antihypertensiveToggleBehaviour = new AjaxFormChoiceComponentUpdatingBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            antihypertensiveToggleModel.setObject(therapyForm.getModelObject().getAntihypertensive());

            target.add(
                    therapyFormComponentsToUpdate.toArray(new Component[therapyFormComponentsToUpdate.size()]));
        }
    };

    AjaxFormChoiceComponentUpdatingBehavior antihypertensiveToggleBehaviour2 = new AjaxFormChoiceComponentUpdatingBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            antihypertensiveToggleModel.setObject(therapyForm.getModelObject().getAntihypertensivePrior());

            target.add(
                    therapyFormComponentsToUpdate.toArray(new Component[therapyFormComponentsToUpdate.size()]));
        }
    };

    YesNoRadioGroupPanel antihypertensiveContainer = new YesNoRadioGroupPanel("antihypertensiveContainer", true,
            therapyFormModel, "antihypertensive", antihypertensiveToggleBehaviour);
    therapyForm.add(antihypertensiveContainer);

    therapyForm.add(new YesNoRadioGroupPanel("antihypertensivePriorContainer", true, therapyFormModel,
            "antihypertensivePrior", antihypertensiveToggleBehaviour2) {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    });

    WebMarkupContainer aceInhibitorContainer = new WebMarkupContainer("aceInhibitorContainer") {
        @Override
        public boolean isVisible() {
            return antihypertensiveToggleModel.getObject();
        }
    };

    therapyFormComponentsToUpdate.add(aceInhibitorContainer);
    aceInhibitorContainer.setOutputMarkupId(true);
    aceInhibitorContainer.setOutputMarkupPlaceholderTag(true);

    YesNoRadioGroupPanel aceInhibitorRadioGroup = new YesNoRadioGroupPanel("aceInhibitorRadioGroup", true,
            therapyFormModel, "aceInhibitor");
    aceInhibitorContainer.add(aceInhibitorRadioGroup);
    YesNoRadioGroupPanel aceInhibitorPriorRadioGroup = new YesNoRadioGroupPanel("aceInhibitorPriorRadioGroup",
            true, therapyFormModel, "aceInhibitorPrior") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    };
    aceInhibitorContainer.add(aceInhibitorPriorRadioGroup);
    therapyForm.add(aceInhibitorContainer);

    WebMarkupContainer arb1AntagonistContainer = new WebMarkupContainer("arb1AntagonistContainer") {
        @Override
        public boolean isVisible() {
            return antihypertensiveToggleModel.getObject();
        }
    };

    therapyFormComponentsToUpdate.add(arb1AntagonistContainer);
    arb1AntagonistContainer.setOutputMarkupId(true);
    arb1AntagonistContainer.setOutputMarkupPlaceholderTag(true);

    arb1AntagonistContainer.add(
            new YesNoRadioGroupPanel("arb1AntagonistRadioGroup", true, therapyFormModel, "arb1Antagonist"));
    arb1AntagonistContainer.add(new YesNoRadioGroupPanel("arb1AntagonistPriorRadioGroup", true,
            therapyFormModel, "arb1AntagonistPrior") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    });
    therapyForm.add(arb1AntagonistContainer);

    WebMarkupContainer calciumChannelBlockerContainer = new WebMarkupContainer(
            "calciumChannelBlockerContainer") {
        @Override
        public boolean isVisible() {
            return antihypertensiveToggleModel.getObject();
        }
    };
    therapyFormComponentsToUpdate.add(calciumChannelBlockerContainer);
    calciumChannelBlockerContainer.setOutputMarkupId(true);
    calciumChannelBlockerContainer.setOutputMarkupPlaceholderTag(true);

    calciumChannelBlockerContainer.add(new YesNoRadioGroupPanel("calciumChannelBlockerRadioGroup", true,
            therapyFormModel, "calciumChannelBlocker"));
    calciumChannelBlockerContainer.add(new YesNoRadioGroupPanel("calciumChannelBlockerPriorRadioGroup", true,
            therapyFormModel, "calciumChannelBlockerPrior") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    });
    therapyForm.add(calciumChannelBlockerContainer);

    WebMarkupContainer betaBlockerContainer = new WebMarkupContainer("betaBlockerContainer") {
        @Override
        public boolean isVisible() {
            return antihypertensiveToggleModel.getObject();
        }
    };
    therapyFormComponentsToUpdate.add(betaBlockerContainer);
    betaBlockerContainer.setOutputMarkupId(true);
    betaBlockerContainer.setOutputMarkupPlaceholderTag(true);

    betaBlockerContainer
            .add(new YesNoRadioGroupPanel("betaBlockerRadioGroup", true, therapyFormModel, "betaBlocker"));
    betaBlockerContainer.add(
            new YesNoRadioGroupPanel("betaBlockerPriorRadioGroup", true, therapyFormModel, "betaBlockerPrior") {
                @Override
                public boolean isVisible() {
                    return isSrnsModel.getObject();
                }
            });
    therapyForm.add(betaBlockerContainer);

    WebMarkupContainer otherAntihypertensiveContainer = new WebMarkupContainer(
            "otherAntihypertensiveContainer") {
        @Override
        public boolean isVisible() {
            return antihypertensiveToggleModel.getObject();
        }
    };
    therapyFormComponentsToUpdate.add(otherAntihypertensiveContainer);
    otherAntihypertensiveContainer.setOutputMarkupId(true);
    otherAntihypertensiveContainer.setOutputMarkupPlaceholderTag(true);

    otherAntihypertensiveContainer.add(new YesNoRadioGroupPanel("otherAntihypertensiveRadioGroup", true,
            therapyFormModel, "otherAntihypertensive"));
    otherAntihypertensiveContainer.add(new YesNoRadioGroupPanel("otherAntihypertensivePriorRadioGroup", true,
            therapyFormModel, "otherAntihypertensivePrior") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    });
    therapyForm.add(otherAntihypertensiveContainer);

    therapyForm.add(new YesNoRadioGroupPanel("insulinContainer", true, therapyFormModel, "insulin"));
    therapyForm.add(new YesNoRadioGroupPanel("insulinPriorContainer", true, therapyFormModel, "insulinPrior") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    });

    WebMarkupContainer lipidLoweringAgentContainerParent = new WebMarkupContainer(
            "lipidLoweringAgentContainerParent") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    };
    lipidLoweringAgentContainerParent.add(new YesNoRadioGroupPanel("lipidLoweringAgentContainer", true,
            therapyFormModel, "lipidLoweringAgent"));
    lipidLoweringAgentContainerParent.add(new YesNoRadioGroupPanel("lipidLoweringAgentPriorContainer", true,
            therapyFormModel, "lipidLoweringAgentPrior") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    });
    therapyForm.add(lipidLoweringAgentContainerParent);

    therapyForm.add(new YesNoRadioGroupPanel("epoContainer", true, therapyFormModel, "epo"));
    therapyForm.add(new YesNoRadioGroupPanel("epoPriorContainer", true, therapyFormModel, "epoPrior") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    });

    therapyForm.add(new TextField("other1"));

    WebMarkupContainer other1PriorContainer = new WebMarkupContainer("other1PriorContainer") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    };
    other1PriorContainer.add(new TextField("other1Prior"));
    therapyForm.add(other1PriorContainer);

    therapyForm.add(new TextField("other2"));

    WebMarkupContainer other2PriorContainer = new WebMarkupContainer("other2PriorContainer") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    };
    other2PriorContainer.add(new TextField("other2Prior"));
    therapyForm.add(other2PriorContainer);

    therapyForm.add(new TextField("other3"));

    WebMarkupContainer other3PriorContainer = new WebMarkupContainer("other3PriorContainer") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    };
    other3PriorContainer.add(new TextField("other3Prior"));
    therapyForm.add(other3PriorContainer);

    therapyForm.add(new TextField("other4"));

    WebMarkupContainer other4PriorContainer = new WebMarkupContainer("other4PriorContainer") {
        @Override
        public boolean isVisible() {
            return isSrnsModel.getObject();
        }
    };
    other4PriorContainer.add(new TextField("other4Prior"));
    therapyForm.add(other4PriorContainer);

    AjaxSubmitLink saveTop = new AjaxSubmitLink("saveTop", therapyForm) {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(
                    therapyFormComponentsToUpdate.toArray(new Component[therapyFormComponentsToUpdate.size()]));
            target.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(
                    therapyFormComponentsToUpdate.toArray(new Component[therapyFormComponentsToUpdate.size()]));
        }
    };

    therapyForm.add(saveTop);
    add(therapyForm);

    AjaxSubmitLink saveBottom = new AjaxSubmitLink("saveBottom", therapyForm) {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(
                    therapyFormComponentsToUpdate.toArray(new Component[therapyFormComponentsToUpdate.size()]));
            target.appendJavaScript(RadarApplication.FORM_IS_DIRTY_FALSE_SCRIPT);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(
                    therapyFormComponentsToUpdate.toArray(new Component[therapyFormComponentsToUpdate.size()]));
        }
    };

    therapyForm.add(saveBottom);
    add(therapyForm);

    // Plasmapheresis
    PlasmaPheresisPanel plasmaPheresisPanel = new PlasmaPheresisPanel("plasmapheresisPanel", radarNumberModel);
    add(plasmaPheresisPanel);

    DialysisTablePanel dialysisTablePanel = new DialysisTablePanel("dialysisContainer", radarNumberModel);
    dialysisTablePanel.setVisible(firstVisit);
    add(dialysisTablePanel);

    if (!firstVisit) {
        for (Component component : followingVisitComponentsToUpdate) {
            therapyFormComponentsToUpdate.add(component);
        }
    }

}

From source file:org.patientview.radar.web.panels.tables.DialysisTablePanel.java

License:Open Source License

public DialysisTablePanel(String id, final IModel<Long> radarNumberModel) {
    super(id);/*www  .ja va 2  s.  co  m*/

    final IModel dialysisListModel = new AbstractReadOnlyModel<List>() {
        @Override
        public List getObject() {
            if (radarNumberModel.getObject() != null) {
                return treatmentManager.getTreatmentsByRadarNumber(radarNumberModel.getObject());
            }
            return Collections.emptyList();
        }
    };

    final WebMarkupContainer dialysisContainer = new WebMarkupContainer("dialysisContainer");
    add(dialysisContainer);

    final List<Component> addDialysisFormComponentsToUpdate = new ArrayList<Component>();
    final List<Component> editDialysisFormComponentsToUpdate = new ArrayList<Component>();

    final IModel editDialysisModel = new Model<Treatment>();

    // Edit dialysis container
    final MarkupContainer editDialysisContainer = new WebMarkupContainer("editDialysisContainer") {
        @Override
        public boolean isVisible() {
            return editDialysisModel.getObject() != null;
        }
    };
    editDialysisContainer.setOutputMarkupPlaceholderTag(true);
    editDialysisContainer.setOutputMarkupPlaceholderTag(true);
    add(editDialysisContainer);

    // Dialysis
    ListView<Treatment> dialysisListView = new ListView<Treatment>("dialysis", dialysisListModel) {
        @Override
        protected void populateItem(final ListItem<Treatment> item) {
            item.setModel(new CompoundPropertyModel<Treatment>(item.getModelObject()));
            item.add(new Label("treatmentModality.description"));
            item.add(DateLabel.forDatePattern("startDate", RadarApplication.DATE_PATTERN));
            item.add(DateLabel.forDatePattern("endDate", RadarApplication.DATE_PATTERN));
            AjaxLink ajaxDeleteLink = new AjaxLink("deleteLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    Treatment treatment = item.getModelObject();
                    treatmentManager.deleteTreatment(treatment);
                    target.add(addDialysisFormComponentsToUpdate
                            .toArray(new Component[addDialysisFormComponentsToUpdate.size()]));
                    target.add(dialysisContainer);

                }
            };
            item.add(ajaxDeleteLink);
            ajaxDeleteLink.add(RadarBehaviourFactory.getDeleteConfirmationBehaviour());
            AjaxLink ajaxEditLink = new AjaxLink("editLink") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    editDialysisModel.setObject(item.getModelObject());
                    target.add(editDialysisContainer);
                }
            };
            item.add(ajaxEditLink);

            AuthenticatedWebSession session = RadarSecuredSession.get();
            if (session.isSignedIn()) {
                if (session.getRoles().hasRole(User.ROLE_PATIENT)) {
                    ajaxDeleteLink.setVisible(false);
                    ajaxEditLink.setVisible(false);
                }
            }
        }
    };
    dialysisContainer.setOutputMarkupId(true);
    dialysisContainer.setOutputMarkupPlaceholderTag(true);
    dialysisContainer.add(dialysisListView);

    DialysisForm editDialysisForm = new DialysisForm("editDialysisForm",
            new CompoundPropertyModel<Treatment>(editDialysisModel), editDialysisFormComponentsToUpdate);

    editDialysisForm.add(new AjaxSubmitLink("saveTop") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(editDialysisContainer);
            target.add(dialysisContainer);
            try {
                treatmentManager.saveTreatment((Treatment) form.getModelObject());
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }
            form.getModel().setObject(null);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(editDialysisFormComponentsToUpdate
                    .toArray(new Component[editDialysisFormComponentsToUpdate.size()]));
        }
    });

    editDialysisForm.add(new AjaxLink("cancelTop") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editDialysisModel.setObject(null);
            target.add(editDialysisContainer);
        }
    });

    editDialysisForm.add(new AjaxSubmitLink("saveBottom") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            target.add(editDialysisContainer);
            target.add(dialysisContainer);
            try {
                treatmentManager.saveTreatment((Treatment) form.getModelObject());
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }
            form.getModel().setObject(null);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(editDialysisFormComponentsToUpdate
                    .toArray(new Component[editDialysisFormComponentsToUpdate.size()]));
        }
    });

    editDialysisForm.add(new AjaxLink("cancelBottom") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            editDialysisModel.setObject(null);
            target.add(editDialysisContainer);
        }
    });

    editDialysisContainer.add(editDialysisForm);

    // Add dialysis form
    DialysisForm addDialysisForm = new DialysisForm("addDialysisForm",
            new CompoundPropertyModel<Treatment>(new Treatment()), addDialysisFormComponentsToUpdate);
    addDialysisForm.add(new AjaxSubmitLink("save") {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            target.add(addDialysisFormComponentsToUpdate
                    .toArray(new Component[addDialysisFormComponentsToUpdate.size()]));
            target.add(dialysisContainer);
            Treatment treatment = (Treatment) form.getModelObject();
            treatment.setRadarNumber(radarNumberModel.getObject());
            try {
                treatmentManager.saveTreatment(treatment);
            } catch (InvalidModelException e) {
                for (String error : e.getErrors()) {
                    error(error);
                }
                return;
            }

            form.getModel().setObject(new Treatment());
            dialysisContainer.setVisible(true);

        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(addDialysisFormComponentsToUpdate
                    .toArray(new Component[addDialysisFormComponentsToUpdate.size()]));
        }
    });
    add(addDialysisForm);
}

From source file:org.sakaiproject.attendance.tool.pages.Overview.java

License:Educational Community License

private void createTable() {
    EventDataProvider eventDataProvider = new EventDataProvider();
    DataView<AttendanceEvent> attendanceEventDataView = new DataView<AttendanceEvent>("events",
            eventDataProvider) {//w  w  w . j  a v  a  2  s . co  m
        @Override
        protected void populateItem(final Item<AttendanceEvent> item) {
            final AttendanceEvent modelObject = item.getModelObject();
            final String name = modelObject.getName();
            final AttendanceItemStats itemStats = attendanceLogic.getStatsForEvent(modelObject);
            Link<Void> eventLink = new Link<Void>("event-link") {
                private static final long serialVersionUID = 1L;

                public void onClick() {
                    setResponsePage(new EventView(modelObject, BasePage.OVERVIEW_PAGE));
                }
            };
            eventLink.add(new Label("event-name", name));

            item.add(eventLink);
            item.add(new Label("event-date", modelObject.getStartDateTime()));

            DataView<AttendanceStatus> activeStatusStats = new DataView<AttendanceStatus>("active-status-stats",
                    attendanceStatusProvider) {
                @Override
                protected void populateItem(Item<AttendanceStatus> item) {
                    Status status = item.getModelObject().getStatus();
                    int stat = attendanceLogic.getStatsForStatus(itemStats, status);
                    item.add(new Label("event-stats", stat));
                }
            };
            item.add(activeStatusStats);

            final AjaxLink eventEditLink = getAddEditWindowAjaxLink(modelObject, "event-edit-link");
            eventEditLink.add(new Label("event-edit-alt",
                    new StringResourceModel("attendance.icon.edit.alt", null, new String[] { name })));
            item.add(eventEditLink);

            final AjaxLink printLink = new AjaxLink<Void>("print-link") {
                @Override
                public void onClick(AjaxRequestTarget ajaxRequestTarget) {
                    printPanel = new PrintPanel("print-panel", item.getModel());
                    printContainer.setOutputMarkupId(true);
                    printContainer.addOrReplace(printPanel);
                    printHiddenClass.setObject("printVisible");
                    ajaxRequestTarget.add(printContainer);
                }
            };
            printLink.add(new Label("event-print-alt",
                    new StringResourceModel("attendance.icon.print.event.alt", null, new String[] { name })));
            item.add(printLink);
        }
    };
    add(attendanceEventDataView);

    // Create empty table placeholder and make visible based on empty data provider
    Label noEvents = new Label("no-events", getString("attendance.overview.no.items"));
    noEvents.setEscapeModelStrings(false);

    if (eventDataProvider.size() > 0) {
        noEvents.setVisible(false);
    }

    add(noEvents);
}

From source file:org.sakaiproject.dash.tool.panels.CalendarLinksPanel.java

License:Educational Community License

/**
 * //from  w  ww . ja va  2 s .c o m
 */
protected void initPanel() {

    if (selectedCalendarTab == null) {
        selectedCalendarTab = TAB_ID_UPCOMING;
    }

    if (this.calendarLinksDivId != null) {
        this.remove(calendarLinksDivId);
    }

    ResourceLoader rl = new ResourceLoader("dash_entity");

    final WebMarkupContainer calendarLinksDiv = new WebMarkupContainer("calendarLinksDiv");
    calendarLinksDiv.setOutputMarkupId(true);
    add(calendarLinksDiv);
    this.calendarLinksDivId = calendarLinksDiv.getId();

    calendarLinksDiv.add(new Label("calendarTitle", rl.getString("dash.calendar.title")));

    AjaxLink<IModel<List<CalendarLink>>> upcomingCalendarLink = new AjaxLink<IModel<List<CalendarLink>>>(
            "link") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            logger.debug("upcomingCalendarLink onClick called");
            // set currentCalendarTab to "upcoming"
            selectedCalendarTab = TAB_ID_UPCOMING;
            // reset calendar dataview to show upcoming stuff
            if (calendarLinksProvider == null) {
                calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
            } else {
                calendarLinksProvider.setCalendarTab(selectedCalendarTab);
            }

            // refresh calendarItemsDiv
            initPanel();
            target.addComponent(CalendarLinksPanel.this);
            target.appendJavascript("resizeFrame('grow');");
            target.appendJavascript("$('#schedPanel').focus();");
            dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING,
                    "/dashboard/calendar/upcoming");
        }

    };

    upcomingCalendarLink.add(new Label("label", rl.getString("dash.calendar.upcoming")));
    WebMarkupContainer upcomingCalendarTab = new WebMarkupContainer("upcomingCalendarTab");
    if (selectedCalendarTab == null || TAB_ID_UPCOMING.equalsIgnoreCase(selectedCalendarTab)) {
        upcomingCalendarTab.add(new SimpleAttributeModifier("class", "activeTab"));
    }
    upcomingCalendarTab.add(upcomingCalendarLink);
    calendarLinksDiv.add(upcomingCalendarTab);

    AjaxLink<IModel<List<CalendarLink>>> pastCalendarLink = new AjaxLink<IModel<List<CalendarLink>>>("link") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            logger.debug("pastCalendarLink onClick called");
            // set currentCalendarTab to "past"
            selectedCalendarTab = TAB_ID_PAST;

            // reset calendar dataview to show past stuff
            if (calendarLinksProvider == null) {
                calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
            } else {
                calendarLinksProvider.setCalendarTab(selectedCalendarTab);
            }

            // refresh calendarItemsDiv
            initPanel();
            target.addComponent(CalendarLinksPanel.this);
            target.appendJavascript("resizeFrame('grow');");
            target.appendJavascript("$('#schedPanel').focus();");
            dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING,
                    "/dashboard/calendar/past");
        }

    };
    pastCalendarLink.add(new Label("label", rl.getString("dash.calendar.past")));
    WebMarkupContainer pastCalendarTab = new WebMarkupContainer("pastCalendarTab");
    if (selectedCalendarTab != null && TAB_ID_PAST.equalsIgnoreCase(selectedCalendarTab)) {
        pastCalendarTab.add(new SimpleAttributeModifier("class", "activeTab"));
    }
    pastCalendarTab.add(pastCalendarLink);
    calendarLinksDiv.add(pastCalendarTab);

    AjaxLink<IModel<List<CalendarLink>>> starredCalendarLink = new AjaxLink<IModel<List<CalendarLink>>>(
            "link") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            logger.debug("starredCalendarLink onClick called");
            // set currentCalendarTab to "starred"
            selectedCalendarTab = TAB_ID_STARRED;

            // reset calendar dataview to show starred stuff
            if (calendarLinksProvider == null) {
                calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
            } else {
                calendarLinksProvider.setCalendarTab(selectedCalendarTab);
            }

            // refresh calendarItemsDiv
            initPanel();
            target.addComponent(CalendarLinksPanel.this);
            target.appendJavascript("resizeFrame('grow');");
            target.appendJavascript("$('#schedPanel').focus();");
            dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING,
                    "/dashboard/calendar/starred");
        }

    };
    starredCalendarLink.add(new Label("label", rl.getString("dash.calendar.starred")));
    WebMarkupContainer starredCalendarTab = new WebMarkupContainer("starredCalendarTab");
    if (selectedCalendarTab != null && TAB_ID_STARRED.equalsIgnoreCase(selectedCalendarTab)) {
        starredCalendarTab.add(new SimpleAttributeModifier("class", "activeTab"));
    }
    starredCalendarTab.add(starredCalendarLink);
    calendarLinksDiv.add(starredCalendarTab);

    AjaxLink<IModel<List<CalendarLink>>> hiddenCalendarLink = new AjaxLink<IModel<List<CalendarLink>>>("link") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            logger.debug("hiddenCalendarLink onClick called");
            // set currentCalendarTab to "hidden"
            selectedCalendarTab = TAB_ID_HIDDEN;

            // reset calendar dataview to show hidden stuff
            if (calendarLinksProvider == null) {
                calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
            } else {
                calendarLinksProvider.setCalendarTab(selectedCalendarTab);
            }

            // refresh calendarItemsDiv
            initPanel();
            target.addComponent(CalendarLinksPanel.this);
            target.appendJavascript("resizeFrame('grow');");
            target.appendJavascript("$('#schedPanel').focus();");
            dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING,
                    "/dashboard/calendar/hidden");
        }

    };
    hiddenCalendarLink.add(new Label("label", rl.getString("dash.calendar.hidden")));
    WebMarkupContainer hiddenCalendarTab = new WebMarkupContainer("hiddenCalendarTab");
    if (selectedCalendarTab != null && TAB_ID_HIDDEN.equalsIgnoreCase(selectedCalendarTab)) {
        hiddenCalendarTab.add(new SimpleAttributeModifier("class", "activeTab"));
    }
    hiddenCalendarTab.add(hiddenCalendarLink);
    calendarLinksDiv.add(hiddenCalendarTab);

    if (calendarLinksProvider == null) {
        calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
    } else {
        calendarLinksProvider.setCalendarTab(selectedCalendarTab);
    }

    WebMarkupContainer haveLinks = new WebMarkupContainer("haveLinks");
    calendarLinksDiv.add(haveLinks);

    //present the calendar data in a table
    final DataView<CalendarLink> calendarDataView = new DataView<CalendarLink>("calendarItems",
            calendarLinksProvider) {

        @Override
        public void populateItem(final Item item) {
            if (item != null && item.getModelObject() != null) {
                item.setOutputMarkupId(true);
                ResourceLoader rl = new ResourceLoader("dash_entity");

                final CalendarLink cLink = (CalendarLink) item.getModelObject();
                final CalendarItem cItem = cLink.getCalendarItem();

                if (logger.isDebugEnabled()) {
                    logger.debug(this + "populateItem()  item: " + item);
                }

                String itemType = cItem.getSourceType().getIdentifier();
                item.add(new Label("itemType", itemType));
                item.add(new Label("itemCount", "1"));
                item.add(new Label("entityReference", cItem.getEntityReference()));
                Component timeLabel = new Label("calendarDate",
                        DateUtil.getCalendarTimeString(cItem.getCalendarTime()));
                timeLabel.add(new AttributeModifier("title", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        // TODO Auto-generated method stub
                        return DateUtil.getFullDateString(cItem.getCalendarTime());
                    }

                }));
                item.add(timeLabel);
                //item.add(new Label("calendarTime", new SimpleDateFormat(TIME_FORMAT).format(cItem.getCalendarTime())));

                Image icon = new Image("icon");
                icon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        // TODO Auto-generated method stub
                        return dashboardCommonLogic.getEntityIconUrl(cItem.getSourceType().getIdentifier(),
                                cItem.getSubtype());
                    }

                }));
                item.add(icon);
                StringBuilder errorMessages = new StringBuilder();
                String title = FormattedText.processFormattedText(cItem.getTitle(), errorMessages, true, true);
                if (errorMessages != null && errorMessages.length() > 0) {
                    logger.warn("Error(s) encountered while cleaning calendarItem title:\n" + errorMessages);
                }
                ExternalLink itemLink = new ExternalLink("itemLink", "#itemEvent");
                itemLink.add(new Label("itemTitle", title));
                itemLink.add(new Label("itemClick", rl.getString("dash.details")));
                item.add(itemLink);

                String calendarItemLabel = dashboardCommonLogic.getString(cItem.getCalendarTimeLabelKey(), "",
                        itemType);
                if (calendarItemLabel == null) {
                    calendarItemLabel = "";
                }
                item.add(new Label("itemLabel", calendarItemLabel));
                item.add(new ExternalLink("siteLink", cItem.getContext().getContextUrl(),
                        cItem.getContext().getContextTitle()));

                if (cLink.isSticky()) {
                    AjaxLink<CalendarLink> starringAction = new AjaxLink<CalendarLink>("starringAction") {
                        protected long calendarItemId = cItem.getId();
                        protected Component thisRow = item;

                        @Override
                        public void onClick(AjaxRequestTarget target) {
                            logger.debug("starringAction onClick() called -- unstar ");
                            // need to keep one item
                            logger.debug(calendarItemId);
                            //logger.debug(this.getModelObject());

                            String sakaiUserId = sakaiProxy.getCurrentUserId();
                            boolean success = dashboardCommonLogic.unkeepCalendarItem(sakaiUserId,
                                    calendarItemId);
                            dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_UNSTAR,
                                    "/dashboard/calendar/" + selectedCalendarTab + "/" + calendarItemId);

                            // if success adjust UI, else report failure?
                            if (success) {
                                target.addComponent(CalendarLinksPanel.this);
                                if (TAB_ID_STARRED.equals(selectedCalendarTab)) {
                                    ResourceLoader rl = new ResourceLoader("dash_entity");

                                    CalendarItem changedItem = dashboardCommonLogic
                                            .getCalendarItem(calendarItemId);
                                    JsonHelper jsonHelper = new JsonHelper(dashboardCommonLogic,
                                            dashboardConfig);
                                    String jsonStr = jsonHelper.getJsonObjectFromCalendarItem(changedItem)
                                            .toString();
                                    String javascript = "reportSuccess('"
                                            + rl.getString("dash.ajax.unstar.success") + "'," + jsonStr + ",'"
                                            + "not-sure-about-url-yet" + "');";
                                    target.appendJavascript(javascript);
                                    target.appendJavascript("resizeFrame('grow');");
                                    target.appendJavascript("$('#schedPanel').focus();");
                                }
                            }
                        }

                    };

                    starringAction.setDefaultModel(item.getModel());
                    item.add(starringAction);

                    Image starringActionIcon = new Image("starringActionIcon");
                    starringActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                        @Override
                        public Object getObject() {
                            return dashboardConfig.getActionIcon(dashboardConfig.ACTION_UNSTAR);
                        }

                    }));
                    starringActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel() {

                        @Override
                        public Object getObject() {
                            ResourceLoader rl = new ResourceLoader("dash_entity");
                            return rl.getString("dash.unstar");
                        }

                    }));
                    starringAction.add(starringActionIcon);
                    //starringAction.add(new Label("starringActionLabel", "Unstar"));

                    if (cLink.isHidden()) {
                        // this shouldn't happen, but just in case ...
                        starringAction.setVisible(false);
                        starringAction.setVisibilityAllowed(false);
                    }
                } else {
                    AjaxLink<CalendarLink> starringAction = new AjaxLink<CalendarLink>("starringAction") {
                        protected long calendarItemId = cItem.getId();
                        protected Component thisRow = item;

                        @Override
                        public void onClick(AjaxRequestTarget target) {
                            logger.debug("starringAction onClick() called -- star ");
                            // need to keep one item
                            logger.debug(calendarItemId);
                            //logger.debug(this.getModelObject());

                            ResourceLoader rl = new ResourceLoader("dash_entity");

                            String sakaiUserId = sakaiProxy.getCurrentUserId();
                            boolean success = dashboardCommonLogic.keepCalendarItem(sakaiUserId,
                                    calendarItemId);
                            dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_STAR,
                                    "/dashboard/calendar/" + selectedCalendarTab + "/" + calendarItemId);

                            // if success adjust UI, else report failure?
                            if (success) {
                                target.addComponent(CalendarLinksPanel.this);
                                //String javascript = "alert('success. (" + thisRow.getMarkupId() + ")');";
                                //target.appendJavascript(javascript );
                                target.appendJavascript("resizeFrame('grow');");
                                target.appendJavascript("$('#schedPanel').focus();");
                            }
                        }

                    };
                    Image starringActionIcon = new Image("starringActionIcon");
                    starringActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                        @Override
                        public Object getObject() {
                            return dashboardConfig.getActionIcon(dashboardConfig.ACTION_STAR);
                        }

                    }));
                    starringActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel() {

                        @Override
                        public Object getObject() {
                            ResourceLoader rl = new ResourceLoader("dash_entity");
                            return rl.getString("dash.star");
                        }

                    }));
                    starringAction.add(starringActionIcon);

                    //starringAction.add(new Label("starringActionLabel", "Star"));
                    item.add(starringAction);

                    if (cLink.isHidden()) {
                        starringAction.setVisible(false);
                        starringAction.setVisibilityAllowed(false);
                    }
                }

                if (cLink.isHidden()) {
                    AjaxLink<CalendarLink> hidingAction = new AjaxLink<CalendarLink>("hidingAction") {
                        protected long calendarItemId = cItem.getId();
                        protected Component thisRow = item;

                        @Override
                        public void onClick(AjaxRequestTarget target) {
                            logger.debug("hidingAction onClick() called -- show");
                            // need to trash one item
                            logger.debug(calendarItemId);
                            //logger.debug(this.getModelObject());
                            String sakaiUserId = sakaiProxy.getCurrentUserId();
                            boolean success = dashboardCommonLogic.unhideCalendarItem(sakaiUserId,
                                    calendarItemId);
                            dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_SHOW,
                                    "/dashboard/calendar/" + selectedCalendarTab + "/" + calendarItemId);

                            // if success adjust UI, else report failure?
                            if (success) {
                                ResourceLoader rl = new ResourceLoader("dash_entity");

                                target.addComponent(CalendarLinksPanel.this);
                                CalendarItem changedItem = dashboardCommonLogic.getCalendarItem(calendarItemId);
                                JsonHelper jsonHelper = new JsonHelper(dashboardCommonLogic, dashboardConfig);
                                String jsonStr = jsonHelper.getJsonObjectFromCalendarItem(changedItem)
                                        .toString();
                                String javascript = "reportSuccess('" + rl.getString("dash.ajax.show.success")
                                        + "'," + jsonStr + ",'" + "not-sure-about-url-yet" + "');";
                                target.appendJavascript(javascript);
                                target.appendJavascript("resizeFrame('grow');");
                                target.appendJavascript("$('#schedPanel').focus();");
                            }
                        }

                    };
                    hidingAction.setDefaultModel(item.getModel());
                    //actionHideThisLink.setModelObject(cItem);
                    item.add(hidingAction);
                    Image hidingActionIcon = new Image("hidingActionIcon");
                    hidingActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                        @Override
                        public Object getObject() {
                            return dashboardConfig.getActionIcon(dashboardConfig.ACTION_SHOW);
                        }

                    }));
                    hidingActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel() {

                        @Override
                        public Object getObject() {
                            ResourceLoader rl = new ResourceLoader("dash_entity");
                            return rl.getString("dash.show");
                        }

                    }));
                    hidingAction.add(hidingActionIcon);
                    //hidingAction.add(new Label("hidingActionLabel", "Show"));

                    if (cLink.isSticky() || TAB_ID_PAST.equals(selectedCalendarTab)) {
                        // this shouldn't happen, but just in case ...
                        hidingAction.setVisible(false);
                        hidingAction.setVisibilityAllowed(false);
                    }

                } else {
                    AjaxLink<CalendarLink> hidingAction = new AjaxLink<CalendarLink>("hidingAction") {
                        protected long calendarItemId = cItem.getId();
                        protected Component thisRow = item;

                        @Override
                        public void onClick(AjaxRequestTarget target) {
                            logger.debug("hidingAction onClick() called -- hide");
                            // need to trash one item
                            logger.debug(calendarItemId);
                            //logger.debug(this.getModelObject());
                            String sakaiUserId = sakaiProxy.getCurrentUserId();
                            boolean success = dashboardCommonLogic.hideCalendarItem(sakaiUserId,
                                    calendarItemId);
                            dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_HIDE,
                                    "/dashboard/calendar/" + selectedCalendarTab + "/" + calendarItemId);

                            // if success adjust UI, else report failure?
                            if (success) {
                                ResourceLoader rl = new ResourceLoader("dash_entity");
                                //renderItemCounter(calendarLinksDiv, calendarDataView); 
                                target.addComponent(CalendarLinksPanel.this);

                                CalendarItem changedItem = dashboardCommonLogic.getCalendarItem(calendarItemId);
                                JsonHelper jsonHelper = new JsonHelper(dashboardCommonLogic, dashboardConfig);
                                String jsonStr = jsonHelper.getJsonObjectFromCalendarItem(changedItem)
                                        .toString();
                                String javascript = "reportSuccess('" + rl.getString("dash.ajax.hide.success")
                                        + "'," + jsonStr + ",'" + "not-sure-about-url-yet" + "');";
                                target.appendJavascript(javascript);
                                target.appendJavascript("resizeFrame('grow');");
                                target.appendJavascript("$('#schedPanel').focus();");
                            }
                        }

                    };
                    hidingAction.setDefaultModel(item.getModel());

                    //actionHideThisLink.setModelObject(cItem);
                    item.add(hidingAction);
                    Image hidingActionIcon = new Image("hidingActionIcon");
                    hidingActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                        @Override
                        public Object getObject() {
                            return dashboardConfig.getActionIcon(dashboardConfig.ACTION_HIDE);
                        }

                    }));
                    hidingActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel() {

                        @Override
                        public Object getObject() {
                            ResourceLoader rl = new ResourceLoader("dash_entity");
                            return rl.getString("dash.hide");
                        }

                    }));
                    hidingAction.add(hidingActionIcon);
                    //hidingAction.add(new Label("hidingActionLabel", "Hide"));

                    if (cLink.isSticky() || TAB_ID_PAST.equals(selectedCalendarTab)) {
                        hidingAction.setVisible(false);
                        hidingAction.setVisibilityAllowed(false);
                    }

                }

            }
        }
    };
    calendarDataView.setItemReuseStrategy(new DefaultItemReuseStrategy());
    calendarDataView.setItemsPerPage(pageSize);
    haveLinks.add(calendarDataView);

    IPagingLabelProvider pagingLabelProvider = new IPagingLabelProvider() {

        public String getPageLabel(int page) {
            ResourceLoader rl = new ResourceLoader("dash_entity");

            int itemCount = 0;
            String pagerStatus = "";
            if (calendarDataView != null) {
                int first = 0;
                int last = 0;
                itemCount = calendarDataView.getItemCount();
                int pageSize = calendarDataView.getItemsPerPage();
                if (itemCount > pageSize) {
                    //int page = calendarDataView.getCurrentPage();
                    first = page * pageSize + 1;
                    last = Math.min(itemCount, (page + 1) * pageSize);
                    if (first == last) {
                        pagerStatus = Integer.toString(first);
                    } else {
                        pagerStatus = rl.getFormattedMessage("dash.pager.range",
                                new Object[] { new Integer(first), new Integer(last) });
                    }
                } else if (itemCount > 1) {
                    pagerStatus = rl.getFormattedMessage("dash.pager.range",
                            new Object[] { new Integer(1), new Integer(itemCount) });
                } else if (itemCount > 0) {
                    pagerStatus = "1";
                } else {
                    pagerStatus = "0";
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("getPageLabel() " + pagerStatus);
            }
            return pagerStatus;
        }
    };
    //add a pager to our table, only visible if we have more than 5 items
    calendarLinksDiv.add(new PagingNavigator("calendarNavigator", calendarDataView, pagingLabelProvider) {

        protected int currentPage = 1;

        @Override
        public boolean isVisible() {
            if (calendarLinksProvider != null && calendarLinksProvider.size() > pageSize) {
                return true;
            }
            return false;
        }

        @Override
        public void onBeforeRender() {
            super.onBeforeRender();

            if (this.getPageable().getCurrentPage() != currentPage) {
                dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_PAGING,
                        "/dashboard/calendar/" + selectedCalendarTab);
                currentPage = this.getPageable().getCurrentPage();
            }

            //renderItemCounter(calendarLinksDiv, (DataView<CalendarLink>) getPageable()); 

            //clear the feedback panel messages
            //clearFeedback(feedbackPanel);
        }

    });

    WebMarkupContainer haveNoLinks = new WebMarkupContainer("haveNoLinks");
    calendarLinksDiv.add(haveNoLinks);

    String noCalendarLinksLabel = null;
    if (TAB_ID_UPCOMING.equals(selectedCalendarTab)) {
        noCalendarLinksLabel = rl.getString("dash.calendar.noupcoming");
    } else if (TAB_ID_PAST.equals(selectedCalendarTab)) {
        noCalendarLinksLabel = rl.getString("dash.calendar.nopast");
    } else if (TAB_ID_STARRED.equals(selectedCalendarTab)) {
        noCalendarLinksLabel = rl.getString("dash.calendar.nostarred");
    } else if (TAB_ID_HIDDEN.equals(selectedCalendarTab)) {
        noCalendarLinksLabel = rl.getString("dash.calendar.nohidden");
    }
    haveNoLinks.add(new Label("message", noCalendarLinksLabel));

    //renderItemCounter(calendarLinksDiv, calendarDataView); 

    int itemCount = 0;
    if (calendarDataView != null) {
        itemCount = calendarDataView.getItemCount();
    }

    if (itemCount > 0) {
        // show the haveLinks
        haveLinks.setVisible(true);
        // hide the haveNoLinks
        haveNoLinks.setVisible(false);
    } else {
        // show the haveNoLinks
        haveNoLinks.setVisible(true);
        // hide the haveLinks
        haveLinks.setVisible(false);
    }
}

From source file:org.sakaiproject.dash.tool.panels.MOTDPanel.java

License:Educational Community License

protected void initPanel() {

    if (this.motdDivId != null) {
        this.remove(motdDivId);
    }//from   ww  w . jav  a2  s  . co  m

    ResourceLoader rl = new ResourceLoader("dash_entity");

    //get list of items from db, wrapped in a dataprovider
    motdProvider = new NewsLinksDataProvider();

    final WebMarkupContainer motdDiv = new WebMarkupContainer("motdDiv");
    motdDiv.setOutputMarkupId(true);
    add(motdDiv);
    this.motdDivId = motdDiv.getId();

    motdDiv.add(new Label("motdPanelTitle", rl.getString("dash.motd.title")));

    WebMarkupContainer haveLinks = new WebMarkupContainer("haveLinks");
    motdDiv.add(haveLinks);

    //present the news data in a table
    final DataView<NewsItem> newsDataView = new DataView<NewsItem>("motd", motdProvider) {

        @Override
        public void populateItem(final Item item) {
            item.setOutputMarkupId(true);
            final NewsItem nItem = (NewsItem) item.getModelObject();

            if (logger.isDebugEnabled()) {
                logger.debug(this + "populateItem()  item: " + item);
            }

            String itemType = nItem.getSourceType().getIdentifier();
            item.add(new Label("itemType", itemType));
            item.add(new Label("itemCount", Integer.toString(nItem.getItemCount())));
            item.add(new Label("entityReference", nItem.getEntityReference()));

            String siteTitle = nItem.getContext().getContextTitle();
            StringBuilder errorMessages = new StringBuilder();
            String title = FormattedText.processFormattedText(nItem.getTitle(), errorMessages, true, true);
            if (errorMessages != null && errorMessages.length() > 0) {
                logger.warn("Error(s) encountered while processing newsItem title:\n" + errorMessages);
            }
            item.add(new ExternalLink("itemLink", "#", title));

            Image icon = new Image("icon");
            icon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                @Override
                public Object getObject() {
                    // TODO Auto-generated method stub
                    return dashboardCommonLogic.getEntityIconUrl(nItem.getSourceType().getIdentifier(),
                            nItem.getSubtype());
                }

            }));
            item.add(icon);
            String newsItemLabel = dashboardCommonLogic.getString(nItem.getNewsTimeLabelKey(), "", itemType);
            if (newsItemLabel == null) {
                newsItemLabel = "";
            }
            item.add(new Label("itemLabel", newsItemLabel));
            item.add(new ExternalLink("siteLink", nItem.getContext().getContextUrl(), siteTitle));
            Component timeLabel = new Label("newsTime", DateUtil.getNewsTimeString(nItem.getNewsTime()));
            timeLabel.add(new AttributeModifier("title", true, new AbstractReadOnlyModel() {

                @Override
                public Object getObject() {
                    // TODO Auto-generated method stub
                    return DateUtil.getFullDateString(nItem.getNewsTime());
                }

            }));
            item.add(timeLabel);

            AjaxLink<NewsLink> starringAction = new AjaxLink<NewsLink>("starringAction") {
                protected long newsItemId = nItem.getId();
                protected Component thisRow = item;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    logger.debug("starringAction onClick() called -- star ");
                    // need to keep one item
                    logger.debug(newsItemId);
                    //logger.debug(this.getModelObject());

                    String sakaiUserId = sakaiProxy.getCurrentUserId();
                    boolean success = dashboardCommonLogic.keepNewsItem(sakaiUserId, newsItemId);

                    // if success adjust UI, else report failure?
                    if (success) {
                        target.addComponent(MOTDPanel.this);
                        //String javascript = "alert('success. (" + thisRow.getMarkupId() + ")');";
                        //target.appendJavascript(javascript );
                    }
                    target.appendJavascript("resizeFrame('grow');");
                }

            };
            Image starringActionIcon = new Image("starringActionIcon");
            starringActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                @Override
                public Object getObject() {
                    return "/dashboard-tool/css/img/star-inact.png";
                }

            }));
            starringActionIcon.add(new AttributeModifier("title", true, new AbstractReadOnlyModel() {

                @Override
                public Object getObject() {
                    ResourceLoader rl = new ResourceLoader("dash_entity");
                    return rl.getString("dash.star");
                }

            }));
            starringAction.add(starringActionIcon);
            // starringAction.add(new Label("starringActionLabel", "Star"));
            item.add(starringAction);

        }
    };

    newsDataView.setItemReuseStrategy(new DefaultItemReuseStrategy());
    newsDataView.setItemsPerPage(pageSize);
    haveLinks.add(newsDataView);

    //add a pager to our table, only visible if we have more than 5 items
    motdDiv.add(new PagingNavigator("newsNavigator", newsDataView) {

        @Override
        public boolean isVisible() {
            if (motdProvider.size() > pageSize) {
                return true;
            }
            return false;
        }

        @Override
        public void onBeforeRender() {
            super.onBeforeRender();

            renderItemCounter(motdDiv, newsDataView);

            //clear the feedback panel messages
            //clearFeedback(feedbackPanel);
        }

    });

    WebMarkupContainer haveNoLinks = new WebMarkupContainer("haveNoLinks");
    motdDiv.add(haveNoLinks);

    String noNewsLinksLabel = null;
    noNewsLinksLabel = rl.getString("dash.news.nocurrent");
    haveNoLinks.add(new Label("message", noNewsLinksLabel));

    renderItemCounter(motdDiv, newsDataView);
    int itemCount = 0;
    if (newsDataView != null) {
        itemCount = newsDataView.getItemCount();
    }

    if (itemCount > 0) {
        // show the haveLinks
        haveLinks.setVisible(true);
        // hide the noNewsLinksDiv
        haveNoLinks.setVisible(false);
    } else {
        // show the noNewsLinksDiv
        haveNoLinks.setVisible(true);
        // hide the haveLinks
        haveLinks.setVisible(false);
    }

    if (motdMode != MOTD_MODE_LIST || itemCount < 1) {
        motdDiv.setVisibilityAllowed(false);
        motdDiv.setVisible(false);
    }

}

From source file:org.sakaiproject.dash.tool.panels.NewsLinksPanel.java

License:Educational Community License

protected void initPanel() {

    if (this.selectedNewsTab == null) {
        this.selectedNewsTab = TAB_ID_CURRENT;
    }//from   w  w  w.  j  a  v  a2  s. c om

    if (this.newsLinksDivId != null) {
        this.remove(newsLinksDivId);
    }

    ResourceLoader rl = new ResourceLoader("dash_entity");

    //get list of items from db, wrapped in a dataprovider
    newsLinksProvider = new NewsLinksDataProvider(this.selectedNewsTab);

    final WebMarkupContainer newsLinksDiv = new WebMarkupContainer("newsLinksDiv");
    newsLinksDiv.setOutputMarkupId(true);
    add(newsLinksDiv);
    this.newsLinksDivId = newsLinksDiv.getId();

    newsLinksDiv.add(new Label("newsTitle", rl.getString("dash.news.title")));

    AjaxLink<IModel<List<NewsLink>>> currentNewsLink = new AjaxLink<IModel<List<NewsLink>>>("link") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            if (logger.isDebugEnabled()) {
                logger.debug("currentNewsLink onClick called");
            }
            // set currentNewsTab to "current"
            selectedNewsTab = TAB_ID_CURRENT;
            // reset news dataview to show current stuff
            if (newsLinksProvider == null) {
                newsLinksProvider = new NewsLinksDataProvider(selectedNewsTab);
            } else {
                newsLinksProvider.setNewsTab(selectedNewsTab);
                dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING,
                        "/dashboard/news/" + selectedNewsTab);
            }
            initPanel();

            // refresh newsLinksDiv
            target.addComponent(NewsLinksPanel.this);
            target.appendJavascript("resizeFrame('grow');");
            target.appendJavascript("$('#newsPanel').focus();");
        }

    };

    currentNewsLink.add(new Label("label", rl.getString("dash.news.current")));
    WebMarkupContainer currentNewsTab = new WebMarkupContainer("currentNewsTab");
    if (selectedNewsTab == null || TAB_ID_CURRENT.equalsIgnoreCase(selectedNewsTab)) {
        currentNewsTab.add(new SimpleAttributeModifier("class", "activeTab"));
    }
    currentNewsTab.add(currentNewsLink);
    newsLinksDiv.add(currentNewsTab);

    AjaxLink<IModel<List<NewsLink>>> starredNewsLink = new AjaxLink<IModel<List<NewsLink>>>("link") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            if (logger.isDebugEnabled()) {
                logger.debug("starredNewsLink onClick called");
            }
            // set currentNewsTab to "starred"
            selectedNewsTab = TAB_ID_STARRED;
            // reset news dataview to show starred stuff
            if (newsLinksProvider == null) {
                newsLinksProvider = new NewsLinksDataProvider(selectedNewsTab);
            } else {
                newsLinksProvider.setNewsTab(selectedNewsTab);
                dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING,
                        "/dashboard/news/" + selectedNewsTab);
            }
            initPanel();

            // refresh newsLinksDiv
            target.addComponent(NewsLinksPanel.this);
            target.appendJavascript("resizeFrame('grow');");
            target.appendJavascript("$('#newsPanel').focus();");
        }

    };
    starredNewsLink.add(new Label("label", rl.getString("dash.news.starred")));
    WebMarkupContainer starredNewsTab = new WebMarkupContainer("starredNewsTab");
    if (selectedNewsTab != null && TAB_ID_STARRED.equalsIgnoreCase(selectedNewsTab)) {
        starredNewsTab.add(new SimpleAttributeModifier("class", "activeTab"));
    }
    starredNewsTab.add(starredNewsLink);
    newsLinksDiv.add(starredNewsTab);

    AjaxLink<IModel<List<NewsLink>>> hiddenNewsLink = new AjaxLink<IModel<List<NewsLink>>>("link") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            if (logger.isDebugEnabled()) {
                logger.debug("hiddenNewsLink onClick called");
            }
            // set currentNewsTab to "hidden"
            selectedNewsTab = TAB_ID_HIDDEN;
            // reset news dataview to show hidden stuff
            if (newsLinksProvider == null) {
                newsLinksProvider = new NewsLinksDataProvider(selectedNewsTab);
            } else {
                newsLinksProvider.setNewsTab(selectedNewsTab);
                dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING,
                        "/dashboard/news/" + selectedNewsTab);
            }
            initPanel();

            // refresh newsLinksDiv
            target.addComponent(NewsLinksPanel.this);
            target.appendJavascript("resizeFrame('grow');");
            target.appendJavascript("$('#newsPanel').focus();");
        }

    };
    hiddenNewsLink.add(new Label("label", rl.getString("dash.news.hidden")));
    WebMarkupContainer hiddenNewsTab = new WebMarkupContainer("hiddenNewsTab");
    if (selectedNewsTab != null && TAB_ID_HIDDEN.equalsIgnoreCase(selectedNewsTab)) {
        hiddenNewsTab.add(new SimpleAttributeModifier("class", "activeTab"));
    }
    hiddenNewsTab.add(hiddenNewsLink);
    newsLinksDiv.add(hiddenNewsTab);

    WebMarkupContainer haveLinks = new WebMarkupContainer("haveLinks");
    newsLinksDiv.add(haveLinks);

    //present the news data in a table
    final DataView<NewsLink> newsDataView = new DataView<NewsLink>("newsLinks", newsLinksProvider) {

        @Override
        public void populateItem(final Item item) {
            item.setOutputMarkupId(true);
            ResourceLoader rl = new ResourceLoader("dash_entity");

            final NewsLink nLink = (NewsLink) item.getModelObject();
            final NewsItem nItem = nLink.getNewsItem();

            if (logger.isDebugEnabled()) {
                logger.debug(this + "populateItem()  item: " + item);
            }

            boolean hideActionLinks = nItem.getItemCount() > 1;

            String itemType = nItem.getSourceType().getIdentifier();
            item.add(new Label("itemType", itemType));
            item.add(new Label("itemCount", Integer.toString(nItem.getItemCount())));
            item.add(new Label("entityReference", nItem.getEntityReference()));

            String siteTitle = nItem.getContext().getContextTitle();
            StringBuilder errorMessages = new StringBuilder();
            String title = FormattedText.processFormattedText(nItem.getTitle(), errorMessages, true, true);
            if (errorMessages != null && errorMessages.length() > 0) {
                logger.warn("Error(s) encountered while processing newsItem title:\n" + errorMessages);
            }

            ExternalLink itemLink = new ExternalLink("itemLink", "#itemEvent");
            itemLink.add(new Label("itemTitle", title));
            itemLink.add(new Label("itemClick", rl.getString("dash.details")));
            item.add(itemLink);

            Image icon = new Image("icon");
            icon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                @Override
                public Object getObject() {
                    // TODO Auto-generated method stub
                    return dashboardCommonLogic.getEntityIconUrl(nItem.getSourceType().getIdentifier(),
                            nItem.getSubtype());
                }

            }));
            item.add(icon);
            String newsItemLabel = dashboardCommonLogic.getString(nItem.getNewsTimeLabelKey(), "", itemType);
            if (newsItemLabel == null || hideActionLinks) {
                newsItemLabel = "";
            }
            Label itemLabel = new Label("itemLabel", newsItemLabel);
            if (!"".equals(newsItemLabel)) {
                itemLabel.add(new SimpleAttributeModifier("class", "itemLabel"));
            }
            item.add(itemLabel);
            item.add(new ExternalLink("siteLink", nItem.getContext().getContextUrl(), siteTitle));
            Component timeLabel = new Label("newsTime", DateUtil.getNewsTimeString(nItem.getNewsTime()));
            timeLabel.add(new AttributeModifier("title", true, new AbstractReadOnlyModel() {

                @Override
                public Object getObject() {
                    // TODO Auto-generated method stub
                    return DateUtil.getFullDateString(nItem.getNewsTime());
                }

            }));
            item.add(timeLabel);

            if (nLink.isSticky()) {
                AjaxLink<NewsLink> starringAction = new AjaxLink<NewsLink>("starringAction") {
                    protected long newsItemId = nItem.getId();
                    protected Component thisRow = item;

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        logger.debug("starringAction onClick() called -- unstar ");
                        // need to keep one item
                        logger.debug(newsItemId);
                        //logger.debug(this.getModelObject());

                        String sakaiUserId = sakaiProxy.getCurrentUserId();
                        boolean success = dashboardCommonLogic.unkeepNewsItem(sakaiUserId, newsItemId);
                        dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_UNSTAR,
                                "/dashboard/news/" + selectedNewsTab + "/" + newsItemId);

                        // if success adjust UI, else report failure?
                        if (success) {
                            target.addComponent(NewsLinksPanel.this);
                            if (TAB_ID_STARRED.equals(selectedNewsTab)) {
                                ResourceLoader rl = new ResourceLoader("dash_entity");
                                NewsItem changedItem = dashboardCommonLogic.getNewsItem(newsItemId);
                                JsonHelper jsonHelper = new JsonHelper(dashboardCommonLogic, dashboardConfig);
                                String jsonStr = jsonHelper.getJsonObjectFromNewsItem(changedItem).toString();
                                String javascript = "reportSuccess('" + rl.getString("dash.ajax.unstar.success")
                                        + "'," + jsonStr + ",'" + "not-sure-about-url-yet" + "');";
                                target.appendJavascript(javascript);
                            }
                            target.appendJavascript("resizeFrame('grow');");
                            target.appendJavascript("$('#newsPanel').focus();");
                        }
                    }

                };

                starringAction.setDefaultModel(item.getModel());
                item.add(starringAction);
                Image starringActionIcon = new Image("starringActionIcon");
                starringActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        return dashboardConfig.getActionIcon(dashboardConfig.ACTION_UNSTAR);
                    }

                }));
                starringActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        ResourceLoader rl = new ResourceLoader("dash_entity");
                        return rl.getString("dash.unstar");
                    }

                }));
                starringAction.add(starringActionIcon);

                //starringAction.add(new Label("starringActionLabel", "Unstar"));

                if (nLink.isHidden() || hideActionLinks) {
                    starringAction.setVisible(false);
                    starringAction.setVisibilityAllowed(false);
                }
            } else {
                AjaxLink<NewsLink> starringAction = new AjaxLink<NewsLink>("starringAction") {
                    protected long newsItemId = nItem.getId();
                    protected Component thisRow = item;

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        logger.debug("starringAction onClick() called -- star ");
                        // need to keep one item
                        logger.debug(newsItemId);
                        //logger.debug(this.getModelObject());

                        String sakaiUserId = sakaiProxy.getCurrentUserId();
                        boolean success = dashboardCommonLogic.keepNewsItem(sakaiUserId, newsItemId);
                        dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_STAR,
                                "/dashboard/news/" + selectedNewsTab + "/" + newsItemId);

                        // if success adjust UI, else report failure?
                        if (success) {
                            target.addComponent(NewsLinksPanel.this);
                            //String javascript = "alert('success. (" + thisRow.getMarkupId() + ")');";
                            //target.appendJavascript(javascript );
                        }
                        target.appendJavascript("resizeFrame('grow');");
                        target.appendJavascript("$('#newsPanel').focus();");
                    }

                };
                Image starringActionIcon = new Image("starringActionIcon");
                starringActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        return dashboardConfig.getActionIcon(dashboardConfig.ACTION_STAR);
                    }

                }));
                starringActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        ResourceLoader rl = new ResourceLoader("dash_entity");
                        return rl.getString("dash.star");
                    }

                }));
                starringAction.add(starringActionIcon);
                // starringAction.add(new Label("starringActionLabel", "Star"));
                item.add(starringAction);

                if (nLink.isHidden() || hideActionLinks) {
                    starringAction.setVisible(false);
                    starringAction.setVisibilityAllowed(false);
                }
            }

            if (nLink.isHidden()) {
                AjaxLink<NewsLink> hidingAction = new AjaxLink<NewsLink>("hidingAction") {
                    protected long newsItemId = nItem.getId();
                    protected Component thisRow = item;

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        logger.debug("hidingAction onClick() called -- show");
                        // need to trash one item
                        logger.debug(newsItemId);
                        //logger.debug(this.getModelObject());
                        String sakaiUserId = sakaiProxy.getCurrentUserId();
                        boolean success = dashboardCommonLogic.unhideNewsItem(sakaiUserId, newsItemId);
                        dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_SHOW,
                                "/dashboard/news/" + selectedNewsTab + "/" + newsItemId);

                        // if success adjust UI, else report failure?
                        if (success) {
                            ResourceLoader rl = new ResourceLoader("dash_entity");
                            target.addComponent(NewsLinksPanel.this);
                            NewsItem changedItem = dashboardCommonLogic.getNewsItem(newsItemId);
                            JsonHelper jsonHelper = new JsonHelper(dashboardCommonLogic, dashboardConfig);
                            String jsonStr = jsonHelper.getJsonObjectFromNewsItem(changedItem).toString();
                            String javascript = "reportSuccess('" + rl.getString("dash.ajax.show.success")
                                    + "'," + jsonStr + ",'" + "not-sure-about-url-yet" + "');";
                            target.appendJavascript(javascript);
                        }
                        target.appendJavascript("resizeFrame('grow');");
                        target.appendJavascript("$('#newsPanel').focus();");
                    }

                };
                hidingAction.setDefaultModel(item.getModel());
                //actionHideThisLink.setModelObject(nItem);
                item.add(hidingAction);
                Image hidingActionIcon = new Image("hidingActionIcon");
                hidingActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        return dashboardConfig.getActionIcon(dashboardConfig.ACTION_SHOW);
                    }

                }));
                hidingActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        ResourceLoader rl = new ResourceLoader("dash_entity");
                        return rl.getString("dash.show");
                    }

                }));
                hidingAction.add(hidingActionIcon);
                //hidingAction.add(new Label("hidingActionLabel", "Show"));

                if (nLink.isSticky() || hideActionLinks) {
                    hidingAction.setVisible(false);
                    hidingAction.setVisibilityAllowed(false);
                }

            } else {
                AjaxLink<NewsLink> hidingAction = new AjaxLink<NewsLink>("hidingAction") {
                    protected long newsItemId = nItem.getId();
                    protected Component thisRow = item;

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        logger.debug("hidingAction onClick() called -- hide");
                        // need to trash one item
                        logger.debug(newsItemId);
                        //logger.debug(this.getModelObject());
                        String sakaiUserId = sakaiProxy.getCurrentUserId();
                        boolean success = dashboardCommonLogic.hideNewsItem(sakaiUserId, newsItemId);
                        dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_HIDE,
                                "/dashboard/news/" + selectedNewsTab + "/" + newsItemId);

                        // if success adjust UI, else report failure?
                        if (success) {
                            ResourceLoader rl = new ResourceLoader("dash_entity");
                            target.addComponent(NewsLinksPanel.this);
                            NewsItem changedItem = dashboardCommonLogic.getNewsItem(newsItemId);
                            JsonHelper jsonHelper = new JsonHelper(dashboardCommonLogic, dashboardConfig);
                            String jsonStr = jsonHelper.getJsonObjectFromNewsItem(changedItem).toString();
                            String javascript = "reportSuccess('" + rl.getString("dash.ajax.hide.success")
                                    + "'," + jsonStr + ",'" + "not-sure-about-url-yet" + "');";
                            target.appendJavascript(javascript);
                        }
                        target.appendJavascript("resizeFrame('grow');");
                        target.appendJavascript("$('#newsPanel').focus();");
                    }

                };
                hidingAction.setDefaultModel(item.getModel());

                //actionHideThisLink.setModelObject(nItem);
                item.add(hidingAction);
                Image hidingActionIcon = new Image("hidingActionIcon");
                hidingActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        return dashboardConfig.getActionIcon(dashboardConfig.ACTION_HIDE);
                    }

                }));
                hidingActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel() {

                    @Override
                    public Object getObject() {
                        ResourceLoader rl = new ResourceLoader("dash_entity");
                        return rl.getString("dash.hide");
                    }

                }));
                hidingAction.add(hidingActionIcon);
                //hidingAction.add(new Label("hidingActionLabel", "Hide"));

                if (nLink.isSticky() || hideActionLinks) {
                    hidingAction.setVisible(false);
                    hidingAction.setVisibilityAllowed(false);
                }

            }
        }
    };

    newsDataView.setItemReuseStrategy(new DefaultItemReuseStrategy());
    newsDataView.setItemsPerPage(pageSize);
    haveLinks.add(newsDataView);

    IPagingLabelProvider pagingLabelProvider = new IPagingLabelProvider() {

        public String getPageLabel(int page) {
            ResourceLoader rl = new ResourceLoader("dash_entity");

            int itemCount = 0;
            String pagerStatus = "";
            if (newsDataView != null) {
                int first = 0;
                int last = 0;
                itemCount = newsDataView.getItemCount();
                int pageSize = newsDataView.getItemsPerPage();
                if (itemCount > pageSize) {
                    //int page = calendarDataView.getCurrentPage();
                    first = page * pageSize + 1;
                    last = Math.min(itemCount, (page + 1) * pageSize);
                    if (first == last) {
                        pagerStatus = Integer.toString(first);
                    } else {
                        pagerStatus = rl.getFormattedMessage("dash.pager.range",
                                new Object[] { new Integer(first), new Integer(last) });
                    }
                } else if (itemCount > 1) {
                    pagerStatus = rl.getFormattedMessage("dash.pager.range",
                            new Object[] { new Integer(1), new Integer(itemCount) });
                } else if (itemCount > 0) {
                    pagerStatus = "1";
                } else {
                    pagerStatus = "0";
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("getPageLabel() " + pagerStatus);
            }
            return pagerStatus;
        }
    };

    //add a pager to our table, only visible if we have more than 5 items
    newsLinksDiv.add(new PagingNavigator("newsNavigator", newsDataView, pagingLabelProvider) {

        protected int currentPage = 1;

        @Override
        public boolean isVisible() {
            if (newsLinksProvider.size() > pageSize) {
                return true;
            }
            return false;
        }

        @Override
        public void onBeforeRender() {

            if (this.getPageable().getCurrentPage() != currentPage) {
                dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_PAGING,
                        "/dashboard/news/" + selectedNewsTab);
                currentPage = this.getPageable().getCurrentPage();
            }

            //renderItemCounter(newsLinksDiv, newsDataView);

            //clear the feedback panel messages
            //clearFeedback(feedbackPanel);
            super.onBeforeRender();
        }

    });

    WebMarkupContainer haveNoLinks = new WebMarkupContainer("haveNoLinks");
    newsLinksDiv.add(haveNoLinks);

    String noNewsLinksLabel = null;
    if (TAB_ID_CURRENT.equals(selectedNewsTab)) {
        noNewsLinksLabel = rl.getString("dash.news.nocurrent");
    } else if (TAB_ID_STARRED.equals(selectedNewsTab)) {
        noNewsLinksLabel = rl.getString("dash.news.nostarred");
    } else if (TAB_ID_HIDDEN.equals(selectedNewsTab)) {
        noNewsLinksLabel = rl.getString("dash.news.nohidden");
    }
    haveNoLinks.add(new Label("message", noNewsLinksLabel));

    //renderItemCounter(newsLinksDiv, newsDataView);
    int itemCount = 0;
    if (newsDataView != null) {
        itemCount = newsDataView.getItemCount();
    }

    if (itemCount > 0) {
        // show the haveLinks
        haveLinks.setVisible(true);
        // hide the noNewsLinksDiv
        haveNoLinks.setVisible(false);
    } else {
        // show the noNewsLinksDiv
        haveNoLinks.setVisible(true);
        // hide the haveLinks
        haveLinks.setVisible(false);
    }

}