List of usage examples for org.apache.wicket.util.string AppendingStringBuffer AppendingStringBuffer
public AppendingStringBuffer(final CharSequence str)
From source file:com.antilia.web.field.impl.TableRadioChoice.java
License:Apache License
/** * @see org.apache.wicket.Component#onComponentTagBody(MarkupStream, ComponentTag) *///ww w .j ava 2 s . c o m @Override protected final void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) { // Iterate through choices final List<? extends T> choices = getChoices(); // Buffer to hold generated body final AppendingStringBuffer buffer = new AppendingStringBuffer((choices.size() + 1) * 70); // The selected value final String selected = getValue(); buffer.append("<table style=\"width: 100%;\" cellpadding=\"0\" cellspacing=\"5\">"); // Loop through choices for (int index = 0; index < choices.size(); index++) { // Get next choice final T choice = choices.get(index); Object displayValue = getChoiceRenderer().getDisplayValue(choice); Class<?> objectClass = (displayValue == null ? null : displayValue.getClass()); // Get label for choice String label = ""; if (objectClass != null && objectClass != String.class) { final IConverter converter = (IConverter) getConverter(objectClass); if (!converter.getClass().isAssignableFrom(objectClass)) { throw new IllegalArgumentException( "converter can not convert " + objectClass.getName() + " to string"); } label = converter.convertToString(displayValue, getLocale()); } else if (displayValue != null) { label = displayValue.toString(); } // If there is a display value for the choice, then we know that the // choice is automatic in some way. If label is /null/ then we know // that the choice is a manually created radio tag at some random // location in the page markup! if (label != null) { // Append option suffix buffer.append(getPrefix()); String id = getChoiceRenderer().getIdValue(choice, index); final String idAttr = getMarkupId() + "_" + id; buffer.append("<tr>"); buffer.append("<td style=\"width: 15px; vertical-align: top;\">"); // Add radio tag buffer.append("<input name=\"").append(getInputName()).append("\"").append(" type=\"radio\"") .append((isSelected(choice, index, selected) ? " checked=\"checked\"" : "")) .append((isEnabled() ? "" : " disabled=\"disabled\"")).append(" value=\"").append(id) .append("\" id=\"").append(idAttr).append("\""); // Should a roundtrip be made (have onSelectionChanged called) // when the option is clicked? if (wantOnSelectionChangedNotifications()) { CharSequence url = urlFor(IOnChangeListener.INTERFACE); Form<?> form = findParent(Form.class); if (form != null) { RequestContext rc = RequestContext.get(); if (rc.isPortletRequest()) { // restore url back to real wicket path as its going to be interpreted // by the form itself url = ((PortletRequestContext) rc).getLastEncodedPath(); } buffer.append(" onclick=\"").append(form.getJsForInterfaceUrl(url)).append(";\""); } else { // TODO: following doesn't work with portlets, should be posted to a dynamic // hidden form // with an ActionURL or something // NOTE: do not encode the url as that would give // invalid JavaScript buffer.append(" onclick=\"window.location.href='").append(url) .append((url.toString().indexOf('?') > -1 ? "&" : "?") + getInputName()) .append("=").append(id).append("';\""); } } buffer.append("/>"); buffer.append("</td>"); buffer.append("<td nowrap=\"nowrap\" style=\"width: 300px;\">"); // Add label for radio button String display = label; if (localizeDisplayValues()) { display = getLocalizer().getString(label, this, label); } CharSequence escaped = Strings.escapeMarkup(display, false, true); buffer.append(escaped); // Append option suffix buffer.append(getSuffix()); buffer.append("</td>"); buffer.append("</tr>"); } } buffer.append("</table>"); // Replace body replaceComponentTagBody(markupStream, openTag, buffer); }
From source file:com.francetelecom.clara.cloud.presentation.tools.ServerPageMetaFilter.java
License:Apache License
/** * @see org.apache.wicket.IResponseFilter#filter(AppendingStringBuffer) *///from w w w . j ava 2 s .c om public AppendingStringBuffer filter(AppendingStringBuffer responseBuffer) { String responseHtmlTagUsed = "</html>"; int index = responseBuffer.indexOf(responseHtmlTagUsed); long timeTaken = System.currentTimeMillis() - RequestCycle.get().getStartTime(); if (index != -1) { AppendingStringBuffer script = new AppendingStringBuffer(125); script.append("\n<!--"); // server time used script.append("\n window.pagemeta.serverPageRenderingTime=' "); script.append(((double) timeTaken) / 1000); script.append("s';\n"); // server ip script.append("\n window.pagemeta.serverIP='"); script.append(retrieveServerIP()); script.append("';\n"); // rendering date script.append("\n window.pagemeta.renderingDate='"); script.append(retrieveRenderingDateStr()); script.append("';\n"); script.append(" -->\n"); responseBuffer.insert(index, script); } log.debug(timeTaken + "ms server time taken for request " + RequestCycle.get().getRequest().getUrl() + " response size: " + responseBuffer.length()); return responseBuffer; }
From source file:com.gitblit.wicket.SessionlessForm.java
License:Apache License
/** * Append an additional hidden input tag that forces Wicket to correctly * determine the destination page class even after a session expiration or * a server restart.// www . j a v a2 s. c o m * * @param markupStream * The markup stream * @param openTag * The open tag for the body */ @Override public void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) { // render the hidden bookmarkable page field AppendingStringBuffer buffer = new AppendingStringBuffer(HIDDEN_DIV_START); buffer.append("<input type=\"hidden\" name=\"").append("wicket:bookmarkablePage").append("\" value=\":") .append(pageClass.getName()).append("\" />"); // insert the page parameters, if any, as hidden fields as long as they // do not collide with any child wicket:id of the form. if (pageParameters != null) { for (String key : pageParameters.getNamedKeys()) { Component c = get(key); if (c != null) { // this form has a field id which matches the // parameter name, skip embedding a hidden value log.warn(MessageFormat.format( "Skipping page parameter \"{0}\" from sessionless form hidden fields because it collides with a form child wicket:id", key)); continue; } String value = pageParameters.get(key).toString(); buffer.append("<input type=\"hidden\" name=\"").append(recode(key)).append("\" value=\"") .append(recode(value)).append("\" />"); } } buffer.append("</div>"); getResponse().write(buffer); super.onComponentTagBody(markupStream, openTag); }
From source file:com.googlecode.ounit.HtmlFile.java
License:Open Source License
@Override public Markup getAssociatedMarkup() { File f = getFile();/*from www. j a v a 2s . c o m*/ if (!getFile().canRead()) { //return Markup.NO_MARKUP; return Markup.of("<wicket:panel></wicket:panel>"); } final AppendingStringBuffer sb = new AppendingStringBuffer("<wicket:panel>"); try { sb.append(f.readString()); } catch (IOException e) { throw new RuntimeException(e); } sb.append("</wicket:panel>"); InvalidMarkupFilter.removeInvalidMarkup(sb); return MarkupFactory.get().loadMarkup(this, new MarkupResourceStream(new StringResourceStream(sb)), false); }
From source file:com.lyndir.lhunath.snaplog.webapp.tab.HomeTabPanel.java
License:Apache License
/** * Create a new {@link HomeTabPanel} instance. * * @param id The wicket ID that will hold the {@link HomeTabPanel}. *///from w w w.j a v a 2 s . co m public HomeTabPanel(final String id) { super(id, new HomeTabModels().getModel()); getModelObject().attach(this); add(new Label("tagsHelp", getModelObject().usersHelp())); add(new AbstractTagsView("tags", new IPredicate<Tag>() { @Override public boolean apply(final Tag input) { return input.isAdvertise(); } }, TAGS_PER_PAGE) { @Override protected void populateItem(final Item<Tag> tagItem) { tagItem.add(new MediaView("tagCover", cover(tagItem.getModel()), Quality.THUMBNAIL, true) { @Override protected void onClick(final AjaxRequestTarget target) { Tab.TAG.activateWithState(new TagTabPanel.TagTabState(tagItem.getModelObject())); } @Override protected String getCaptionString() { // TODO: Tags? return null; } }); } }); add((searchForm = new Form<String>("searchForm", new Model<String>()) { final AbstractUsersView usersView; final AbstractTagsView tagsView; { // Search Query final IModel<String> queryModel = getModel(); add(new RequiredTextField<String>("query", queryModel)); // Results add(new Label("results", new LoadableDetachableModel<String>() { @Override protected String load() { int resultCount = usersView.getItemCount() + tagsView.getItemCount(); if (resultCount == 0) return msgs.noResults(); else if (resultCount == 1) return msgs.singularResult(resultCount); else return msgs.multipleResults(resultCount); } }) { @Override public boolean isVisible() { return queryModel.getObject() != null && queryModel.getObject().length() > 0; } }); // Found Users add(usersView = new AbstractUsersView("users", new IPredicate<User>() { @Override public boolean apply(final User input) { // Applies for a user whose userName contains the search string (case insensitively). return input != null && queryModel.getObject() != null && queryModel.getObject().length() > 0 // && input.getUserName().toUpperCase().contains(queryModel.getObject().toUpperCase()); } }, USERS_PER_PAGE) { @Override protected void populateItem(final Item<User> userItem) { userItem.add(new UserLink("userName", userItem.getModel())); userItem.add(new AbstractTagsView("tags", userItem.getModel(), TAGS_PER_PAGE) { @Override protected void populateItem(final Item<Tag> tagItem) { tagItem.add(new MediaView("tagCover", cover(tagItem.getModel()), Quality.THUMBNAIL, true) { @Override protected void onClick(final AjaxRequestTarget target) { Tab.TAG.activateWithState( new TagTabPanel.TagTabState(tagItem.getModelObject())); } @Override protected String getCaptionString() { return tagItem.getModelObject().getName(); } }); } }); } }); // Found Albums add(tagsView = new AbstractTagsView("tags", new IPredicate<Tag>() { @Override public boolean apply(final Tag input) { // Applies for an album whose name contains the search string (case insensitively). return input != null && queryModel.getObject() != null && queryModel.getObject().length() > 0 // && input.getName().toUpperCase().contains(queryModel.getObject().toUpperCase()); } }, TAGS_PER_PAGE) { @Override protected void populateItem(final Item<Tag> tagItem) { tagItem.add(new MediaView("cover", cover(tagItem.getModel()), Quality.THUMBNAIL, true) { @Override public void onClick(final AjaxRequestTarget target) { Tab.TAG.activateWithState(new TagTabPanel.TagTabState(tagItem.getModelObject())); } @Override protected String getCaptionString() { return tagItem.getModelObject().getName(); } }); } }); } }).add(new AjaxFormSubmitBehavior(searchForm, "onsubmit") { @Override protected void onSubmit(final AjaxRequestTarget target) { target.addComponent(getForm()); } @Override protected void onError(final AjaxRequestTarget target) { // TODO: Feedback. } @Override protected CharSequence getEventHandler() { // Prevents the form from generating an http request. // If we do not provide this, the AJAX event is processed AND the form still gets submitted. // FIXME: Ugly. Should probably be moved into AjaxFormSubmitBehaviour. return new AppendingStringBuffer(super.getEventHandler()).append("; return false;"); } }).setOutputMarkupId(true)); }
From source file:com.servoy.j2db.server.headlessclient.dataui.ServoyChoiceComponentUpdatingBehavior.java
License:Open Source License
/** * @see wicket.ajax.AjaxEventBehavior#getEventHandler() *//*from ww w .j a v a 2 s .c o m*/ protected final CharSequence getEventHandler() { return generateCallbackScript(new AppendingStringBuffer("wicketAjaxPost('").append(getCallbackUrl()).append( "', wicketSerializeForm(document.getElementById('" + getComponent().getMarkupId() + "',false))")); }
From source file:com.servoy.j2db.server.headlessclient.dataui.WebCellBasedView.java
License:Open Source License
@SuppressWarnings("nls") public String getColumnResizeScript() { if (resizedComponent instanceof IProviderStylePropertyChanges) { String tableId = getMarkupId(); String classId = resizedComponent.getId(); String sWidth = (String) ((IProviderStylePropertyChanges) resizedComponent).getStylePropertyChanges() .getChanges().get("width"); //$NON-NLS-1$ if (sWidth != null) { resizedComponent = null;//from ww w. j av a 2 s . co m return new AppendingStringBuffer("Servoy.TableView.setTableColumnWidth('").append(tableId) .append("', '").append(classId).append("', ") .append(Integer.parseInt(sWidth.substring(0, sWidth.length() - 2))).append(")").toString(); } } return null; }
From source file:com.servoy.j2db.server.headlessclient.dataui.WebDataHtmlView.java
License:Open Source License
/** * @see com.servoy.j2db.server.headlessclient.dataui.ISupportScriptCallback#getCallBackUrl(java.lang.String, boolean) */// www . ja v a 2 s . com @SuppressWarnings("nls") public CharSequence getCallBackUrl(String scriptName, boolean testDoubleClick) { boolean useAJAX = Utils.getAsBoolean(application.getRuntimeProperties().get("useAJAX")); if (useAJAX) { if (inlineScriptExecutor == null) { inlineScriptExecutor = new InlineScriptExecutorBehavior(this); add(inlineScriptExecutor); } AppendingStringBuffer asb = new AppendingStringBuffer(80); if (testDoubleClick) { asb.append("if (testDoubleClickId('"); asb.append(getMarkupId()); asb.append("')) { "); } asb.append("document.getElementById('").append(getMarkupId()).append("').focus();"); asb.append("window.setTimeout(function() { wicketAjaxGet('"); asb.append(inlineScriptExecutor.getCallbackUrl()); ICrypt urlCrypt = Application.get().getSecuritySettings().getCryptFactory().newCrypt(); asb.append("&snenc="); String escapedScriptName = Utils.stringReplace(Utils.stringReplace(scriptName, "\\\'", "\'"), """, "\""); asb.append(WicketURLEncoder.QUERY_INSTANCE.encode(urlCrypt.encryptUrlSafe(escapedScriptName))); for (String browserArgument : inlineScriptExecutor.getBrowserArguments(scriptName)) { asb.append("&").append(browserArgument).append("=' + ").append(browserArgument).append(" + '"); } asb.append("');}, 0);"); if (testDoubleClick) { asb.append("} "); } asb.append("return false;"); return asb.toString(); } else { return StripHTMLTagsConverter.getTriggerJavaScript(this, scriptName); } }
From source file:com.servoy.j2db.server.headlessclient.DivWindow.java
License:Open Source License
/** * When show was initially called from a child iframe request (thus callback scripts were generated using that * page's target), you need to call this method subsequently on a request from the root main frame, to make * behaviors work with the main page as you would expect (otherwise problems occur when you try to close it). * @param mainFrameTarget// w w w .ja v a2 s .c o m * @param childFrameBatchId should never be null; it is the child frame batchId that will execute/has executed the show. */ public void reAttachBehaviorsAfterShow(AjaxRequestTarget mainFrameTarget, String childFrameBatchId) { if (childFrameBatchId == null) throw new IllegalArgumentException( "'reAttachBehaviors' is only to be called if a show happened on child frame."); AppendingStringBuffer settingsToUpdate = new AppendingStringBuffer(500); // if show was already called (as a result of a child frame request), just re-register; otherwise wait for show to be called and that will do the re-register directly settingsToUpdate.append("function (settings) {\n"); attachOnMove(settingsToUpdate); attachOnResize(settingsToUpdate); reattachOnClose(settingsToUpdate); reattachOnCloseButton(settingsToUpdate); settingsToUpdate.append("}"); mainFrameTarget.appendJavascript("Wicket.DivWindow.reAttachBehaviorsAfterShow(" + settingsToUpdate.toString() + ", \"" + getJSId() + "\", \"" + childFrameBatchId + "\");"); }
From source file:com.servoy.j2db.server.ngclient.NGClient.java
private void initLocaleAndTimeZone() { Object retValue = null;// w w w. ja v a 2s. c o m try { retValue = this.getWebsocketSession().getClientService(NGClient.APPLICATION_SERVICE) .executeServiceCall("getUtcOffsetsAndLocale", null); } catch (IOException e) { Debug.warn(e); return; } if (retValue instanceof JSONObject) { String userAgent = ((JSONObject) retValue).optString("userAgent"); if (userAgent != null) { getClientInfo().addInfo("useragent:" + userAgent); } String platform = ((JSONObject) retValue).optString("platform"); if (platform != null) { getClientInfo().addInfo("platform:" + platform); } if (timeZone == null) { String utc = ((JSONObject) retValue).optString("utcOffset"); if (utc != null) { // apparently it is platform dependent on whether you get the // offset in a decimal form or not. This parses the decimal // form of the UTC offset, taking into account several // possibilities // such as getting the format in +2.5 or -1.2 int dotPos = utc.indexOf('.'); if (dotPos >= 0) { String hours = utc.substring(0, dotPos); String hourPart = utc.substring(dotPos + 1); if (hours.startsWith("+")) { hours = hours.substring(1); } int offsetHours = Integer.parseInt(hours); int offsetMins = (int) (Double.parseDouble(hourPart) * 6); // construct a GMT timezone offset string from the retrieved // offset which can be parsed by the TimeZone class. AppendingStringBuffer sb = new AppendingStringBuffer("GMT"); sb.append(offsetHours > 0 ? "+" : "-"); sb.append(Math.abs(offsetHours)); sb.append(":"); if (offsetMins < 10) { sb.append("0"); } sb.append(offsetMins); timeZone = TimeZone.getTimeZone(sb.toString()); } else { int offset = Integer.parseInt(utc); if (offset < 0) { utc = utc.substring(1); } timeZone = TimeZone.getTimeZone("GMT" + ((offset > 0) ? "+" : "-") + utc); } String dstOffset = ((JSONObject) retValue).optString("utcDstOffset"); if (timeZone != null && dstOffset != null) { TimeZone dstTimeZone = null; dotPos = dstOffset.indexOf('.'); if (dotPos >= 0) { String hours = dstOffset.substring(0, dotPos); String hourPart = dstOffset.substring(dotPos + 1); if (hours.startsWith("+")) { hours = hours.substring(1); } int offsetHours = Integer.parseInt(hours); int offsetMins = (int) (Double.parseDouble(hourPart) * 6); // construct a GMT timezone offset string from the // retrieved // offset which can be parsed by the TimeZone class. AppendingStringBuffer sb = new AppendingStringBuffer("GMT"); sb.append(offsetHours > 0 ? "+" : "-"); sb.append(Math.abs(offsetHours)); sb.append(":"); if (offsetMins < 10) { sb.append("0"); } sb.append(offsetMins); dstTimeZone = TimeZone.getTimeZone(sb.toString()); } else { int offset = Integer.parseInt(dstOffset); if (offset < 0) { dstOffset = dstOffset.substring(1); } dstTimeZone = TimeZone.getTimeZone("GMT" + ((offset > 0) ? "+" : "-") + dstOffset); } // if the dstTimezone (1 July) has a different offset then // the real time zone (1 January) try to combine the 2. if (dstTimeZone != null && dstTimeZone.getRawOffset() != timeZone.getRawOffset()) { int dstSaving = dstTimeZone.getRawOffset() - timeZone.getRawOffset(); String[] availableIDs = TimeZone.getAvailableIDs(timeZone.getRawOffset()); for (String availableID : availableIDs) { TimeZone zone = TimeZone.getTimeZone(availableID); if (zone.getDSTSavings() == dstSaving) { // this is a best guess... still the start and end of the DST should // be needed to know to be completely correct, or better yet // not just the GMT offset but the TimeZone ID should be transfered // from the browser. timeZone = zone; break; } } } // if the timezone is really just the default of the server just use that one. TimeZone dftZone = TimeZone.getDefault(); if (timeZone.getRawOffset() == dftZone.getRawOffset() && timeZone.getDSTSavings() == dftZone.getDSTSavings()) { timeZone = dftZone; } } } } if (locale == null) { String browserLocale = ((JSONObject) retValue).optString("locale"); if (browserLocale != null) { String[] languageAndCountry = browserLocale.split("-"); if (languageAndCountry.length == 1) { locale = new Locale(languageAndCountry[0]); } else if (languageAndCountry.length == 2) { locale = new Locale(languageAndCountry[0], languageAndCountry[1]); } getClientInfo().addInfo("locale:" + locale); } } } if (timeZone != null) { getClientInfo().setTimeZone(timeZone); } getClientInfo().addInfo("session uuid: " + getWebsocketSession().getUuid()); try { getClientHost().pushClientInfo(getClientInfo().getClientId(), getClientInfo()); } catch (RemoteException e) { Debug.error(e); } }