List of usage examples for java.lang StringBuffer setCharAt
@Override public synchronized void setCharAt(int index, char ch)
From source file:com.aurel.track.dbase.UpgradeDatabase.java
private String migrateRoleAccessKey(int accessKey) { int thousand; // close int hundred; // read int ten; // modify int one; // create StringBuffer extendedAccessKey = new StringBuffer(); //create the string buffer with no rights //-2 because at this time we have the last two permission flags not yet defined for (int i = 0; i < AccessBeans.NUMBER_OF_ACCESS_FLAGS; i++) { extendedAccessKey.append(AccessBeans.OFFVALUE); }/*w w w .j ava 2s.co m*/ thousand = accessKey / 1000;//close switch (thousand) { case 1: extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CLOSETASKIFMANAGERORORIGINATOR, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CLOSETASKIFRESPONSIBLE, AccessBeans.ONVALUE); break; case 2: extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CLOSETASKIFMANAGERORORIGINATOR, AccessBeans.ONVALUE); break; default: extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CLOSEANYTASK, AccessBeans.ONVALUE); break; } switch (accessKey % 1000) { case 999: extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.PROJECTADMIN, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.MANAGER, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.READANYTASK, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.MODIFYANYTASK, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CREATETASK, AccessBeans.ONVALUE); break; case 777: extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.MANAGER, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.READANYTASK, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.MODIFYANYTASK, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CREATETASK, AccessBeans.ONVALUE); break; case 770: extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.MANAGER, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CREATETASK, AccessBeans.ONVALUE); break; case 666: extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.RESPONSIBLE, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.READANYTASK, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.MODIFYANYTASK, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CREATETASK, AccessBeans.ONVALUE); break; case 660: extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.RESPONSIBLE, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CREATETASK, AccessBeans.ONVALUE); break; default: // pattern: read modify create hundred = (accessKey - thousand * 1000) / 100; // read ten = (accessKey - thousand * 1000 - hundred * 100) / 10; // modify one = accessKey - thousand * 1000 - hundred * 100 - ten * 10; // create if (hundred == 2) { extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.READANYTASK, AccessBeans.ONVALUE); } if (ten == 2) { extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.MODIFYANYTASK, AccessBeans.ONVALUE); //extendedAccessKey.setCharAt(AccessBeans.AccessFlagMigrationIndexes.ADDMODIFYDELETEDUEDATES, AccessBeans.ONVALUE); } if (one == 1) { extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CREATETASK, AccessBeans.ONVALUE); } break; } extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.CONSULTANT, AccessBeans.ONVALUE); extendedAccessKey.setCharAt(AccessBeans.AccessFlagIndexes.INFORMANT, AccessBeans.ONVALUE); return extendedAccessKey.toString(); }
From source file:org.apache.poi.ss.format.CellNumberFormatter.java
private void writeFractional(StringBuffer result, StringBuffer output) { int digit;//w ww .ja v a2s.c om int strip; ListIterator<Special> it; if (fractionalSpecials.size() > 0) { digit = result.indexOf(".") + 1; if (exponent != null) strip = result.indexOf("e") - 1; else strip = result.length() - 1; while (strip > digit && result.charAt(strip) == '0') strip--; it = fractionalSpecials.listIterator(); while (it.hasNext()) { Special s = it.next(); char resultCh = result.charAt(digit); if (resultCh != '0' || s.ch == '0' || digit < strip) output.setCharAt(s.pos, resultCh); else if (s.ch == '?') { // This is when we're in trailing zeros, and the format is '?'. We still strip out remaining '#'s later output.setCharAt(s.pos, ' '); } digit++; } } }
From source file:org.medici.bia.controller.search.AjaxController.java
/** * //from w w w . j a v a 2 s .c om * @param simpleSearchPerimeter * @param uuid * @param sortingColumnNumber * @param sortingDirection * @param firstRecord * @param length * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/src/ExpandResultsAdvancedSearch.json", method = RequestMethod.GET) public ModelAndView expandResultsAdvancedSearch(HttpSession httpSession, @RequestParam(value = "simpleSearchPerimeter") SimpleSearchPerimeter simpleSearchPerimeter, @RequestParam(value = "sSearch") String uuid, @RequestParam(value = "iSortCol_0", required = false) Integer sortingColumnNumber, @RequestParam(value = "sSortDir_0", required = false) String sortingDirection, @RequestParam(value = "iDisplayStart") Integer firstRecord, @RequestParam(value = "iDisplayLength") Integer length) { Map<String, Object> model = new HashMap<String, Object>(0); Map<String, SearchFilter> searchFilterMap = (Map<String, SearchFilter>) httpSession .getAttribute("searchFilterMap"); SearchFilter searchFilter = searchFilterMap.get(uuid); PaginationFilter paginationFilter = new PaginationFilter(firstRecord, length, sortingColumnNumber, sortingDirection, simpleSearchPerimeter); Page page = null; try { page = getSearchService().searchAdvancedDocuments(searchFilter.getFilterData(), paginationFilter); } catch (ApplicationThrowable aex) { page = new Page(paginationFilter); } List resultList = new ArrayList(); for (Document currentDocument : (List<Document>) page.getList()) { List singleRow = new ArrayList(); if (currentDocument.getSenderPeople() != null) { if (!currentDocument.getSenderPeople().getMapNameLf() .equals("Person Name Lost, Not Indicated or Unidentifiable")) singleRow.add(currentDocument.getSenderPeople().getMapNameLf()); else singleRow.add("Person Name Lost"); } else singleRow.add(""); if (currentDocument.getRecipientPeople() != null) { if (!currentDocument.getRecipientPeople().getMapNameLf() .equals("Person Name Lost, Not Indicated or Unidentifiable")) singleRow.add(currentDocument.getRecipientPeople().getMapNameLf()); else singleRow.add("Person Name Lost"); } else singleRow.add(""); if (currentDocument.getYearModern() != null) { singleRow.add(DateUtils.getStringDateHTMLForTable(currentDocument.getYearModern(), currentDocument.getDocMonthNum(), currentDocument.getDocDay())); } else { singleRow.add(DateUtils.getStringDateHTMLForTable(currentDocument.getDocYear(), currentDocument.getDocMonthNum(), currentDocument.getDocDay())); } if (currentDocument.getSenderPlace() != null) { if (!currentDocument.getSenderPlace().getPlaceName() .equals("Place Name Lost, Not Indicated or Unidentifable")) singleRow.add(currentDocument.getSenderPlace().getPlaceName()); else singleRow.add("Place Name Lost"); } else singleRow.add(""); if (currentDocument.getRecipientPlace() != null) { if (!currentDocument.getRecipientPlace().getPlaceName() .equals("Place Name Lost, Not Indicated or Unidentifable")) singleRow.add(currentDocument.getRecipientPlace().getPlaceName()); else singleRow.add("Place Name Lost"); } else singleRow.add(""); String lastColumn = getLastColumn(currentDocument, new StringBuilder()); singleRow.add(lastColumn); AdvancedSearchDocument advancedSearchDocument = (AdvancedSearchDocument) searchFilter.getFilterData(); StringBuffer yourSearch = new StringBuffer(); if (simpleSearchPerimeter.equals(SimpleSearchPerimeter.EXTRACT)) { if (advancedSearchDocument.getExtract() != null) { for (String currentExtract : advancedSearchDocument.getExtract()) { if (StringUtils.countMatches(currentExtract, "\"") % 2 != 0) { StringBuffer tempString = new StringBuffer(currentExtract); tempString.setCharAt(tempString.lastIndexOf("\""), ' '); currentExtract = tempString.toString(); } //This code is for highlight the correct words if (currentExtract.contains("\"")) { StringTokenizer stringTokenizer = new StringTokenizer(currentExtract.replace('"', ' '), " "); while (stringTokenizer.hasMoreTokens()) { String currentToken = stringTokenizer.nextToken(); if (currentToken.length() > 0 && currentToken != "") { if (yourSearch.toString().length() > 0) yourSearch.append(" " + currentToken); else yourSearch.append(currentToken); } } } else { if (yourSearch.toString().length() > 0) yourSearch.append(" " + currentExtract); else yourSearch.append(currentExtract); } } } if (currentDocument.getSynExtract().getDocExtract() != null) { if (yourSearch.length() != 0) { String text = DocumentUtils.searchTextResultExpand( currentDocument.getSynExtract().getDocExtract(), yourSearch.toString()); singleRow.add(HtmlUtils.highlightText(text, yourSearch.toString())); } else { if (currentDocument.getSynExtract().getDocExtract().length() > 200) { String text = currentDocument.getSynExtract().getDocExtract().substring(0, 197); singleRow.add(text.substring(0, text.lastIndexOf(" ")) + " ..."); } else { singleRow.add(currentDocument.getSynExtract().getDocExtract()); } } } else singleRow.add(""); } else if (simpleSearchPerimeter.equals(SimpleSearchPerimeter.SYNOPSIS)) { if (advancedSearchDocument.getSynopsis() != null) { for (String currentSynopsis : advancedSearchDocument.getSynopsis()) { if (StringUtils.countMatches(currentSynopsis, "\"") % 2 != 0) { StringBuffer tempString = new StringBuffer(currentSynopsis); tempString.setCharAt(tempString.lastIndexOf("\""), ' '); currentSynopsis = tempString.toString(); } //This code is for highlight the correct words if (currentSynopsis.contains("\"")) { StringTokenizer stringTokenizer = new StringTokenizer(currentSynopsis.replace('"', ' '), " "); while (stringTokenizer.hasMoreTokens()) { String currentToken = stringTokenizer.nextToken(); if (currentToken.length() > 0 && currentToken != "") { if (yourSearch.toString().length() > 0) yourSearch.append(" " + currentToken); else yourSearch.append(currentToken); } } } else { if (yourSearch.toString().length() > 0) yourSearch.append(" " + currentSynopsis); else yourSearch.append(currentSynopsis); } } } if (currentDocument.getSynExtract().getSynopsis() != null) { if (yourSearch.length() != 0) { String text = DocumentUtils.searchTextResultExpand( currentDocument.getSynExtract().getSynopsis(), yourSearch.toString()); singleRow.add(HtmlUtils.highlightText(text, yourSearch.toString())); } else { if (currentDocument.getSynExtract().getSynopsis().length() > 200) { String text = currentDocument.getSynExtract().getSynopsis().substring(0, 197); singleRow.add(text.substring(0, text.lastIndexOf(" ")) + " ..."); } else { singleRow.add(currentDocument.getSynExtract().getSynopsis()); } } } else singleRow.add(""); } else singleRow.add(""); resultList.add(HtmlUtils.showDocumentExpand(singleRow, currentDocument.getEntryId())); } model.put("iEcho", "1"); model.put("iTotalDisplayRecords", page.getTotal()); model.put("iTotalRecords", page.getTotal()); model.put("aaData", resultList); return new ModelAndView("responseOK", model); }
From source file:com.tasktop.internal.hp.qc.core.model.comments.mylyn3_8.HtmlStreamTokenizer_m3_8.java
/** * Replaces (in-place) HTML escapes in a StringBuffer with their corresponding characters. * //from w ww. j a v a 2s .c o m * @deprecated use {@link StringEscapeUtils#unescapeHtml(String)} instead */ @Deprecated public static StringBuffer unescape(StringBuffer sb) { int i = 0; // index into the unprocessed section of the buffer int j = 0; // index into the processed section of the buffer while (i < sb.length()) { char ch = sb.charAt(i); if (ch == '&') { int start = i; String escape = null; for (i = i + 1; i < sb.length(); i++) { ch = sb.charAt(i); if (!Character.isLetterOrDigit(ch) && !(ch == '#' && i == (start + 1))) { escape = sb.substring(start + 1, i); break; } } if (i == sb.length() && i != (start + 1)) { escape = sb.substring(start + 1); } if (escape != null) { Character character = parseReference(escape); if (character != null && !((0x0A == character || 0x0D == character || 0x09 == ch) || (character >= 0x20 && character <= 0xD7FF) || (character >= 0xE000 && character <= 0xFFFD) || (character >= 0x10000 && character <= 0x10FFFF))) { // Character is an invalid xml character // http://www.w3.org/TR/REC-xml/#charsets character = null; } if (character != null) { ch = character.charValue(); } else { // not an HTML escape; rewind i = start; ch = '&'; } } } sb.setCharAt(j, ch); i++; j++; } sb.setLength(j); return sb; }
From source file:repast.simphony.relogo.ide.wizards.NetlogoImportWizard.java
protected String camelCase(String text, boolean cap) { StringBuffer buf = new StringBuffer(text); for (int i = 0; i < buf.length(); i++) { if (buf.charAt(i) == '-' && buf.length() > (i + 1)) { buf.deleteCharAt(i);//from w ww. jav a 2 s.com if (buf.charAt(i) != '?' && buf.charAt(i) != '%') { buf.setCharAt(i, Character.toUpperCase(buf.charAt(i))); } 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, 'Q'); } else if (buf.charAt(i) == '%') { buf.setCharAt(i, 'p'); } } if (cap) buf.setCharAt(0, Character.toUpperCase(buf.charAt(0))); return buf.toString(); }
From source file:repast.simphony.relogo.ide.wizards.NetlogoImportWizard.java
public String getJavaName(String name) { StringBuffer buf = new StringBuffer(); buf.append(name.trim());//from www.j a va2 s. c o 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:org.freedesktop.dbus.Message.java
/** * Formats the message in a human-readable format. *//* w w w.ja va 2 s .c om*/ @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getClass().getSimpleName()); sb.append('('); sb.append(this.flags); sb.append(','); sb.append(this.serial); sb.append(')'); sb.append(' '); sb.append('{'); sb.append(' '); if (this.headers.size() == 0) sb.append('}'); else { for (Byte field : this.headers.keySet()) { sb.append(getHeaderFieldName(field)); sb.append('='); sb.append('>'); sb.append(this.headers.get(field).toString()); sb.append(','); sb.append(' '); } sb.setCharAt(sb.length() - 2, ' '); sb.setCharAt(sb.length() - 1, '}'); } sb.append(' '); sb.append('{'); sb.append(' '); Object[] params = null; try { params = getParameters(); } catch (DBusException DBe) { log.warn("Failed to get parameters", DBe); } if (null == params || 0 == params.length) sb.append('}'); else { for (Object o : params) { if (o instanceof Object[]) sb.append(Arrays.deepToString((Object[]) o)); else if (o instanceof byte[]) sb.append(Arrays.toString((byte[]) o)); else if (o instanceof int[]) sb.append(Arrays.toString((int[]) o)); else if (o instanceof short[]) sb.append(Arrays.toString((short[]) o)); else if (o instanceof long[]) sb.append(Arrays.toString((long[]) o)); else if (o instanceof boolean[]) sb.append(Arrays.toString((boolean[]) o)); else if (o instanceof double[]) sb.append(Arrays.toString((double[]) o)); else if (o instanceof float[]) sb.append(Arrays.toString((float[]) o)); else sb.append(o.toString()); sb.append(','); sb.append(' '); } sb.setCharAt(sb.length() - 2, ' '); sb.setCharAt(sb.length() - 1, '}'); } return sb.toString(); }
From source file:org.apache.axis.wsdl.toJava.JavaGeneratorFactory.java
/** Refactored to call recursively for JAX-RPC 1.1 spec 4.2.5. */ protected int javifyTypeEntryName(SymbolTable symbolTable, TypeEntry entry, HashMap anonQNames, int uniqueNum) { TypeEntry tEntry = entry;//www .j a va 2 s .co m String dims = tEntry.getDimensions(); TypeEntry refType = tEntry.getRefType(); while (refType != null) { tEntry = refType; dims += tEntry.getDimensions(); refType = tEntry.getRefType(); } TypeEntry te = tEntry; while (te != null) { TypeEntry base = SchemaUtils.getBaseType(te, symbolTable); if (base == null) break; uniqueNum = javifyTypeEntryName(symbolTable, base, anonQNames, uniqueNum); if (Utils.getEnumerationBaseAndValues(te.getNode(), symbolTable) == null && SchemaUtils.getComplexElementExtensionBase(te.getNode(), symbolTable) == null && te.getContainedAttributes() == null) { if (!SchemaUtils.isSimpleTypeWithUnion(te.getNode())) { if (base.isSimpleType()) { // Case 1: // <simpleType name="mySimpleStringType"> // <restriction base="xs:string"> // </restriction> // </simpleType> te.setSimpleType(true); te.setName(base.getName()); te.setRefType(base); } if (base.isBaseType()) { // Case 2: // <simpleType name="FooString"> // <restriction base="foo:mySimpleStringType"> // </restriction> // </simpleType> te.setBaseType(true); te.setName(base.getName()); te.setRefType(base); } } } if (!te.isSimpleType()) break; te = base; } // Need to javify the ref'd TypeEntry if it was not // already processed if (tEntry.getName() == null) { boolean processed = false; // true if the java name is already determined // Get the QName of the ref'd TypeEntry, which // is will be used to javify the name QName typeQName = tEntry.getQName(); // In case of <xsd:list itemType="...">, // set typeQName to the value of the itemType attribute. QName itemType = SchemaUtils.getListItemType(tEntry.getNode()); if (itemType != null) { // Get the typeEntry so we know the absolute base type TypeEntry itemEntry = symbolTable.getTypeEntry(itemType, false); // TODO - If the itemEntry is not found, we need to throw // an exception. "Item is referenced, but not defined" javifyTypeEntryName(symbolTable, itemEntry, anonQNames, uniqueNum); // Grab the referenced type, If it's there. TypeEntry refedEntry = itemEntry.getRefType(); QName baseName = refedEntry == null ? itemEntry.getQName() : refedEntry.getQName(); typeQName = new QName(baseName.getNamespaceURI(), baseName.getLocalPart() + "[]"); } if (emitter.isDeploy()) { Class class1 = (Class) emitter.getQName2ClassMap().get(typeQName); if (class1 != null && !class1.isArray()) { tEntry.setName(getJavaClassName(class1)); processed = true; } } if (!processed) { if ((typeQName.getLocalPart().indexOf(SymbolTable.ANON_TOKEN) < 0)) { // Normal Case: The ref'd type is not anonymous // Simply construct the java name from // the qName tEntry.setName(emitter.getJavaName(typeQName)); } else { // This is an anonymous type name. // Axis uses '>' as a nesting token to generate // unique qnames for anonymous types. // Only consider the localName after the last '>' // when generating the java name // String localName = typeQName.getLocalPart(); // localName = // localName.substring( // localName.lastIndexOf( // SymbolTable.ANON_TOKEN)+1); // typeQName = new QName(typeQName.getNamespaceURI(), // localName); String localName = typeQName.getLocalPart(); // Check to see if this is an anonymous type, // if it is, replace Axis' ANON_TOKEN with // an underscore to make sure we don't run // into name collisions with similarly named // non-anonymous types StringBuffer sb = new StringBuffer(localName); int aidx; while ((aidx = sb.toString().indexOf(SymbolTable.ANON_TOKEN)) > -1) { sb.replace(aidx, aidx + SymbolTable.ANON_TOKEN.length(), ""); char c = sb.charAt(aidx); if (Character.isLetter(c) && Character.isLowerCase(c)) { sb.setCharAt(aidx, Character.toUpperCase(c)); } } localName = sb.toString(); typeQName = new QName(typeQName.getNamespaceURI(), localName); if (emitter.isTypeCollisionProtection() && !emitter.getNamespaceExcludes() .contains(new NamespaceSelector(typeQName.getNamespaceURI()))) { // If there is already an existing type, // there will be a collision. // If there is an existing anon type, // there will be a collision. // In both cases, mangle the name. if (symbolTable.getType(typeQName) != null || anonQNames.get(typeQName) != null) { localName += "Type" + uniqueNum++; typeQName = new QName(typeQName.getNamespaceURI(), localName); } anonQNames.put(typeQName, typeQName); } // Now set the name with the constructed qname tEntry.setName(emitter.getJavaName(typeQName)); } } // if (!processed) Vector elements = tEntry.getContainedElements(); if (elements != null) { for (int i = 0; i < elements.size(); i++) { ElementDecl elem = (ElementDecl) elements.get(i); String varName = emitter.getJavaVariableName(typeQName, elem.getQName(), true); elem.setName(varName); } } Vector attributes = tEntry.getContainedAttributes(); if (attributes != null) { for (int i = 0; i < attributes.size(); i++) { ContainedAttribute attr = (ContainedAttribute) attributes.get(i); String varName = emitter.getJavaVariableName(typeQName, attr.getQName(), false); attr.setName(varName); } } } // Set the entry with the same name as the ref'd entry // but add the appropriate amount of dimensions entry.setName(tEntry.getName() + dims); return uniqueNum; }
From source file:com.prasanna.android.stacknetwork.utils.MarkdownFormatter.java
/** * Format HTML text to fit into one or more vertically aligned text views. * Parses the given text and removes {@code <code> </code>} tags. If the code * text is of multiple lines a new {@link android.widget.TextView TextView} is * created and added to the view container else the code text is added to * already created {@link android.widget.TextView TextView}. * // w w w .j a v a2 s .c om * @param context * @param markdownText * @return */ public static ArrayList<View> parse(Context context, String markdownText) { if (context != null && markdownText != null) { ArrayList<View> views = new ArrayList<View>(); try { markdownText = clean(markdownText); XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance(); XmlPullParser xmlPullParser = xmlPullParserFactory.newPullParser(); xmlPullParser.setInput(new StringReader(markdownText)); int eventType = xmlPullParser.getEventType(); StringBuffer buffer = new StringBuffer(); StringBuffer code = new StringBuffer(); boolean codeFound = false; boolean oneLineCode = false; LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_DOCUMENT) { } else if (eventType == XmlPullParser.START_TAG) { if (xmlPullParser.getName().equals(Tags.CODE)) codeFound = true; else if (xmlPullParser.getName().equals(Tags.IMG)) { addSimpleTextToView(context, views, buffer, params); String attributeValue = xmlPullParser.getAttributeValue(null, Attributes.SRC); addImgLinkText(context, views, attributeValue, params); } else { buffer.append("<" + xmlPullParser.getName()); for (int i = 0; i < xmlPullParser.getAttributeCount(); i++) { buffer.append(" " + xmlPullParser.getAttributeName(i) + "=\"" + xmlPullParser.getAttributeValue(i) + "\""); } buffer.append(">"); } } else if (eventType == XmlPullParser.END_TAG) { if (xmlPullParser.getName().equals(Tags.CODE)) { codeFound = false; if (oneLineCode) oneLineCode = false; else { addSimpleTextToView(context, views, buffer, params); views.add(getTextViewForCode(context, code.toString())); code.delete(0, code.length()); } } else if (xmlPullParser.getName().equals(Tags.IMG)) { LogWrapper.v(TAG, "Ignore img tag"); } else { buffer.append("</" + xmlPullParser.getName() + ">"); } } else if (eventType == XmlPullParser.TEXT) { String text = xmlPullParser.getText(); if (codeFound) { if (!text.contains(NEW_LINE)) { if (buffer.length() > 0 && buffer.lastIndexOf(NEW_LINE) == buffer.length() - 1) buffer.setCharAt(buffer.length() - 1, ' '); buffer.append(text); oneLineCode = true; } else { code.append(text); } } else { text = text.replace(NEW_LINE, " ").replace(CR, " "); buffer.append(text); } } eventType = xmlPullParser.next(); } addSimpleTextToView(context, views, buffer, params); } catch (XmlPullParserException e) { LogWrapper.e(TAG, "Error parsing: " + e); } catch (IOException e) { LogWrapper.e(TAG, "Error parsing: " + e); } return views; } return null; }