@UiHandler("createNewPostBtn") void createNewPost(ClickEvent event) { String userId = utils.retrUserId(); String projectId = utils.retrFromState("projectId"); String title = newPostTtlTextBox.getText(); utils.showStaticMessage(messages.showSentRequestMsg(utils.retrFromState("projectName"))); try { service.createNewPost( projectId, userId, title, new AsyncCallback<JSONValue>() { @Override public void onSuccess(JSONValue result) { Log.debug(result.toString()); utils.dismissStaticMessage(); utils.showSuccessMessage(constants.successStr(), 3); } @Override public void onFailure(Throwable caught) { utils.dismissStaticMessage(); utils.alert(caught.getMessage()); } }); } catch (RequestException e) { Log.error("error in createNewPost", e); } utils.reportEvent("/newpost/", "createNewPost", projectId, 1); }
/** Instantiates a new change log panel. */ private ChangeLogPanel() { MainPanel.setCommInfo(true); try { new RequestBuilder(RequestBuilder.GET, "CHANGELOG") .sendRequest( "", new RequestCallback() { @Override public void onError(Request res, Throwable throwable) { MainPanel.setCommInfo(false); Log.error(throwable.getMessage()); } @Override public void onResponseReceived(Request request, Response response) { MainPanel.setCommInfo(false); String text = response.getText(); HTML w = new HTML("<p>" + text + "</p>"); d.setWidget(w); } }); } catch (RequestException e) { MainPanel.setCommInfo(false); Log.error(e.getMessage()); } d = new DecoratorPanel(); d.setWidth("100%"); initWidget(d); }
private static void matchSubElements( ModelNode descriptionModel, List<String> fieldNames, SafeHtmlBuilder html) { if (descriptionModel.hasDefined(RESULT)) descriptionModel = descriptionModel.get(RESULT).asObject(); try { // match attributes if (descriptionModel.hasDefined(ATTRIBUTES)) { List<Property> elements = descriptionModel.get(ATTRIBUTES).asPropertyList(); for (Property element : elements) { String childName = element.getName(); ModelNode value = element.getValue(); if (fieldNames.contains(childName)) { // make sure it's not processed twice fieldNames.remove(childName); html.appendHtmlConstant("<tr class='help-field-row'>"); html.appendHtmlConstant("<td class='help-field-name'>"); html.appendEscaped(childName).appendEscaped(": "); html.appendHtmlConstant("</td>"); html.appendHtmlConstant("<td class='help-field-desc'>"); html.appendEscaped(value.get("description").asString()); html.appendHtmlConstant("</td>"); html.appendHtmlConstant("</tr>"); } } } if (fieldNames.isEmpty()) return; // visit child elements if (descriptionModel.hasDefined("children")) { List<Property> children = descriptionModel.get("children").asPropertyList(); for (Property child : children) { ModelNode childDesc = child.getValue(); for (Property modDescProp : childDesc.get(MODEL_DESCRIPTION).asPropertyList()) { matchSubElements( childDesc.get(MODEL_DESCRIPTION, modDescProp.getName()), fieldNames, html); // exit early if (fieldNames.isEmpty()) return; } } } } catch (IllegalArgumentException e) { Log.error("Failed to read help descriptionModel", e); } }
@Override public void onValueChange(ValueChangeEvent<String> event) { String hash = event.getValue(); recordAnalyticsHit(Window.Location.getPath() + Window.Location.getHash()); String[] parts = hash.split(","); if (parts.length == 12) { String code = parts[0]; Integer year = Integer.decode(parts[1]); try { Integer timeLineDataType = Integer.decode(parts[2]); Integer timeLineChartSelect0 = Integer.decode(parts[3]); Integer timeLineChartSelect1 = Integer.decode(parts[4]); Integer timeLineChartSelect2 = Integer.decode(parts[5]); Integer timeLineChartSelect3 = Integer.decode(parts[6]); Integer timeLineChartSelect4 = Integer.decode(parts[7]); Integer timeLineChartSelect5 = Integer.decode(parts[8]); Integer pieChartDataType = Integer.decode(parts[9]); Integer pieChartNet = Integer.decode(parts[10]); Integer resultsGridNet = Integer.decode(parts[11]); selectBudgetCode(code, year); mTimeLineCharter.setState( timeLineDataType, timeLineChartSelect0, timeLineChartSelect1, timeLineChartSelect2, timeLineChartSelect3, timeLineChartSelect4, timeLineChartSelect5); mPieCharter.setState(pieChartDataType, pieChartNet); mResultsGrid.setState(resultsGridNet); } catch (Exception e) { Log.error("Application::onValueChange: Error while parsing url", e); newCodeAndYear("00", 2012); } } else { Log.error("Application::onValueChange: Error while parsing url"); newCodeAndYear("00", 2012); } }
@Override public void refresh() { try { super.refresh(); if ((getListGrid() != null) && (CoreGUI.getMessageCenter().getMessages() != null)) { getListGrid().setRecords(transform(CoreGUI.getMessageCenter().getMessages())); } refreshTableInfo(); } catch (Throwable e) { Log.error("Cannot refresh messages", e); } }
@Override public void onMessage(final Message message) { try { if (!message.isTransient()) { refresh(); if (window != null) { window.blink(); } } } catch (Throwable e) { Log.error("Cannot process message", e); } }
public void blink() { try { // window.flash() isn' t working so do it ourselves if (getMinimized()) { setTitle(TABLE_TITLE + " *"); } else { setBodyColor(getHiliteBodyColor()); } redraw(); blinkTimer.schedule(250); } catch (Throwable e) { Log.error("Cannot blink message center window", e); } }
private void log(Message message) { String formattedMessage = "At [" + message.getFired() + "] MessageCenter received: " + message.getConciseMessage(); if (message.severity == Message.Severity.Info) { Log.info(formattedMessage); } else if (message.severity == Message.Severity.Warning) { Log.warn(formattedMessage); } else if (message.severity == Message.Severity.Error) { Log.error(formattedMessage); } else if (message.severity == Message.Severity.Fatal) { Log.fatal(formattedMessage); } else { Log.debug(formattedMessage); } }
public void run() { _stopFlag = false; long seqNr = 0; while (!_stopFlag) { try { seqNr = Math.max(seqNr, _statisticDao.getMaxSequenceNr()); CouchDbConfig configuration = CouchDbDaoFactory.getConfiguration(); String host = configuration.getCouchHost(); String userInfo = null; if (configuration.getCouchUser() != null || configuration.getCouchPassword() != null) { userInfo = configuration.getCouchUser() + ":" + configuration.getCouchPassword(); } int port = configuration.getCouchPort(); String path = "/" + configuration.getCouchDatabase() + "/_changes"; String query = "feed=continuous&include_docs=true&since=" + seqNr; _client = new DefaultHttpClient(); URI uri = new URI("http", userInfo, host, port, path, query, null); _getRequest = new HttpGet(uri); HttpResponse response = _client.execute(_getRequest); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { if (line.length() > 0) { seqNr = Math.max(seqNr, parseLine(line)); } } } } catch (Throwable e) { Log.error("Exception in StatisticAggregator caught: " + e.getMessage(), e); } // make sure we won't hang in a CPU eating loop if there is an error try { sleep(5000); } catch (InterruptedException e) { // ignore it } } }
@Override public void orderEdited(final AnamnesisCheckProxy proxy, String sortOrderStr) { try { requests .anamnesisCheckRequest() .changeSortOrder(Integer.parseInt(sortOrderStr)) .using(proxy) .fire( new OSCEReceiver<Void>() { @Override public void onSuccess(Void response) { // TODO Auto-generated method stub view.filterTitle(proxy.getAnamnesisCheckTitle()); performSearch(); } }); } catch (Exception e) { Log.error(e.getMessage()); } }
private void logAtomicOperation(ModelNode operation) { if (operation.get(OP).asString().equals(COMPOSITE)) // nested composite ops? { Log.error("Failed to to log resources access", operation.toString()); } else if (operation.hasDefined(CHILD_TYPE)) { // ModelNode address = operation.get(ADDRESS).clone(); // address.add(operation.get(CHILD_TYPE).toString(), "*"); resourceLog.log( Window.Location.getHash(), operation.get(ADDRESS).toString() + " : " + operation.get(OP).asString() + "(child-type=" + operation.get(CHILD_TYPE) + ")"); } else { resourceLog.log( Window.Location.getHash(), operation.get(ADDRESS).toString() + " : " + operation.get(OP).asString()); } }
/** This will popup a non-modal dialog window with the messages in a list. */ public void showMessageCenterWindow() { try { if (window == null) { window = new MessageCenterWindow("MessageCenterViewWindow"); window.addItem(this); window.addCloseClickHandler( new CloseClickHandler() { @Override public void onCloseClick(CloseClientEvent event) { try { window.hide(); } catch (Throwable e) { Log.warn("Cannot hide message center", e); } } }); } window.show(); markForRedraw(); // need this to ensure the list grid rows are selectable } catch (Throwable e) { Log.error("Cannot show message center window", e); } }
public List<RenderPiece> handle(RenderContext renderContext, Map<String, String> values) throws RenderHandlerException { String view = values.get(NameConstants.VIEW); String name = values.get(NameConstants.NAME); List<RenderPiece> pieces = new ArrayList<RenderPiece>(); int type = NumberUtils.toInt(values.get(NameConstants.TYPE)); if (name != null) { if (type == LinkModel.LINK_TO_ATTACHMENT) { // download link for attachment String spaceUname = renderContext.getSpaceUname(); CrFileNode node = null; try { ITicket ticket = repositoryService.login(spaceUname, spaceUname, spaceUname); node = repositoryService.getLatestCRFileNode( ticket, RepositoryService.TYPE_ATTACHMENT, pageUuid, name); if (node != null) { Map<String, String> attributes = new HashMap<String, String>(); attributes.put( NameConstants.HREF, renderContext.buildDownloadURL(name, node.getNodeUuid(), true)); attributes.put( NameConstants.TITLE, "Download file " + StringEscapeUtils.escapeHtml(name)); pieces.add(new TextModel(HTMLUtil.buildTagString("a", view, attributes))); } } catch (RepositoryException e) { Log.error("Unable to get file node", e); } if (node == null) { // error - doesn't exist throw new RenderHandlerException("The attachment doesn't exist."); } } else if (type == LinkModel.LINK_TO_READONLY) { // the case is, page no "link to create" permission, and linked page not existed. then // simple put view // this view maybe pure text, or some markup, such as image // build tag Map<String, String> attributes = new HashMap<String, String>(); // We don't need put link meta info into Wajax as it won't convert back to Markup at this // scenario. // Map<String,String> wajaxMap = new HashMap<String,String>(); // wajaxMap.put(NameConstants.TYPE, String.valueOf(type)); // //here, name is already removed leading "^" // wajaxMap.put(NameConstants.LINK, name); // String wajax = // RichTagUtil.buildWajaxAttributeString(LinkModel.class.getName(),wajaxMap); // attributes.put(NameConstants.WAJAX, wajax); attributes.put(NameConstants.HREF, "javascript:;"); attributes.put("onClick", "alert(\"" + messageService.getMessage("readonly.link") + "\")"); pieces.add(new TextModel(HTMLUtil.buildTagString("a", view, attributes))); } else { // page link LinkModel link = new LinkModel(); link.setLink(name); link.setType(type); link.setSpaceUname(values.get(NameConstants.SPACE)); link.setView(view); if (!StringUtils.isBlank(values.get(NameConstants.ANCHOR))) { link.setAnchor(values.get(NameConstants.ANCHOR)); } link.setLinkTagStr(renderContext.buildURL(link)); pieces.add(link); } } else { // [http://foo.com] will go here..., no name, but view is http... // please note, at this moment, view is already surrounding by link, e.g., <a // href=xxx>view</a>, so here just replace view. pieces.add(new TextModel(view)); } return pieces; }
@Override public void onFailure(Throwable e) { Log.error("UpdateTransUnit failure ", e); saveFailure(e.getMessage()); }
public void init() { TotalBudget.getInstance(); Integer height = null; Integer width = null; Map<String, List<String>> parameters = Window.Location.getParameterMap(); if (parameters.containsKey("w") && parameters.containsKey("h")) { height = Integer.parseInt(parameters.get("h").get(0)); width = Integer.parseInt(parameters.get("w").get(0)); } mResultsGrid = new ResultGrid(); mResultsGrid.setWidth("100%"); Integer pieWidth = width == null ? 485 : width; Integer pieHeight = height == null ? 400 : height; mPieCharter = new PieCharter(this, mEmbedded, pieWidth, pieHeight); mPieCharter.setWidth(pieWidth + "px"); mPieCharter.setHeight(pieHeight + "px"); Integer timeWidth = width == null ? 686 : width; Integer timeHeight = height == null ? 400 : height; mTimeLineCharter = new TimeLineCharter(this, mEmbedded, timeWidth, timeHeight); mTimeLineCharter.setWidth(timeWidth + "px"); mTimeLineCharter.setHeight(timeHeight + "px"); mBreadcrumbs = new HTML(""); mBreadcrumbs.setHeight("20px"); mBreadcrumbs.setWidth("100%"); mYearSelection = new ListBox(); mYearSelection.addChangeHandler( new ChangeHandler() { @Override public void onChange(ChangeEvent event) { Integer index = mYearSelection.getSelectedIndex(); String yearStr = mYearSelection.getItemText(index); Integer year; try { year = Integer.parseInt(yearStr); } catch (Exception e) { yearStr = yearStr.split(" ")[0]; year = Integer.parseInt(yearStr); } selectYear(year); } }); mSearchBox = new SuggestBox(new BudgetSuggestionOracle()); mSearchBox.setWidth("300px"); mSearchBox.setAutoSelectEnabled(false); mSearchBox.addSelectionHandler( new SelectionHandler<Suggestion>() { @Override public void onSelection(SelectionEvent<Suggestion> event) { final BudgetSuggestion bs = (BudgetSuggestion) event.getSelectedItem(); BudgetAPICaller api = new BudgetAPICaller(); api.setCode(bs.getCode()); api.setParameter("depth", "0"); api.setParameter("text", bs.getTitle()); api.go( new BudgetAPICallback() { @Override public void onSuccess(JSONArray data) { if (data.size() > 0) { Integer year = (int) data.get(0).isObject().get("year").isNumber().doubleValue(); newCodeAndYear(bs.getCode(), year); } } }); } }); mSummary1 = new Label(); mSummary2 = new Label(); mSummary2_1 = new Label(); mSummary3 = new HTML(); mSummary3_1 = new HTML(); try { mBudgetNews = new BudgetNews(); } catch (Exception e) { Log.error("Failed to init mBudgetNews", e); } mCheatSheet = new HTML("(הסברים)"); final DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true); simplePopup.setWidth("450px"); HTML simplePopupContents = new HTML( "<h4>מונחון מקוצר</h4>" + "<lu>" + "<li><b>נטו</b>: <u>תקציב הוצאה נטו</u> – הסכום המותר להוצאה בשנה כלשהי כפי שמפורט בחוק התקציב. תקציב זה מכונה גם \"תקציב המזומנים\".</li>" + "<li><b>ברוטו</b>: <u>תקציב ההוצאה נטו</u> בתוספת <u>תקציב ההוצאה המותנית בהכנסה</u> – תקציב נוסף המותר בהוצאה, ובלבד שיתקבלו תקבולים למימון ההוצאה מגורמים חוץ-ממשלתיים. תקבולים אלו אינם כוללים אגרה המשולמת לאוצר המדינה שהוטלה על-פי חיקוק שנחקק אחרי תחילת שנת הכספים 1992, ואינה כוללת הכנסה שמקורה במלווה (חוץ מתקציבי פיתוח וחשבון הון).</li>" + "<li><b>הקצאה</b>: <u>תקציב מקורי</u> – התקציב שאושר בכנסת במסגרת חוק התקציב. ייתכנו הבדלים בין הצעת התקציב לבין התקציב שיאושר בכנסת בסופו של דבר.</li>" + "<li><b>הקצאה מעודכנת</b>: <u>תקציב על שינוייו</u> – תקציב המדינה עשוי להשתנות במהלך השנה. שינויים אלו כוללים תוספות, הפחתות והעברות תקציביות בין סעיפי תקציב (באישור ועדת הכספים של הכנסת). נוסף על כך, פעמים רבות מועברים עודפים מחויבים משנה קודמת הנכללים בתקציב זה. רוב השינויים בתקציב דורשים את אישורה של ועדת הכספים של הכנסת. התקציב בסוף השנה הכולל את השינויים שנעשו בו במהלך השנה נקרא התקציב על שינוייו או התקציב המאושר.</li>" + "<li><b>שימוש</b>: <u>ביצוע</u> – התקציב שכבר נוצל ושולם בפועל על-ידי החשב.</li>" + "<li><b>ערך ריאלי ונומינלי</b>: ראו הסבר ב<a href='http://he.wikipedia.org/wiki/%D7%A2%D7%A8%D7%9A_%D7%A8%D7%99%D7%90%D7%9C%D7%99_%D7%95%D7%A2%D7%A8%D7%9A_%D7%A0%D7%95%D7%9E%D7%99%D7%A0%D7%9C%D7%99' target ='_blank'>ויקיפדיה</a>.</li>" + "<li><b>ערך יחסי</b>: האחוז היחסי של סעיף זה מכלל תקציב המדינה</li>" + "</lu>" + "<br/>" + "<i>לחץ מחוץ לחלונית זו לסגירתה</i>" + "<br/>" + "מקור: <a href='http://www.knesset.gov.il/mmm/data/docs/m02217.doc' target='_blank'>מסמך Word ממחלקת המחקר של הכנסת</a>" + "<p><b>התקציב הפתוח הוא פרויקט התנדבותי של עמותת 'הסדנא לידע ציבורי'. הנתונים המופיעים" + " בתקציב הפתוח נסמכים על פרסומי המדינה ואינם באים לשקף כל דעה שהיא. אין לסדנא לידע ציבורי" + " כל אחריות על השימוש בפרויקט וראוי לבדוק את הנתונים לגופם במקורותיהם לפני הסתמכות עליהם.</b></p>"); simplePopupContents.setStyleName("obudget-cheatsheet-popup"); simplePopup.setWidget(simplePopupContents); mCheatSheet.addClickHandler( new ClickHandler() { @Override public void onClick(ClickEvent event) { Widget source = (Widget) event.getSource(); int left = source.getAbsoluteLeft() + 10; int top = source.getAbsoluteTop() + 10; simplePopup.setPopupPosition(left, top); simplePopup.show(); } }); History.addValueChangeHandler(this); }
@Override protected void configureTable() { getListGrid().setEmptyMessage(MSG.view_messageCenter_noRecentMessages()); updateTitleCanvas( MSG.view_messageCenter_lastNMessages( String.valueOf(CoreGUI.getMessageCenter().getMaxMessages()))); ListGridField severityField = new ListGridField(FIELD_SEVERITY); severityField.setType(ListGridFieldType.ICON); severityField.setAlign(Alignment.CENTER); severityField.setShowValueIconOnly(true); HashMap<String, String> severityIcons = new HashMap<String, String>(5); severityIcons.put(Severity.Blank.name(), getSeverityIcon(Severity.Blank)); severityIcons.put(Severity.Info.name(), getSeverityIcon(Severity.Info)); severityIcons.put(Severity.Warning.name(), getSeverityIcon(Severity.Warning)); severityIcons.put(Severity.Error.name(), getSeverityIcon(Severity.Error)); severityIcons.put(Severity.Fatal.name(), getSeverityIcon(Severity.Fatal)); severityField.setValueIcons(severityIcons); severityField.setShowHover(true); severityField.setHoverCustomizer( new HoverCustomizer() { @Override public String hoverHTML(Object value, ListGridRecord record, int rowNum, int colNum) { try { Severity severity = ((Message) record.getAttributeAsObject(FIELD_OBJECT)).getSeverity(); switch (severity) { case Info: return MSG.common_severity_info(); case Warning: return MSG.common_severity_warn(); case Error: return MSG.common_severity_error(); case Fatal: return MSG.common_severity_fatal(); } } catch (Throwable e) { Log.error("Cannot get severity hover", e); } return null; } }); severityField.setSortNormalizer( new SortNormalizer() { @Override public Object normalize(ListGridRecord record, String fieldName) { try { Severity severity = ((Message) record.getAttributeAsObject(FIELD_OBJECT)).getSeverity(); return Integer.valueOf(severity.ordinal()); } catch (Throwable e) { Log.error("Cannot get sort nomalizer", e); } return Integer.valueOf(0); } }); ListGridField timeField = new ListGridField(FIELD_TIME, MSG.view_messageCenter_messageTime()); timeField.setType(ListGridFieldType.TIME); timeField.setAttribute("displayFormat", TimeFormatter.TOPADDEDTIME); timeField.setAlign(Alignment.LEFT); timeField.setShowHover(true); timeField.setHoverCustomizer(TimestampCellFormatter.getHoverCustomizer(FIELD_TIME)); ListGridField messageField = new ListGridField(FIELD_CONCISEMESSAGE, MSG.common_title_message()); severityField.setWidth(25); timeField.setWidth("15%"); messageField.setWidth("*"); getListGrid().setFields(severityField, timeField, messageField); setListGridDoubleClickHandler( new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { try { ListGrid listGrid = (ListGrid) event.getSource(); ListGridRecord[] selectedRows = listGrid.getSelection(); if (selectedRows != null && selectedRows.length > 0) { Message message = (Message) selectedRows[0].getAttributeAsObject( FIELD_OBJECT); // show the first selected showDetails(message); } } catch (Throwable e) { Log.error("Cannot show details for message", e); } } }); addTableAction( extendLocatorId("delete"), MSG.common_button_delete(), MSG.common_msg_areYouSure(), new AbstractTableAction(TableActionEnablement.ANY) { @Override public void executeAction(ListGridRecord[] selection, Object actionValue) { try { for (ListGridRecord record : selection) { Object doomed = record.getAttributeAsObject(FIELD_OBJECT); CoreGUI.getMessageCenter().getMessages().remove(doomed); } refresh(); } catch (Throwable e) { Log.error("Cannot delete messages", e); } } }); addTableAction( extendLocatorId("deleteAll"), MSG.common_button_delete_all(), MSG.common_msg_areYouSure(), new AbstractTableAction(TableActionEnablement.ALWAYS) { @Override public void executeAction(ListGridRecord[] selection, Object actionValue) { try { CoreGUI.getMessageCenter().getMessages().clear(); refresh(); } catch (Throwable e) { Log.error("Cannot delete all messages", e); } } }); LinkedHashMap<String, Integer> maxMessagesMap = new LinkedHashMap<String, Integer>(); maxMessagesMap.put("10", Integer.valueOf("10")); maxMessagesMap.put("25", Integer.valueOf("25")); maxMessagesMap.put("50", Integer.valueOf("50")); maxMessagesMap.put("100", Integer.valueOf("100")); maxMessagesMap.put("200", Integer.valueOf("200")); addTableAction( extendLocatorId("maxMessageMenu"), MSG.view_messageCenter_maxMessages(), null, maxMessagesMap, new AbstractTableAction(TableActionEnablement.ALWAYS) { @Override public void executeAction(ListGridRecord[] selection, Object actionValue) { try { Integer maxSize = (Integer) actionValue; CoreGUI.getMessageCenter().setMaxMessages(maxSize.intValue()); updateTitleCanvas(MSG.view_messageCenter_lastNMessages(maxSize.toString())); refresh(); } catch (Throwable e) { Log.error("Cannot set max messages", e); } } }); /* // TODO only for testing, remove this when done testing addTableAction(extendLocatorId("test"), "TEST MSG", null, new AbstractTableAction(TableActionEnablement.ALWAYS) { @Override public void executeAction(ListGridRecord[] selection, Object actionValue) { for (Severity severity : java.util.EnumSet.allOf(Severity.class)) { Message m = new Message(severity.name() + ':' + System.currentTimeMillis(), severity); CoreGUI.getMessageCenter().notify(m); } } }); */ // initial population of the list with current messages try { refresh(); } catch (Throwable e) { Log.error("Cannot perform initial refresh", e); } }
public FormAssets build() { // pre-requisite if (createMode && !modelDescription.hasDefined("operations")) { throw new IllegalStateException("Operation descriptions not defined"); } this.form = new ModelNodeForm(this.address, this.securityContext); this.form.setNumColumns(2); this.form.setEnabled(false); assert modelDescription.hasDefined("attributes") : "Invalid model description. Expected child 'attributes'"; List<Property> attributeDescriptions = new ArrayList<Property>(); if (createMode && modelDescription.get("operations").get("add").hasDefined("request-properties")) { attributeDescriptions = modelDescription.get("operations").get("add").get("request-properties").asPropertyList(); } else if (!createMode) { attributeDescriptions = modelDescription.get("attributes").asPropertyList(); } // sort fields if (!unsorted) { Collections.sort( attributeDescriptions, new Comparator<Property>() { @Override public int compare(Property property, Property property1) { return property.getName().compareTo(property1.getName()); } }); } // catch-all directive, if no explicit attributes given if (includes.isEmpty()) { for (Property attr : attributeDescriptions) { includes.add(attr.getName()); } } // in any case remove attributes marked for exclusion includes.removeAll(excludes); LinkedList<FormItem> requiredItems = new LinkedList<FormItem>(); LinkedList<FormItem> optionalItems = new LinkedList<FormItem>(); SafeHtmlBuilder helpTexts = new SafeHtmlBuilder(); helpTexts.appendHtmlConstant("<table class='help-attribute-descriptions'>"); Map<String, ModelNode> defaultValues = new HashMap<String, ModelNode>(); int numWritable = 0; boolean hasRequired = false; // for some decision below we need to know wether or not required attributes exist at all if (requiredOnly) { for (Property attr : attributeDescriptions) { ModelNode value = attr.getValue(); boolean required = isRequired(value); boolean readOnly = value.get("access-type").asString().equals("read-only"); if (required & !readOnly) { hasRequired = true; break; } } } Set<String[]> unsupportedTypes = new HashSet<>(); for (String attribute : includes) { for (Property attr : attributeDescriptions) { boolean isRuntime = attr.getValue().get("storage").asString().equals("runtime"); boolean isConfig = !attr.getValue().get("storage").asString().equals("runtime"); // TODO: verify statement if (runtimeAttributes == false && isRuntime) { continue; } if (configAttributes == false && isConfig) { continue; } if (!attr.getName().equals(attribute)) continue; // ------- // Attribute meta data // name char[] attrName = attr.getName().toCharArray(); attrName[0] = Character.toUpperCase(attrName[0]); // field label String label = new String(attrName).replace("-", " "); ModelNode attrDesc = attr.getValue(); // skip deprecated attributes if (attrDesc.hasDefined("deprecated")) { // Log.error("Skip deprecated attribute '" + attr.getName() + "'"); continue; } // type ModelType type = ModelType.valueOf(attrDesc.get("type").asString().toUpperCase()); // default value if (attrDesc.hasDefined("default")) { ModelNode defaultValue = attrDesc.get("default"); ModelNode value = new ModelNode(); // value.set(type, ModelNodeForm.downCast(defaultValue)); setValue( value, type, ModelNodeForm.downCast(defaultValue, attrDesc)); // workaround for numeric types defaultValues.put(attr.getName(), value); } // read-only final boolean readOnly = attrDesc.hasDefined("access-type") ? attrDesc.get("access-type").asString().equals("read-only") : false; // nillable boolean isRequired = isRequired(attrDesc); // createMode flag if ((createMode && readOnly)) continue; // requiredOnly flag if (requiredOnly && hasRequired && !isRequired) continue; // count writable attributes if (!readOnly && !isRuntime) numWritable++; // ------- // help helpTexts.appendHtmlConstant("<tr class='help-field-row'>"); helpTexts.appendHtmlConstant("<td class='help-field-name'>"); helpTexts.appendEscaped(label).appendEscaped(": "); helpTexts.appendHtmlConstant("</td>"); helpTexts.appendHtmlConstant("<td class='help-field-desc'>"); try { String descWorkaround = attrDesc.get("description").asString(); helpTexts.appendHtmlConstant(descWorkaround.equals("null") ? "n/a" : descWorkaround); } catch (Throwable e) { // ignore parse errors helpTexts.appendHtmlConstant("<i>Failed to parse description</i>"); } helpTexts.appendHtmlConstant("</td>"); helpTexts.appendHtmlConstant("</tr>"); FormItem formItem = null; // explicitly created form items (monkey patching) if (itemFactories.containsKey(attr.getName())) { formItem = itemFactories.get(attr.getName()).create(attr); } // not created by explicit factory if (null == formItem) { switch (type) { case BOOLEAN: formItem = new CheckBoxItem(attr.getName(), label); formItem.setRequired(isRequired); formItem.setEnabled(!readOnly && !isRuntime); break; case DOUBLE: formItem = new DoubleFormItem(attr.getName(), label); formItem.setRequired(isRequired); formItem.setEnabled(!readOnly && !isRuntime); break; case LONG: boolean allowNegativeValues = false; if (attrDesc.hasDefined("default")) allowNegativeValues = attrDesc.get("default").asLong() < 0; formItem = new NumberBoxItem(attr.getName(), label, allowNegativeValues); formItem.setRequired(isRequired); formItem.setEnabled(!readOnly && !isRuntime); break; case BIG_DECIMAL: formItem = new NumberBoxItem(attr.getName(), label); formItem.setRequired(isRequired); formItem.setEnabled(!readOnly && !isRuntime); break; case INT: if (attrDesc.hasDefined("min") && attrDesc.hasDefined("max")) { formItem = new NumberBoxItem( attr.getName(), label, attrDesc.get("min").asLong(), attrDesc.get("max").asLong()); } else { formItem = new NumberBoxItem(attr.getName(), label); } formItem.setRequired(isRequired); formItem.setEnabled(!readOnly && !isRuntime); break; case LIST: formItem = new ListItem(attr.getName(), label); formItem.setRequired(isRequired); formItem.setEnabled(!readOnly && !isRuntime); break; case STRING: if (attrDesc.get("allowed").isDefined()) { List<ModelNode> allowed = attrDesc.get("allowed").asList(); Set<String> allowedValues = new HashSet<String>(allowed.size()); for (ModelNode value : allowed) allowedValues.add(value.asString()); final boolean isNillable = attrDesc.hasDefined(NILLABLE) && attrDesc.get(NILLABLE).asBoolean(); ComboBoxItem combo = new ComboBoxItem(attr.getName(), label, isNillable); combo.setValueMap(allowedValues); combo.setEnabled(!readOnly && !isRuntime); combo.setRequired(isRequired); formItem = combo; } else { formItem = createSuggestBoxForCapabilityReference(attr, label, isRequired); if (formItem == null) { // there is no capability-reference TextBoxItem textBoxItem = new TextBoxItem(attr.getName(), label); textBoxItem.setAllowWhiteSpace(true); textBoxItem.setRequired(isRequired); textBoxItem.setEnabled(!readOnly && !isRuntime); formItem = textBoxItem; } } // TODO: Support for TextAreaItem break; case OBJECT: if (attrDesc.has("value-type") && attrDesc.get("value-type").asString().equals("STRING")) { PropertyListItem propList = new PropertyListItem(attr.getName(), label); propList.setRequired(isRequired); propList.setEnabled(!readOnly && !isRuntime); formItem = propList; break; } default: { unsupportedTypes.add(new String[] {attr.getName(), type.toString()}); Log.error("Unsupported ModelType " + type + ", attribute '" + attr.getName() + "'"); } } } if (formItem != null) { if (createMode) { if (isRequired && includeOptionals) requiredItems.add(formItem); else optionalItems.add(formItem); } else { requiredItems.add(formItem); } // attribute meta data attached to form item formItem.setMetadata(attrDesc); } } } // some resources already contain a name attribute FormItem nameItem = null; if (createMode) { for (FormItem item : requiredItems) { if ("name".equals(item.getName())) { nameItem = item; break; } } for (FormItem item : optionalItems) { if ("name".equals(item.getName())) { nameItem = item; break; } } } // remove so it can be prepended if (nameItem != null) { requiredItems.remove(nameItem); optionalItems.remove(nameItem); } // distinguish required and optional fields (createMode) if (requiredItems.isEmpty()) { // no required fields explicitly given, treat all fields as required if (createMode) { optionalItems.addFirst(new TextBoxItem("name", "Name", true)); numWritable++; } form.setFields(optionalItems.toArray(new FormItem[] {})); } else { if (createMode) { requiredItems.addFirst(new TextBoxItem("name", "Name", true)); numWritable++; } form.setFields(requiredItems.toArray(new FormItem[] {})); if (optionalItems.size() > 0) form.setFieldsInGroup( "Optional Fields", new DisclosureGroupRenderer(), optionalItems.toArray(new FormItem[] {})); } // form meta data form.setDefaults(defaultValues); form.setHasWritableAttributes(numWritable > 0); FormAssets formAssets = new FormAssets(form, helpTexts.toSafeHtml()); formAssets.setUnsupportedTypes(unsupportedTypes); return formAssets; }