Example usage for org.apache.wicket.markup.html.link ExternalLink setEnabled

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

Introduction

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

Prototype

public final Component setEnabled(final boolean enabled) 

Source Link

Document

Sets whether this component is enabled.

Usage

From source file:com.doculibre.constellio.wicket.panels.results.DefaultSearchResultPanel.java

License:Open Source License

public DefaultSearchResultPanel(String id, SolrDocument doc, final SearchResultsDataProvider dataProvider) {
    super(id);/*from   ww w  . j  av a2  s  .c om*/

    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
    SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils
            .getSearchInterfaceConfigServices();

    String collectionName = dataProvider.getSimpleSearch().getCollectionName();

    RecordCollection collection = collectionServices.get(collectionName);
    Record record = recordServices.get(doc);
    if (record != null) {
        SearchInterfaceConfig searchInterfaceConfig = searchInterfaceConfigServices.get();

        IndexField uniqueKeyField = collection.getUniqueKeyIndexField();
        IndexField defaultSearchField = collection.getDefaultSearchIndexField();
        IndexField urlField = collection.getUrlIndexField();
        IndexField titleField = collection.getTitleIndexField();

        if (urlField == null) {
            urlField = uniqueKeyField;
        }
        if (titleField == null) {
            titleField = urlField;
        }

        final String recordURL = record.getUrl();
        final String displayURL;

        if (record.getDisplayUrl().startsWith("/get?file=")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            displayURL = ContextUrlUtils.getContextUrl(req) + record.getDisplayUrl();

        } else {
            displayURL = record.getDisplayUrl();
        }

        String title = record.getDisplayTitle();

        final String protocol = StringUtils.substringBefore(displayURL, ":");
        boolean linkEnabled = isLinkEnabled(protocol);

        // rcupration des champs highlight  partir de la cl unique
        // du document, dans le cas de Nutch c'est l'URL
        QueryResponse response = dataProvider.getQueryResponse();
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL);

        String titleHighlight = getTitleFromHighlight(titleField.getName(), fieldsHighlighting);
        if (titleHighlight != null) {
            title = titleHighlight;
        }

        String excerpt = null;
        String description = getDescription(record);
        String summary = getSummary(record);

        if (StringUtils.isNotBlank(description) && searchInterfaceConfig.isDescriptionAsExcerpt()) {
            excerpt = description;
        } else {
            excerpt = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting);
            if (excerpt == null) {
                excerpt = description;
            }
        }

        toggleSummaryLink = new WebMarkupContainer("toggleSummaryLink");
        add(toggleSummaryLink);
        toggleSummaryLink.setVisible(StringUtils.isNotBlank(summary));
        toggleSummaryLink.add(new AttributeModifier("onclick", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                return "toggleSearchResultSummary('" + summaryLabel.getMarkupId() + "')";
            }
        }));

        summaryLabel = new Label("summary", summary);
        add(summaryLabel);
        summaryLabel.setOutputMarkupId(true);
        summaryLabel.setVisible(StringUtils.isNotBlank(summary));

        ExternalLink titleLink;
        if (displayURL.startsWith("file://")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            String newDisplayURL = ContextUrlUtils.getContextUrl(req) + "app/getSmbFile?"
                    + SmbServletPage.RECORD_ID + "=" + record.getId() + "&" + SmbServletPage.COLLECTION + "="
                    + collectionName;
            titleLink = new ExternalLink("titleLink", newDisplayURL);
        } else {
            titleLink = new ExternalLink("titleLink", displayURL);
        }

        final RecordModel recordModel = new RecordModel(record);
        AttributeModifier computeClickAttributeModifier = new AttributeModifier("onmousedown", true,
                new LoadableDetachableModel() {
                    @Override
                    protected Object load() {
                        Record record = recordModel.getObject();
                        SimpleSearch simpleSearch = dataProvider.getSimpleSearch();
                        WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest();
                        HttpServletRequest httpRequest = webRequest.getHttpServletRequest();
                        return ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch,
                                record);
                    }
                });
        titleLink.add(computeClickAttributeModifier);
        titleLink.setEnabled(linkEnabled);

        boolean resultsInNewWindow;
        PageParameters params = RequestCycle.get().getPageParameters();
        if (params != null && params.getString(POPUP_LINK) != null) {
            resultsInNewWindow = params.getBoolean(POPUP_LINK);
        } else {
            resultsInNewWindow = searchInterfaceConfig.isResultsInNewWindow();
        }
        titleLink.add(new SimpleAttributeModifier("target", resultsInNewWindow ? "_blank" : "_self"));

        // Add title
        title = StringUtils.remove(title, "\n");
        title = StringUtils.remove(title, "\r");
        if (StringUtils.isEmpty(title)) {
            title = StringUtils.defaultString(displayURL);
            title = StringUtils.substringAfterLast(title, "/");
            title = StringUtils.substringBefore(title, "?");
            try {
                title = URLDecoder.decode(title, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (title.length() > 120) {
                title = title.substring(0, 120) + " ...";
            }
        }

        Label titleLabel = new Label("title", title);
        titleLink.add(titleLabel.setEscapeModelStrings(false));
        add(titleLink);

        Label excerptLabel = new Label("excerpt", excerpt);
        add(excerptLabel.setEscapeModelStrings(false));
        // add(new ExternalLink("url", url,
        // url).add(computeClickAttributeModifier).setEnabled(linkEnabled));
        if (displayURL.startsWith("file://")) {
            // Creates a Windows path for file URLs
            String urlLabel = StringUtils.substringAfter(displayURL, "file:");
            urlLabel = StringUtils.stripStart(urlLabel, "/");
            urlLabel = "\\\\" + StringUtils.replace(urlLabel, "/", "\\");
            try {
                urlLabel = URLDecoder.decode(urlLabel, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            add(new Label("url", urlLabel));
        } else {
            add(new Label("url", displayURL));
        }

        final ReloadableEntityModel<RecordCollection> collectionModel = new ReloadableEntityModel<RecordCollection>(
                collection);
        add(new ListView("searchResultFields", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                RecordCollection collection = collectionModel.getObject();
                return collection.getSearchResultFields();
            }

            /**
             * Detaches from the current request. Implement this method with
             * custom behavior, such as setting the model object to null.
             */
            protected void onDetach() {
                recordModel.detach();
                collectionModel.detach();
            }
        }) {
            @Override
            protected void populateItem(ListItem item) {
                SearchResultField searchResultField = (SearchResultField) item.getModelObject();
                IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
                Record record = recordModel.getObject();
                IndexField indexField = searchResultField.getIndexField();
                Locale locale = getLocale();
                String indexFieldTitle = indexField.getTitle(locale);
                if (StringUtils.isBlank(indexFieldTitle)) {
                    indexFieldTitle = indexField.getName();
                }
                StringBuffer fieldValueSb = new StringBuffer();
                List<Object> fieldValues = indexFieldServices.extractFieldValues(record, indexField);
                Map<String, String> defaultLabelledValues = indexFieldServices
                        .getDefaultLabelledValues(indexField, locale);
                for (Object fieldValue : fieldValues) {
                    if (fieldValueSb.length() > 0) {
                        fieldValueSb.append("\n");
                    }
                    String fieldValueLabel = indexField.getLabelledValue("" + fieldValue, locale);
                    if (fieldValueLabel == null) {
                        fieldValueLabel = defaultLabelledValues.get("" + fieldValue);
                    }
                    if (fieldValueLabel == null) {
                        fieldValueLabel = "" + fieldValue;
                    }
                    fieldValueSb.append(fieldValueLabel);
                }

                item.add(new Label("indexField", indexFieldTitle));
                item.add(new MultiLineLabel("indexFieldValue", fieldValueSb.toString()));
                item.setVisible(fieldValueSb.length() > 0);
            }

            @SuppressWarnings("unchecked")
            @Override
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    List<SearchResultField> searchResultFields = (List<SearchResultField>) getModelObject();
                    visible = !searchResultFields.isEmpty();
                }
                return visible;
            }
        });

        // md5
        ConstellioSession session = ConstellioSession.get();
        ConstellioUser user = session.getUser();
        // TODO Provide access to unauthenticated users ?
        String md5 = "";
        if (user != null) {
            IntelliGIDServiceInfo intelligidServiceInfo = ConstellioSpringUtils.getIntelliGIDServiceInfo();
            if (intelligidServiceInfo != null) {
                Collection<Object> md5Coll = doc.getFieldValues(IndexField.MD5);
                if (md5Coll != null) {
                    for (Object md5Obj : md5Coll) {
                        try {
                            String md5Str = new String(Hex.encodeHex(Base64.decodeBase64(md5Obj.toString())));
                            InputStream is = HttpClientHelper
                                    .get(intelligidServiceInfo.getIntelligidUrl() + "/connector/checksum",
                                            "md5=" + URLEncoder.encode(md5Str, "ISO-8859-1"),
                                            "username=" + URLEncoder.encode(user.getUsername(), "ISO-8859-1"),
                                            "password=" + URLEncoder.encode(Base64.encodeBase64String(
                                                    ConstellioSession.get().getPassword().getBytes())),
                                            "ISO-8859-1");
                            try {
                                Document xmlDocument = new SAXReader().read(is);
                                Element root = xmlDocument.getRootElement();
                                for (Iterator<Element> it = root.elementIterator("fichier"); it.hasNext();) {
                                    Element fichier = it.next();
                                    String url = fichier.attributeValue("url");
                                    md5 += "<a href=\"" + url + "\">" + url + "</a> ";
                                }
                            } finally {
                                IOUtils.closeQuietly(is);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        Label md5Label = new Label("md5", md5) {
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    visible = StringUtils.isNotBlank(this.getModelObjectAsString());
                }
                return visible;
            }
        };
        md5Label.setEscapeModelStrings(false);
        add(md5Label);

        add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch()));
    } else {
        setVisible(false);
    }
}

From source file:org.sakaiproject.oauth.tool.user.pages.ListAccessors.java

License:Educational Community License

public ListAccessors() {
    String userId = sessionManager.getCurrentSessionUserId();
    Collection<Accessor> accessors = oAuthService.getAccessAccessorForUser(userId);
    ListView<Accessor> accessorList = new ListView<Accessor>("accessorlist",
            new ArrayList<Accessor>(accessors)) {
        @Override/*  w  ww  .  j  a  v  a 2 s . co m*/
        protected void populateItem(ListItem<Accessor> components) {
            try {
                final Consumer consumer = oAuthService.getConsumer(components.getModelObject().getConsumerId());
                ExternalLink consumerHomepage = new ExternalLink("consumerUrl", consumer.getUrl(),
                        consumer.getName());
                consumerHomepage.add(new SimpleAttributeModifier("target", "_blank"));
                consumerHomepage.setEnabled(consumer.getUrl() != null && !consumer.getUrl().isEmpty());
                components.add(consumerHomepage);
                components.add(new Label("consumerDescription", consumer.getDescription()));
                components.add(new Label("creationDate", new StringResourceModel("creation.date", null,
                        new Object[] { components.getModelObject().getCreationDate() })));
                components.add(new Label("expirationDate", new StringResourceModel("expiration.date", null,
                        new Object[] { components.getModelObject().getExpirationDate() })));

                components.add(new Link<Accessor>("delete", components.getModel()) {
                    @Override
                    public void onClick() {
                        try {
                            oAuthService.revokeAccessor(getModelObject().getToken());
                            setResponsePage(getPage().getClass());
                            getSession().info(consumer.getName() + "' token has been removed.");
                        } catch (Exception e) {
                            warn("Couldn't remove " + consumer.getName() + "'s token': "
                                    + e.getLocalizedMessage());
                        }
                    }
                });
            } catch (InvalidConsumerException invalidConsumerException) {
                // Invalid consumer, it is probably deleted
                // For security reasons, this token should be revoked
                oAuthService.revokeAccessor(components.getModelObject().getToken());
                components.setVisible(false);
            }
        }

        @Override
        public boolean isVisible() {
            return !getModelObject().isEmpty() && super.isVisible();
        }
    };
    add(accessorList);

    Label noAccessorLabel = new Label("noAccessor", new ResourceModel("no.accessor"));
    noAccessorLabel.setVisible(!accessorList.isVisible());
    add(noAccessorLabel);
}

From source file:org.sakaiproject.sitestats.tool.wicket.components.ImageWithLink.java

License:Educational Community License

public ImageWithLink(String id, String imgUrl, String lnkUrl, String lnkLabel, String lnkTarget) {
    super(id);/*from w ww . j a va 2s.co m*/
    setRenderBodyOnly(false);
    boolean exists = (lnkTarget != null && lnkLabel != null && lnkUrl != null);
    ExternalLink lnk = null;
    if (exists) {
        add(new ExternalImage("image", imgUrl).setVisible(imgUrl != null));
        lnk = new ExternalLink("link", lnkUrl, lnkLabel);
        lnk.add(new AttributeModifier("target", true, new Model(lnkTarget)));
    } else {
        StringBuilder b = new StringBuilder();
        b.append(lnkLabel);
        b.append(' ');
        b.append(((String) new ResourceModel("resource_unknown").getObject()));
        add(new ExternalImage("image", StatsManager.SILK_ICONS_DIR + "cross.png").setVisible(true));
        lnk = new ExternalLink("link", lnkUrl, b.toString());
        lnk.setEnabled(false);
    }
    add(lnk);
}

From source file:org.sakaiproject.wicket.markup.html.repeater.data.table.ExternalAction.java

License:Educational Community License

public Component newLink(String id, Object bean) {
    IModel labelModel = null;/*from  w  w w  . j  a va2 s. c o  m*/
    if (displayModel != null) {
        labelModel = displayModel;
    } else {
        String labelValue = String.valueOf(PropertyResolver.getValue(labelPropertyExpression, bean));
        labelModel = new Model(labelValue);
    }

    String urlValue = String.valueOf(PropertyResolver.getValue(urlPropertyExpression, bean));

    ExternalLink link = new ExternalLink(id, new Model(urlValue), labelModel);

    if (popupWindowName != null)
        link.setPopupSettings(new PopupSettings(PopupSettings.RESIZABLE | PopupSettings.SCROLLBARS)
                .setWindowName(popupWindowName));

    link.setEnabled(isEnabled(bean));

    if (targetAttribute == null)
        link.add(new AttributeModifier("target", true, new Model(targetAttribute)));

    return link;
}