List of usage examples for java.lang StringBuffer insert
@Override public StringBuffer insert(int offset, double d)
From source file:com.chalmers.schmaps.CheckInActivity.java
/******************************************************************* * Method parses through in parameter jsonObject and creates an array of geopoints * each geopoint representing an checked-in person * @param jsonObject//from w w w . ja v a 2 s . c om * @return arraylist of geopoints **********************************************************************/ public void parseJsonAndDraw(JSONObject jsonObject) { //greates an geopoint with our location OverlayItem overlayitem; GeoPoint geopoint; int lat, lng; String name, time; StringBuffer timebuffer = new StringBuffer(); List<Overlay> overlayList; MapItemizedOverlay mapItemizedCheckIn; Drawable checkInDot; overlayList = mapview.getOverlays(); //drawable checkInDot = this.getResources().getDrawable(R.drawable.chalmersandroid); //mapitemizedoverlay with drawable mapItemizedCheckIn = new MapItemizedOverlay(checkInDot, this); result = null; try { result = jsonObject.getJSONArray("result"); JSONObject checkedInPerson; //loop through the jsonarray and extract all checked-in points //collect data, create geopoint and add to list of overlays that will be drawn on map for (int count = 0; count < result.length(); count++) { checkedInPerson = result.getJSONObject(count); //extract time time = checkedInPerson.getString("time"); //insert in stringbuffer timebuffer.insert(0, time); //delete seconds timebuffer.delete(VALUEOFSECONDS, timebuffer.length()); //delete date timebuffer.delete(0, VALUEOFDATE); //convert back to string time = timebuffer.toString(); //clear buffer timebuffer.delete(0, timebuffer.length()); name = checkedInPerson.getString("name"); lat = (int) checkedInPerson.getInt("lat"); lng = (int) checkedInPerson.getInt("lng"); geopoint = new GeoPoint(lat, lng); overlayitem = new OverlayItem(geopoint, name, "Checked in at " + time); mapItemizedCheckIn.addOverlay(overlayitem); overlayList.add(mapItemizedCheckIn); } } catch (JSONException e) { } mapview.postInvalidate(); }
From source file:org.apache.poi.ss.examples.ToCSV.java
/** * Checks to see whether the field - which consists of the formatted * contents of an Excel worksheet cell encapsulated within a String - contains * any embedded characters that must be escaped. The method is able to * comply with either Excel's or UNIX formatting conventions in the * following manner;// w ww.j a va 2s . c om * * With regard to UNIX conventions, if the field contains any embedded * field separator or EOL characters they will each be escaped by prefixing * a leading backspace character. These are the only changes that have yet * emerged following some research as being required. * * Excel has other embedded character escaping requirements, some that emerged * from empirical testing, other through research. Firstly, with regards to * any embedded speech marks ("), each occurrence should be escaped with * another speech mark and the whole field then surrounded with speech marks. * Thus if a field holds <em>"Hello" he said</em> then it should be modified * to appear as <em>"""Hello"" he said"</em>. Furthermore, if the field * contains either embedded separator or EOL characters, it should also * be surrounded with speech marks. As a result <em>1,400</em> would become * <em>"1,400"</em> assuming that the comma is the required field separator. * This has one consequence in, if a field contains embedded speech marks * and embedded separator characters, checks for both are not required as the * additional set of speech marks that should be placed around ay field * containing embedded speech marks will also account for the embedded * separator. * * It is worth making one further note with regard to embedded EOL * characters. If the data in a worksheet is exported as a CSV file using * Excel itself, then the field will be surounded with speech marks. If the * resulting CSV file is then re-imports into another worksheet, the EOL * character will result in the original simgle field occupying more than * one cell. This same 'feature' is replicated in this classes behaviour. * * @param field An instance of the String class encapsulating the formatted * contents of a cell on an Excel worksheet. * @return A String that encapsulates the formatted contents of that * Excel worksheet cell but with any embedded separator, EOL or * speech mark characters correctly escaped. */ private String escapeEmbeddedCharacters(String field) { StringBuffer buffer = null; // If the fields contents should be formatted to confrom with Excel's // convention.... if (this.formattingConvention == ToCSV.EXCEL_STYLE_ESCAPING) { // Firstly, check if there are any speech marks (") in the field; // each occurrence must be escaped with another set of spech marks // and then the entire field should be enclosed within another // set of speech marks. Thus, "Yes" he said would become // """Yes"" he said" if (field.contains("\"")) { buffer = new StringBuffer(field.replaceAll("\"", "\\\"\\\"")); buffer.insert(0, "\""); buffer.append("\""); } else { // If the field contains either embedded separator or EOL // characters, then escape the whole field by surrounding it // with speech marks. buffer = new StringBuffer(field); if ((buffer.indexOf(this.separator)) > -1 || (buffer.indexOf("\n")) > -1) { buffer.insert(0, "\""); buffer.append("\""); } } return (buffer.toString().trim()); } // The only other formatting convention this class obeys is the UNIX one // where any occurrence of the field separator or EOL character will // be escaped by preceding it with a backslash. else { if (field.contains(this.separator)) { field = field.replaceAll(this.separator, ("\\\\" + this.separator)); } if (field.contains("\n")) { field = field.replaceAll("\n", "\\\\\n"); } return (field); } }
From source file:org.openadaptor.auxil.connector.jndi.AbstractJNDIReadConnector.java
public void tailorSearchToThisRecord(IOrderedMap orderedMapRecord) throws RecordException { // Use a dynamic search base from the incoming record? if (recordKeyUsedAsSearchBase != null) { Object incomingBase = orderedMapRecord.get(recordKeyUsedAsSearchBase); if ((incomingBase == null) || !(incomingBase instanceof CharSequence)) { log.warn("Empty search base produced: recordKeyUsedAsSearchBase missing from this record: " + orderedMapRecord); throw new RecordException( "Empty search base produced: recordKeyUsedAsSearchBase missing from this record."); }// www. ja va2 s. c o m if (!(incomingBase instanceof String)) { incomingBase = incomingBase.toString(); } search.setSearchBases(new String[] { (String) incomingBase }); } // Set up the search filter to use all incomingMap values (GDS attribute names) with // any corresponding record values (if null then use "*"). StringBuffer searchFilter = new StringBuffer(); if (incomingMap != null) { if (incomingMap.size() > 1) { searchFilter.append("(&"); } Iterator incomingMapIterator = incomingMap.entrySet().iterator(); while (incomingMapIterator.hasNext()) { Map.Entry entry = (Map.Entry) incomingMapIterator.next(); Object recordValue = orderedMapRecord.get(entry.getKey()); if (recordValue != null) { searchFilter.append("(").append(entry.getValue()).append("=").append(recordValue).append(")"); } } if (incomingMap.size() > 1) { searchFilter.append(")"); } } // Combine it with any config defined search filter (e.g. it might restrict objectclass) if (configDefinedSearchFilter != null && configDefinedSearchFilter.length() > 0) { if (incomingMap != null) { searchFilter.insert(0, "(&"); } searchFilter.append(configDefinedSearchFilter); if (incomingMap != null) { searchFilter.append(")"); } } // Sanity check (don't want to do unconstrained searches): if (searchFilter.length() == 0) { log.warn("Empty search filter produced: probably missing incomingMap keys in record: " + orderedMapRecord); throw new RecordException( "Empty search filter produced: probably missing incomingMap keys in tbis record."); } // Set this updated filter: search.setFilter(searchFilter.toString()); }
From source file:org.apache.ojb.broker.accesslayer.sql.SqlGeneratorDefaultImpl.java
/** * @param crit Selection criteria/*ww w . ja v a2 s . c o m*/ * * 26/06/99 Change statement to a StringBuffer for efficiency */ public String asSQLStatement(Criteria crit, ClassDescriptor cld) { Enumeration e = crit.getElements(); StringBuffer statement = new StringBuffer(); while (e.hasMoreElements()) { Object o = e.nextElement(); if (o instanceof Criteria) { String addAtStart; String addAtEnd; Criteria pc = (Criteria) o; // need to add parenthesises? if (pc.isEmbraced()) { addAtStart = " ("; addAtEnd = ") "; } else { addAtStart = ""; addAtEnd = ""; } switch (pc.getType()) { case (Criteria.OR): { statement.append(" OR ").append(addAtStart); statement.append(asSQLStatement(pc, cld)); statement.append(addAtEnd); break; } case (Criteria.AND): { statement.insert(0, "( "); statement.append(") "); statement.append(" AND ").append(addAtStart); statement.append(asSQLStatement(pc, cld)); statement.append(addAtEnd); break; } } } else { SelectionCriteria c = (SelectionCriteria) o; if (statement.length() == 0) { statement.append(asSQLClause(c, cld)); } else { statement.insert(0, "("); statement.append(") "); statement.append(" AND "); statement.append(asSQLClause(c, cld)); } } } // while if (statement.length() == 0) { return null; } return statement.toString(); }
From source file:org.eclim.plugin.jdt.command.src.ClassPrototypeCommand.java
/** * Top level method for generating a prototype of the supplied type. * * @param type The type./* ww w. j a v a 2 s .co m*/ * @return The resulting prototype. */ protected String prototype(IType type) throws Exception { Set<String> imports = new TreeSet<String>(); StringBuffer buffer = new StringBuffer(); buffer.append(Services.getMessage("prototype.header")); buffer.append("package ").append(type.getPackageFragment().getElementName()).append(";\n"); prototype(buffer, type, "", imports); // insert the imports StringBuffer importClauses = new StringBuffer().append("\n\n"); for (String className : imports) { importClauses.append("import ").append(className).append(";\n"); } buffer.insert(buffer.indexOf(";") + 1, importClauses.toString()); return buffer.toString(); }
From source file:unikn.dbis.univis.sql.VQuery.java
public String getFilterWhereClause(VDimension dimension) { String tableName = dimension.getTableName(); //StringBuffer from = new StringBuffer("FROM " + tableName + " AS " + tableName); StringBuffer where = new StringBuffer(); VDimension oldDimension = dimension; boolean filtered = true; while (dimension.isDependent() && filtered) { dimension = (VDimension) dimension.getParent(); boolean appended = false; for (Filterable filter : dimension.getSelections()) { Long selection = (Long) filter.getId(); appended = true;/*from ww w.j a v a 2s. c o m*/ filtered = false; if (where.length() > 0) { where.append(" OR "); } else { where.append("("); } if (oldDimension.isVisible()) { where.append(tableName).append(".parent = ").append(selection); } else { where.append(tableName).append(".").append(dimension.getForeignKey()).append(" = ") .append(selection); } } if (appended) { where.append(")"); } } if (where.length() > 0) { where.insert(0, " AND "); } //return from.toString() + where.toString(); return where.toString(); }
From source file:it.cnr.icar.eric.server.query.CompressContentQueryFilterPlugin.java
protected void resolveHasMemberAssociations(ServerRequestContext serverContext, String queryId, String id, StringBuffer zipEntryValue) throws RegistryException, Exception { ServerRequestContext context = null; try {//from www . ja v a 2 s .c o m Map<String, String> queryParamsMap = new HashMap<String, String>(); queryParamsMap.put("$memberId", id); context = new ServerRequestContext("CompressContentQueryFilterPlugin:internalGetZipEntryValue", null); context.setUser(serverContext.getUser()); List<?> res = executeQuery(context, queryId, queryParamsMap); Iterator<?> roItr = res.iterator(); if (roItr.hasNext()) { RegistryObjectType ro = (RegistryObjectType) roItr.next(); id = ro.getId(); if (!id.equalsIgnoreCase(CanonicalConstants.CANONICAL_USERDATA_FOLDER_ID)) { String packageName = getLocalizedString(serverContext, ro.getName().getLocalizedString()); zipEntryValue.insert(0, '/'); zipEntryValue.insert(0, packageName); resolveHasMemberAssociations(serverContext, queryId, id, zipEntryValue); } } } finally { if (context != null) { context.rollback(); } } }
From source file:org.pentaho.platform.repository.solution.filebased.FileBasedSolutionRepository.java
private String getPathNames(final String solutionId, final String path) { Document repository = (Document) getRepositoryObjectFromCache(getRepositoryKey()); if (repository == null) { reloadSolutionRepository(getSession(), loggingLevel); repository = (Document) getRepositoryObjectFromCache(getRepositoryKey()); }/*w w w. jav a 2s . c o m*/ if (solutionId == null) { return ""; //$NON-NLS-1$ } // TODO sbarkdull, extract to a method, this same code is repeated in this class String xPath = "/repository/file[@type=\"" + FileInfo.FILE_TYPE_FOLDER + "\"][@name=\"" //$NON-NLS-1$//$NON-NLS-2$ + XmlHelper.encode(solutionId) + "\"]"; //$NON-NLS-1$ if (path != null) { String folders[] = path.split("/"); //$NON-NLS-1$ if (folders != null) { for (String element : folders) { xPath += "/file[@type=\"" + FileInfo.FILE_TYPE_FOLDER + "\"][@name=\"" //$NON-NLS-1$//$NON-NLS-2$ + XmlHelper.encode(element) + "\"]"; //$NON-NLS-1$ xPath += "[@visible=\"true\"]"; //$NON-NLS-1$ } } } StringBuffer sb = new StringBuffer(); List list = repository.selectNodes(xPath); if ((list != null) && (list.size() > 0)) { // grab the first one Element node = (Element) list.get(0); // walk up the ancestors boolean done = false; while ((node != null) && !done) { Node titleNode = node.selectSingleNode("title"); //$NON-NLS-1$ if (titleNode != null) { String name = titleNode.getText(); sb.insert(0, name + "/"); //$NON-NLS-1$ } else { // if we don't have a title node then there is nothing more we can do to construct the path done = true; } node = node.getParent(); } } return sb.toString(); }
From source file:org.photovault.swingui.ExportSelectedAction.java
/** Returns a proper filename in a numbered sequence. Examples: <table>/* www . java2s .c o m*/ <tr> <td>pattern</td> <td>example file names</td> </tr> <tr> <td>photo.jpg</td> <td>photo1.jpg, photo2.jpg</td> </tr> <tr> <td>photo_$n.jpg</td> <td>photo_1.jpg, photo_2.jpg, ..., photo_10000.jpg, ...</td> </tr> <tr> <td>photo_$4n.jpg</td> <td>photo_0001.jpg, photo_0002.jpg, ..., photo_10000.jpg, ...</td> </tr> </table> */ String getSequenceFnameFormat(String seqBase) { seqBase = seqBase.replaceAll("%", "%%"); StringBuffer formatStrBuf = new StringBuffer(seqBase); Pattern seqNumPattern = Pattern.compile("\\$(\\d*)n"); Matcher m = seqNumPattern.matcher(seqBase); if (m.find()) { int start = m.start(); int end = m.end(); //Check padding String padStr = m.group(1); /* Check for case in which padStr contains only zeros since format() throws exception for format string like %00d. */ if (padStr.matches("^0*$")) { padStr = "1"; } if (padStr.length() > 0) { padStr = "0" + padStr; } String seqNumFormat = "%1$" + padStr + "d"; formatStrBuf.replace(start, end, seqNumFormat); } else { // No format template found, add number just before extension Pattern extPattern = Pattern.compile("\\.[^\\.]+$"); int seqNumPos = seqBase.length(); Matcher extMatcher = extPattern.matcher(seqBase); if (extMatcher.find()) { seqNumPos = extMatcher.start(); } formatStrBuf.insert(seqNumPos, "%d"); } return formatStrBuf.toString(); }
From source file:org.apache.poi.ss.format.CellNumberFormatter.java
private void writeInteger(StringBuffer result, StringBuffer output, List<Special> numSpecials, Set<StringMod> mods, boolean showCommas) { int pos = result.indexOf(".") - 1; if (pos < 0) { if (exponent != null && numSpecials == integerSpecials) pos = result.indexOf("E") - 1; else/*from ww w .j a va2 s .com*/ pos = result.length() - 1; } int strip; for (strip = 0; strip < pos; strip++) { char resultCh = result.charAt(strip); if (resultCh != '0' && resultCh != ',') break; } ListIterator<Special> it = numSpecials.listIterator(numSpecials.size()); boolean followWithComma = false; Special lastOutputIntegerDigit = null; int digit = 0; while (it.hasPrevious()) { char resultCh; if (pos >= 0) resultCh = result.charAt(pos); else { // If result is shorter than field, pretend there are leading zeros resultCh = '0'; } Special s = it.previous(); followWithComma = showCommas && digit > 0 && digit % 3 == 0; boolean zeroStrip = false; if (resultCh != '0' || s.ch == '0' || s.ch == '?' || pos >= strip) { zeroStrip = s.ch == '?' && pos < strip; output.setCharAt(s.pos, (zeroStrip ? ' ' : resultCh)); lastOutputIntegerDigit = s; } if (followWithComma) { mods.add(insertMod(s, zeroStrip ? " " : ",", StringMod.AFTER)); followWithComma = false; } digit++; --pos; } StringBuffer extraLeadingDigits = new StringBuffer(); if (pos >= 0) { // We ran out of places to put digits before we ran out of digits; put this aside so we can add it later ++pos; // pos was decremented at the end of the loop above when the iterator was at its end extraLeadingDigits = new StringBuffer(result.substring(0, pos)); if (showCommas) { while (pos > 0) { if (digit > 0 && digit % 3 == 0) extraLeadingDigits.insert(pos, ','); digit++; --pos; } } mods.add(insertMod(lastOutputIntegerDigit, extraLeadingDigits, StringMod.BEFORE)); } }