List of usage examples for org.apache.wicket.util.resource StringResourceStream StringResourceStream
public StringResourceStream(final CharSequence string, final String contentType)
From source file:com.chitek.ignition.drivers.generictcp.meta.config.ui.MessageConfigUI.java
License:Apache License
private void addComponents() { // Select the first message for initial display if (getConfig().messages.isEmpty()) { // No messages configured. Create a new message with id=1. getConfig().addMessageConfig(new MessageConfig(1)); }//from w ww .j a v a2 s. c o m currentMessage = getConfig().getMessageList().get(0); currentMessage.calcOffsets(getConfig().getMessageIdType().getByteSize()); currentMessageId = currentMessage.getMessageId(); // ******************************************************************************************* // *** Form for XML import final FileUploadField uploadField = new FileUploadField("upload-field", new ListModel<FileUpload>()); Form<?> uploadForm = new Form<Object>("upload-form") { @Override protected void onSubmit() { try { FileUpload upload = uploadField.getFileUpload(); if (upload != null) { handleOnUpload(upload.getInputStream()); } else { warn(new StringResourceModel("warn.noFileToUpload", this, null).getString()); } } catch (Exception e) { this.error(new StringResourceModel("import.error", this, null).getString() + " Exception: " + e.toString()); } } }; uploadForm.add(uploadField); SubmitLink importLink = new SubmitLink("import-link"); uploadForm.add(importLink); add(uploadForm); // ******************************************************************************************* // *** The message configuration currentMessageModel = new PropertyModel<MessageConfig>(this, "currentMessage"); editForm = new Form<MessageConfig>("edit-form", new CompoundPropertyModel<MessageConfig>(currentMessageModel)) { @Override protected void onError() { // Validation error - reset the message dropdown to the original value // Clear input causes the component to reload the model currentMessageIdDropdown.clearInput(); super.onError(); } }; editForm.add(new MessageFormValidator()); WebMarkupContainer tableContainer = new WebMarkupContainer("table-container"); messageIdTypeDropDown = getMessageIdTypeDropdown(); tableContainer.add(messageIdTypeDropDown); currentMessageIdDropdown = getCurrentMessageIdDropdown(); tableContainer.add(currentMessageIdDropdown); Button buttonNew = new Button("new"); buttonNew.add(new AjaxFormSubmitBehavior("onclick") { @Override protected void onSubmit(AjaxRequestTarget target) { handleNew(target); } @Override protected void onError(AjaxRequestTarget target) { handleError(target); } }); tableContainer.add(buttonNew); Button buttonCopy = new Button("copy"); buttonCopy.add(new AjaxFormSubmitBehavior("onclick") { @Override protected void onSubmit(AjaxRequestTarget target) { handleCopy(target); } @Override protected void onError(AjaxRequestTarget target) { handleError(target); } }); tableContainer.add(buttonCopy); Button deleteButton = new Button("delete"); deleteButton.add(new AjaxEventBehavior("onclick") { @Override protected void onEvent(AjaxRequestTarget target) { handleDelete(target); } }); tableContainer.add(deleteButton); messageTypeDropdown = getMessageTypeDropdown(); tableContainer.add(messageTypeDropdown); tableContainer.add(getQueueModeDropdown()); tableContainer.add(new CheckBox("usePersistance").setOutputMarkupId(true)); WebMarkupContainer listEditorContainer = new WebMarkupContainer("list-editor"); messageIdTextField = getMessageIdTextField(); listEditorContainer.add(messageIdTextField); messageAliasTextField = getMessageAliasTextField(); listEditorContainer.add(messageAliasTextField); // Create the list editor editor = new ListEditor<TagConfig>("tags", new PropertyModel<List<TagConfig>>(currentMessageModel, "tags")) { @Override protected void onPopulateItem(EditorListItem<TagConfig> item) { item.setModel(new CompoundPropertyModel<TagConfig>(item.getModelObject())); BinaryDataType dataType = item.getModelObject().getDataType(); boolean enable = dataType.isSpecial() ? false : true; // Offset is displayed only for information item.add(new Label("offset").setOutputMarkupId(true)); if (enable) { item.add(getIdTextField()); } else { // The static TextField has no validation. Validation would fail for special tags. item.add(getSpecialIdTextField().setEnabled(false)); } item.add(getAliasTextField().setVisible(enable)); item.add(getSizeTextField().setEnabled(dataType.isArrayAllowed())); item.add(getTagLengthTypeDropDown().setEnabled(dataType.supportsVariableLength())); item.add(getDataTypeDropdown()); // Create the edit links to be used in the list editor item.add(getInsertLink()); item.add(getDeleteLink()); item.add(getMoveUpLink().setVisible(item.getIndex() > 0)); item.add(getMoveDownLink().setVisible(item.getIndex() < getList().size() - 1)); } }; listEditorContainer.add(editor); Label noItemsLabel = new Label("no-items-label", new StringResourceModel("noitems", this, null)) { @Override public boolean isVisible() { return editor.getList().size() == 0; } }; listEditorContainer.add(noItemsLabel); listEditorContainer.add(new EditorSubmitLink("add-row-link") { @Override public void onSubmit() { editor.addItem(new TagConfig()); // Adjust the visibility of the edit links updateListEditor(editor); } }); listEditorContainer.setOutputMarkupId(true); tableContainer.add(listEditorContainer); editForm.add(tableContainer); // XML export SubmitLink exportLink = new SubmitLink("export-link", editForm) { @Override public void onSubmit() { ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(getResourceStream(), getFileName()); handler.setContentDisposition(ContentDisposition.ATTACHMENT); handler.setCacheDuration(Duration.NONE); getRequestCycle().scheduleRequestHandlerAfterCurrent(handler); } private String getFileName() { return String.format("MsgConfig_%s.xml", currentMessageModel.getObject().getMessageId()); } private IResourceStream getResourceStream() { String config = currentMessageModel.getObject().toXMLString(); return new StringResourceStream(config, "text/xml"); } }; editForm.add(exportLink); uploadForm.add(editForm); }
From source file:com.servoy.j2db.server.headlessclient.FormCssResource.java
License:Open Source License
/** * @see org.apache.wicket.Resource#getResourceStream() *///from w w w.j a v a 2 s . co m @Override public IResourceStream getResourceStream() { String css = ""; ValueMap params = getParameters(); Long time = null; if (params.size() == 1) { Iterator iterator = params.entrySet().iterator(); if (iterator.hasNext()) { Map.Entry entry = (Entry) iterator.next(); String solutionName = (String) entry.getKey(); Pair<String, Long> filterTime = filterTime((String) entry.getValue()); String formInstanceName = filterTime.getLeft(); time = filterTime.getRight(); String solutionAndForm = solutionName + "/" + formInstanceName; //$NON-NLS-1$ String templateDir = "default"; //$NON-NLS-1$ IServiceProvider sp = null; Solution solution = null; Form form = null; if (Session.exists()) { sp = WebClientSession.get().getWebClient(); if (sp != null) { IForm fc = ((WebClient) sp).getFormManager().getForm(formInstanceName); if (fc instanceof FormController) { FlattenedSolution clientSolution = sp.getFlattenedSolution(); form = clientSolution.getForm(((FormController) fc).getForm().getName()); } } templateDir = WebClientSession.get().getTemplateDirectoryName(); } final String fullpath = "/servoy-webclient/templates/" + templateDir + "/" + solutionAndForm + ".css"; try { URL url = context.getResource(fullpath); if (url != null) { return new NullUrlResourceStream(url); } } catch (Exception e) { Debug.error(e); } try { IApplicationServerSingleton as = ApplicationServerRegistry.get(); RootObjectMetaData sd = as.getLocalRepository().getRootObjectMetaData(solutionName, IRepository.SOLUTIONS); if (sd != null) { solution = (Solution) as.getLocalRepository().getActiveRootObject(sd.getRootObjectId()); if (form == null) { form = solution.getForm(formInstanceName); } } if (form != null) { Pair<String, String> formHTMLAndCSS = TemplateGenerator.getFormHTMLAndCSS(solution, form, sp, formInstanceName); css = formHTMLAndCSS.getRight(); } } catch (Exception e) { Debug.error(e); } } } StringResourceStream stream = new StringResourceStream(css, "text/css"); //$NON-NLS-1$ stream.setLastModified(time != null ? Time.valueOf(time.longValue()) : null); return stream; }
From source file:de.alpharogroup.wicket.js.addon.core.StringTextTemplate.java
License:Apache License
/** * Creates a new instance of a {@link StringTextTemplate}. * //from w ww . j a v a 2s. c o m * @param content * The content of the template. * @param contentType * The content type. * @param encoding * the file's encoding */ public StringTextTemplate(final String content, final String contentType, final String encoding) { super(contentType); final IResourceStream stream = new StringResourceStream(content, getContentType()); try { if (encoding != null) { buffer.append(Streams.readString(stream.getInputStream(), encoding)); } else { buffer.append(Streams.readString(stream.getInputStream())); } } catch (final IOException e) { throw new RuntimeException(e); } catch (final ResourceStreamNotFoundException e) { throw new RuntimeException(e); } finally { try { stream.close(); } catch (final IOException e) { LOGGER.error("" + e.getMessage(), e); } } }
From source file:de.jetwick.ui.ResultsPanel.java
License:Apache License
public ResultsPanel(String id, final String toLanguage) { super(id);//www . j a v a 2 s . c o m add(new Label("qm", new PropertyModel(this, "queryMessage"))); add(new Label("qmWarn", new PropertyModel(this, "queryMessageWarn")) { @Override public boolean isVisible() { return queryMessageWarn != null && queryMessageWarn.length() > 0; } }); add(createHitLink(15)); add(createHitLink(30)); add(createHitLink(60)); Model qModel = new Model() { @Override public Serializable getObject() { if (query == null) return ""; String str = query; if (str.length() > 20) str = str.substring(0, 20) + ".."; return "Find origin of '" + str + "'"; } }; findOriginLink = new LabeledLink("findOriginLink", null, qModel, false) { @Override public void onClick(AjaxRequestTarget target) { PageParameters pp = new PageParameters(); pp.add("findOrigin", query); setResponsePage(TweetSearchPage.class, pp); } }; add(findOriginLink); translateAllLink = new LabeledLink("translateAllLink", null, new Model<String>() { @Override public String getObject() { if (translateAll) return "Show original language"; else // get english name of iso language chars return "Translate tweets into " + new Locale(toLanguage).getDisplayLanguage(new Locale("en")); } }) { @Override public void onClick(AjaxRequestTarget target) { if (target == null) return; translateAll = !translateAll; if (!translateAll) translateMap.clear(); target.addComponent(ResultsPanel.this); } }; add(translateAllLink); add(createSortLink("sortRelevance", ElasticTweetSearch.RELEVANCE, "desc")); add(createSortLink("sortRetweets", ElasticTweetSearch.RT_COUNT, "desc")); add(createSortLink("sortLatest", ElasticTweetSearch.DATE, "desc")); add(createSortLink("sortOldest", ElasticTweetSearch.DATE, "asc")); add(new DialogUtilsBehavior()); userView = new ListView("users", users) { @Override public void populateItem(final ListItem item) { final JUser user = (JUser) item.getModelObject(); String name = user.getScreenName(); if (user.getRealName() != null) name = user.getRealName() + " (" + name + ")"; LabeledLink userNameLink = new LabeledLink("userNameLink", name, false) { @Override public void onClick(AjaxRequestTarget target) { onUserClick(user.getScreenName(), null); } }; item.add(userNameLink); Link showLatestTweets = new Link("profileUrl") { @Override public void onClick() { onUserClick(user.getScreenName(), null); } }; item.add(showLatestTweets.add(new ContextImage("profileImg", user.getProfileImageUrl()))); final List<JTweet> tweets = new ArrayList<JTweet>(); int counter = 0; for (JTweet tw : user.getOwnTweets()) { if (tweetsPerUser > 0 && counter >= tweetsPerUser) break; tweets.add(tw); allTweets.put(tw.getTwitterId(), tw); counter++; } ListView tweetView = new ListView("tweets", tweets) { @Override public void populateItem(final ListItem item) { item.add(createOneTweet("oneTweet", toLanguage).init(item.getModel(), false)); } }; item.add(tweetView); } }; add(userView); WebResource export = new WebResource() { @Override public IResourceStream getResourceStream() { return new StringResourceStream(getTweetsAsString(), "text/plain"); } @Override protected void setHeaders(WebResponse response) { super.setHeaders(response); response.setAttachmentHeader("tweets.txt"); } }; export.setCacheable(false); add(new ResourceLink("exportTsvLink", export)); add(new Link("exportHtmlLink") { @Override public void onClick() { onHtmlExport(); } }); }
From source file:net.kornr.swit.wicket.layout.threecol.ThreeColumnsLayoutResource.java
License:Apache License
@Override public IResourceStream getResourceStream() { ValueMap map = this.getParameters(); String name = map.getString("id", null); if (name == null) return null; LayoutInfo current = m_layouts.get(name); current = current.duplicate();//from www. ja va2s . co m try { current.setLeftSize(map.getInt("left", current.getLeftSize())); current.setRightSize(map.getInt("right", current.getRightSize())); current.setUnit(map.getInt("unit", current.getUnit())); String leftcol = map.getString("leftcol", null); if (leftcol != null) current.setLeftColor(new Color(Integer.parseInt(leftcol))); String rightcol = map.getString("rightcol", null); if (rightcol != null) current.setLeftColor(new Color(Integer.parseInt(rightcol))); String middlecol = map.getString("middlecol", null); if (middlecol != null) current.setLeftColor(new Color(Integer.parseInt(middlecol))); } catch (Exception exc) { // We don't really care if there's an error exc.printStackTrace(); } String css = getStyle(current); return new StringResourceStream(css, "text/css"); }
From source file:nl.knaw.dans.dccd.web.download.DownloadPanel.java
License:Apache License
private WebResource getXMLWebResource() //final Project project) { WebResource export = new WebResource() { private static final long serialVersionUID = -5599977621589734872L; @Override/*from ww w . j a v a 2 s .c o m*/ public IResourceStream getResourceStream() { CharSequence xml = null; java.io.StringWriter sw = new StringWriter(); // get complete project from repository, // just overwrite any thing allready downloaded // convert that to TRiDaS // // Note: make it a service to get xml from a project try { // NOTE for refactoring; we only need an StroreId, not a whole project project = DccdDataService.getService().getProject(storeId); // JAXBContext jaxbContext = null; // System.out.println("\n TRiDaS XML, non valid, but with the structure"); jaxbContext = JAXBContext.newInstance("org.tridas.schema"); // now marshall the pruned clone Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, TRIDAS_XML_CHARSET); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// testing marshaller.marshal(project.getTridas(), sw); // System.out.print(sw.toString()); } catch (DataServiceException e) { e.printStackTrace(); error(e.getMessage()); } catch (JAXBException e) { e.printStackTrace(); error(e.getMessage()); } xml = sw.toString(); StringResourceStream rs = new StringResourceStream(xml, "text/xml"); rs.setCharset(Charset.forName(TRIDAS_XML_CHARSET)); // must be according to tridas return rs; } @Override protected void setHeaders(WebResponse response) { super.setHeaders(response); // construct filename final String XML_EXTENSION = "xml"; String filename = project.getTitle(); if (filename.length() == 0) filename = "tridas"; // at least have decent filename filename = filename + "-" + project.getSid(); // add the repository unique id? filename = filename + "." + XML_EXTENSION; response.setAttachmentHeader(filename); } }; export.setCacheable(false); return export; }
From source file:nl.knaw.dans.dccd.web.search.SearchResultDownloadPage.java
License:Apache License
private IResourceStream getResourceStreamForXML() { CharSequence txt = theData;//getAllResultsAsXML(); StringResourceStream rs = new StringResourceStream(txt, MIMETYPE_XML); rs.setCharset(Charset.forName("UTF-8")); return rs;//from w w w . j a v a 2 s. c o m }
From source file:nl.knaw.dans.dccd.web.search.SearchResultDownloadPage.java
License:Apache License
private IResourceStream getResourceStreamForCSV() { // prepend BOM, some programs like it others don't CharSequence txt = UTF8_BOM + getDataAsTabDelimitedText(); StringResourceStream rs = new StringResourceStream(txt, MIMETYPE_CSV); rs.setCharset(Charset.forName("UTF-8")); return rs;// ww w . ja va 2 s.co m }
From source file:org.apache.isis.viewer.wicket.model.models.ActionModel.java
License:Apache License
private static IResourceStream resourceStreamFor(final Clob clob) { final IResourceStream resourceStream = new StringResourceStream(clob.getChars(), clob.getMimeType().toString()); return resourceStream; }
From source file:org.apache.openmeetings.web.room.StartSharingEventBehavior.java
License:Apache License
@Override protected void respond(AjaxRequestTarget target) { //TODO deny download in case other screen sharing is in progress String app = ""; try (InputStream jnlp = getClass().getClassLoader().getResourceAsStream("APPLICATION.jnlp")) { ConfigurationDao cfgDao = getBean(ConfigurationDao.class); app = IOUtils.toString(jnlp, StandardCharsets.UTF_8); String baseUrl = cfgDao.getBaseUrl(); Room room = getBean(RoomDao.class).get(roomId); String publicSid = getParam(getComponent(), PARAM_PUBLIC_SID).toString(); SessionManager sessionManager = getBean(SessionManager.class); Client rc = getClient(publicSid); if (rc == null) { throw new RuntimeException(String.format("Unable to find client by publicSID '%s'", publicSid)); }// w w w . j a v a 2 s.co m String _url = rc.getTcUrl(); URI url = new URI(_url); String path = url.getPath(); path = path.substring(path.lastIndexOf('/') + 1); if (Strings.isEmpty(path) || rc.getRoomId() == null || !path.equals(rc.getRoomId().toString()) || !rc.getRoomId().equals(roomId)) { throw new RuntimeException(String.format("Invalid room id passed %s, expected, %s", path, roomId)); } Protocol protocol = Protocol.valueOf(url.getScheme()); app = addKeystore(rc, app, protocol).replace("$codebase", baseUrl + "screenshare") .replace("$applicationName", cfgDao.getAppName()).replace("$url", _url) .replace("$publicSid", publicSid) .replace("$labels", CDATA_BEGIN + getLabels(730, 731, 732, 733, 734, 735, 737, 738, 739, 740, 741, 742, 844, 869, 870, 871, 872, 878, 1089, 1090, 1091, 1092, 1093, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474, 1475, 1476, 1477, 1589, 1598, 1078) + CDATA_END) .replace("$defaultQuality", cfgDao.getConfValue(CONFIG_SCREENSHARING_QUALITY, String.class, "")) .replace("$defaultFps", cfgDao.getConfValue(CONFIG_SCREENSHARING_FPS, String.class, "")) .replace("$showFps", cfgDao.getConfValue(CONFIG_SCREENSHARING_FPS_SHOW, String.class, "true")) .replace("$allowRemote", cfgDao.getConfValue(CONFIG_SCREENSHARING_ALLOW_REMOTE, String.class, "true")) .replace("$allowRecording", "" + (rc.getUserId() > 0 && room.isAllowRecording() && rc.isAllowRecording() && (0 == sessionManager.getRecordingCount(roomId)))) .replace("$allowPublishing", "" + (0 == sessionManager.getPublishingCount(roomId))); } catch (Exception e) { log.error("Unexpected error while creating jnlp file", e); } StringResourceStream srs = new StringResourceStream(app, "application/x-java-jnlp-file"); srs.setCharset(StandardCharsets.UTF_8); download.setResourceStream(srs); download.initiate(target); }