List of usage examples for java.lang StringBuilder insert
@Override public StringBuilder insert(int offset, double d)
From source file:com.edgenius.wiki.render.macro.TableMacro.java
public void execute(StringBuffer buffer, MacroParameter params) throws MalformedMacroException { //style for cells boolean layout = GRID_NAME.equals(params.getMacroName()); StringBuilder styleBuf = new StringBuilder(); StringBuilder tableAttrsBuf = new StringBuilder(); //put cells style into context for TableCellMacro uses Map<String, String> cellParams = new HashMap<String, String>(); int[] key = TableGroupProcessor.getTableInfo(params); if (key != null && key.length == 1) { int tableId = key[0]; RenderContext context = params.getRenderContext(); Map<Integer, Map<String, String>> tableParams = (Map<Integer, Map<String, String>>) context .getGlobalParam(TableMacro.class.getName()); if (tableParams == null) { //init tableParams = new HashMap<Integer, Map<String, String>>(); context.putGlobalParam(TableMacro.class.getName(), tableParams); }// w ww .j av a 2 s . c o m tableParams.put(tableId, cellParams); } if (layout) { styleBuf.append("width:100%;border-width:0px;"); //!!!please note: this size has same value in MceInsertTableMacro.java, please keep consist. tableAttrsBuf.append("cellpadding=\"5\" cellspacing=\"5\""); cellParams.put(IS_GRID_LAYOUT, Boolean.TRUE.toString()); } else { //table String borderColor = params.getParam(BORDER_COLOR); String borderWidth = params.getParam(BORDER_WIDTH); if (!StringUtils.isBlank(borderWidth)) { borderWidth = GwtUtils.removeUnit(borderWidth); } String cellStyle = StringUtils.isBlank(borderColor) ? "" : ("border-color:" + borderColor); cellStyle = (StringUtils.isBlank(cellStyle) ? "" : cellStyle + ";") + (StringUtils.isBlank(borderWidth) ? "" : "border-width:" + borderWidth + "px"); cellStyle = StringUtils.isBlank(cellStyle) ? "" : ("style='" + cellStyle + "'"); cellParams.put(CELL_STYLE, cellStyle); cellParams.put(FIRST_LINE_AS_TITLE, params.getParam(FIRST_LINE_AS_TITLE)); cellParams.put(IS_GRID_LAYOUT, Boolean.FALSE.toString()); //table style String bgColor = params.getParam(BG_COLOR); String width = params.getParam(NameConstants.WIDTH); String height = params.getParam(NameConstants.HEIGHT); if (!StringUtil.isBlank(borderColor)) { styleBuf.append("border-color:").append(borderColor).append(";"); } if (!StringUtil.isBlank(bgColor)) { styleBuf.append("background-color:").append(bgColor).append(";"); } if (!StringUtil.isBlank(width)) { styleBuf.append("width:").append(width).append(";"); ; } if (!StringUtil.isBlank(height)) { styleBuf.append("height:").append(height).append(";"); ; } if (!StringUtil.isBlank(borderWidth)) { styleBuf.append("border-width:").append(borderWidth).append("px;"); ; } } if (styleBuf.length() > 0) { styleBuf.insert(0, "style=\""); styleBuf.append("\""); } String content = params.getContent(); buffer.append("<table class=").append(layout ? "\"macroGrid\"" : "\"macroTable\"") .append(styleBuf.length() == 0 ? "" : " ").append(styleBuf) .append(tableAttrsBuf.length() == 0 ? "" : " ").append(tableAttrsBuf).append("><tr>") .append(content).append("</tr></table>"); }
From source file:de.rahn.finances.commons.metrics.MetricsExporterService.java
/** * Schreibe jede volle Stunde die aktuellen Metriken und setze sie zurck. */// w w w .j av a 2s . c o m @Scheduled(cron = "0 0 * * * ?") public void exportMetrics() { StringBuilder builder = new StringBuilder(); registry.getGauges().forEach((s, m) -> { registry.remove(s); builder.append("metric=GAUGE, name=").append(s).append(", value=").append(m.getValue()) .append('\n'); }); registry.getCounters().forEach((s, m) -> { registry.remove(s); builder.append("metric=COUNTER, name=").append(s).append(", count=").append(m.getCount()) .append('\n'); }); registry.getHistograms().forEach((s, m) -> { registry.remove(s); Snapshot snapshot = m.getSnapshot(); builder.append("metric=HISTOGRAM, name=").append(s).append(", count=").append(m.getCount()) .append(", min=").append(snapshot.getMin()).append(", max=").append(snapshot.getMax()) .append(", mean=").append(snapshot.getMean()).append(", stddev=").append(snapshot.getStdDev()) .append(", median=").append(snapshot.getMedian()).append(", 75%=") .append(snapshot.get75thPercentile()).append(", 95%=").append(snapshot.get95thPercentile()) .append(", 98%=").append(snapshot.get98thPercentile()).append(", 99%=") .append(snapshot.get99thPercentile()).append(", 99.9%=").append(snapshot.get999thPercentile()) .append('\n'); }); registry.getMeters().forEach((s, m) -> { registry.remove(s); builder.append("metric=METER, name=").append(s).append(", count=").append(m.getCount()) .append(", mean-rate=").append(convertRate(m.getMeanRate())).append(", 1-minute-rate=") .append(convertRate(m.getOneMinuteRate())).append(", 5-minute-rate=") .append(convertRate(m.getFiveMinuteRate())).append(", 15-minute-rate=") .append(convertRate(m.getFifteenMinuteRate())).append(", rate-unit=events/").append(rateUnit) .append('\n'); }); registry.getTimers().forEach((s, m) -> { registry.remove(s); Snapshot snapshot = m.getSnapshot(); builder.append("metric=TIMER, name=").append(s).append(", count=").append(m.getCount()) .append(", mean-rate=").append(convertRate(m.getMeanRate())).append(", 1-minute-rate=") .append(convertRate(m.getOneMinuteRate())).append(", 5-minute-rate=") .append(convertRate(m.getFiveMinuteRate())).append(", 15-minute-rate=") .append(convertRate(m.getFifteenMinuteRate())).append(", rate-unit=calls/").append(rateUnit) .append(", min=").append(convertDuration(snapshot.getMin())).append(", max=") .append(convertDuration(snapshot.getMax())).append(", mean=") .append(convertDuration(snapshot.getMean())).append(", stddev=") .append(convertDuration(snapshot.getStdDev())).append(", median=") .append(convertDuration(snapshot.getMedian())).append(", 75%=") .append(convertDuration(snapshot.get75thPercentile())).append(", 95%=") .append(convertDuration(snapshot.get95thPercentile())).append(", 98%=") .append(convertDuration(snapshot.get98thPercentile())).append(", 99%=") .append(convertDuration(snapshot.get99thPercentile())).append(", 99.9%=") .append(convertDuration(snapshot.get999thPercentile())).append(", duration-unit=") .append(durationUnit).append('\n'); }); if (builder.length() > 0) { LOGGER.info(builder.insert(0, "\n***** Metrics Report *****\n").append("***************************") .toString()); } }
From source file:com.alu.e3.logger.LogCollector.java
/** * Returns the specified number of most-recent log lines from previously- * collected log files for a particular instance and log source. * /*from w w w . j a v a 2s . co m*/ * @param ipAddress The ip-address of the instance * @param logSource The source for the logs (JAVA, SMX, SYSLOG) * @param numLines The number of lines to retrieve. Fewer lines may be returned if the * requested number is not available. * @return Log lines in XML structure, with a top-level <code><log></code> node. */ public String getCollectedLogLinesFromInstance(String ipAddress, LogFileSource logSource, int numLines) { StringBuilder logLines = null; String logFilePath = null; int lineCount = 0; File collectionDir = new File(COLLECTION_PATH, LogCollector.ipToCollectionDirectory(ipAddress)); if (!collectionDir.exists() || !collectionDir.isDirectory()) { logger.warn("No log collection directory for ipAddress: {}", ipAddress); return null; } File logSourceSubdir = new File(collectionDir, logSource.toString()); if (!logSourceSubdir.exists() || !logSourceSubdir.isDirectory()) { logger.warn("No log-type '{}' collection subdirectory for ipAddress: {}", logSource.toString(), ipAddress); return null; } // Get the list of collected log files in date order File[] files = logSourceSubdir.listFiles(new LogFileFilter(null)); // get all log files, regardless of basename and ext Arrays.sort(files, new Comparator<Object>() { public int compare(Object o1, Object o2) { // Sort by decreasing date first, and then decreasing alphabetical File f1 = (File) o1; File f2 = (File) o2; int result = (Long.valueOf(f2.lastModified())).compareTo(Long.valueOf(f1.lastModified())); if (result == 0) { result = f2.getName().compareTo(f1.getName()); } return result; } }); logger.trace("Sorted log-files:"); for (File logFile : files) { logger.trace("{}", logFile.getName()); } logLines = new StringBuilder(); try { for (File file : files) { String fileName = file.getName(); if (logger.isDebugEnabled()) { logger.debug("Consider file: {}", fileName); } logFilePath = file.getAbsolutePath(); if (logger.isDebugEnabled()) { logger.debug("Retrieving {} log lines from file {}", String.valueOf(numLines - lineCount), logFilePath); } String logContent = LogCollector.getTailOfFile(file, numLines - lineCount); logLines.insert(0, logContent); int retrievedCount = lineCount(logContent); if (logger.isDebugEnabled()) { logger.debug("Actually got {} lines", String.valueOf(retrievedCount)); } lineCount += retrievedCount; if (lineCount >= numLines) { break; } } } catch (IOException ex) { // Swallow exception from any one file read and hope to get lines from the next log logger.warn("Couldn't read from log file {}", logFilePath == null ? "(null)" : logFilePath); } if (logger.isDebugEnabled()) { logger.debug("Got {} of {} requested lines", String.valueOf(lineCount), String.valueOf(numLines)); } return LoggingResponseBuilder.logLinesToXml(logSource, ipAddress, StringEscapeUtils.escapeXml(logLines.toString())); }
From source file:net.ymate.platform.persistence.jdbc.dialect.impl.MySQLDialect.java
@Override public String buildCreateSQL(Class<? extends IEntity> entityClass, String prefix, IShardingable shardingable) { EntityMeta _meta = EntityMeta.createAndGet(entityClass); if (_meta != null) { ExpressionUtils _exp = ExpressionUtils .bind("CREATE TABLE ${table_name} (\n${fields} ${primary_keys} ${indexes}) ${comment} ") .set("table_name", buildTableName(prefix, _meta, shardingable)); if (StringUtils.isNotBlank(_meta.getComment())) { _exp.set("comment", "COMMENT='" + StringUtils.trimToEmpty(_meta.getComment()) + "'"); } else {//from w ww . j av a 2 s. c o m _exp.set("comment", ""); } StringBuilder _tmpBuilder = new StringBuilder(); // FIELDs List<EntityMeta.PropertyMeta> _propMetas = new ArrayList<EntityMeta.PropertyMeta>( _meta.getProperties()); Collections.sort(_propMetas, new Comparator<EntityMeta.PropertyMeta>() { @Override public int compare(EntityMeta.PropertyMeta o1, EntityMeta.PropertyMeta o2) { return o1.getName().compareTo(o2.getName()); } }); for (EntityMeta.PropertyMeta _propMeta : _propMetas) { _tmpBuilder.append("\t").append(wrapIdentifierQuote(_propMeta.getName())).append(" "); String _propType = ""; if (!_propMeta.getType().equals(Type.FIELD.UNKNOW)) { _propType = _propMeta.getType().name(); } else { _propType = __doGetColumnType(_propMeta.getField().getType()); } if ("VARCHAR".equals(_propType) && _propMeta.getLength() > 2000) { _propType = "TEXT"; } else if ("BOOLEAN".equals(_propType) || "BIT".equals(_propType)) { _propType = "SMALLINT"; } boolean _needLength = true; if ("DATE".equals(_propType) || "TIME".equals(_propType) || "TIMESTAMP".equals(_propType) || "TEXT".equals(_propType)) { _needLength = false; } _tmpBuilder.append(_propType); if (_needLength) { _tmpBuilder.append("(").append(_propMeta.getLength()); if (_propMeta.getDecimals() > 0) { _tmpBuilder.append(",").append(_propMeta.getDecimals()); } _tmpBuilder.append(")"); } if (_propMeta.isUnsigned()) { if ("NUMERIC".equals(_propType) || "LONG".equals(_propType) || "FLOAT".equals(_propType) || "DOUBLE".equals(_propType) || "SMALLINT".equals(_propType) || "TINYINT".equals(_propType) || "DOUBLE".equals(_propType) || "INTEGER".equals(_propType)) { _tmpBuilder.append(" unsigned "); } } if (_propMeta.isNullable()) { if (StringUtils.isNotBlank(_propMeta.getDefaultValue())) { if ("@NULL".equals(_propMeta.getDefaultValue())) { _tmpBuilder.append(" DEFAULT NULL"); } else { _tmpBuilder.append(" DEFAULT '").append(_propMeta.getDefaultValue()).append("'"); } } } else { _tmpBuilder.append(" NOT NULL"); } if (_propMeta.isAutoincrement()) { _tmpBuilder.append(" AUTO_INCREMENT"); } if (StringUtils.isNotBlank(_propMeta.getComment())) { _tmpBuilder.append(" COMMENT '").append(_propMeta.getComment()).append("'"); } _tmpBuilder.append(__LINE_END_FLAG); } _exp.set("fields", _tmpBuilder.length() > 2 ? _tmpBuilder.substring(0, _tmpBuilder.lastIndexOf(__LINE_END_FLAG)) : ""); // PKs _tmpBuilder.setLength(0); for (String _key : _meta.getPrimaryKeys()) { _tmpBuilder.append(wrapIdentifierQuote(_key)).append(","); } if (_tmpBuilder.length() > 0) { _tmpBuilder.setLength(_tmpBuilder.length() - 1); _tmpBuilder.insert(0, ",\n\tPRIMARY KEY (").append(")"); _exp.set("primary_keys", _tmpBuilder.toString()); } // INDEXs _tmpBuilder.setLength(0); if (!_meta.getIndexes().isEmpty()) { _tmpBuilder.append(__LINE_END_FLAG); for (EntityMeta.IndexMeta _index : _meta.getIndexes()) { if (!_index.getFields().isEmpty()) { List<String> _idxFields = new ArrayList<String>(_index.getFields().size()); for (String _idxField : _index.getFields()) { _idxFields.add(wrapIdentifierQuote(_idxField)); } if (_index.isUnique()) { _tmpBuilder.append("\tUNIQUE KEY "); } else { _tmpBuilder.append("\tINDEX "); } _tmpBuilder.append(wrapIdentifierQuote(_index.getName())).append(" (") .append(StringUtils.join(_idxFields, ",")).append(")").append(__LINE_END_FLAG); } } if (_tmpBuilder.length() > 2) { _tmpBuilder.setLength(_tmpBuilder.length() - 2); } } else { _tmpBuilder.append(""); } return _exp.set("indexes", _tmpBuilder.toString()).getResult(); } return null; }
From source file:com.kodemore.utility.Kmu.java
/** * Pad s with leading c's and (space provided) trailing c's until its length * is n. Return s if its length is greater than n. *//*from w ww . j a v a2 s .co m*/ public static String outsidePad(String s, int n, char c) { StringBuilder out; out = new StringBuilder(n); out.append(s); while (out.length() < n) { out.insert(0, c); if (out.length() < n) out.append(c); } return out.toString(); }
From source file:com.kodemore.utility.Kmu.java
/** * Add commas to the integer in standard american format. *///from w w w. j a v a 2s . com public static String formatInteger(long value) { int min = value < 0 ? 2 : 1; StringBuilder out; out = new StringBuilder(); out.append(value); int i = out.length() - 3; while (i >= min) { out.insert(i, CHAR_COMMA); i -= 3; } return out.toString(); }
From source file:edu.ku.brc.specify.conversion.ConvertVerifier.java
/** * @param oldNewIdStr/* ww w . jav a 2s . c o m*/ * @param newColInx * @param oldColInx * @return * @throws SQLException */ private StatusType compareDates(final String oldNewIdStr, final int newColInx, final int oldColInx) throws SQLException { PartialDateConv datePair = new PartialDateConv(); Object newObj = newDBRS.getObject(newColInx); Object oldObj = oldDBRS.getObject(oldColInx); ResultSetMetaData newRsmd = newDBRS.getMetaData(); ResultSetMetaData oldRsmd = oldDBRS.getMetaData(); String newColName = newRsmd.getColumnName(newColInx); String oldColName = oldRsmd.getColumnName(oldColInx); if (newObj == null) { String clsName = newRsmd.getColumnClassName(newColInx); if (compareTo6DBs) { if (!clsName.equals("java.sql.Date") || oldObj != null) { String msg = "New Value was null and shouldn't have been for Key Value New Field [" + newColName + "] [" + oldObj + "]"; log.error(msg); tblWriter.logErrors(newColName, msg); return StatusType.NEW_VAL_NULL; } } else if (oldObj != null) { if (oldObj instanceof Number && ((Number) oldObj).intValue() == 0) { return StatusType.COMPARE_OK; } else if (!clsName.equals("java.sql.Date") || (!(oldObj instanceof String) && ((Number) oldObj).intValue() != 0)) { String msg = "New Value was null and shouldn't have been for Key Value New Field [" + newColName + "] [" + oldObj + "]"; log.error(msg); tblWriter.logErrors(newColName, msg); return StatusType.NEW_VAL_NULL; } } else { return StatusType.COMPARE_OK; } } StringBuilder errSB = new StringBuilder(); //System.out.println(newObj.getClass().getName()+" "+oldObj.getClass().getName()); if (newObj instanceof java.sql.Date) { boolean isPartialDate = false; Byte partialDateType = null; if (StringUtils.contains(newRsmd.getColumnName(newColInx + 1), "DatePrecision")) { partialDateType = newDBRS.getByte(newColInx); isPartialDate = true; } if (compareTo6DBs) { Object dateObj = oldDBRS.getObject(oldColInx); boolean isPartialDate2 = false; Byte partialDateType2 = null; if (StringUtils.contains(oldRsmd.getColumnName(oldColInx + 1), "DatePrecision")) { partialDateType2 = newDBRS.getByte(oldColInx); isPartialDate2 = true; } else { log.error("Next isn't DatePrecision and can't be!"); tblWriter.logErrors(oldNewIdStr, errSB.toString()); } if (!newObj.equals(dateObj) || (isPartialDate2 && !partialDateType2.equals(partialDateType))) { errSB.insert(0, oldColName + " "); errSB.append("["); errSB.append(datePair); errSB.append("]["); errSB.append(dateFormatter.format((Date) newObj)); errSB.append("] oldDate["); errSB.append(dateFormatter.format((Date) dateObj)); errSB.append("]"); log.error(errSB.toString()); tblWriter.logErrors(oldNewIdStr, errSB.toString()); return StatusType.BAD_DATE; } } else { int oldIntDate = oldDBRS.getInt(oldColInx); if (oldIntDate == 0) { return StatusType.NO_OLD_REC; } BasicSQLUtils.getPartialDate(oldIntDate, datePair, false); if (partialDateType != null) { if (Byte.parseByte(datePair.getPartial()) != partialDateType.byteValue()) { errSB.append("Partial Dates Type do not match. Old[" + datePair.getPartial() + "] New [" + partialDateType.byteValue() + "]"); // error partial dates don't match } } Calendar cal = Calendar.getInstance(); cal.setTime((Date) newObj); int year = Integer.parseInt(datePair.getDateStr().substring(0, 4)); int mon = Integer.parseInt(datePair.getDateStr().substring(5, 7)); int day = Integer.parseInt(datePair.getDateStr().substring(8, 10)); if (mon > 0) mon--; boolean isYearOK = true; int yr = cal.get(Calendar.YEAR); if (year != yr) { errSB.append("Year mismatch Old[" + year + "] New [" + yr + "] "); isYearOK = false; } if (mon != cal.get(Calendar.MONTH)) { errSB.append("Month mismatch Old[" + mon + "] New [" + cal.get(Calendar.MONTH) + "] "); } if (day != cal.get(Calendar.DAY_OF_MONTH)) { errSB.append("Day mismatch Old[" + day + "] New [" + cal.get(Calendar.DAY_OF_MONTH) + "] "); } if (errSB.length() > 0 && (!isYearOK || !isPartialDate)) { errSB.insert(0, oldColName + " "); errSB.append("["); errSB.append(datePair); errSB.append("]["); errSB.append(dateFormatter.format((Date) newObj)); errSB.append("]"); log.error(errSB.toString()); tblWriter.logErrors(oldNewIdStr, errSB.toString()); return StatusType.BAD_DATE; } } } return StatusType.COMPARE_OK; }
From source file:it.grid.storm.config.Configuration.java
@Override public String toString() { StringBuilder configurationStringBuilder = new StringBuilder(); try {/*from w ww .jav a 2 s . c o m*/ // This class methods Method methods[] = Configuration.instance.getClass().getDeclaredMethods(); // This class fields Field[] fields = Configuration.instance.getClass().getDeclaredFields(); HashMap<String, String> methodKeyMap = new HashMap<String, String>(); for (Field field : fields) { String fieldName = field.getName(); if (fieldName.endsWith("KEY") && field.getType().equals(String.class)) { // from a field like GROUP_TAPE_WRITE_BUFFER_KEY = // "tape.buffer.group.write" // puts in the map the pair // <getgrouptapewritebuffer,tape.buffer.group.write> String mapKey = "get" + fieldName.substring(0, fieldName.lastIndexOf("_")).replaceAll("_", "").toLowerCase(); if (methodKeyMap.containsKey(mapKey)) { String value = methodKeyMap.get(mapKey); methodKeyMap.put(mapKey, value + " , " + (String) field.get(Configuration.instance)); } else { methodKeyMap.put(mapKey, (String) field.get(Configuration.instance)); } } } Object field = null; Object[] dummyArray = new Object[0]; for (Method method : methods) { /* * with method.getModifiers() == 1 we check that the method is public * (otherwise he can request real parameters) */ if (method.getName().substring(0, 3).equals("get") && (!method.getName().equals("getInstance")) && method.getModifiers() == 1) { field = method.invoke(Configuration.instance, dummyArray); if (field.getClass().isArray()) { field = ArrayUtils.toString(field); } String value = methodKeyMap.get(method.getName().toLowerCase()); if (value == null) { configurationStringBuilder.insert(0, "!! Unable to find method " + method.getName() + " in methode key map!"); } else { configurationStringBuilder.append("Property " + value + " : "); } if (field.getClass().equals(String.class)) { field = '\'' + ((String) field) + '\''; } configurationStringBuilder.append(method.getName() + "() == " + field.toString() + "\n"); } } return configurationStringBuilder.toString(); } catch (Exception e) { if (e.getClass().isAssignableFrom(java.lang.reflect.InvocationTargetException.class)) { configurationStringBuilder.insert(0, "!!! Cannot do toString! Got an Exception: " + e.getCause() + "\n"); } else { configurationStringBuilder.insert(0, "!!! Cannot do toString! Got an Exception: " + e + "\n"); } return configurationStringBuilder.toString(); } }