List of usage examples for java.lang StringBuffer insert
@Override public StringBuffer insert(int offset, double d)
From source file:com.clustercontrol.collect.util.CollectGraphUtil.java
/** * ??????????/* www . j a v a 2 s . com*/ * ?????? * @param summaryType * @return */ public static String drawGraphSheets(int summaryType) { long start = System.currentTimeMillis(); m_log.debug("drawGraphSheets()"); Long nowDate = System.currentTimeMillis(); long formatTerm = MILLISECOND_MONTH; if (getInstance().m_targetConditionEndDate == null && getInstance().m_targetConditionStartDate == null) { // ??null?????(????)??????-1h???? m_log.debug("drawGraphSheets() first draw."); getInstance().m_targetConditionEndDate = nowDate; // ????? switch (summaryType) { case SummaryTypeConstant.TYPE_AVG_HOUR: case SummaryTypeConstant.TYPE_MIN_HOUR: case SummaryTypeConstant.TYPE_MAX_HOUR: // ??????1???1? getInstance().m_targetConditionStartDate = nowDate - MILLISECOND_DAY; formatTerm = MILLISECOND_WEEK; break; case SummaryTypeConstant.TYPE_AVG_DAY: case SummaryTypeConstant.TYPE_MIN_DAY: case SummaryTypeConstant.TYPE_MAX_DAY: // ??????1???1? getInstance().m_targetConditionStartDate = nowDate - MILLISECOND_WEEK; formatTerm = MILLISECOND_MONTH; break; case SummaryTypeConstant.TYPE_AVG_MONTH: case SummaryTypeConstant.TYPE_MIN_MONTH: case SummaryTypeConstant.TYPE_MAX_MONTH: // ??????1???10? getInstance().m_targetConditionStartDate = nowDate - MILLISECOND_YEAR; formatTerm = MILLISECOND_10YEAR; break; default:// raw // ??????1???1? getInstance().m_targetConditionStartDate = nowDate - MILLISECOND_HOUR; formatTerm = MILLISECOND_DAY; break; } } else { m_log.debug("drawGraphSheets() already draw."); // ????????????????? // ?1???????????????12??(??) if (isSelectTermOverDay() && summaryType == SummaryTypeConstant.TYPE_RAW) { long center = (getSelectTermDiff() / 2) + getInstance().m_targetConditionStartDate; getInstance().m_targetConditionStartDate = center - (MILLISECOND_DAY / 2); getInstance().m_targetConditionEndDate = center + (MILLISECOND_DAY / 2); m_log.debug("drawGraphSheets() summaryType:raw, term over day. shortcut term. center:" + center); } // ????????? formatTerm = getInstance().m_sliderEnd - getInstance().m_sliderStart; } // ?????? long centerDate = getTargetConditionStartDate() + (getTargetConditionEndDate() - getTargetConditionStartDate()) / 2; getInstance().m_sliderStart = centerDate - (formatTerm / 2); getInstance().m_sliderEnd = centerDate + (formatTerm / 2); // ??? ArrayList<String> plotJsonList = new ArrayList<>(); int countgraph = 0; int dispCount = ClusterControlPlugin.getDefault().getPreferenceStore() .getInt(PerformancePreferencePage.P_GRAPH_MAX); boolean allbreak = false; boolean itembreak = false; for (CollectKeyInfoPK collectKeyInfoPK : getInstance().m_collectKeyInfoList) { // manager for (Map.Entry<String, TreeMap<String, List<Integer>>> entry : getInstance().m_targetManagerFacilityCollectMap .entrySet()) { String managerName = entry.getKey(); Map<String, List<Integer>> facilityCollectMap = entry.getValue(); for (Map.Entry<String, List<Integer>> faci_entry : facilityCollectMap.entrySet()) { String facilityId = faci_entry.getKey(); // add? String params = createBaseGraphDiv(managerName, collectKeyInfoPK.getItemName(), collectKeyInfoPK.getMonitorId(), collectKeyInfoPK.getDisplayName(), facilityId); plotJsonList.add(params); if (getInstance().totalFlg) { // ????on????itemcode???1???????????break? countgraph += facilityCollectMap.size(); if (countgraph >= dispCount) { allbreak = true; break; } itembreak = true; break; } countgraph++; if (countgraph >= dispCount) { allbreak = true; break; } } if (allbreak) { break; } if (itembreak) { break; } } if (allbreak) { break; } } StringBuffer sb = new StringBuffer(); for (String plotStr : plotJsonList) { sb.append(plotStr); sb.append(","); } sb.insert(0, "{\'all\':["); if (plotJsonList.size() > 0) { sb.deleteCharAt(sb.length() - 1); // ,?? } sb.append("], "); sb.append(orderItemInfoSelection()); sb.append("}"); m_log.info("createDrawGraphs() time:" + (System.currentTimeMillis() - start) + "ms"); return sb.toString(); }
From source file:com.safi.workshop.sqlexplorer.sqlpanel.AbstractSQLExecution.java
/** * Logs the query to the debug log file, but only if the preferences require it. If the * query failed, the exception should be included too. * //from w ww .j a va 2 s.co m * @param query * @param e */ protected void debugLogQuery(Query query, SQLException sqlException) { // Get the logging level String level = SQLExplorerPlugin.getDefault().getPreferenceStore() .getString(IConstants.QUERY_DEBUG_LOG_LEVEL); if (level == null || level.equals(IConstants.QUERY_DEBUG_OFF)) return; if (sqlException == null && level.equals(IConstants.QUERY_DEBUG_FAILED)) return; // Get the log files; if the current log is too big, retire it File dir = SQLExplorerPlugin.getDefault().getStateLocation().toFile(); File log = new File(dir.getAbsolutePath() + '/' + "query-debug.log"); File oldLog = new File(dir.getAbsolutePath() + '/' + "query-debug.old.log"); // Too big? Then delete the old and archive the current if (log.exists() && log.length() > MAX_DEBUG_LOG_SIZE) { oldLog.delete(); log.renameTo(oldLog); } // Copy it to the output PrintWriter writer = null; try { FileWriter fw = new FileWriter(log, true); writer = new PrintWriter(fw); try { writer.write("==============================================\r\n"); StringBuffer sb = new StringBuffer(query.toString()); for (int i = 0; i < sb.length(); i++) if (sb.charAt(i) == '\n') sb.insert(i++, '\r'); sb.append("\r\n"); writer.write(sb.toString()); if (sqlException != null) writer.write("FAILED: " + sqlException.getMessage() + "\r\n"); } finally { writer.flush(); writer.close(); } } catch (IOException e) { SQLExplorerPlugin.error("Failed to log query", e); } }
From source file:com.appleframework.monitor.action.LogsAction.java
@RequestMapping(value = "/projects/{projectName}/logs/more", method = RequestMethod.GET) public void console(final HttpServletResponse response, ModelMap map, @PathVariable String projectName, LogQuery logQuery) throws IOException, ParseException { Project project = projectService.findProject(projectName); map.put("project", project); final MongoConverter converter = project.fetchMongoTemplate().getConverter(); final DBCursor cursor = logsService.findLogs(projectName, logQuery); final StringBuffer buf = new StringBuffer(); FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override/*from ww w . ja v a 2 s .c om*/ public String call() throws Exception { long startTime = System.currentTimeMillis(); //???20 logger.debug("result:"); while (cursor.hasNext()) { Log log = converter.read(Log.class, cursor.next()); buf.insert(0, log.toString() + "\n"); long current = System.currentTimeMillis(); if ((current - startTime) / 1000 >= mongWaitSeconds) break; } return buf.toString(); } }); executor.execute(task); try { task.get(mongWaitSeconds + 5, TimeUnit.SECONDS); cursor.close(); } catch (Exception e) { logger.error("time out ", e); task.cancel(true); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(buf.toString()); response.getWriter().flush(); }
From source file:org.apache.jasper.compiler.JspUtil.java
/** * Produces a String representing a call to the EL interpreter. * @param expression a String containing zero or more "${}" expressions * @param expectedType the expected type of the interpreted result * @param fnmapvar Variable pointing to a function map. * @param XmlEscape True if the result should do XML escaping * @return a String representing a call to the EL interpreter. *///from w ww. ja va 2 s . c om public static String interpreterCall(boolean isTagFile, String expression, Class expectedType, String fnmapvar, boolean XmlEscape) { /* * Determine which context object to use. */ String jspCtxt = null; if (isTagFile) jspCtxt = "this.getJspContext()"; else jspCtxt = "pageContext"; /* * Determine whether to use the expected type's textual name * or, if it's a primitive, the name of its correspondent boxed * type. */ String targetType = expectedType.getName(); String primitiveConverterMethod = null; if (expectedType.isPrimitive()) { if (expectedType.equals(Boolean.TYPE)) { targetType = Boolean.class.getName(); primitiveConverterMethod = "booleanValue"; } else if (expectedType.equals(Byte.TYPE)) { targetType = Byte.class.getName(); primitiveConverterMethod = "byteValue"; } else if (expectedType.equals(Character.TYPE)) { targetType = Character.class.getName(); primitiveConverterMethod = "charValue"; } else if (expectedType.equals(Short.TYPE)) { targetType = Short.class.getName(); primitiveConverterMethod = "shortValue"; } else if (expectedType.equals(Integer.TYPE)) { targetType = Integer.class.getName(); primitiveConverterMethod = "intValue"; } else if (expectedType.equals(Long.TYPE)) { targetType = Long.class.getName(); primitiveConverterMethod = "longValue"; } else if (expectedType.equals(Float.TYPE)) { targetType = Float.class.getName(); primitiveConverterMethod = "floatValue"; } else if (expectedType.equals(Double.TYPE)) { targetType = Double.class.getName(); primitiveConverterMethod = "doubleValue"; } } if (primitiveConverterMethod != null) { XmlEscape = false; } /* * Build up the base call to the interpreter. */ // XXX - We use a proprietary call to the interpreter for now // as the current standard machinery is inefficient and requires // lots of wrappers and adapters. This should all clear up once // the EL interpreter moves out of JSTL and into its own project. // In the future, this should be replaced by code that calls // ExpressionEvaluator.parseExpression() and then cache the resulting // expression objects. The interpreterCall would simply select // one of the pre-cached expressions and evaluate it. // Note that PageContextImpl implements VariableResolver and // the generated Servlet/SimpleTag implements FunctionMapper, so // that machinery is already in place (mroth). targetType = toJavaSourceType(targetType); StringBuffer call = new StringBuffer( "(" + targetType + ") " + "org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate" + "(" + Generator.quote(expression) + ", " + targetType + ".class, " + "(PageContext)" + jspCtxt + ", " + fnmapvar + ", " + XmlEscape + ")"); /* * Add the primitive converter method if we need to. */ if (primitiveConverterMethod != null) { call.insert(0, "("); call.append(")." + primitiveConverterMethod + "()"); } return call.toString(); }
From source file:org.qedeq.base.io.IoUtility.java
/** * Reads contents of a file into a string buffer. Uses default encoding. * * @param file This file will be loaded. * @param buffer Buffer to fill with file contents. * @throws IOException File exception occurred. * * @deprecated Use {@link #loadFile(File, StringBuffer, String)}. */// ww w . j av a2 s .c o m public static void loadFile(final File file, final StringBuffer buffer) throws IOException { final int size = (int) file.length(); final char[] data = new char[size]; buffer.setLength(0); FileReader in = null; try { in = new FileReader(file); int charsread = 0; while (charsread < size) { charsread += in.read(data, charsread, size - charsread); } } finally { close(in); } buffer.insert(0, data); }
From source file:com.edgenius.wiki.render.macro.TableCellMacro.java
public void execute(StringBuffer buffer, MacroParameter params) throws MalformedMacroException { /*/* www . j a va 2 s . c o m*/ * !!! Important * This class has an assumption: Table macro must processed before its cells. This is rely on * MacroFilter.getRegions() to return correct sequence region. Then MarkupRenderEngineImpl.processRegions() * process region by this sequence... * * If any change impact this process sequence, here has to use ObjectHandler to eliminate sequence dependent. */ int[] tableInfo = TableGroupProcessor.getTableInfo(params); if (tableInfo == null || tableInfo.length != 4) { AuditLogger .error("There is no valid Table Group processed for key:" + params.getParam(Macro.GROUP_KEY)); //Failure tolerance buffer.append("<td>").append(params.getContent()).append("</td>"); return; } RenderContext context = params.getRenderContext(); Map<Integer, Map<String, String>> tableParams = (Map<Integer, Map<String, String>>) context .getGlobalParam(TableMacro.class.getName()); String style = null; boolean hasTitle = false; boolean isLayout = false; if (tableParams != null) { Map<String, String> tableParam = tableParams.get(tableInfo[0]); //this is for non-Grid check if (tableParam != null) { hasTitle = BooleanUtil.toBoolean(tableParam.get(TableMacro.FIRST_LINE_AS_TITLE)); style = tableParam.get(TableMacro.CELL_STYLE); isLayout = BooleanUtil.toBoolean(tableParam.get(TableMacro.IS_GRID_LAYOUT)); } } String cellWidth = ""; if (isLayout) { int columns = tableInfo[3]; if (columns > 0) { cellWidth = " width='" + 100 / columns + "%' "; } } StringBuffer att = new StringBuffer(); String colspan = params.getParam(COL_SPAN); if (!StringUtils.isBlank(colspan)) { att.append("colspan=").append(colspan); } String rowspan = params.getParam(ROW_SPAN); if (!StringUtils.isBlank(rowspan)) { if (att.length() > 0) att.append(" "); att.append("rowspan=").append(rowspan); } if (att.length() > 0) { att.insert(0, " "); } String start = "<td" + (StringUtils.isBlank(style) ? "" : (" " + style)) + att.toString() + cellWidth + ">"; String end = "</td>"; if (tableInfo[1] == 0) { //first row if (hasTitle) { start = "<th" + (StringUtils.isBlank(style) ? "" : (" " + style)) + att.toString() + cellWidth + ">"; end = "</th>"; } } StringBuffer content = new StringBuffer(params.getContent().replaceAll("\\r", "")); if (content.length() == 0) content.append(" "); buffer.append(start).append(content).append(end); }
From source file:com.coco.rolldigitaltextview.RollDigitalTextView.java
private CharSequence formatCurrency(double digital) { StringBuffer sb = new StringBuffer(); // sign/*w w w.j a v a 2s.c o m*/ sb.append(digital < 0 ? "-" : ""); digital = Math.abs(digital); // integer part String integerPart = String.valueOf((int) digital); sb.append(integerPart); int commaCount = (integerPart.length() + 2) / 3; if (commaCount > 0) { commaCount -= 1; } for (int i = 0; i < commaCount; i++) { sb.insert(sb.length() - (i * 4 + 3), ','); } // point part sb.append(String.format(".%02d", (long) (digital * 100) % 100)); return sb.toString(); }
From source file:com.sfs.beans.PrivilegesBean.java
/** * Gets a list of email addresses for the supplied user. * * @param user the user bean//from www . ja v a 2 s . c om * * @return the list of email addresses */ public final Collection<String> getEmailAddresses(final UserBean user) { Collection<String> addresses = new ArrayList<String>(); TreeMap<String, String> unique = new TreeMap<String, String>(); if (user.getMemberOf() != null) { for (String role : user.getMemberOf()) { if (role != null) { RoleBean roleBean = (RoleBean) this.roles.get(role); StringBuffer address = new StringBuffer(); if (StringUtils.isNotBlank(roleBean.getEmailAddress())) { address.append(roleBean.getEmailAddress().trim()); if (StringUtils.isNotBlank(roleBean.getEmailName())) { address.insert(0, roleBean.getEmailName().trim() + " <"); address.append(">"); } } if (StringUtils.isNotBlank(address.toString())) { unique.put(address.toString(), address.toString()); } } } } StringBuffer userAddress = new StringBuffer(); if (StringUtils.isNotBlank(user.getEmail())) { userAddress.append(user.getEmail().trim()); if (StringUtils.isNotBlank(user.getLastName())) { userAddress.insert(0, user.getLastName().trim() + " <"); userAddress.append(">"); } if (StringUtils.isNotBlank(user.getPreferredName())) { userAddress.insert(0, user.getPreferredName().trim() + " "); } // Remove the address if it is already in the unique tree map if (unique.containsKey(userAddress.toString())) { unique.remove(userAddress.toString()); } } // Add the user name to the top of the list if (StringUtils.isNotBlank(userAddress.toString())) { addresses.add(userAddress.toString()); } for (String address : unique.keySet()) { addresses.add(address); } return addresses; }
From source file:com.skymobi.monitor.action.LogsAction.java
@RequestMapping(value = "/projects/{projectName}/logs/more", method = RequestMethod.GET) public void console(final HttpServletResponse response, ModelMap map, @PathVariable String projectName, LogQuery logQuery) throws IOException, ParseException { Project project = projectService.findProject(projectName); map.put("project", project); final MongoConverter converter = project.fetchMongoTemplate().getConverter(); final DBCursor cursor = logsService.findLogs(projectName, logQuery); final StringBuffer buf = new StringBuffer(); @SuppressWarnings("unchecked") FutureTask<String> task = new FutureTask(new Callable<String>() { @Override/*from w w w .j a va 2 s . c om*/ public String call() throws Exception { long startTime = System.currentTimeMillis(); //???20 logger.debug("result:"); while (cursor.hasNext()) { Log log = converter.read(Log.class, cursor.next()); buf.insert(0, log.toString() + "\n"); long current = System.currentTimeMillis(); if ((current - startTime) / 1000 >= mongWaitSeconds) break; } return buf.toString(); } }); executor.execute(task); try { task.get(mongWaitSeconds + 5, TimeUnit.SECONDS); cursor.close(); } catch (Exception e) { logger.error("time out ", e); task.cancel(true); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(buf.toString()); response.getWriter().flush(); }
From source file:org.collectionspace.chain.csp.persistence.file.IdGenerator.java
private String sequenceToString(String path, int v) { // XXX temporary implementation path = path.substring(3);/*from w w w .j a v a 2 s . co m*/ String pattern = patterns.get(path); if (pattern == null) pattern = patterns.get(""); StringBuffer out = new StringBuffer(); for (int i = pattern.length() - 1; i >= 0; i--) { char c = pattern.charAt(i); switch (c) { case '%': case '^': c = digits[v % digits.length]; v /= digits.length; break; case '@': c = letters[v % letters.length]; v /= letters.length; break; case '$': c = '\0'; out.insert(0, Integer.toString(v)); v = 0; break; } if (c != '\0') out.insert(0, c); } return out.toString(); }