List of usage examples for java.lang StringBuffer insert
@Override public StringBuffer insert(int offset, double d)
From source file:org.openflexo.foundation.wkf.FlexoProcess.java
public static String beautifyName(String name) { if (name == null) { return null; }/*from w w w.j a v a 2 s. c om*/ if (name.matches(JavaUtils.JAVA_CLASS_NAME_REGEXP)) { return name; } Matcher m = JavaUtils.JAVA_VARIABLE_ACCEPTABLE_PATTERN.matcher(name); StringBuffer sb = new StringBuffer(); int i = 0; while (m.find()) { int n = m.start() - i; for (int j = 0; j < n; j++) { sb.append('_'); } sb.append(ToolBox.capitalize(m.group(), true)); i = m.start() + m.end(); } if (sb.length() == 0 || sb.charAt(0) >= '0' && sb.charAt(0) <= '9') { sb.insert(0, '_'); } return sb.toString(); }
From source file:org.jets3t.gui.ErrorDialog.java
private String buildDetailedText(Throwable throwable) { if (!jets3tProperties.getBoolProperty("gui.verboseErrorDialog", true)) { return null; }//from ww w . ja va 2s.c om StringBuffer detailsText = new StringBuffer(); if (throwable instanceof S3ServiceException) { detailsText.append("<table border=\"0\">"); S3ServiceException s3se = (S3ServiceException) throwable; if (s3se.getS3ErrorCode() != null) { detailsText.append("<tr><td><b>S3 Error Code</b></td><td>").append(s3se.getS3ErrorCode()) .append("</td></tr>"); } else { String msg = throwable.getMessage(); if (msg.length() > 80) { ServiceUtils.wrapString(msg, "<br/>", 80); } detailsText.append("<tr><td><b>Exception message</b></td></tr><tr><td>").append(msg) .append("</td></tr>"); } if (s3se.getS3ErrorMessage() != null) { detailsText.append("<tr><td><b>S3 Message</b></td><td>").append(s3se.getS3ErrorMessage()) .append("</td></tr>"); } detailsText.append("<tr><td><b>HTTP Status Code</b></td><td>").append(s3se.getResponseCode()) .append("</td></tr>"); if (s3se.getS3ErrorRequestId() != null) { detailsText.append("<tr><td><b>S3 Request Id</b></td><td>").append(s3se.getS3ErrorRequestId()) .append("</td></tr>"); } if (s3se.getS3ErrorHostId() != null) { detailsText.append("<tr><td><b>S3 Host Id</b></td><td>").append(s3se.getS3ErrorHostId()) .append("</td></tr>"); } boolean firstCause = true; Throwable cause = s3se.getCause(); while (cause != null && cause.getMessage() != null) { if (firstCause) { detailsText.append("<tr><td><b>Cause</b></td></tr>"); } detailsText.append("<tr><td>").append(cause.getMessage()).append("</td></tr>"); firstCause = false; cause = cause.getCause(); } detailsText.append("</table>"); } else { boolean firstCause = true; Throwable cause = throwable; while (cause != null && cause.getMessage() != null) { if (firstCause) { detailsText.append("<tr><td><b>Cause</b></td></tr>"); } detailsText.append("<tr><td>").append(cause.getMessage()).append("</td></tr>"); firstCause = false; cause = cause.getCause(); } } if (detailsText.length() > 0) { detailsText.insert(0, "<html>"); detailsText.append("</html>"); } return detailsText.toString(); }
From source file:org.apache.poi.ss.format.CellNumberFormatter.java
/** {@inheritDoc} */ public void formatValue(StringBuffer toAppendTo, Object valueObject) { double value = ((Number) valueObject).doubleValue(); value *= scale;//from w ww .ja v a 2 s.c o m // the '-' sign goes at the front, always, so we pick it out boolean negative = value < 0; if (negative) value = -value; // Split out the fractional part if we need to print a fraction double fractional = 0; if (slash != null) { if (improperFraction) { fractional = value; value = 0; } else { fractional = value % 1.0; //noinspection SillyAssignment value = (long) value; } } Set<StringMod> mods = new TreeSet<>(); StringBuffer output = new StringBuffer(desc); if (exponent != null) { writeScientific(value, output, mods); } else if (improperFraction) { writeFraction(value, null, fractional, output, mods); } else { StringBuffer result = new StringBuffer(); Formatter f = new Formatter(result); f.format(LOCALE, printfFmt, value); if (numerator == null) { writeFractional(result, output); writeInteger(result, output, integerSpecials, mods, integerCommas); } else { writeFraction(value, result, fractional, output, mods); } } // Now strip out any remaining '#'s and add any pending text ... ListIterator<Special> it = specials.listIterator(); Iterator<StringMod> changes = mods.iterator(); StringMod nextChange = (changes.hasNext() ? changes.next() : null); int adjust = 0; BitSet deletedChars = new BitSet(); // records chars already deleted while (it.hasNext()) { Special s = it.next(); int adjustedPos = s.pos + adjust; if (!deletedChars.get(s.pos) && output.charAt(adjustedPos) == '#') { output.deleteCharAt(adjustedPos); adjust--; deletedChars.set(s.pos); } while (nextChange != null && s == nextChange.special) { int lenBefore = output.length(); int modPos = s.pos + adjust; int posTweak = 0; switch (nextChange.op) { case StringMod.AFTER: // ignore adding a comma after a deleted char (which was a '#') if (nextChange.toAdd.equals(",") && deletedChars.get(s.pos)) break; posTweak = 1; //noinspection fallthrough case StringMod.BEFORE: output.insert(modPos + posTweak, nextChange.toAdd); break; case StringMod.REPLACE: int delPos = s.pos; // delete starting pos in original coordinates if (!nextChange.startInclusive) { delPos++; modPos++; } // Skip over anything already deleted while (deletedChars.get(delPos)) { delPos++; modPos++; } int delEndPos = nextChange.end.pos; // delete end point in original if (nextChange.endInclusive) delEndPos++; int modEndPos = delEndPos + adjust; // delete end point in current if (modPos < modEndPos) { if (nextChange.toAdd == "") output.delete(modPos, modEndPos); else { char fillCh = nextChange.toAdd.charAt(0); for (int i = modPos; i < modEndPos; i++) output.setCharAt(i, fillCh); } deletedChars.set(delPos, delEndPos); } break; default: throw new IllegalStateException("Unknown op: " + nextChange.op); } adjust += output.length() - lenBefore; if (changes.hasNext()) nextChange = changes.next(); else nextChange = null; } } // Finally, add it to the string if (negative) toAppendTo.append('-'); toAppendTo.append(output); }
From source file:repast.simphony.relogo.ide.wizards.NetlogoImportWizard.java
public String getJavaName(String name) { StringBuffer buf = new StringBuffer(); buf.append(name.trim());//w ww. j a v a 2 s .co m for (int i = 0; i < buf.length(); i++) { if (Character.isLetterOrDigit(buf.charAt(i))) { continue; } else if (buf.charAt(i) == '_') { continue; } else if (buf.charAt(i) == '?') { buf.setCharAt(i, 'Q'); } else if (buf.charAt(i) == '%') { buf.setCharAt(i, 'p'); } else if (buf.charAt(i) == '!') { buf.setCharAt(i, 'X'); } else if (Character.isWhitespace(buf.charAt(i)) || buf.charAt(i) == '-') { buf.deleteCharAt(i); if (i < buf.length() && Character.isLetterOrDigit(buf.charAt(i))) { if (buf.charAt(i) != '?' && buf.charAt(i) != '%' && buf.charAt(i) != '!') { buf.setCharAt(i, Character.toUpperCase(buf.charAt(i))); } else if (buf.charAt(i) == '_') { continue; } else if (buf.charAt(i) == '?') { buf.setCharAt(i, 'Q'); } else if (buf.charAt(i) == '%') { buf.setCharAt(i, 'P'); } else if (buf.charAt(i) == '!') { buf.setCharAt(i, 'X'); } } } else { buf.setCharAt(i, 'Q'); } } if (Character.isDigit(buf.charAt(0))) { buf.insert(0, '_'); } return buf.toString(); }
From source file:cx.fbn.nevernote.sql.NoteTable.java
public Note mapNoteFromQuery(NSqlQuery query, boolean loadContent, boolean loadResources, boolean loadRecognition, boolean loadBinary, boolean loadTags) { DateFormat indfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); // indfm = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy"); Note n = new Note(); NoteAttributes na = new NoteAttributes(); n.setAttributes(na);/* www. j a va 2 s. co m*/ n.setGuid(query.valueString(0)); n.setUpdateSequenceNum(new Integer(query.valueString(1))); n.setTitle(query.valueString(2)); try { n.setCreated(indfm.parse(query.valueString(3)).getTime()); n.setUpdated(indfm.parse(query.valueString(4)).getTime()); n.setDeleted(indfm.parse(query.valueString(5)).getTime()); } catch (ParseException e) { e.printStackTrace(); } n.setActive(query.valueBoolean(6, true)); n.setNotebookGuid(query.valueString(7)); try { String attributeSubjectDate = query.valueString(8); if (!attributeSubjectDate.equals("")) na.setSubjectDate(indfm.parse(attributeSubjectDate).getTime()); } catch (ParseException e) { e.printStackTrace(); } na.setLatitude(new Float(query.valueString(9))); na.setLongitude(new Float(query.valueString(10))); na.setAltitude(new Float(query.valueString(11))); na.setAuthor(query.valueString(12)); na.setSource(query.valueString(13)); na.setSourceURL(query.valueString(14)); na.setSourceApplication(query.valueString(15)); na.setContentClass(query.valueString(16)); if (loadTags) { List<String> tagGuids = noteTagsTable.getNoteTags(n.getGuid()); List<String> tagNames = new ArrayList<String>(); TagTable tagTable = db.getTagTable(); for (int i = 0; i < tagGuids.size(); i++) { String currentGuid = tagGuids.get(i); Tag tag = tagTable.getTag(currentGuid); if (tag.getName() != null) tagNames.add(tag.getName()); else tagNames.add(""); } n.setTagNames(tagNames); n.setTagGuids(tagGuids); } if (loadContent) { QTextCodec codec = QTextCodec.codecForLocale(); codec = QTextCodec.codecForName("UTF-8"); String unicode = codec.fromUnicode(query.valueString(17)).toString(); // This is a hack. Basically I need to convert HTML Entities to "normal" text, but if I // convert the < character to < it will mess up the XML parsing. So, to get around this // I am "bit stuffing" the < to &< so StringEscapeUtils doesn't unescape it. After // I'm done I convert it back. StringBuffer buffer = new StringBuffer(unicode); if (Global.enableHTMLEntitiesFix && unicode.indexOf("&#") > 0) { unicode = query.valueString(17); //System.out.println(unicode); //unicode = unicode.replace("<", "&_lt;"); //unicode = codec.fromUnicode(StringEscapeUtils.unescapeHtml(unicode)).toString(); //unicode = unicode.replace("&_lt;", "<"); //System.out.println("************************"); int j = 1; for (int i = buffer.indexOf("&#"); i != -1 && buffer.indexOf("&#", i) > 0; i = buffer.indexOf("&#", i + 1)) { j = buffer.indexOf(";", i) + 1; if (i < j) { String entity = buffer.substring(i, j).toString(); int len = entity.length() - 1; String tempEntity = entity.substring(2, len); try { Integer.parseInt(tempEntity); entity = codec.fromUnicode(StringEscapeUtils.unescapeHtml4(entity)).toString(); buffer.delete(i, j); buffer.insert(i, entity); } catch (Exception e) { } } } } n.setContent(unicode); // n.setContent(query.valueString(16).toString()); String contentHash = query.valueString(18); if (contentHash != null) n.setContentHash(contentHash.getBytes()); n.setContentLength(new Integer(query.valueString(19))); } if (loadResources) n.setResources(noteResourceTable.getNoteResources(n.getGuid(), loadBinary)); if (loadRecognition) { if (n.getResources() == null) { List<Resource> resources = noteResourceTable.getNoteResourcesRecognition(n.getGuid()); n.setResources(resources); } else { // We need to merge the recognition resources with the note resources retrieved earlier for (int i = 0; i < n.getResources().size(); i++) { Resource r = noteResourceTable.getNoteResourceRecognition(n.getResources().get(i).getGuid()); n.getResources().get(i).setRecognition(r.getRecognition()); } } } n.setContent(fixCarriageReturn(n.getContent())); return n; }
From source file:com.cloud.api.ApiServer.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//w w w. j a v a2 s .c om public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { // get some information for the access log... StringBuffer sb = new StringBuffer(); HttpServerConnection connObj = (HttpServerConnection) context.getAttribute("http.connection"); if (connObj instanceof SocketHttpServerConnection) { InetAddress remoteAddr = ((SocketHttpServerConnection) connObj).getRemoteAddress(); sb.append(remoteAddr.toString() + " -- "); } sb.append(request.getRequestLine()); try { String uri = request.getRequestLine().getUri(); int requestParamsStartIndex = uri.indexOf('?'); if (requestParamsStartIndex >= 0) { uri = uri.substring(requestParamsStartIndex + 1); } String[] paramArray = uri.split("&"); if (paramArray.length < 1) { s_logger.info("no parameters received for request: " + uri + ", aborting..."); return; } Map parameterMap = new HashMap<String, String[]>(); String responseType = BaseCmd.RESPONSE_TYPE_XML; for (String paramEntry : paramArray) { String[] paramValue = paramEntry.split("="); if (paramValue.length != 2) { s_logger.info("malformed parameter: " + paramEntry + ", skipping"); continue; } if ("response".equalsIgnoreCase(paramValue[0])) { responseType = paramValue[1]; } else { // according to the servlet spec, the parameter map should be in the form (name=String, // value=String[]), so // parameter values will be stored in an array parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] }); } } try { // always trust commands from API port, user context will always be UID_SYSTEM/ACCOUNT_ID_SYSTEM UserContext.registerContext(_systemUser.getId(), _systemAccount, null, true); sb.insert(0, "(userId=" + User.UID_SYSTEM + " accountId=" + Account.ACCOUNT_ID_SYSTEM + " sessionId=" + null + ") "); String responseText = handleRequest(parameterMap, true, responseType, sb); sb.append(" 200 " + ((responseText == null) ? 0 : responseText.length())); writeResponse(response, responseText, HttpStatus.SC_OK, responseType, null); } catch (ServerApiException se) { String responseText = getSerializedApiError(se.getErrorCode(), se.getDescription(), parameterMap, responseType, se); writeResponse(response, responseText, se.getErrorCode(), responseType, se.getDescription()); sb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (RuntimeException e) { // log runtime exception like NullPointerException to help identify the source easier s_logger.error("Unhandled exception, ", e); throw e; } } finally { s_accessLogger.info(sb.toString()); UserContext.unregisterContext(); } }
From source file:org.apache.fop.render.ps.PSPainter.java
private void writeText(String text, int start, int len, int letterSpacing, int wordSpacing, int[][] dp, Font font, Typeface tf, boolean multiByte) throws IOException { PSGenerator generator = getGenerator(); int end = start + len; int initialSize = len; initialSize += initialSize / 2;/*ww w . ja va 2s .com*/ boolean hasLetterSpacing = (letterSpacing != 0); boolean needTJ = false; int lineStart = 0; StringBuffer accText = new StringBuffer(initialSize); StringBuffer sb = new StringBuffer(initialSize); int[] dx = IFUtil.convertDPToDX(dp); int dxl = (dx != null ? dx.length : 0); for (int i = start; i < end; i++) { char orgChar = text.charAt(i); char ch; int cw; int glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { //Fixed width space are rendered as spaces so copy/paste works in a reader ch = font.mapChar(CharUtilities.SPACE); cw = font.getCharWidth(orgChar); glyphAdjust = font.getCharWidth(ch) - cw; } else { if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust -= wordSpacing; } ch = font.mapChar(orgChar); cw = font.getCharWidth(orgChar); } if (dx != null && i < dxl - 1) { glyphAdjust -= dx[i + 1]; } if (multiByte) { accText.append(HexEncoder.encode(ch)); } else { char codepoint = (char) (ch % 256); PSGenerator.escapeChar(codepoint, accText); //add character to accumulated text } if (glyphAdjust != 0) { needTJ = true; if (sb.length() == 0) { sb.append('['); //Need to start TJ } if (accText.length() > 0) { if ((sb.length() - lineStart + accText.length()) > 200) { sb.append(PSGenerator.LF); lineStart = sb.length(); } lineStart = writePostScriptString(sb, accText, multiByte, lineStart); sb.append(' '); accText.setLength(0); //reset accumulated text } sb.append(Integer.toString(glyphAdjust)).append(' '); } } if (needTJ) { if (accText.length() > 0) { if ((sb.length() - lineStart + accText.length()) > 200) { sb.append(PSGenerator.LF); } writePostScriptString(sb, accText, multiByte); } if (hasLetterSpacing) { sb.append("] " + formatMptAsPt(generator, letterSpacing) + " ATJ"); } else { sb.append("] TJ"); } } else { writePostScriptString(sb, accText, multiByte); if (hasLetterSpacing) { StringBuffer spb = new StringBuffer(); spb.append(formatMptAsPt(generator, letterSpacing)).append(" 0 "); sb.insert(0, spb.toString()); sb.append(" " + generator.mapCommand("ashow")); } else { sb.append(" " + generator.mapCommand("show")); } } generator.writeln(sb.toString()); }
From source file:com.xwtec.xwserver.util.json.JSONArray.java
/** * Make a prettyprinted JSON text of this JSONArray. Warning: This method * assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of * indentation.// www.j av a 2 s . c o m * @param indent The indention of the top level. * @return a printable, displayable, transmittable representation of the * array. * @throws JSONException */ public String toString(int indentFactor, int indent) { int len = size(); if (len == 0) { return "[]"; } if (indentFactor == 0) { return this.toString(); } int i; StringBuffer sb = new StringBuffer("["); if (len == 1) { sb.append(JSONUtils.valueToString(this.elements.get(0), indentFactor, indent)); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONUtils.valueToString(this.elements.get(i), indentFactor, newindent)); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } for (i = 0; i < indent; i += 1) { sb.insert(0, ' '); } } sb.append(']'); return sb.toString(); }
From source file:io.manasobi.utils.StringUtils.java
/** * ?(char) ? ? ? ?? ? ? ?? ?.<br> * ? ? 0? ""? ? ? 0 null? .<br> * length String.getBytes().length ? String.length() ? ?.<br><br> * * StringUtils.padding(5, 'e') = "eeeee" * * @param size/* w w w.jav a 2s . c o m*/ * the length to pad to * @param padChar * the character to pad with * @return padded String */ public static String padding(int size, char padChar) { if (size < 0) { return null; } StringBuffer buffer = new StringBuffer(size); for (int i = 0; i < size; i++) { buffer.insert(i, padChar); } return buffer.toString(); }
From source file:org.zkoss.poi.ss.format.CellNumberFormatter.java
/** {@inheritDoc} */ public void formatValue(StringBuffer toAppendTo, Object valueObject) { double value = ((Number) valueObject).doubleValue(); value *= scale;// w w w .j av a2 s . c o m // For negative numbers: // - If the cell format has a negative number format, this method // is called with a positive value and the number format has // the negative formatting required, e.g. minus sign or brackets. // - If the cell format does not have a negative number format, // this method is called with a negative value and the number is // formatted with a minus sign at the start. boolean negative = value < 0; if (negative) value = -value; // Split out the fractional part if we need to print a fraction double fractional = 0; if (slash != null) { if (improperFraction) { fractional = value; value = 0; } else { fractional = value % 1.0; //noinspection SillyAssignment value = (long) value; } } Set<StringMod> mods = new TreeSet<StringMod>(); StringBuffer output = new StringBuffer(desc); if (exponent != null) { writeScientific(value, output, mods); } else if (improperFraction) { writeFraction(value, null, fractional, output, mods); } else { StringBuffer result = new StringBuffer(); Formatter f = new Formatter(result, locale); //ZSS-68 f.format(locale, printfFmt, value); //ZSS-68 if (numerator == null) { writeFractional(result, output); writeInteger(result, output, integerSpecials, mods, integerCommas, false); } else { writeFraction(value, result, fractional, output, mods); } } // Now strip out any remaining '#'s and add any pending text ... ListIterator<Special> it = specials.listIterator(); Iterator<StringMod> changes = mods.iterator(); StringMod nextChange = (changes.hasNext() ? changes.next() : null); int adjust = 0; BitSet deletedChars = new BitSet(); // records chars already deleted final String groupSeparator = "" + Formatters.getGroupingSeparator(locale); //ZSS-68 while (it.hasNext()) { Special s = it.next(); int adjustedPos = s.pos + adjust; if (!deletedChars.get(s.pos) && output.charAt(adjustedPos) == '#') { output.deleteCharAt(adjustedPos); adjust--; deletedChars.set(s.pos); } while (nextChange != null && s == nextChange.special) { int lenBefore = output.length(); int modPos = s.pos + adjust; int posTweak = 0; switch (nextChange.op) { case StringMod.AFTER: // ignore adding a comma after a deleted char (which was a '#') if (nextChange.toAdd.equals(groupSeparator) && deletedChars.get(s.pos)) //20110321, henrichen@zkoss.org: respect current locale break; posTweak = 1; //noinspection fallthrough case StringMod.BEFORE: output.insert(modPos + posTweak, nextChange.toAdd); break; case StringMod.REPLACE: int delPos = s.pos; // delete starting pos in original coordinates if (!nextChange.startInclusive) { delPos++; modPos++; } // Skip over anything already deleted while (deletedChars.get(delPos)) { delPos++; modPos++; } int delEndPos = nextChange.end.pos; // delete end point in original if (nextChange.endInclusive) delEndPos++; int modEndPos = delEndPos + adjust; // delete end point in current if (modPos < modEndPos) { if (nextChange.toAdd == "") output.delete(modPos, modEndPos); else { char fillCh = nextChange.toAdd.charAt(0); for (int i = modPos; i < modEndPos; i++) output.setCharAt(i, fillCh); } deletedChars.set(delPos, delEndPos); } break; default: throw new IllegalStateException("Unknown op: " + nextChange.op); } adjust += output.length() - lenBefore; if (changes.hasNext()) nextChange = changes.next(); else nextChange = null; } } // Finally, add it to the string if (negative) toAppendTo.append('-'); toAppendTo.append(output); }