List of usage examples for java.lang StringBuffer delete
@Override public synchronized StringBuffer delete(int start, int end)
From source file:com.sun.socialsite.util.Utilities.java
/** * Need need to get rid of any user-visible HTML tags once all text has been * removed such as <BR>. This sounds like a better approach than removing * all HTML tags and taking the chance to leave some tags un-closed. * * WARNING: this method has serious performance problems a * * @author Alexis Moussine-Pouchkine (alexis.moussine-pouchkine@france.sun.com) * @author Lance Lavandowska// w w w.j a v a2 s.c o m * @param str the String object to modify * @return the new String object without the HTML "visible" tags */ private static String removeVisibleHTMLTags(String str) { str = stripLineBreaks(str); StringBuffer result = new StringBuffer(str); StringBuffer lcresult = new StringBuffer(str.toLowerCase()); // <img should take care of smileys String[] visibleTags = { "<img" }; // are there others to add? int stringIndex; for (int j = 0; j < visibleTags.length; j++) { while ((stringIndex = lcresult.indexOf(visibleTags[j])) != -1) { if (visibleTags[j].endsWith(">")) { result.delete(stringIndex, stringIndex + visibleTags[j].length()); lcresult.delete(stringIndex, stringIndex + visibleTags[j].length()); } else { // need to delete everything up until next closing '>', for <img for instance int endIndex = result.indexOf(">", stringIndex); if (endIndex > -1) { // only delete it if we find the end! If we don't the HTML may be messed up, but we // can't safely delete anything. result.delete(stringIndex, endIndex + 1); lcresult.delete(stringIndex, endIndex + 1); } } } } // TODO: This code is buggy by nature. It doesn't deal with nesting of tags properly. // remove certain elements with open & close tags String[] openCloseTags = { "li", "a", "div", "h1", "h2", "h3", "h4" }; // more ? for (int j = 0; j < openCloseTags.length; j++) { // could this be better done with a regular expression? String closeTag = "</" + openCloseTags[j] + ">"; int lastStringIndex = 0; while ((stringIndex = lcresult.indexOf("<" + openCloseTags[j], lastStringIndex)) > -1) { lastStringIndex = stringIndex; // Try to find the matching closing tag (ignores possible nesting!) int endIndex = lcresult.indexOf(closeTag, stringIndex); if (endIndex > -1) { // If we found it delete it. result.delete(stringIndex, endIndex + closeTag.length()); lcresult.delete(stringIndex, endIndex + closeTag.length()); } else { // Try to see if it is a self-closed empty content tag, i.e. closed with />. endIndex = lcresult.indexOf(">", stringIndex); int nextStart = lcresult.indexOf("<", stringIndex + 1); if (endIndex > stringIndex && lcresult.charAt(endIndex - 1) == '/' && (endIndex < nextStart || nextStart == -1)) { // Looks like it, so remove it. result.delete(stringIndex, endIndex + 1); lcresult.delete(stringIndex, endIndex + 1); } } } } return result.toString(); }
From source file:org.wso2.carbon.registry.samples.reporting.ServiceReportGenerator.java
public ByteArrayOutputStream execute(String template, String type) throws IOException { try {//from w w w . ja v a 2 s . c o m Registry registry = getRegistry(); Registry gov = GovernanceUtils.getGovernanceUserRegistry(registry, "admin"); if (registry == null) { throw new RuntimeException("Registry is null"); } if (!registry.resourceExists(template)) { throw new FileNotFoundException("Template is not found"); } // Read Template String templateContent = RegistryUtils.decodeBytes((byte[]) registry.get(template).getContent()); //Read html file if (HTML.equalsIgnoreCase(type)) { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(templateContent))); //Find images and embed them NodeList nodes = doc.getElementsByTagName(IMAGE); for (int i = 0; i < nodes.getLength(); i++) { Node image = nodes.item(i); NodeList list = image.getChildNodes(); for (int j = 0; j != list.getLength(); ++j) { Node child = list.item(j); if (IMAGE_EXPRESSION.equals(child.getNodeName()) && child.getTextContent() != null) { String imgUrlStr = child.getTextContent().trim().replaceAll("^\"|\"$", ""); //Get image extension String imageExtension = imgUrlStr.substring(imgUrlStr.lastIndexOf(".") + 1); byte[] imageBytes = convertInputStream(imgUrlStr); Element imgExp = doc.createElement(IMAGE_EXPRESSION); String strBuilder = "\"data:image/" + imageExtension + ";base64," + new String(Base64.encodeBase64(imageBytes)) + "\""; imgExp.appendChild(doc.createCDATASection(strBuilder)); imgExp.setAttribute(CLASS, String.class.getName()); image.replaceChild(imgExp, child); } } } Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(doc); StringWriter outWriter = new StringWriter(); StreamResult result = new StreamResult(outWriter); transformer.transform(source, result); StringBuffer stringBuffer = outWriter.getBuffer(); templateContent = stringBuffer.toString(); stringBuffer.delete(0, stringBuffer.length()); } GovernanceUtils.loadGovernanceArtifacts((UserRegistry) gov); // Create Report Bean Collection GenericArtifactManager genericArtifactManager = new GenericArtifactManager(gov, "restservice"); List<ReportBean> beanList = new LinkedList<ReportBean>(); for (GenericArtifact genericArtifact : genericArtifactManager.getAllGenericArtifacts()) { beanList.add(new ReportBean(genericArtifact.getAttribute("overview_name"), genericArtifact.getAttribute("overview_version"), genericArtifact.getAttribute("overview_description"))); } // Return Report Stream as a ByteArrayOutputStream return new ReportStream().getReportStream(new JasperPrintProvider().createJasperPrint( new JRBeanCollectionDataSource(beanList), templateContent, new ReportParamMap[0]), type); } catch (RuntimeException e) { throw new IOException("Failed to get input stream", e); } catch (RegistryException e) { throw new IOException("Failed to find report template", e); } catch (TransformerException e) { throw new IOException("Failed to transform file", e); } catch (JRException e) { throw new IOException("Failed to create jasperprint", e); } catch (ReportingException e) { throw new IOException("Failed to create jasperprint", e); } catch (ParserConfigurationException e) { throw new IOException("Failed to create DocumentBuilder", e); } catch (SAXException e) { throw new IOException("Failed to parse inputSource", e); } }
From source file:de.unidue.inf.is.ezdl.dlbackend.misc.TemplateParser.java
private StringBuffer replace(StringBuffer stringbuffer, String s, String s1) { StringBuffer sb = new StringBuffer(stringbuffer.toString()); if (stringbuffer.length() < 1 || s.length() < 1) { return sb; }/*from ww w.j a va 2 s . c om*/ int i; int j = 0; while ((i = sb.toString().indexOf(s, j)) != -1) { sb = sb.delete(i, i + s.length()); sb = sb.insert(i, s1); j = i + s1.length(); } return sb; }
From source file:org.openmrs.web.servlet.LoginServlet.java
/** * Convenience method for pulling the correct page to redirect to out of the request * * @param request the current request// w w w .j ava 2 s. c om * @return the page to redirect to as determined by parameters in the request */ private String determineRedirect(HttpServletRequest request) { // first option for redirecting is the "redirect" parameter (set on login.jsp from the session attr) String redirect = request.getParameter("redirect"); // second option for redirecting is the referrer parameter set at login.jsp if (redirect == null || "".equals(redirect)) { redirect = request.getParameter("refererURL"); if (redirect != null && !redirect.startsWith("/")) { // if we have an absolute url, make sure its in our domain Integer requestURLLength = request.getRequestURL().length(); StringBuffer domainAndPort = request.getRequestURL(); domainAndPort.delete(requestURLLength - request.getRequestURI().length(), requestURLLength); if (!redirect.startsWith(domainAndPort.toString())) { redirect = null; // send them to the homepage } else { // now cut out everything but the path // get the first slash after https:// or http:// redirect = redirect.substring(redirect.indexOf("/", 9)); } } } // third option for redirecting is the main page of the webapp if (StringUtils.isEmpty(redirect)) { redirect = request.getContextPath(); } // don't redirect back to the login page on success. (I assume the login page is {something}login.{something} else if (redirect.contains("login.")) { log.debug("Redirect contains 'login.', redirecting to main page"); redirect = request.getContextPath(); } // don't redirect to pages outside of openmrs else if (!redirect.startsWith(request.getContextPath())) { log.debug("redirect is outside of openmrs, redirecting to main page"); redirect = request.getContextPath(); } // don't redirect back to the initialsetup page else if (redirect.endsWith(WebConstants.SETUP_PAGE_URL)) { log.debug("redirect is back to the setup page because this is their first ever login"); redirect = request.getContextPath(); } else if (redirect.contains("/options.form") || redirect.contains("/changePassword.form") || redirect.contains("/forgotPassword.form")) { log.debug( "The user was on a page for setting/changing passwords. Send them to the homepage to reduce confusion"); redirect = request.getContextPath(); } log.debug("Going to use redirect: '" + redirect + "'"); return redirect; }
From source file:com.callidusrobotics.ui.MessageBox.java
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public void addLine(final String string, final Color foreground, final Color background, final boolean preformatted) { final List<String> tokens = getMessageTokens(string, preformatted); final StringBuffer stringBuffer = new StringBuffer(lineLength); // Append the string token-by-token, line-by-line to the end of the messagebuffer while (!tokens.isEmpty()) { stringBuffer.delete(0, stringBuffer.length()); stringBuffer.append(tokens.remove(0)); // The first word to be printed on the line is too long and needs to be hyphenated if (stringBuffer.length() > lineLength) { tokens.add(0, stringBuffer.substring(lineLength - 1, stringBuffer.length())); stringBuffer.delete(lineLength - 1, stringBuffer.length()); stringBuffer.append('-'); }/*from w ww . ja v a 2 s .co m*/ // Continue to append tokens to the linebuffer one-by-one and append enough whitespace to fill the buffer while (stringBuffer.length() < lineLength) { stringBuffer.append(' '); final boolean tokenWillFit = !tokens.isEmpty() && stringBuffer.length() + tokens.get(0).length() <= lineLength; if (!preformatted && tokenWillFit) { stringBuffer.append(tokens.remove(0)); } } lineBuffer.add(new BufferLine(stringBuffer.toString(), foreground, background)); // Delete the oldest message line if (lineBuffer.size() > maxLines) { lineBuffer.remove(0); } } }
From source file:org.exoplatform.wiki.rendering.internal.parser.confluence.ConfluenceLinkReferenceParser.java
private String divideAfter(StringBuffer buffer, int index) { if (index < 0) { return null; }/*from w w w. j av a 2s.c om*/ if (index == buffer.length() - 1) { buffer.deleteCharAt(buffer.length() - 1); return null; } String body = buffer.substring(index + 1); buffer.delete(index, buffer.length()); return body; }
From source file:org.kalypso.optimize.SceIOHandler.java
private String[] getLines(final StringBuffer buffer) { final String out = buffer.toString(); final int lastBR = out.lastIndexOf('\n'); if (lastBR > -1) { buffer.delete(0, lastBR); final String linesComplete = out.substring(0, lastBR); if (linesComplete.length() > 0) { return linesComplete.split("\n"); }// w ww .ja va 2 s. c o m } return new String[0]; }
From source file:com.flexive.core.search.genericSQL.GenericSQLForeignTableSelector.java
/** * {@inheritDoc}/*from w w w . j ava 2s. co m*/ */ @Override public void apply(Property prop, PropertyEntry entry, StringBuffer statement) throws FxSqlSearchException { if (hasTranslationTable && translatedColumn.equalsIgnoreCase(prop.getField())) { // select label from translation table statement.delete(0, statement.length()); final long lang = FxContext.getUserTicket().getLanguage().getId(); DBStorage storage = StorageManager.getStorageImpl(); statement.append(("COALESCE(\n" + getLabelSelect() + "lang=" + lang + storage.getLimit(true, 1) + ") ,\n" + getLabelSelect() + "deflang=" + storage.getBooleanTrueExpression() + " " + storage.getLimit(true, 1) + ") \n" + ")")); entry.overrideDataType(FxDataType.String1024); return; } FxDataType type = columns.get(prop.getField().toUpperCase()); if (type == null) { // This field does not exist throw new FxSqlSearchException(LOG, "ex.sqlSearch.query.undefinedField", prop.getField(), prop.getPropertyName(), getAllowedFields()); } else { statement.insert(0, "(SELECT " + prop.getField() + " FROM " + tableName + " WHERE " + linksOn + "=") .append(")"); entry.overrideDataType(type); } }
From source file:hydrograph.ui.expression.editor.datastructure.MethodDetails.java
private void createPlaceHolderFromSource(IMethod iMethod, String className) throws JavaModelException { StringBuffer buffer = new StringBuffer(iMethod.getSource()); int indexOfPlaceHolder = buffer.lastIndexOf("@see"); if (indexOfPlaceHolder != -1 && iMethod.getParameterNames() != null && iMethod.getParameterNames().length > 0) { buffer = buffer.delete(0, indexOfPlaceHolder + 4); buffer = buffer.delete(buffer.indexOf("\n") + 1, buffer.capacity()); if (StringUtils.contains(buffer.toString(), className + Constants.DOT + iMethod.getElementName())) { placeHolder = StringUtils.trim(buffer.toString()); } else//from w w w . ja v a 2 s . com placeHolder = createDefaultPlaceHolder(iMethod, className); } else { placeHolder = createDefaultPlaceHolder(iMethod, className); } }
From source file:de.rrze.idmone.utils.jpwgen.PwGenerator.java
/** * The real password generation is performed in this method * /*from w w w.ja v a 2 s.c o m*/ * @param size * the length of the password * @param pw_flags * the settings for the password * @return the newly created password */ private synchronized static String phonemes(int size, int pw_flags, Random random) { int c, i, len, flags, feature_flags; int prev, should_be; boolean first; String str; char ch; StringBuffer buf = new StringBuffer(); do { buf.delete(0, buf.length()); feature_flags = pw_flags; c = 0; prev = 0; should_be = 0; first = true; should_be = random.nextBoolean() ? VOWEL : CONSONANT; while (c < size) { i = random.nextInt(PW_ELEMENTS.length); str = PW_ELEMENTS[i].getValue(); len = str.length(); flags = PW_ELEMENTS[i].getType(); /* Filter on the basic type of the next element */ if ((flags & should_be) == 0) { continue; } /* Handle the NOT_FIRST flag */ if (first && ((flags & NOT_FIRST) != 0)) continue; /* Don't allow VOWEL followed a Vowel/Dipthong pair */ if (((prev & VOWEL) != 0) && ((flags & VOWEL) != 0) && ((flags & DIPTHONG) != 0)) continue; /* Don't allow us to overflow the buffer */ if (len > size - c) continue; /* * OK, we found an element which matches our criteria, let's do * it! */ buf.append(str); c += len; /* Handle the AMBIGUOUS flag */ if ((pw_flags & PW_AMBIGUOUS) != 0) { int k = -1; for (int j = 0; j < PW_AMBIGUOUS_SYMBOLS.length(); j++) { k = buf.indexOf(String.valueOf(PW_AMBIGUOUS_SYMBOLS.charAt(j))); if (k != -1) break; } if (k != -1) { buf.delete(k, buf.length()); c = buf.length(); } } /* Time to stop? */ if (c >= size) { // System.out.println("BREAK 1: "+c + " - "+size); break; } /* * Handle PW_DIGITS */ if ((pw_flags & PW_DIGITS) != 0) { if (!first && (random.nextInt(10) < 3)) { do { ch = (new Integer(random.nextInt(10))).toString().charAt(0); } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1)); c++; buf = buf.append(ch); feature_flags &= ~PW_DIGITS; first = true; prev = 0; should_be = random.nextBoolean() ? VOWEL : CONSONANT; continue; } } /* Handle PW_SYMBOLS */ if ((pw_flags & PW_SYMBOLS) != 0) { if (!first && (random.nextInt(10) < 2)) { do { ch = PW_SPECIAL_SYMBOLS.charAt(random.nextInt(PW_SPECIAL_SYMBOLS.length())); } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1)); c++; buf = buf.append(ch); feature_flags &= ~PW_SYMBOLS; } } else if ((pw_flags & PW_SYMBOLS_REDUCED) != 0) { if (!first && (random.nextInt(10) < 2)) { do { ch = PW_SPECIAL_SYMBOLS_REDUCED .charAt(random.nextInt(PW_SPECIAL_SYMBOLS_REDUCED.length())); } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1)); c++; buf = buf.append(ch); feature_flags &= ~PW_SYMBOLS_REDUCED; } } /* Handle PW_UPPERS */ if ((pw_flags & PW_UPPERS) != 0) { if ((first || ((flags & CONSONANT) != 0)) && (random.nextInt(10) < 2)) { int lastChar = buf.length() - 1; buf.setCharAt(lastChar, Character.toUpperCase(buf.charAt(lastChar))); feature_flags &= ~PW_UPPERS; } } /* * OK, figure out what the next element should be */ if (should_be == CONSONANT) { should_be = VOWEL; } else { /* should_be == VOWEL */ if (((prev & VOWEL) != 0) || ((flags & DIPTHONG) != 0) || (random.nextInt(10) > 3)) should_be = CONSONANT; else should_be = VOWEL; } prev = flags; first = false; } } while ((feature_flags & (PW_UPPERS | PW_DIGITS | PW_SYMBOLS | PW_SYMBOLS_REDUCED)) != 0); return buf.toString(); }