Example usage for org.apache.wicket.markup.html.link ResourceLink ResourceLink

List of usage examples for org.apache.wicket.markup.html.link ResourceLink ResourceLink

Introduction

In this page you can find the example usage for org.apache.wicket.markup.html.link ResourceLink ResourceLink.

Prototype

public ResourceLink(final String id, final IResource resource) 

Source Link

Document

Constructs a link directly to the provided resource.

Usage

From source file:org.apache.isis.viewer.wicket.ui.components.scalars.isisapplib.IsisBlobOrClobPanelAbstract.java

License:Apache License

private ResourceLink<?> createResourceLink(String id) {
    final T blob = getBlobOrClobFromModel();
    if (blob == null) {
        return null;
    }//from   w  w w.  j  a va2s .  co m
    final IResource bar = newResource(blob);
    return new ResourceLink<Object>(id, bar);
}

From source file:org.cast.cwm.admin.EventLog.java

License:Open Source License

public EventLog(final PageParameters params) {
    super(params);
    setPageTitle("Event Log");

    addFilterForm();//w w  w . j  av a2 s  .c  o m

    OrderingCriteriaBuilder builder = makeCriteriaBuilder();
    SortableHibernateProvider<Event> eventsprovider = makeHibernateProvider(builder);
    List<IDataColumn<Event>> columns = makeColumns();
    DataTable<Event, String> table = new DataTable<Event, String>("eventtable", columns, eventsprovider, 30);
    table.addTopToolbar(new HeadersToolbar<String>(table, eventsprovider));
    table.addTopToolbar(new NavigationToolbar(table));
    table.addBottomToolbar(new NavigationToolbar(table));
    table.addBottomToolbar(new NoRecordsToolbar(table, new Model<String>("No events found")));
    add(table);

    CSVDownload<Event> download = new CSVDownload<Event>(columns, eventsprovider);
    add(new ResourceLink<Object>("downloadLink", download));
}

From source file:org.cast.cwm.admin.SiteInfoPage.java

License:Open Source License

public SiteInfoPage(PageParameters param) {
    super(param);

    // Current Site
    Long siteId = param.get("siteId").toOptionalLong();
    mSite = siteService.getSiteById(siteId); // May create a Transient Instance
    if (siteId != null && mSite.getObject() == null)
        throw new RestartResponseAtInterceptPageException(adminPageService.getSiteListPage());

    // Breadcrumb link
    add(adminPageService.getSiteListPageLink("siteList"));

    // Directions (Create New vs Existing)
    add(new Label("instructions", new AbstractReadOnlyModel<String>() {

        private static final long serialVersionUID = 1L;

        @Override/*from  w ww . j a v a2  s.c o m*/

        public String getObject() {
            Site s = mSite.getObject();
            return (s == null ? "Create New Site" : "Edit Site: " + s.getName());
        }
    }));

    add(new SiteForm("form", mSite));

    // List Existing Periods
    ListView<Period> list = new ListView<Period>("periodList",
            new PropertyModel<List<Period>>(mSite, "periodsAsSortedReadOnlyList")) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<Period> item) {
            Link link = adminPageService.getPeriodEditPageLink("periodLink", item.getModel());
            item.add(link);
            link.add(new Label("name", item.getModelObject().getName()));

            DeletePersistedObjectDialog<Period> dialog = new DeletePersistedObjectDialog<Period>(
                    "deletePeriodModal", item.getModel()) {

                private static final long serialVersionUID = 1L;

                @Override
                protected void deleteObject() {
                    siteService.deletePeriod(getModel());
                }
            };
            item.add(dialog);
            item.add(new WebMarkupContainer("deletePeriodLink")
                    .add(dialog.getDialogBorder().getClickToOpenBehavior()));
        }
    };
    add(list);

    // Link to create a new Period
    Link createNewPeriod = adminPageService.getNewPeriodEditPageLink("createNewPeriod", mSite);
    createNewPeriod.setVisible(!mSite.getObject().isTransient()); // For Enclosure Visibility
    add(createNewPeriod);

    // Sample CSV File
    add(new ResourceLink<Void>("sampleLink",
            new PackageResourceReference(SiteInfoPage.class, "sample_class_list.csv")));

    // Upload CSV File to populate Site
    add(new UserFileUploadForm("upload-form", mSite));
}

From source file:org.cast.cwm.admin.UserContentLogPage.java

License:Open Source License

public UserContentLogPage(PageParameters parameters) {
    super(parameters);

    addFilterForm();//from   w  ww. j a v  a2 s  .  co  m

    AuditDataProvider<UserContent, DefaultRevisionEntity> provider = getDataProvider();

    List<IDataColumn<AuditTriple<UserContent, DefaultRevisionEntity>>> columns = makeColumns();
    // Annoying to have to make a new List here; DataTable should use <? extends IColumn>.
    ArrayList<IColumn<AuditTriple<UserContent, DefaultRevisionEntity>, String>> colList = new ArrayList<IColumn<AuditTriple<UserContent, DefaultRevisionEntity>, String>>(
            columns);
    DataTable<AuditTriple<UserContent, DefaultRevisionEntity>, String> table = new DataTable<AuditTriple<UserContent, DefaultRevisionEntity>, String>(
            "table", colList, provider, ITEMS_PER_PAGE);

    table.addTopToolbar(new HeadersToolbar<String>(table, provider));
    table.addBottomToolbar(new NavigationToolbar(table));
    table.addBottomToolbar(new NoRecordsToolbar(table, new Model<String>("No revisions found")));
    add(table);

    CSVDownload<AuditTriple<UserContent, DefaultRevisionEntity>> download = new CSVDownload<AuditTriple<UserContent, DefaultRevisionEntity>>(
            columns, provider);
    add(new ResourceLink<Object>("downloadLink", download));

    // Look for a configuration variable with site's URL, called either cwm.url or app.url.
    // If it is set, it is used to make URLs absolute in the downloaded file
    if (Application.get() instanceof CwmApplication) {
        IAppConfiguration config = CwmApplication.get().getConfiguration();
        urlPrefix = config.getString("cwm.url", config.getString("app.url", ""));
    }
}

From source file:org.cast.isi.ISIXmlComponent.java

License:Open Source License

@Override
public Component getDynamicComponent(final String wicketId, final Element elt) {

    if (wicketId.startsWith("object_")) {
        NodeList nodes = elt.getChildNodes();
        String archive = null;/*from ww w  .j a va  2 s .c o m*/
        String dataFile = null;
        for (int i = 0; i < nodes.getLength(); i++) {
            Node nextNode = nodes.item(i);
            if (nextNode instanceof Element) {
                Element next = (Element) nodes.item(i);
                if (next.getAttribute("name").equals("archive")) {
                    archive = next.getAttribute("value");
                } else if (next.getAttribute("name").equals("dataFile")) {
                    dataFile = next.getAttribute("value");
                }
            }
        }
        if (archive != null) {

            String jarUrl = RequestCycle.get().urlFor(getRelativeRef(archive + ".jar"), new PageParameters())
                    .toString();
            String dataUrl = RequestCycle.get().urlFor(getRelativeRef(dataFile), new PageParameters())
                    .toString();

            DeployJava dj = new DeployJava(wicketId);
            dj.setArchive(jarUrl);
            dj.setCode(elt.getAttribute("src"));
            dj.addParameter("dataFile", dataUrl);
            return dj;
        }
        return super.getDynamicComponent(wicketId, elt);

        // link to a short glossary definition modal or main glossary window
    } else if (wicketId.startsWith("glossaryLink_")) {
        IModel<String> wordModel = new Model<String>(elt.getAttribute("word"));
        String glossaryLinkType = ISIApplication.get().getGlossaryLinkType();
        if (glossaryLinkType.equals(ISIApplication.GLOSSARY_TYPE_MODAL) && pageHasMiniGlossary()
                && miniGlossaryModal != null) {
            return new MiniGlossaryLink(wicketId, wordModel, miniGlossaryModal);

        } else if (glossaryLinkType.equals(ISIApplication.GLOSSARY_TYPE_INLINE)) {
            return new EmptyPanel(wicketId);

        } else {
            // Default case: glossary type is MAIN, or we wanted a modal but have no place to put it
            // (eg, we're in a popup window, or modal window)
            GlossaryLink glossaryLink = new GlossaryLink(wicketId, wordModel);
            ISIApplication.get().setLinkProperties(glossaryLink);
            return glossaryLink;
        }

        // inline glossary: linked word
    } else if (wicketId.startsWith("glossword")) {
        WebMarkupContainer glossaryWord = new WebMarkupContainer(wicketId);
        glossaryWord
                .setVisible(ISIApplication.get().glossaryLinkType.equals(ISIApplication.GLOSSARY_TYPE_INLINE));
        return glossaryWord;

        // inline glossary: definition
    } else if (wicketId.startsWith("glossdef")) {
        // Span element, to be filled in with the glossary short def.
        String word = elt.getAttribute("word");
        final String def = ISIApplication.get().getGlossary().getShortDefById(word);
        WebMarkupContainer container;
        container = new WebMarkupContainer(wicketId) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
                replaceComponentTagBody(markupStream, openTag, def);
            }
        };
        container.add(new AttributeRemover("word"));
        container.setVisible(ISIApplication.get().glossaryLinkType.equals(ISIApplication.GLOSSARY_TYPE_INLINE));
        return container;

        // inline glossary: "more" link to main glossary window         
    } else if (wicketId.startsWith("glosslink")) {
        IModel<String> wordModel = new Model<String>(elt.getAttribute("word"));
        GlossaryLink glossaryLink = new GlossaryLink(wicketId, wordModel);
        ISIApplication.get().setLinkProperties(glossaryLink);
        glossaryLink
                .setVisible(ISIApplication.get().glossaryLinkType.equals(ISIApplication.GLOSSARY_TYPE_INLINE));
        return glossaryLink;

    } else if (wicketId.startsWith("link_")) {
        String href = elt.getAttribute("href");
        // According to NIMAS, href should be in the form "filename.xml#ID"  or just "#ID" for within-file link
        // For authors' convenience, we accept simple "ID" as well.
        int hashLocation = href.indexOf('#');
        if (hashLocation > 0) {
            // filename#ID case
            return new SectionLinkFactory().linkTo(wicketId, href.substring(0, hashLocation),
                    href.substring(hashLocation + 1));
        }
        // "#ID" or "ID" case:
        String file = getModel().getObject().getXmlDocument().getName(); // same file as we're currently viewing
        String id = href.substring(hashLocation + 1); // start at index 0 or 1
        return new SectionLinkFactory().linkTo(wicketId, file, id);

    } else if (wicketId.startsWith("popupLink_")) {
        String href = elt.getAttribute("href");
        // According to NIMAS, href should be in the form "filename.xml#ID"  or just "#ID" for within-file link
        // For authors' convenience, we accept simple "ID" as well.
        int hashLocation = href.indexOf('#');
        String file;
        if (hashLocation > 0) {
            file = href.substring(0, hashLocation);
        } else { // "#ID" or "ID" case:
            file = getModel().getObject().getXmlDocument().getName(); // same file as we're currently viewing
        }
        XmlDocument document = xmlService.getDocument(file);
        String xmlId = href.substring(hashLocation + 1);
        XmlSection section = document.getById(xmlId);
        XmlSectionModel mSection = new XmlSectionModel(section);
        return new AuthoredPopupLink(wicketId, xmlId, mSection);

    } else if (wicketId.startsWith("noteBackLink_")) {
        // Link back from a note to its (first) noteref.
        String idref = elt.getAttribute("idref");
        // Find candidate noterefs in this chapter
        XmlSection sec = getModel().getObject();
        XPath xPath = XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(XmlService.get().getNamespaceContext());
        XmlSection linkSection = null;
        String linkText = "?";
        try {
            String path = String.format("//dtb:noteref[@idref='#%s']", idref);
            NodeList nl = (NodeList) xPath.evaluate(path,
                    sec.getXmlDocument().getDocument().getDocumentElement(), XPathConstants.NODESET);
            if (nl.getLength() > 0) {
                Element node = null;
                node = (Element) nl.item(0);
                linkText = node.getTextContent();
                // Scan parents until you find the smallest enclosing XML Section.
                while (linkSection == null && node.getParentNode() != null) {
                    String id = node.getAttributeNS(null, "id");
                    if (id != null) {
                        linkSection = sec.getXmlDocument().getById(id);
                    }
                    node = (Element) node.getParentNode();
                }
            }
        } catch (XPathExpressionException e) {
            e.printStackTrace(); // malformed expression - shouldn't happen
        }
        if (linkSection != null) {
            BookmarkablePageLink<ISIStandardPage> link = new SectionLinkFactory().linkTo(wicketId, linkSection,
                    "note_" + idref);
            link.add(new AttributeRemover("idref"));
            link.add(new Label("text", linkText));
            return link;
        } else {
            log.debug("Could not find noteref for note: idref={}", idref);
            return new SectionLinkFactory().linkToPage(wicketId, null);
        }

    } else if (wicketId.startsWith("fileLink_")) {
        // link to file in content directory
        return new ResourceLink<Object>(wicketId, getRelativeRef(elt.getAttribute("href")));

    } else if (wicketId.startsWith("sectionIcon_")) {
        WebComponent icon = ISIApplication.get().makeIcon(wicketId, elt.getAttribute("class"));
        icon.add(AttributeModifier.replace("class", new Model<String>("sectionIcon")));
        return icon;

    } else if (wicketId.startsWith("thumbRating_")) {
        ContentLoc loc = new ContentLoc(getModel().getObject());
        String thumbId = elt.getAttribute("id");
        ThumbPanel thumbPanel = new ThumbPanel(wicketId, loc, thumbId);
        thumbPanel.add(new AttributeRemover("id"));
        return thumbPanel;

    } else if (wicketId.startsWith("thumbRatingDescription_")) {
        Label thumbRatingDescription = new Label(wicketId,
                new ResourceModel("thumbRatingPanel.ratingDescription", "Rate It:"));
        return thumbRatingDescription;

    } else if (wicketId.startsWith("mediaThumbImage_")) {
        String src = elt.getAttribute("src");
        ResourceReference imgRef = getRelativeRef(src);
        Image image = new Image(wicketId, imgRef) {
            private static final long serialVersionUID = 1L;

            @Override
            protected void onComponentTag(final ComponentTag tag) {
                super.onComponentTag(tag);
                tag.put("width", elt.getAttribute("width"));
                tag.put("height", elt.getAttribute("height"));
            }
        };
        return image;

    } else if (wicketId.startsWith("mediaThumbLink_")) {
        String videoId = elt.getAttributeNS(null, "videoId");
        XmlSectionModel currentSectionModel = getModel();
        VideoLink videoLink = new VideoLink(wicketId, videoId, currentSectionModel);
        videoLink.add(new AttributeRemover("videoId"));
        return videoLink;

    } else if (wicketId.startsWith("videoplayer_")) {
        String videoSrc = elt.getAttribute("src");
        ResourceReference videoRef = getRelativeRef(videoSrc);
        String videoUrl = getRequestCycle().mapUrlFor(videoRef, null).toString();

        Integer width = Integer.valueOf(elt.getAttribute("width"));
        Integer height = Integer.valueOf(elt.getAttribute("height"));

        String preview = elt.getAttribute("poster");
        String captions = elt.getAttribute("captions");
        String audioDescription = elt.getAttribute("audiodescription");

        MediaPlayerPanel comp = new MediaPlayerPanel(wicketId, videoUrl, width, height) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onPlay(String status) {
                if (cwmSessionService.isSignedIn())
                    eventService.saveEvent("video:view",
                            "id=" + elt.getAttribute("videoId") + ",state=" + status, contentPage);
            }
        };

        comp.setFullScreen(true);
        comp.setUseOnPlay(true);

        if (!Strings.isEmpty(preview))
            comp.setPreview(getRelativeRef(preview));

        if (!Strings.isEmpty(captions))
            comp.setCaptionFile(getRelativeRef(captions));

        if (!Strings.isEmpty(audioDescription))
            comp.setAudioDescriptionFile(getRelativeRef(audioDescription));

        comp.add(new AttributeRemover("src", "width", "height", "poster", "captions", "audiodescription",
                "videoId"));

        return comp;

    } else if (wicketId.startsWith("audioplayer_")) {
        String audioSrc = elt.getAttribute("src");
        ResourceReference audioRef = getRelativeRef(audioSrc);
        String audioUrl = getRequestCycle().mapUrlFor(audioRef, null).toString();

        int width = 400;
        if (!elt.getAttribute("width").equals("")) {
            try {
                width = Integer.parseInt(elt.getAttribute("width").trim());
            } catch (Exception e) {
                log.debug("Can't get width for {}: {}", audioUrl, e);
                width = 400;
            }
        }
        AudioPlayerPanel player = new AudioPlayerPanel(wicketId, audioUrl, width, 20);
        player.setShowDownloadLink(false);
        player.setRenderBodyOnly(true);

        String preview = elt.getAttribute("poster");
        if (!Strings.isEmpty(preview))
            player.setPreview(getRelativeRef(preview));

        return player;

    } else if (wicketId.startsWith("swf_")) {

        ResourceReference swfRef = getRelativeRef(elt.getAttribute("src"));
        return new FlashAppletPanel(wicketId, swfRef, Integer.valueOf(elt.getAttribute("width")),
                Integer.valueOf(elt.getAttribute("height")), "");

    } else if (wicketId.startsWith("feedbackButton_")) {
        ContentLoc loc = new ContentLoc(getModel().getObject());
        String responseGroupId = elt.getAttribute("rgid");
        IModel<Prompt> pm = responseService.getOrCreatePrompt(PromptType.FEEDBACK, loc, responseGroupId);
        ResponseFeedbackButtonPanel component = new ResponseFeedbackButtonPanel(wicketId, pm,
                responseFeedbackPanel);
        String forRole = elt.getAttribute("for");
        component.setVisibilityAllowed(isTeacher ? forRole.equals("teacher") : forRole.equals("student"));
        component.add(new AttributeRemover("rgid", "for"));
        return component;
    } else if (wicketId.startsWith("scoreButtons_")) {
        if (isGuest)
            return new EmptyPanel(wicketId);
        IModel<Prompt> promptModel = getPrompt(elt);
        IModel<User> studentModel = ISISession.get().getTargetUserModel();
        ISortableDataProvider<Response> responseProvider = responseService
                .getResponseProviderForPrompt(promptModel, studentModel);
        TeacherScoreResponseButtonPanel component = new TeacherScoreResponseButtonPanel(wicketId,
                responseProvider);
        return component;
    } else if (wicketId.startsWith("showScore_")) {
        if (isGuest)
            return new EmptyPanel(wicketId);
        IModel<Prompt> promptModel = getPrompt(elt);
        IModel<User> studentModel = cwmSessionService.getUserModel();
        ISortableDataProvider<Response> responseProvider = responseService
                .getResponseProviderForPrompt(promptModel, studentModel);
        ScorePanel component = new StudentScorePanel(wicketId, responseProvider);
        return component;
        // A container for a single-select form and whiteboard, notebook links
    } else if (wicketId.startsWith("responseContainer")) {
        return new WebMarkupContainer(wicketId);
        // A single-select, multiple choice form.  MultipleChoiceItems will be added to a RadioGroup
        // child of this form.  
    } else if (wicketId.startsWith("select1_immediate_")) {
        return makeImmediateResponseForm(wicketId, elt);
        // A single-select, multiple choice form.  MultipleChoiceItems will be added to a RadioGroup
        // child of this form.  
    } else if (wicketId.startsWith("select1_delay_")) {
        return makeDelayedResponseForm(wicketId, elt);
        // buttons for viewing in whiteboard and notebook
    } else if (wicketId.startsWith("viewActions")) {
        IModel<Prompt> mPrompt = getPrompt(elt, PromptType.SINGLE_SELECT);
        Long promptId = mPrompt.getObject().getId();
        ResponseViewActionsPanel component = new ResponseViewActionsPanel(wicketId, promptId);
        component.add(new AttributeRemover("rgid", "title", "group", "type"));
        return component;
        // A single-select, multiple choice disabled form.  MultipleChoiceItems will be added to a RadioGroup
        // child of this form.  
    } else if (wicketId.startsWith("select1_view_immediate")) {
        return makeImmediateResponseView(wicketId, elt);
        // A single-select, multiple choice disabled form.  MultipleChoiceItems will be added to a RadioGroup
        // child of this form.  
    } else if (wicketId.startsWith("select1_view_delay")) {
        return makeDelayedResponseView(wicketId, elt);
        // A multiple choice radio button. Stores a "correct" value. This is
        // added to a generic RadioGroup in a SingleSelectForm.
    } else if (wicketId.startsWith("selectItem_")) {
        Component mcItem = new SingleSelectItem(wicketId,
                new Model<String>(wicketId.substring("selectItem_".length())),
                Boolean.valueOf(elt.getAttribute("correct")));
        mcItem.add(new AttributeRemover("correct"));
        return mcItem;

        // A message associated with a wicketId.startsWith("selectItem_").
        // The wicketId of the associated SingleSelectItem should be provided as a "for" attribute.
        // Visibility based on whether the corresponding radio button is selected in the enclosing form.
    } else if (wicketId.startsWith("selectMessage_")) {
        return new SingleSelectMessage(wicketId, elt.getAttribute("for")).add(new AttributeRemover("for"));

        // A delayed feedback message associated with a wicketId.startsWith("selectItem_").
        // The wicketId of the associated SingleSelectItem should be provided as a "for" attribute.
        // Visibility based on whether the response has been reviewed.
    } else if (wicketId.startsWith("selectDelayMessage_")) {
        ISIXmlSection section = getISIXmlSection();
        IModel<XmlSection> currentSectionModel = new XmlSectionModel(section);
        SingleSelectDelayMessage component = new SingleSelectDelayMessage(wicketId, currentSectionModel);
        return component.add(new AttributeRemover("for"));

    } else if (wicketId.startsWith("responseList_")) {
        if (isGuest)
            return new MessageBox(wicketId, "guestResponseArea");
        ContentLoc loc = new ContentLoc(getModel().getObject());
        String responseGroupId = elt.getAttribute("rgid");
        ResponseMetadata metadata = getResponseMetadata(responseGroupId);
        IModel<Prompt> mPrompt = responseService.getOrCreatePrompt(PromptType.RESPONSEAREA, loc,
                responseGroupId, metadata.getCollection());
        ResponseList dataView = new ResponseList(wicketId, mPrompt, metadata, loc,
                ISISession.get().getTargetUserModel());
        dataView.setContext(getResponseListContext(false));
        dataView.setAllowEdit(!isTeacher);
        dataView.setAllowNotebook(!inGlossary && !isTeacher && ISIApplication.get().isNotebookOn());
        dataView.setAllowWhiteboard(!inGlossary && ISIApplication.get().isWhiteboardOn());
        dataView.add(new AttributeRemover("rgid", "group"));
        return dataView;

    } else if (wicketId.startsWith("locking_responseList_")) {
        if (isGuest)
            return new EmptyPanel(wicketId);
        ContentLoc loc = new ContentLoc(getModel().getObject());
        String responseGroupId = elt.getAttribute("rgid");
        ResponseMetadata metadata = getResponseMetadata(responseGroupId);
        IModel<Prompt> mPrompt = responseService.getOrCreatePrompt(PromptType.RESPONSEAREA, loc,
                responseGroupId, metadata.getCollection());
        ResponseList dataView = new LockingResponseList(wicketId, mPrompt, metadata, loc,
                ISISession.get().getTargetUserModel());
        dataView.setContext(getResponseListContext(false));
        dataView.setAllowEdit(!isTeacher);
        dataView.setAllowNotebook(!inGlossary && !isTeacher && ISIApplication.get().isNotebookOn());
        dataView.setAllowWhiteboard(!inGlossary && ISIApplication.get().isWhiteboardOn());
        dataView.add(new AttributeRemover("rgid", "group"));
        return dataView;

    } else if (wicketId.startsWith("period_responseList_")) {
        if (isGuest)
            return new MessageBox(wicketId, "guestResponseArea");
        ContentLoc loc = new ContentLoc(getModel().getObject());
        String responseGroupId = elt.getAttribute("rgid");
        ResponseMetadata metadata = getResponseMetadata(responseGroupId);
        IModel<Prompt> mPrompt = responseService.getOrCreatePrompt(PromptType.RESPONSEAREA, loc,
                responseGroupId, metadata.getCollection());
        PeriodResponseList dataView = new PeriodResponseList(wicketId, mPrompt, metadata, loc,
                ISISession.get().getCurrentPeriodModel());
        dataView.setContext(getResponseListContext(true));
        dataView.setAllowEdit(!isTeacher);
        dataView.setAllowNotebook(!inGlossary && !isTeacher && ISIApplication.get().isNotebookOn());
        dataView.setAllowWhiteboard(!inGlossary && ISIApplication.get().isWhiteboardOn());
        dataView.add(new AttributeRemover("rgid", "group"));
        return dataView;

    } else if (wicketId.startsWith("responseButtons_")) {
        ContentLoc loc = new ContentLoc(getModel().getObject());
        String responseGroupId = elt.getAttribute("rgid");
        Element xmlElement = getModel().getObject().getElement().getOwnerDocument()
                .getElementById(responseGroupId);
        ResponseMetadata metadata = new ResponseMetadata(xmlElement);
        if (!ISIApplication.get().isUseAuthoredResponseType()) {
            // set all the response types to the default per application configuration here
            metadata = adjustResponseTypes(metadata);
        }
        IModel<Prompt> mPrompt = responseService.getOrCreatePrompt(PromptType.RESPONSEAREA, loc,
                metadata.getId(), metadata.getCollection());
        ResponseButtons buttons = new ResponseButtons(wicketId, mPrompt, metadata, loc);
        buttons.setVisible(!isTeacher);
        return buttons;

    } else if (wicketId.startsWith("locking_responseButtons_")) {
        ContentLoc loc = new ContentLoc(getModel().getObject());
        String responseGroupId = elt.getAttribute("rgid");
        Element xmlElement = getModel().getObject().getElement().getOwnerDocument()
                .getElementById(responseGroupId);
        ResponseMetadata metadata = new ResponseMetadata(xmlElement);
        if (!ISIApplication.get().isUseAuthoredResponseType()) {
            // set all the response types to the default per application configuration here
            metadata = adjustResponseTypes(metadata);
        }
        IModel<Prompt> mPrompt = responseService.getOrCreatePrompt(PromptType.RESPONSEAREA, loc,
                metadata.getId(), metadata.getCollection());
        return new LockingResponseButtons(wicketId, mPrompt, metadata, loc, cwmSessionService.getUserModel());

    } else if (wicketId.startsWith("ratePanel_")) {
        if (isGuest)
            return ISIApplication.get().getLoginMessageComponent(wicketId);
        ContentLoc loc = new ContentLoc(getModel().getObject());
        String promptText = null;
        String ratingId = elt.getAttribute("id");
        NodeList nodes = elt.getChildNodes();
        // extract the prompt text authored - we might want to consider re-writing this
        // to use xsl instead of this - but this works for now - ldm
        for (int i = 0; i < nodes.getLength(); i++) {
            Node nextNode = nodes.item(i);
            if (nextNode instanceof Element) {
                Element next = (Element) nodes.item(i);
                if (next.getAttribute("class").equals("prompt")) {
                    //get all the html under the prompt element
                    promptText = new TransformResult(next).getString();
                }
            }
        }
        RatePanel ratePanel = new RatePanel(wicketId, loc, ratingId, promptText);
        ratePanel.add(new AttributeRemover("id"));
        ratePanel.add(new AttributeRemover("type"));
        return ratePanel;

    } else if (wicketId.startsWith("teacherBar_")) {
        WebMarkupContainer teacherBar = new WebMarkupContainer(wicketId);
        teacherBar.setVisible(isTeacher && !inGlossary);
        return teacherBar;

    } else if (wicketId.startsWith("compareResponses_")) {
        IModel<Prompt> mPrompt = getPrompt(elt);
        BookmarkablePageLink<Page> bpl = new BookmarkablePageLink<Page>(wicketId,
                ISIApplication.get().getPeriodResponsePageClass());
        bpl.getPageParameters().add("promptId", mPrompt.getObject().getId());
        ISIApplication.get().setLinkProperties(bpl);
        bpl.setVisible(isTeacher);
        bpl.add(new AttributeRemover("rgid", "for", "type"));
        return bpl;

    } else if (wicketId.startsWith("agent_")) {
        String title = elt.getAttribute("title");
        if (Strings.isEmpty(title))
            title = new StringResourceModel("isi.defaultAgentButtonText", this, null, "Help").getObject();
        AgentLink link = new AgentLink(wicketId, title, elt.getAttribute("responseAreaId"));
        link.add(new AttributeRemover("title", "responseAreaId"));
        return link;

    } else if (wicketId.startsWith("image_")) {
        String src = elt.getAttribute("src");
        ResourceReference imgRef = getRelativeRef(src);
        return new Image(wicketId, imgRef);

    } else if (wicketId.startsWith("imageThumb_")) {
        String src = elt.getAttribute("src");
        int ext = src.lastIndexOf('.');
        src = src.substring(0, ext) + "_t" + src.substring(ext);
        ResourceReference imgRef = getRelativeRef(src);
        Image img = new Image(wicketId, imgRef);
        // FIXME these attributes were removed because indira was adding height and width of the detail image
        // not the thumbnail image - remove when indira gets removed
        img.add(new AttributeRemover("width", "height"));
        return img;

    } else if (wicketId.startsWith("imageDetailButton_")) {
        // for thumbnail images only - no longer for more info
        return new ImageDetailButtonPanel(wicketId, wicketId.substring("imageDetailButton_".length()));
        //        We may want to put some of this back, but for now assuming that any time XSLT requests an image detail button we'll put one in.
        //         if (contentPage == null && !inGlossary) // Don't do imageDetails on non-content pages (e.g. the Table of Contents)
        //            return new WebMarkupContainer(wicketId).setVisible(false);

    } else if (wicketId.startsWith("imgToggleHeader") || wicketId.startsWith("imgDetailToggleHeader")
            || wicketId.startsWith("objectToggleHeader")) {
        // long description header for toggle area

        String src = elt.getAttribute("src");

        // remove everything but the name of the media
        int lastIndex = src.lastIndexOf("/") + 1;
        src = src.substring(lastIndex, src.length());

        Label label;
        String eventType = "ld";
        String detail = null;
        if (wicketId.startsWith("img")) {
            label = new Label(wicketId,
                    new ResourceModel("imageLongDescription.toggleHeading", "image information"));
            String imageId = elt.getAttribute("imageId");
            detail = "imageId=" + imageId;
            label.add(new AttributeRemover("imageId"));
            if (wicketId.startsWith("imgDetailToggleHeader")) {
                label = new Label(wicketId,
                        new ResourceModel("imageLongDescription.toggleHeading", "image information"));
                detail = detail + ",context=detail";
            }
        } else { // video or mp3 files
            if (src.contains(".mp3")) {
                label = new Label(wicketId,
                        new ResourceModel("audioLongDescription.toggleHeading", "more audio information"));
            } else {
                label = new Label(wicketId,
                        new ResourceModel("videoLongDescription.toggleHeading", "more video information"));
            }
            detail = "src=" + src;
        }

        label.add(
                new CollapseBoxBehavior("onclick", eventType, ((ISIBasePage) getPage()).getPageName(), detail));
        label.add(new AttributeRemover("src"));
        return label;

    } else if (wicketId.startsWith("annotatedImage_")) {
        // image with hotspots
        AnnotatedImageComponent annotatedImageComponent = new AnnotatedImageComponent(wicketId, elt,
                getModel());
        annotatedImageComponent.add(new AttributeRemover("annotatedImageId"));
        return annotatedImageComponent;

    } else if (wicketId.startsWith("hotSpot_")) {
        // clickable areas on annotated images
        HotSpotComponent hotSpotComponent = new HotSpotComponent(wicketId, elt);
        hotSpotComponent.add(new AttributeRemover("annotatedImageId"));
        return hotSpotComponent;

    } else if (wicketId.startsWith("slideShow_")) {
        SlideShowComponent slideShowComponent = new SlideShowComponent(wicketId, elt);
        return slideShowComponent;

    } else if (wicketId.startsWith("collapseBox_")) {
        WebMarkupContainer collapseBox = new WebMarkupContainer(wicketId);
        return collapseBox;

    } else if (wicketId.startsWith("feedbackStatusIndicator_")) {
        FeedbackStatusIndicator feedbackStatusIndicator = new FeedbackStatusIndicator(wicketId);
        return feedbackStatusIndicator;

    } else if (wicketId.startsWith("collapseBoxControl-")) {
        String boxSequence = (wicketId.substring("collapseBoxControl-".length()).equals("") ? "0"
                : wicketId.substring("collapseBoxControl-".length()));
        CollapseBoxHeader collapseBoxHeader = new CollapseBoxHeader(wicketId, boxSequence);
        return collapseBoxHeader;

    } else if (wicketId.startsWith("iScienceLink-")) {
        return new AjaxFallbackLink<Object>(wicketId) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                target.prependJavaScript(
                        "$('#iScienceVideo-" + wicketId.substring("iScienceLink-".length()) + "').jqmShow();");
                eventService.saveEvent("iscience:view",
                        "Video #" + wicketId.substring("iScienceLink-".length()),
                        ((ISIBasePage) getPage()).getPageName());
            }
        };

    } else if (wicketId.startsWith("youtube_")) {
        int width = getWidth(elt, 640);
        int height = getHeight(elt, 385);
        String src = elt.getAttribute("src");
        src = src.replace("youtube.com/watch?v=", "youtube.com/v/");

        FlashAppletPanel panel = new FlashAppletPanel(wicketId, width, height);
        panel.add(new AttributeRemover("src", "width", "height"));
        panel.setAppletHRef(src);
        panel.setFullScreen(true);
        return panel;

    } else if (wicketId.startsWith("pageLinkPanel_")) {
        String id = elt.getAttribute("id");
        IModel<XmlSection> currentSectionModel = new XmlSectionModel(
                getModel().getObject().getXmlDocument().getById(id));
        PageLinkPanel panel = new PageLinkPanel(wicketId, currentSectionModel, null);
        panel.add(new AttributeRemover("id"));
        return panel;

    } else if (wicketId.startsWith("sectionStatusIcon_")) {
        String id = elt.getAttribute("id");
        IModel<XmlSection> currentSectionModel = new XmlSectionModel(
                getModel().getObject().getXmlDocument().getById(id));
        return new StudentSectionCompleteToggleImageLink(wicketId, currentSectionModel);

    } else if (wicketId.startsWith("inactiveSectionStatusIcon_")) {
        String id = elt.getAttribute("id");
        IModel<XmlSection> currentSectionModel = new XmlSectionModel(
                getModel().getObject().getXmlDocument().getById(id));
        return new SectionCompleteImageContainer(wicketId, currentSectionModel);

    } else if (wicketId.startsWith("itemSummary_")) {
        boolean noAnswer = Boolean.parseBoolean(elt.getAttributeNS(null, "noAnswer"));
        Component singleSelectComponent = new SingleSelectSummaryXmlComponentHandler().makeComponent(wicketId,
                elt, getModel(), noAnswer);
        singleSelectComponent.add(new AttributeRemover("noAnswer"));
        return singleSelectComponent;

    } else if (wicketId.startsWith("shy")) {
        return new ShyContainer(wicketId);
    } else {
        return super.getDynamicComponent(wicketId, elt);
    }
}

From source file:org.dcache.webadmin.view.beans.ThumbnailPanelBean.java

License:Open Source License

public ThumbnailPanelBean(File file, int height, int width) {
    String name = file.getName();
    int end = name.indexOf(RrdSettings.FILE_SUFFIX);
    this.name = name.substring(0, end);
    IResource resource = new ResourceStreamResource(new FileResourceStream(file));
    Image image = new Image("thumbnail", resource);
    PopupSettings popupSettings = new PopupSettings(PopupSettings.RESIZABLE | PopupSettings.SCROLLBARS)
            .setHeight(height).setWidth(width);

    ResourceLink link = new ResourceLink("plotlink", resource);
    link.setPopupSettings(popupSettings);
    link.add(image);//from w w  w . j av  a  2s  .  c  om
    this.link = link;
}

From source file:org.dcache.webadmin.view.panels.billingplots.PlotsPanel.java

License:Open Source License

/**
 * Two thirds of this method is shared with {@link ThumbnailPanelBean};
 * the latter needs to be generalized to cover this case. TODO
 *//*  w ww .  j  a  v  a  2  s  . c  o  m*/
private void loadPlots(File[] files, int width, int height) {
    int n = 0;
    int m = 0;
    for (File file : files) {
        String suffix = "_" + m + n;
        ResourceStreamResource resource = new ResourceStreamResource(new FileResourceStream(file));
        resource.setCacheDuration(Duration.NONE);
        Image image = new Image(IMAGE_NAME + suffix, resource);
        PopupSettings popupSettings = new PopupSettings(PopupSettings.RESIZABLE | PopupSettings.SCROLLBARS)
                .setHeight(height).setWidth(width);
        ResourceLink link = new ResourceLink(LINK_NAME + suffix, resource);
        link.setPopupSettings(popupSettings);
        link.add(image);
        add(link);
        n = (n + 1) % 4;
        if (n == 0) {
            ++m;
        }
    }
}

From source file:org.dcm4chee.web.war.tc.TCDocumentsView.java

License:LGPL

public TCDocumentsView(final String id, IModel<? extends TCObject> model, final boolean editing) {
    super(id, model);

    this.editing = editing;

    final TCModalDialog removeDocDlg = TCModalDialog.getOkCancel("remove-doc-dialog",
            TCUtilities.getLocalizedString("tc.documents.removedialog.msg"), null);
    removeDocDlg.setInitialHeight(100);//  w w  w. j  a  va  2  s .  com
    removeDocDlg.setInitialWidth(420);
    removeDocDlg.setUseInitialHeight(true);

    final WebMarkupContainer items = new WebMarkupContainer("document-items");
    items.setOutputMarkupId(true);
    items.add(new ListView<TCDocumentObject>("document-item", new ListModel<TCDocumentObject>() {
        @Override
        public List<TCDocumentObject> getObject() {
            return getTC().getReferencedDocumentObjects();
        }
    }) {
        @Override
        protected void populateItem(final ListItem<TCDocumentObject> item) {
            final TCDocumentObject doc = item.getModelObject();

            // compile text
            MimeType mimeType = doc.getMimeType();
            Date addedDate = doc.getDocumentAddedDate();
            String docDescription = doc.getDocumentDescription();
            if (docDescription == null) {
                docDescription = doc.getDocumentName();
            }

            StringBuilder sbuilder = new StringBuilder();
            if (docDescription != null) {
                sbuilder.append(docDescription).append("\n");
            }
            sbuilder.append("<i>");
            sbuilder.append(mimeType.getDocumentType().getHumanReadableName());
            sbuilder.append("; ");
            sbuilder.append(TCUtilities.getLocalizedString("tc.documents.addedon.text")).append(" ");
            sbuilder.append(DateFormat.getDateInstance(DateFormat.MEDIUM).format(addedDate));
            sbuilder.append("</i>");

            // add components
            final WebMarkupContainer actions = new WebMarkupContainer("document-item-actions");
            actions.setOutputMarkupId(true);
            actions.setOutputMarkupPlaceholderTag(true);
            actions.add(new ResourceLink<Void>("document-item-download-btn", doc.getDocumentContent(true))
                    .add(new TCHoverImage("document-item-download-image", ImageManager.IMAGE_TC_DISK_MONO,
                            ImageManager.IMAGE_TC_DISK)
                                    .add(new ImageSizeBehaviour(20, 20, "vertical-align: middle;"))
                                    .add(new TooltipBehaviour("tc.documents.", "download"))));
            actions.add(new AjaxLink<Void>("document-item-remove-btn") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    try {
                        if (editing) {
                            removeDocDlg.setCallback(new ModalDialogCallbackAdapter() {
                                @Override
                                public void dialogAcknowledged(AjaxRequestTarget target) {
                                    getEditableTC().removeReferencedDocument(doc);
                                    target.addComponent(items);
                                }
                            });

                            removeDocDlg.show(target);
                        }
                    } catch (Exception e) {
                        log.error("Removing referenced document from teaching-file failed!", e);
                    }
                }

                @Override
                public boolean isVisible() {
                    return editing;
                }
            }.add(new TCHoverImage("document-item-remove-image", ImageManager.IMAGE_TC_CANCEL_MONO,
                    ImageManager.IMAGE_TC_CANCEL).add(new ImageSizeBehaviour(20, 20, "vertical-align: middle;"))
                            .add(new TooltipBehaviour("tc.documents.", "remove"))));

            item.add(new AttributeModifier("onmouseover", true,
                    new Model<String>("$('#" + actions.getMarkupId(true) + "').show();")));
            item.add(new AttributeModifier("onmouseout", true,
                    new Model<String>("$('#" + actions.getMarkupId(true) + "').hide();")));

            item.add(new ResourceLink<Void>("document-item-view-link", doc.getDocumentContent(false))
                    .add(new NonCachingImage("document-item-image", doc.getDocumentThumbnail())
                            .add(new TCMaxImageSizeBehavior(32, 32).setAdditionalCSS("vertical-align:middle")))
                    .add(new TooltipBehaviour("tc.documents.", "view"))
                    .add(new AttributeAppender("target", true, new Model<String>("_blank"), " ")));
            item.add(new MultiLineLabel("document-item-text", sbuilder.toString()) {
                @Override
                protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {
                    final CharSequence body = Strings.toMultilineMarkup(getDefaultModelObjectAsString());

                    replaceComponentTagBody(markupStream, openTag,
                            body.toString().replaceFirst("<p>", "<p style=\"margin:0px\">"));
                }
            }.setEscapeModelStrings(false));
            item.add(actions);
        }
    });

    final FileUploadField uploadField = new FileUploadField("file-upload-field") {
        @Override
        protected void onComponentTag(ComponentTag tag) {
            super.onComponentTag(tag);

            MimeType[] types = MimeType.values();
            if (types != null && types.length > 0) {
                StringBuilder accept = new StringBuilder();
                accept.append(types[0].getMimeTypeString());
                for (int i = 1; i < types.length; i++) {
                    accept.append(",").append(types[i].getMimeTypeString());
                }
                tag.put("accept", accept.toString());
            }
        }
    };
    final long maxUploadSize = Bytes.megabytes(25).bytes();
    final TextArea<String> uploadDescription = new TextArea<String>("file-upload-description-text",
            new Model<String>());
    final Form<Void> uploadForm = new Form<Void>("file-upload-form");
    uploadForm.setMultiPart(true);
    uploadForm.setMaxSize(Bytes.megabytes(25)); // seems that this doesn't work because of a bug in WICKET 1.4
    uploadForm.add(new Label("file-upload-label", TCUtilities.getLocalizedString("tc.documents.upload.text")));
    uploadForm.add(new Label("file-upload-description-label",
            TCUtilities.getLocalizedString("tc.documents.upload.description.text")));
    uploadForm.add(uploadField);
    uploadForm.add(uploadDescription);
    uploadForm.add(new AjaxButton("file-upload-btn") {
        @Override
        public void onSubmit(AjaxRequestTarget target, Form<?> form) {
            final FileUpload upload = uploadField.getFileUpload();
            if (upload != null) {
                String contentType = null, fileName = null;
                final long totalBytes = upload.getSize();
                try {
                    if (totalBytes > 0) {
                        if (totalBytes <= maxUploadSize) {
                            getEditableTC().addReferencedDocument(
                                    MimeType.get(contentType = upload.getContentType()),
                                    fileName = upload.getClientFileName(), upload.getInputStream(),
                                    uploadDescription.getModelObject());
                        } else {
                            log.warn("File upload denied: Max upload size is " + maxUploadSize + " bytes!");
                        }
                    }

                    target.addComponent(items);
                } catch (Exception e) {
                    log.error("Unable to upload teaching-file referenced document (content-type='" + contentType
                            + "', file-name='" + fileName + "')!", e);
                } finally {
                    upload.closeStreams();

                    uploadField.clearInput();
                    uploadDescription.clearInput();
                    uploadDescription.setModelObject(null);

                    target.addComponent(uploadForm);
                }
            }
        }

        @Override
        public void onError(AjaxRequestTarget target, Form<?> form) {
        }

        @Override
        protected IAjaxCallDecorator getAjaxCallDecorator() {
            return new TCMaskingAjaxDecorator(true, true);
        }
    }.add(new Label("file-upload-btn-text", TCUtilities.getLocalizedString("tc.documents.upload.start.text"))));

    add(items);
    add(removeDocDlg);
    add(new WebMarkupContainer("file-upload") {
        @Override
        public boolean isVisible() {
            return editing;
        }
    }.add(new Image("file-upload-info-img", ImageManager.IMAGE_TC_INFO) {
        @Override
        protected void onComponentTag(ComponentTag tag) {
            super.onComponentTag(tag);

            StringBuilder sbuilder = new StringBuilder();
            sbuilder.append(
                    MessageFormat.format(TCUtilities.getLocalizedString("tc.documents.upload.maxsize.text"),
                            Bytes.bytes(maxUploadSize).megabytes()));
            sbuilder.append("\n");

            MimeType[] mimeTypes = MimeType.values();
            if (mimeTypes != null) {
                boolean firstExt = true;
                int nExtPerLine = 8;
                int nExtInLine = 0;
                for (MimeType type : mimeTypes) {
                    String[] exts = type.getSupportedFileExtensions();
                    if (exts != null) {
                        for (String ext : exts) {
                            String s = "*." + ext;
                            if (firstExt) {
                                sbuilder.append(
                                        TCUtilities.getLocalizedString("tc.documents.upload.files.text"));
                                sbuilder.append("\n");
                                sbuilder.append(s);
                                firstExt = false;
                                nExtInLine++;
                            } else {
                                if (!sbuilder.toString().contains(s)) {
                                    if (nExtInLine == nExtPerLine) {
                                        sbuilder.append("\n");
                                        nExtInLine = 0;
                                    } else {
                                        sbuilder.append(", ");
                                    }
                                    sbuilder.append(s);
                                    nExtInLine++;
                                }
                            }
                        }
                    }
                }
            }
            tag.put("title", sbuilder.toString());
        }
    }.add(new ImageSizeBehaviour(16, 16, "vertical-align:middle;margin:5px;"))).add(uploadForm)
            .setMarkupId("documents-file-upload"));
}

From source file:org.devgateway.ocvn.forms.wicket.page.EditVietnamImportSourceFiles.java

License:Open Source License

@Override
protected void onInitialize() {
    super.onInitialize();

    TextFieldBootstrapFormComponent<String> name = new TextFieldBootstrapFormComponent<>("name");
    name.required();//from ww w .  j a  v  a  2 s.c  o  m
    editForm.add(name);

    TextAreaFieldBootstrapFormComponent<String> description = new TextAreaFieldBootstrapFormComponent<>(
            "description");
    editForm.add(description);

    FileInputBootstrapFormComponent prototypeDatabaseFile = new FileInputBootstrapFormComponent(
            "prototypeDatabaseFile");
    prototypeDatabaseFile.maxFiles(1);
    prototypeDatabaseFile.required();
    editForm.add(prototypeDatabaseFile);

    FileInputBootstrapFormComponent publicInstitutionsSuppliersFile = new FileInputBootstrapFormComponent(
            "publicInstitutionsSuppliersFile");
    publicInstitutionsSuppliersFile.maxFiles(1);
    publicInstitutionsSuppliersFile.required();
    editForm.add(publicInstitutionsSuppliersFile);

    FileInputBootstrapFormComponent cityDepartmentGroupFile = new FileInputBootstrapFormComponent(
            "cityDepartmentGroupFile");
    cityDepartmentGroupFile.maxFiles(1);
    cityDepartmentGroupFile.required();
    editForm.add(cityDepartmentGroupFile);

    ResourceLink locationsTemplate = new ResourceLink("locationsTemplate",
            new PackageResourceReference(RootXlsx.class, "Location_Table_SO.xlsx"));
    editForm.add(locationsTemplate);

    ResourceLink suppliersTemplate = new ResourceLink("suppliersTemplate",
            new PackageResourceReference(RootXlsx.class, "UM_PUBINSTITU_SUPPLIERS_DQA.xlsx"));
    editForm.add(suppliersTemplate);

    ResourceLink prototypeDatabase = new ResourceLink("prototypeDatabase",
            new PackageResourceReference(RootXlsx.class, "Prototype_Database_OCDSCore.xlsx"));
    editForm.add(prototypeDatabase);

    ResourceLink cityDepartmentGroupFileTemplate = new ResourceLink("cityDepartmentGroupFileTemplate",
            new PackageResourceReference(RootXlsx.class, "test_city_department_group.xlsx"));
    editForm.add(cityDepartmentGroupFileTemplate);

    FileInputBootstrapFormComponent locationsFile = new FileInputBootstrapFormComponent("locationsFile");
    locationsFile.maxFiles(1);
    locationsFile.required();
    editForm.add(locationsFile);

}

From source file:org.hippoecm.frontend.plugins.cms.root.RootPlugin.java

License:Apache License

public RootPlugin(IPluginContext context, IPluginConfig config) {
    super(context, config);

    // keep all feedback messages after each request cycle
    getApplication().getApplicationSettings().setFeedbackMessageCleanupFilter(IFeedbackMessageFilter.NONE);

    addPinger();//from  w  ww.j a  va  2 s .co  m

    add(new Label("pageTitle", getString("page.title", null, "Hippo CMS 10")));

    addUserMenu();

    services = new LinkedList<>();

    final IDataProvider<IRenderService> provider = new ListDataProvider<IRenderService>(services) {
        @Override
        public IModel<IRenderService> model(IRenderService object) {
            return new RenderServiceModel(object);
        }
    };

    view = new AbstractView<IRenderService>("view", provider) {

        @Override
        protected void populateItem(Item<IRenderService> item) {
            IRenderService renderer = item.getModelObject();
            renderer.bind(RootPlugin.this, "item");
            item.add(renderer.getComponent());
            RootPlugin.this.onAddRenderService(item, renderer);
            item.setVisible(renderer.getComponent().isVisible());
        }

        @Override
        protected void destroyItem(Item<IRenderService> item) {
            IRenderService renderer = item.getModelObject();
            item.remove(renderer.getComponent());
            RootPlugin.this.onRemoveRenderService(item, renderer);
            renderer.unbind();
        }
    };

    String itemId = getItemId();
    if (itemId != null) {
        tracker = new ServiceTracker<IRenderService>(IRenderService.class) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onServiceAdded(IRenderService service, String name) {
                log.debug("adding " + service + " to ListViewService at " + name);
                services.add(service);
            }

            @Override
            public void onServiceChanged(IRenderService service, String name) {
            }

            @Override
            public void onRemoveService(IRenderService service, String name) {
                log.debug("removing " + service + " from ListViewService at " + name);
                services.remove(service);
            }
        };
        context.registerTracker(tracker, itemId);
    } else {
        log.warn("No item id configured");
    }

    add(view);

    add(new AjaxIndicatorBehavior());

    add(new ExtHippoThemeBehavior());

    extWidgetRegistry = new ExtWidgetRegistry(getPluginContext());
    add(extWidgetRegistry);

    if (config.containsKey("top")) {
        log.warn(
                "Usage of property 'top' on the RootPlugin is deprecated. The documents tabs is now configured "
                        + "as an extension. Add a value to property wicket.extensions named 'extension.tabs.documents' and "
                        + "add a property named 'extension.tabs.documents' with the value of the document tabs service, "
                        + "by default it's 'service.browse.tabscontainer'.");
    }

    TabbedPanel tabbedPanel = getTabbedPanel();
    tabbedPanel.setIconType(IconSize.L);
    tabbedPanel.add(new WireframeBehavior(new WireframeSettings(config.getPluginConfig("layout.wireframe"))));

    get("tabs:panel-container").add(new UnitBehavior("center"));
    get("tabs:tabs-container").add(new UnitBehavior("left"));

    final PageLayoutSettings pageLayoutSettings = getPageLayoutSettings(config);
    add(new PageLayoutBehavior(pageLayoutSettings));
    add(new ResourceLink("faviconLink",
            ((PluginApplication) getApplication()).getPluginApplicationFavIconReference()));
}