List of usage examples for java.text NumberFormat getInstance
public static final NumberFormat getInstance()
From source file:edu.cmu.ark.QuestionTransducer.java
/** * main method for testing stage 2 in isolation. The QuestionAsker class's main method should be * used to generate questions from the end-to-end system. * /*from w w w . j a va 2 s. c o m*/ * @param args */ public static void main(String[] args) { QuestionTransducer qt = new QuestionTransducer(); AnalysisUtilities.getInstance(); String buf; Tree inputTree; boolean printParse = false; boolean printOriginal = false; boolean treeInput = false; boolean printFeatures = false; Set<Question> inputTrees = new HashSet<Question>(); qt.setAvoidPronounsAndDemonstratives(true); for (int i = 0; i < args.length; i++) { if (args[i].equals("--debug")) { GlobalProperties.setDebug(true); } else if (args[i].equals("--print-parse")) { printParse = true; } else if (args[i].equals("--print-original")) { printOriginal = true; } else if (args[i].equals("--print-features")) { printFeatures = true; } else if (args[i].equals("--print-extracted-phrases")) { qt.setPrintExtractedPhrases(true); } else if (args[i].equals("--tree-input")) { treeInput = true; } else if (args[i].equals("--keep-pro")) { qt.setAvoidPronounsAndDemonstratives(false); } else if (args[i].equals("--properties")) { GlobalProperties.loadProperties(args[i + 1]); } } try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //take input from the user on stdin if (GlobalProperties.getDebug()) System.err.println("\nInput Declarative Sentence:"); while ((buf = br.readLine()) != null) { if (treeInput) { buf = AnalysisUtilities.preprocessTreeString(buf); inputTree = AnalysisUtilities.getInstance().readTreeFromString(buf); AnalysisUtilities.getInstance().normalizeTree(inputTree); } else { if (AnalysisUtilities.filterOutSentenceByPunctuation(buf)) { continue; } buf = AnalysisUtilities.preprocess(buf); if (printOriginal) System.out.println("\n" + buf); ParseResult parseRes = AnalysisUtilities.getInstance().parseSentence(buf); inputTree = parseRes.parse; if (GlobalProperties.getDebug()) System.err.println("Parse Score: " + parseRes.score); } if (printParse) System.out.println(inputTree); inputTrees.clear(); Question tmp = new Question(); tmp.setIntermediateTree(inputTree.deepCopy()); tmp.setSourceTree(inputTree); inputTrees.add(tmp); //iterate over the trees given by the input List<Question> questions; for (Question q : inputTrees) { try { qt.generateQuestionsFromParse(q); questions = qt.getQuestions(); QuestionTransducer.removeDuplicateQuestions(questions); //iterate over the questions for each tree for (Question curQuestion : questions) { System.out.print(curQuestion.yield()); if (printFeatures) { System.out.print("\t"); int cnt = 0; for (Double val : curQuestion.featureValueList()) { if (cnt > 0) System.out.print(";"); System.out.print(NumberFormat.getInstance().format(val)); cnt++; } } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } if (GlobalProperties.getDebug()) System.err.println("\nInput Declarative Sentence:"); } } catch (IOException e) { e.printStackTrace(); } }
From source file:org.operamasks.faces.render.graph.ChartRenderer.java
private void setCategoryToolTipGenerator(CategoryPlot plot, UIChart comp) { NumberFormat format;/*from w ww. j a v a 2s .c o m*/ UIAxis axis = comp.getyAxis(); if (axis != null && axis.getItemTipFormat() != null) { format = new DecimalFormat(axis.getItemTipFormat()); } else { format = NumberFormat.getInstance(); } plot.getRenderer() .setToolTipGenerator(new StandardCategoryToolTipGenerator("<h3>{1}</h3>{0} = {2}", format)); }
From source file:org.operamasks.faces.render.graph.ChartRenderer.java
private void setXYToolTipGenerator(XYPlot plot, UIChart comp) { UIAxis xAxis = comp.getxAxis();//from www .ja va 2s . com UIAxis yAxis = comp.getyAxis(); String xLabel = comp.getxAxisLabel(); if (xLabel == null && xAxis != null) xLabel = xAxis.getLabel(); String yLabel = comp.getyAxisLabel(); if (yLabel == null && yAxis != null) yLabel = yAxis.getLabel(); String labelFormat; if (xLabel != null && yLabel != null) { labelFormat = String.format("<h3>{0}</h3>%s: {1}<br/>%s: {2}", xLabel, yLabel); } else { labelFormat = "<h3>{0}</h3>({1}, {2})"; } if (comp.getDataSeries() instanceof UITimeSeries) { DateFormat xfmt; if (xAxis != null && xAxis.getItemTipFormat() != null) { xfmt = new SimpleDateFormat(xAxis.getItemTipFormat()); } else { xfmt = DateFormat.getInstance(); } NumberFormat yfmt; if (yAxis != null && yAxis.getItemTipFormat() != null) { yfmt = new DecimalFormat(yAxis.getItemTipFormat()); } else { yfmt = NumberFormat.getInstance(); } plot.getRenderer().setToolTipGenerator(new StandardXYToolTipGenerator(labelFormat, xfmt, yfmt)); } else { NumberFormat xfmt; if (xAxis != null && xAxis.getItemTipFormat() != null) { xfmt = new DecimalFormat(xAxis.getItemTipFormat()); } else { xfmt = NumberFormat.getInstance(); } NumberFormat yfmt; if (yAxis != null && yAxis.getItemTipFormat() != null) { yfmt = new DecimalFormat(yAxis.getItemTipFormat()); } else { yfmt = NumberFormat.getInstance(); } plot.getRenderer().setToolTipGenerator(new StandardXYToolTipGenerator(labelFormat, xfmt, yfmt)); } }
From source file:com.pironet.tda.TDA.java
private void displayTable(HistogramTableModel htm) { setThreadDisplay(false);/*from w ww . j av a 2s. c om*/ htm.setFilter(""); htm.setShowHotspotClasses(PrefManager.get().getShowHotspotClasses()); TableSorter ts = new TableSorter(htm); histogramTable = new JTable(ts); ts.setTableHeader(histogramTable.getTableHeader()); histogramTable.getColumnModel().getColumn(0).setPreferredWidth(700); final ViewScrollPane tableView = new ViewScrollPane(histogramTable, runningAsVisualVMPlugin); JPanel histogramView = new JPanel(new BorderLayout()); JPanel histoStatView = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0)); JLabel infoLabel = new JLabel( NumberFormat.getInstance().format(htm.getRowCount()) + " classes and base types"); infoLabel.setFont(SANS_SERIF); histoStatView.add(infoLabel); infoLabel = new JLabel(NumberFormat.getInstance().format(htm.getBytes()) + " bytes"); infoLabel.setFont(SANS_SERIF); histoStatView.add(infoLabel); infoLabel = new JLabel(NumberFormat.getInstance().format(htm.getInstances()) + " live objects"); infoLabel.setFont(SANS_SERIF); histoStatView.add(infoLabel); if (htm.isOOM()) { infoLabel = new JLabel("<html><b>OutOfMemory found!</b>"); infoLabel.setFont(SANS_SERIF); histoStatView.add(infoLabel); } if (htm.isIncomplete()) { infoLabel = new JLabel("<html><b>Class Histogram is incomplete! (broken logfile?)</b>"); infoLabel.setFont(SANS_SERIF); histoStatView.add(infoLabel); } JPanel filterPanel = new JPanel(new FlowLayout()); infoLabel = new JLabel("Filter-Expression"); infoLabel.setFont(SANS_SERIF); filterPanel.add(infoLabel); filter = new JTextField(30); filter.setFont(SANS_SERIF); filter.addCaretListener(new FilterListener(htm)); filterPanel.add(infoLabel); filterPanel.add(filter); checkCase = new JCheckBox(); checkCase.addChangeListener(new CheckCaseListener(htm)); infoLabel = new JLabel("Ignore Case"); infoLabel.setFont(SANS_SERIF); filterPanel.add(infoLabel); filterPanel.add(checkCase); histoStatView.add(filterPanel); histogramView.add(histoStatView, BorderLayout.SOUTH); histogramView.add(tableView, BorderLayout.CENTER); histogramView.setPreferredSize(splitPane.getBottomComponent().getSize()); splitPane.setBottomComponent(histogramView); }
From source file:de.tor.tribes.ui.views.DSWorkbenchReportFrame.java
private void fireRebuildStatsEvent() { List selection = jList1.getSelectedValuesList(); if (selection == null || selection.isEmpty()) { jOverallStatsArea.setText("<html>Kein Stamm ausgewhlt</html>"); jAllyStatsArea.setText("<html>Kein Stamm ausgewhlt</html>"); jTribeStatsArea.setText("<html>Kein Stamm ausgewhlt</html>"); return;/*from w w w .java 2 s . co m*/ } int overallDefAllies = lastStats.getDefendingAllies().length; int overallDefTribes = lastStats.getDefendingTribes().length; NumberFormat f = NumberFormat.getInstance(); f.setMinimumFractionDigits(0); f.setMaximumFractionDigits(0); StringBuilder allyBuffer = new StringBuilder(); StringBuilder tribeBuffer = new StringBuilder(); HashMap<Ally, AllyStatResult> allyResults = new HashMap<>(); OverallStatResult overallResult = new OverallStatResult(); for (Object o : selection) { Ally a = (Ally) o; AllyStatResult result = new AllyStatResult(); allyResults.put(a, result); for (Tribe t : lastStats.getAttackingTribes(a)) { TribeStatResult tribeResult = new TribeStatResult(); SingleAttackerStat stats = lastStats.getStatsForTribe(t); tribeResult.setTribeStats(stats, jGuessUnknownLosses.isSelected()); result.addTribeStatResult(tribeResult); } overallResult.addAllyStatsResult(result); } overallResult.setStartDate(lastStats.getStartDate()); overallResult.setEndDate(lastStats.getEndDate()); overallResult.setReportCount(lastStats.getReportCount()); overallResult.setAttackerAllies(selection.size()); overallResult.setDefenders(overallDefTribes); overallResult.setDefenderAllies(overallDefAllies); for (Ally a : allyResults.keySet()) { AllyStatResult res = allyResults.get(a); res.setAlly(a); res.setOverallKills(overallResult.getKills()); res.setOverallLosses(overallResult.getLosses()); for (TribeStatResult tRes : res.getTribeStats()) { tRes.setOverallKills(res.getOverallKills()); tRes.setOverallLosses(res.getOverallLosses()); tRes.setAllyKills(res.getKills()); tRes.setAllyLosses(res.getLosses()); } } try { List<OverallStatResult> list = Arrays.asList(overallResult); overallResultCodes = new OverallReportStatsFormatter().formatElements(list, true); jOverallStatsArea.setText("<html><head>" + BBCodeFormatter.getStyles() + "</head><body>" + BBCodeFormatter.toHtml(overallResultCodes) + "</body></html>"); } catch (Exception e) { overallResultCodes = null; jOverallStatsArea.setText("<html>Fehler bei der Darstellung der Auswertung</html>"); logger.error("Failed to render overall BB representation", e); } try { List<AllyStatResult> list = new LinkedList<>(); CollectionUtils.addAll(list, allyResults.values()); allyResultCodes = new AllyReportStatsFormatter().formatElements(list, true); jAllyStatsArea.setText("<html><head>" + BBCodeFormatter.getStyles() + "</head><body>" + BBCodeFormatter.toHtml(allyResultCodes) + "</body></html>"); } catch (Exception e) { allyResultCodes = null; jAllyStatsArea.setText("<html>Fehler bei der Darstellung der Auswertung</html>"); logger.error("Failed to render BB representation for allies", e); } try { List<TribeStatResult> list = new LinkedList<>(); for (AllyStatResult allyStat : allyResults.values()) { Collections.addAll(list, allyStat.getTribeStats().toArray(new TribeStatResult[allyStat.getTribeStats().size()])); } tribeResultCodes = new TribeReportStatsFormatter().formatElements(list, true); jTribeStatsArea.setText("<html><head>" + BBCodeFormatter.getStyles() + "</head><body>" + BBCodeFormatter.toHtml(tribeResultCodes) + "</body></html>"); } catch (Exception e) { tribeResultCodes = null; jTribeStatsArea.setText("<html>Fehler bei der Darstellung der Auswertung</html>"); logger.error("Failed to render BB representation for tribes", e); } jResultTabbedPane.setSelectedIndex(0); }
From source file:com.concursive.connect.web.modules.wiki.utils.WikiToHTMLUtils.java
public static String toHtmlFormField(CustomFormField field, WikiToHTMLContext context) { // Set a default value if (field.getValue() == null) { field.setValue(field.getDefaultValue()); }//from w w w .j a va2s.c o m // Protect against any arbitrary input String fieldName = StringUtils.toHtmlValue(field.getName()); // Return output based on type switch (field.getType()) { case CustomFormField.TEXTAREA: String textAreaValue = StringUtils.replace(field.getValue(), "^", CRLF); return ("<textarea cols=\"" + field.getColumns() + "\" rows=\"" + field.getRows() + "\" name=\"" + fieldName + "\">" + StringUtils.toString(textAreaValue) + "</textarea>"); case CustomFormField.SELECT: LookupList lookupList = field.getLookupList(); int selectedItemId = -1; for (LookupElement thisElement : lookupList) { if (field.getValue().equals(thisElement.getDescription())) { selectedItemId = thisElement.getCode(); } } return lookupList.getHtmlSelect(fieldName, selectedItemId); case CustomFormField.CHECKBOX: return ("<input type=\"checkbox\" name=\"" + fieldName + "\" value=\"ON\" " + ("true".equals(field.getValue()) ? "checked" : "") + ">"); case CustomFormField.CALENDAR: String calendarValue = field.getValue(); if (StringUtils.hasText(calendarValue)) { try { String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT, DateFormat.LONG, field.getValue()); Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate); Locale locale = Locale.getDefault(); int dateFormat = DateFormat.SHORT; SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat, locale); calendarValue = dateFormatter.format(timestamp); } catch (Exception e) { LOG.error("toHtmlFormField calendar", e); } } // Output with a calendar control String language = System.getProperty("LANGUAGE"); String country = System.getProperty("COUNTRY"); return ("<input type=\"text\" name=\"" + fieldName + "\" id=\"" + fieldName + "\" size=\"10\" value=\"" + StringUtils.toHtmlValue(calendarValue) + "\" > " + "<a href=\"javascript:popCalendar('inputForm', '" + fieldName + "','" + language + "','" + country + "');\">" + "<img src=\"" + context.getServerUrl() + "/images/icons/stock_form-date-field-16.gif\" " + "border=\"0\" align=\"absmiddle\" height=\"16\" width=\"16\"/></a>"); case CustomFormField.PERCENT: return ("<input type=\"text\" name=\"" + fieldName + "\" size=\"5\" value=\"" + StringUtils.toHtmlValue(field.getValue()) + "\"> " + "%"); case CustomFormField.INTEGER: // Determine the value to display in the field String integerValue = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(integerValue)) { try { NumberFormat formatter = NumberFormat.getInstance(); integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue())); } catch (Exception e) { LOG.warn("Could not format integer: " + field.getValue()); } } return ("<input type=\"text\" name=\"" + fieldName + "\" size=\"8\" value=\"" + integerValue + "\"> "); case CustomFormField.FLOAT: // Determine the value to display in the field String decimalValue = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(decimalValue)) { try { NumberFormat formatter = NumberFormat.getInstance(); decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue())); } catch (Exception e) { LOG.warn("Could not decimal format: " + field.getValue()); } } return ("<input type=\"text\" name=\"" + fieldName + "\" size=\"8\" value=\"" + decimalValue + "\"> "); case CustomFormField.CURRENCY: // Use a currencyCode for formatting String currencyCode = field.getValueCurrency(); if (currencyCode == null) { currencyCode = field.getCurrency(); } if (!StringUtils.hasText(currencyCode)) { currencyCode = "USD"; } HtmlSelect currencyCodeList = HtmlSelectCurrencyCode.getSelect(fieldName + "Currency", currencyCode); // Determine the valut to display in the field String currencyValue = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(currencyValue)) { try { NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMaximumFractionDigits(2); currencyValue = formatter.format(StringUtils.getDoubleNumber(field.getValue())); } catch (Exception e) { LOG.warn("Could not currencyCode format: " + field.getValue()); } } return (currencyCodeList.getHtml() + "<input type=\"text\" name=\"" + fieldName + "\" size=\"8\" value=\"" + currencyValue + "\"> "); case CustomFormField.EMAIL: return ("<input type=\"text\" " + "name=\"" + fieldName + "\" maxlength=\"255\" size=\"40\" value=\"" + StringUtils.toHtmlValue(field.getValue()) + "\" />"); case CustomFormField.PHONE: return ("<input type=\"text\" " + "name=\"" + fieldName + "\" maxlength=\"60\" size=\"20\" value=\"" + StringUtils.toHtmlValue(field.getValue()) + "\" />"); case CustomFormField.URL: String value = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(value)) { if (!value.contains("://")) { value = "http://" + field.getValue(); } } return ("<input type=\"text\" " + "name=\"" + fieldName + "\" maxlength=\"255\" size=\"40\" value=\"" + StringUtils.toHtmlValue(value) + "\" />"); default: int maxlength = field.getMaxLength(); int size = -1; if (maxlength > -1) { if (maxlength > 40) { size = 40; } else { size = maxlength; } } return ("<input type=\"text\" " + "name=\"" + fieldName + "\" " + (maxlength == -1 ? "" : "maxlength=\"" + maxlength + "\" ") + (size == -1 ? "" : "size=\"" + size + "\" ") + "value=\"" + StringUtils.toHtmlValue(field.getValue()) + "\" />"); } }
From source file:com.concursive.connect.web.modules.wiki.utils.WikiPDFUtils.java
public static String getFieldValue(WikiPDFContext context, CustomFormField field) { // Return output based on type switch (field.getType()) { case CustomFormField.TEXTAREA: return StringUtils.replace(field.getValue(), "^", CRLF); case CustomFormField.SELECT: return field.getValue(); case CustomFormField.CHECKBOX: if ("true".equals(field.getValue())) { return "Yes"; } else {//from w w w . j a v a2 s. c om return "No"; } case CustomFormField.CALENDAR: String calendarValue = field.getValue(); if (StringUtils.hasText(calendarValue)) { try { String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT, DateFormat.LONG, field.getValue()); Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate); Locale locale = Locale.getDefault(); int dateFormat = DateFormat.SHORT; SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat, locale); calendarValue = dateFormatter.format(timestamp); } catch (Exception e) { LOG.error(e); } } return calendarValue; case CustomFormField.PERCENT: return field.getValue() + "%"; case CustomFormField.INTEGER: // Determine the value to display in the field String integerValue = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(integerValue)) { try { NumberFormat formatter = NumberFormat.getInstance(); integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue())); } catch (Exception e) { LOG.warn("Could not integer format: " + field.getValue()); } } return integerValue; case CustomFormField.FLOAT: // Determine the value to display in the field String decimalValue = field.getValue(); if (StringUtils.hasText(decimalValue)) { try { NumberFormat formatter = NumberFormat.getInstance(); decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue())); } catch (Exception e) { LOG.warn("Could not decimal format: " + field.getValue()); } } return decimalValue; case CustomFormField.CURRENCY: // Use a currency for formatting String currencyCode = field.getValueCurrency(); if (currencyCode == null) { currencyCode = field.getCurrency(); } if (!StringUtils.hasText(currencyCode)) { currencyCode = "USD"; } try { NumberFormat formatter = NumberFormat.getCurrencyInstance(); if (currencyCode != null) { Currency currency = Currency.getInstance(currencyCode); formatter.setCurrency(currency); } return (formatter.format(StringUtils.getDoubleNumber(field.getValue()))); } catch (Exception e) { LOG.error(e.getMessage()); } return field.getValue(); case CustomFormField.EMAIL: return field.getValue(); case CustomFormField.PHONE: PhoneNumberBean phone = new PhoneNumberBean(); phone.setNumber(field.getValue()); PhoneNumberUtils.format(phone, Locale.getDefault()); return phone.toString(); case CustomFormField.URL: String value = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(value)) { if (!value.contains("://")) { value = "http://" + value; } if (value.contains("://")) { return value; } } return value; case CustomFormField.IMAGE: String image = field.getValue(); if (StringUtils.hasText(image)) { return "WikiImage:" + image; } return image; default: return field.getValue(); } }
From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java
private Object[] getItemBeans(String dataClusterPK, ViewBean viewBean, EntityModel entityModel, String criteria, int skip, int max, String sortDir, String sortCol, String language) throws Exception { int totalSize = 0; String dateFormat = "yyyy-MM-dd"; //$NON-NLS-1$ String dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"; //$NON-NLS-1$ List<ItemBean> itemBeans = new ArrayList<ItemBean>(); String concept = ViewHelper.getConceptFromDefaultViewName(viewBean.getViewPK()); Map<String, String[]> formatMap = this.checkDisplayFormat(entityModel, language); WSWhereItem wi = null;// ww w. jav a 2 s .c o m if (criteria != null) { wi = CommonUtil.buildWhereItems(criteria); } String[] results = CommonUtil.getPort().viewSearch(new WSViewSearch(new WSDataClusterPK(dataClusterPK), new WSViewPK(viewBean.getViewPK()), wi, -1, skip, max, sortCol, sortDir)).getStrings(); // set foreignKey's EntityModel Map<String, EntityModel> map = new HashMap<String, EntityModel>(); if (results.length > 0 && viewBean.getViewableXpaths() != null) { for (String xpath : viewBean.getViewableXpaths()) { TypeModel typeModel = entityModel.getMetaDataTypes().get(xpath); if (typeModel != null && typeModel.getForeignkey() != null) { map.put(xpath, getEntityModel(typeModel.getForeignkey().split("/")[0], language)); //$NON-NLS-1$ } } } // TODO change ids to array? List<String> idsArray = new ArrayList<String>(); for (int i = 0; i < results.length; i++) { if (i == 0) { try { // Qizx doesn't wrap the count in a XML element, so try to parse it totalSize = Integer.parseInt(results[i]); } catch (NumberFormatException e) { totalSize = Integer.parseInt(com.amalto.webapp.core.util.Util.parse(results[i]) .getDocumentElement().getTextContent()); } continue; } Document doc = parseResultDocument(results[i], "result"); //$NON-NLS-1$ idsArray.clear(); for (String key : entityModel.getKeys()) { String id = com.amalto.core.util.Util.getFirstTextNode(doc.getDocumentElement(), "." + key.substring(key.lastIndexOf('/'))); //$NON-NLS-1$ if (id != null) { idsArray.add(id); } } Set<String> keySet = formatMap.keySet(); Map<String, Object> originalMap = new HashMap<String, Object>(); Map<String, String> formateValueMap = new HashMap<String, String>(); for (String key : keySet) { String[] value = formatMap.get(key); TypeModel tm = entityModel.getMetaDataTypes().get(key); String xpath = tm.getXpath(); String dataText = null; if (!key.equals(xpath)) { NodeList list = com.amalto.core.util.Util.getNodeList(doc.getDocumentElement(), xpath.replaceFirst(concept + "/", "./")); //$NON-NLS-1$//$NON-NLS-2$ if (list != null) { for (int k = 0; k < list.getLength(); k++) { Node node = list.item(k); String realType = ((Element) node.getParentNode()).getAttribute("xsi:type"); //$NON-NLS-1$ if (key.replaceAll(":" + realType, "").equals(xpath)) { //$NON-NLS-1$//$NON-NLS-2$ dataText = node.getTextContent(); break; } } } } else { dataText = com.amalto.core.util.Util.getFirstTextNode(doc.getDocumentElement(), key.replaceFirst(concept + "/", "./")); //$NON-NLS-1$ //$NON-NLS-2$ } if (dataText != null) { if (dataText.trim().length() != 0) { if (dateTypeNames.contains(tm.getType().getBaseTypeName())) { SimpleDateFormat sdf = null; if (value[1].equalsIgnoreCase("DATE")) { //$NON-NLS-1$ sdf = new SimpleDateFormat(dateFormat, java.util.Locale.ENGLISH); } else if (value[1].equalsIgnoreCase("DATETIME")) { //$NON-NLS-1$ sdf = new SimpleDateFormat(dateTimeFormat, java.util.Locale.ENGLISH); } try { Date date = sdf.parse(dataText.trim()); originalMap.put(key, date); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); String formatValue = com.amalto.webapp.core.util.Util.formatDate(value[0], calendar); formateValueMap.put(key, formatValue); com.amalto.core.util.Util .getNodeList(doc.getDocumentElement(), key.replaceFirst(concept + "/", "./")) //$NON-NLS-1$//$NON-NLS-2$ .item(0).setTextContent(formatValue); } catch (Exception e) { originalMap.remove(key); formateValueMap.remove(key); } } else if (numberTypeNames.contains(tm.getType().getBaseTypeName())) { try { NumberFormat nf = NumberFormat.getInstance(); Number num = nf.parse(dataText.trim()); String formatValue = ""; //$NON-NLS-1$ if (tm.getType().getBaseTypeName() .equals(DataTypeConstants.DOUBLE.getBaseTypeName())) { formatValue = String.format(value[0], num.doubleValue()).trim(); } else if (tm.getType().getBaseTypeName() .equals(DataTypeConstants.FLOAT.getBaseTypeName())) { formatValue = String.format(value[0], num.floatValue()).trim(); } else if (tm.getType().getBaseTypeName() .equals(DataTypeConstants.DECIMAL.getBaseTypeName())) { formatValue = String.format(value[0], new BigDecimal(dataText.trim())).trim(); } else { formatValue = String.format(value[0], num).trim(); } originalMap.put(key, num); formateValueMap.put(key, formatValue); com.amalto.core.util.Util .getNodeList(doc.getDocumentElement(), key.replaceFirst(concept + "/", "./")) //$NON-NLS-1$//$NON-NLS-2$ .item(0).setTextContent(formatValue); } catch (Exception e) { Log.info("format has error 111"); //$NON-NLS-1$ originalMap.remove(key); formateValueMap.remove(key); } } } } } ItemBean itemBean = new ItemBean(concept, CommonUtil.joinStrings(idsArray, "."), //$NON-NLS-1$ XMLUtils.nodeToString(doc.getDocumentElement(), true, true)); itemBean.setOriginalMap(originalMap); itemBean.setFormateMap(formateValueMap); if (checkSmartViewExistsByLang(concept, language)) { itemBean.setSmartViewMode(ItemBean.SMARTMODE); } else if (checkSmartViewExistsByOpt(concept, language)) { itemBean.setSmartViewMode(ItemBean.PERSOMODE); } dynamicAssembleByResultOrder(itemBean, viewBean, entityModel, map, language); itemBeans.add(itemBean); } return new Object[] { itemBeans, totalSize }; }
From source file:com.concursive.connect.web.modules.wiki.utils.WikiToHTMLUtils.java
public static String toHtml(CustomFormField field, Wiki wiki, String contextPath) { // Return output based on type switch (field.getType()) { case CustomFormField.TEXTAREA: String textAreaValue = StringUtils.replace(field.getValue(), "^", CRLF); return StringUtils.toHtml(textAreaValue); case CustomFormField.SELECT: return StringUtils.toHtml(field.getValue()); case CustomFormField.CHECKBOX: if ("true".equals(field.getValue())) { return "Yes"; } else {/*from w w w .j a v a 2 s. com*/ return "No"; } case CustomFormField.CALENDAR: String calendarValue = field.getValue(); if (StringUtils.hasText(calendarValue)) { try { String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT, DateFormat.LONG, field.getValue()); Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate); Locale locale = Locale.getDefault(); int dateFormat = DateFormat.SHORT; SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat, locale); calendarValue = dateFormatter.format(timestamp); } catch (Exception e) { LOG.error("toHtml calendar", e); } } return StringUtils.toHtml(calendarValue); case CustomFormField.PERCENT: return StringUtils.toHtml(field.getValue()) + "%"; case CustomFormField.INTEGER: // Determine the value to display in the field String integerValue = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(integerValue)) { try { NumberFormat formatter = NumberFormat.getInstance(); integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue())); } catch (Exception e) { LOG.warn("Could not integer format: " + field.getValue()); } } return integerValue; case CustomFormField.FLOAT: // Determine the value to display in the field String decimalValue = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(decimalValue)) { try { NumberFormat formatter = NumberFormat.getInstance(); decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue())); } catch (Exception e) { LOG.warn("Could not decimal format: " + field.getValue()); } } return decimalValue; case CustomFormField.CURRENCY: // Use a currency for formatting String currencyCode = field.getValueCurrency(); if (currencyCode == null) { currencyCode = field.getCurrency(); } if (!StringUtils.hasText(currencyCode)) { currencyCode = "USD"; } try { NumberFormat formatter = NumberFormat.getCurrencyInstance(); if (currencyCode != null) { Currency currency = Currency.getInstance(currencyCode); formatter.setCurrency(currency); } return (StringUtils.toHtml(formatter.format(StringUtils.getDoubleNumber(field.getValue())))); } catch (Exception e) { LOG.error("toHtml currency", e); } return StringUtils.toHtml(field.getValue()); case CustomFormField.EMAIL: return StringUtils.toHtml(field.getValue()); case CustomFormField.PHONE: PhoneNumberBean phone = new PhoneNumberBean(); phone.setNumber(field.getValue()); PhoneNumberUtils.format(phone, Locale.getDefault()); return StringUtils.toHtml(phone.toString()); case CustomFormField.URL: String value = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(value)) { if (!value.contains("://")) { value = "http://" + value; } if (value.contains("://")) { return ("<a href=\"" + StringUtils.toHtml(value) + "\">" + StringUtils.toHtml(value) + "</a>"); } } return StringUtils.toHtml(value); case CustomFormField.IMAGE: String image = StringUtils.toHtmlValue(field.getValue()); if (StringUtils.hasText(image)) { Project project = ProjectUtils.loadProject(wiki.getProjectId()); return ("<img src=\"" + contextPath + "/show/" + project.getUniqueId() + "/wiki-image/" + image + "\"/>"); } return StringUtils.toHtml(image); default: return StringUtils.toHtml(field.getValue()); } }
From source file:com.naryx.tagfusion.cfm.tag.awt.cfCHART.java
private JFreeChart renderPieChart(cfSession _Session, cfCHARTInternalData chartData, List<cfCHARTSERIESData> series, String tipStyle, String drillDownUrl) throws cfmRunTimeException { // Retrieve the attributes of the chart String backgroundColorStr = getDynamic(_Session, "BACKGROUNDCOLOR").toString(); Color backgroundColor = convertStringToColor(backgroundColorStr); String foregroundColorStr = getDynamic(_Session, "FOREGROUNDCOLOR").toString(); Color foregroundColor = convertStringToColor(foregroundColorStr); String labelFormat = getDynamic(_Session, "LABELFORMAT").toString().toLowerCase(); if (!labelFormat.equals("number") && !labelFormat.equals("currency") && !labelFormat.equals("percent")) throw newRunTimeException( "The labelFormat value '" + labelFormat + "' is not supported with pie charts"); String pieSliceStyle = getDynamic(_Session, "PIESLICESTYLE").toString().toLowerCase(); String title = null;/* w w w.j a va 2 s.c o m*/ if (containsAttribute("TITLE")) title = getDynamic(_Session, "TITLE").toString(); Font font = getFont(_Session); cfCHARTSERIESData seriesData = series.get(0); boolean bShow3D = getDynamic(_Session, "SHOW3D").getBoolean(); if (bShow3D && !seriesData.getType().equals("pie")) throw newRunTimeException("Only bar, line, horizontal bar and pie charts can be displayed in 3D"); boolean bShowBorder = getDynamic(_Session, "SHOWBORDER").getBoolean(); boolean bShowLegend = true; // default to true for pie charts if (containsAttribute("SHOWLEGEND")) bShowLegend = getDynamic(_Session, "SHOWLEGEND").getBoolean(); // Get the plot for the chart and configure it PiePlot plot = getPiePlot(series, pieSliceStyle, bShow3D); setBackgroundImage(_Session, plot, chartData.getImageData()); plot.setBackgroundPaint(backgroundColor); plot.setLabelBackgroundPaint(backgroundColor); plot.setLabelShadowPaint(backgroundColor); // Set the labels color plot.setLabelPaint(convertStringToColor(seriesData.getDataLabelColor())); // Set the labels font plot.setLabelFont(getFont(seriesData.getDataLabelFont(), seriesData.getDataLabelFontBold(), seriesData.getDataLabelFontItalic(), seriesData.getDataLabelFontSize())); String dataLabelStyle = seriesData.getDataLabelStyle(); NumberFormat percentInstance = NumberFormat.getPercentInstance(); percentInstance.setMaximumFractionDigits(3); NumberFormat numberFormat = null; if (labelFormat.equals("number")) { // Only display the value in the Label as a number numberFormat = NumberFormat.getInstance(); if (dataLabelStyle.equals("none")) plot.setLabelGenerator(null); else if (dataLabelStyle.equals("value")) plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{1}")); else if (dataLabelStyle.equals("rowlabel")) plot.setLabelGenerator( new org.jfree.chart.labels.StandardPieSectionLabelGenerator(seriesData.getSeriesLabel())); else if (dataLabelStyle.equals("columnlabel")) plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0}")); else if (dataLabelStyle.equals("pattern")) plot.setLabelGenerator( new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0} {1} ({2} of {3})")); else { String pattern = java.text.MessageFormat.format(dataLabelStyle, new Object[] { seriesData.getSeriesLabel(), "{0}", "{1}", "{2}", "{3}" }); plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(pattern)); } } else if (labelFormat.equals("currency")) { // Only display the value in the Label as a currency numberFormat = NumberFormat.getCurrencyInstance(); if (dataLabelStyle.equals("none")) plot.setLabelGenerator(null); else if (dataLabelStyle.equals("value")) plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{1}", NumberFormat.getCurrencyInstance(), percentInstance)); else if (dataLabelStyle.equals("rowlabel")) plot.setLabelGenerator( new org.jfree.chart.labels.StandardPieSectionLabelGenerator(seriesData.getSeriesLabel())); else if (dataLabelStyle.equals("columnlabel")) plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0}")); else if (dataLabelStyle.equals("pattern")) plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator( "{0} {1} ({2} of {3})", NumberFormat.getCurrencyInstance(), percentInstance)); else { String pattern = java.text.MessageFormat.format(dataLabelStyle, new Object[] { seriesData.getSeriesLabel(), "{0}", "{1}", "{2}", "{3}" }); plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(pattern, NumberFormat.getCurrencyInstance(), percentInstance)); } } else if (labelFormat.equals("percent")) { // Only display the value in the Label as a percent numberFormat = percentInstance; if (dataLabelStyle.equals("none")) plot.setLabelGenerator(null); else if (dataLabelStyle.equals("value")) plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{1}", percentInstance, percentInstance)); else if (dataLabelStyle.equals("rowlabel")) plot.setLabelGenerator( new org.jfree.chart.labels.StandardPieSectionLabelGenerator(seriesData.getSeriesLabel())); else if (dataLabelStyle.equals("columnlabel")) plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0}")); else if (dataLabelStyle.equals("pattern")) plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator( "{0} {1} ({2} of {3})", percentInstance, percentInstance)); else { String pattern = java.text.MessageFormat.format(dataLabelStyle, new Object[] { seriesData.getSeriesLabel(), "{0}", "{1}", "{2}", "{3}" }); plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(pattern, percentInstance, percentInstance)); } } if (!tipStyle.equals("none")) { plot.setToolTipGenerator(new StandardPieToolTipGenerator( StandardPieToolTipGenerator.DEFAULT_SECTION_LABEL_FORMAT, numberFormat, numberFormat)); } if (drillDownUrl != null) { plot.setURLGenerator(new com.newatlanta.bluedragon.PieURLGenerator(drillDownUrl, numberFormat)); } // Get the chart and configure it JFreeChart chart = new JFreeChart(null, null, plot, false); chart.setBorderVisible(bShowBorder); chart.setBackgroundPaint(backgroundColor); setTitle(chart, title, font, foregroundColor, chartData.getTitles()); setLegend(chart, bShowLegend, font, foregroundColor, backgroundColor, chartData.getLegendData()); return chart; }