List of usage examples for java.lang StringBuffer substring
@Override public synchronized String substring(int start, int end)
From source file:org.jboss.dashboard.commons.text.StringUtil.java
/** * @param template the parametrized template * @param params the parameters structure * @param leftMark the left delimiter of the parameters to replace * @param rightMark the right delimiter of the parameters to replace * @param nullifyNotFound if true, change the not found params to "null"; * if false, don't change * @return The template with parameters replaced * @see #parseASCIITemplate(String,Map)// www .ja va2 s. c o m */ public static String parseASCIITemplate(String template, Map params, String leftMark, String rightMark, boolean nullifyNotFound) { if (params == null) { if (!nullifyNotFound) { return template; } else { // Como hay que cambiar los parmetros por "null", creamos una // tabla de parmetros vaca params = new HashMap(); } } StringBuffer buffer = new StringBuffer(template); int leftIndex, rightIndex = 0; while ((leftIndex = indexOf(leftMark, rightIndex, buffer)) != -1) { rightIndex = indexOf(rightMark, leftIndex + leftMark.length(), buffer); if (rightIndex == -1) { break; // no right mark, this is likely to mean bad syntax } String param = buffer.substring(leftIndex + leftMark.length(), rightIndex); rightIndex += rightMark.length(); if (params.containsKey(param)) { Object ref = params.get(param); String value = ref == null ? "null" : ref.toString(); buffer.replace(leftIndex, rightIndex, value); rightIndex -= leftMark.length() + param.length() + rightMark.length(); rightIndex += value.length(); } else if (nullifyNotFound) { String value = "null"; buffer.replace(leftIndex, rightIndex, value); rightIndex -= leftMark.length() + param.length() + rightMark.length(); rightIndex += value.length(); } } return buffer.toString(); }
From source file:org.pssframework.xsqlbuilder.XsqlBuilder.java
private List getKeys(StringBuffer xsql, int start, int end, String keyPrifix, String keySuffix) { List results = new ArrayList(); int keyStart = start; int keyEnd = keyStart; while (true) { //get keyStart keyStart = xsql.indexOf(keyPrifix, keyStart); if (keyStart > end || keyStart < 0) { break; }//from w w w. j ava 2 s . c o m //get keyEnd keyEnd = xsql.indexOf(keySuffix, keyStart + 1); if (keyEnd > end || keyEnd < 0) { break; } //get key string String key = xsql.substring(keyStart + 1, keyEnd); results.add(key); keyStart = keyEnd + 1; } return results; }
From source file:org.latticesoft.util.common.StringUtil.java
/** * Formats a map into string/* w w w . j a va2 s . c o m*/ * @param map the map to be formatted * @param separator the separator to separate the elements * @param enclosing to include the enclosing braces or not * @return the formatted string */ public static String formatMap(Map map, String separator, boolean enclosing) { StringBuffer sb = new StringBuffer(); if (map == null || separator == null) { return null; } Iterator iter = map.keySet().iterator(); if (enclosing) { sb.append("{"); } while (iter.hasNext()) { Object key = iter.next(); Object value = map.get(key); if (key != null) { sb.append(key).append("="); if (value != null) { sb.append(value); } sb.append(separator); } } int len = separator.length(); if (sb.length() > len) { int startIndex = sb.length() - len; int endIndex = sb.length(); String s = sb.substring(startIndex, endIndex); if (s.equals(separator)) { for (int i = 0; i < len; i++) { sb.deleteCharAt(sb.length() - 1); } } } if (enclosing) { sb.append("}"); } return sb.toString(); }
From source file:org.apache.nutch.protocol.htmlunit.HttpResponse.java
private void processHeaderLine(StringBuffer line) throws IOException, HttpException { int colonIndex = line.indexOf(":"); // key is up to colon if (colonIndex == -1) { int i;// ww w.j ava2 s. c o m for (i = 0; i < line.length(); i++) if (!Character.isWhitespace(line.charAt(i))) break; if (i == line.length()) return; throw new HttpException("No colon in header:" + line); } String key = line.substring(0, colonIndex); int valueStart = colonIndex + 1; // skip whitespace while (valueStart < line.length()) { int c = line.charAt(valueStart); if (c != ' ' && c != '\t') break; valueStart++; } String value = line.substring(valueStart); headers.set(key, value); }
From source file:org.sakaiproject.component.app.roster.RosterManagerImpl.java
private List<Participant> buildParticipantList(Map<String, UserRole> userMap, Map<String, Profile> profilesMap) { List<Participant> participants = new ArrayList<Participant>(); Site site = null;/*from ww w .jav a2s . c o m*/ try { site = siteService().getSite(getSiteId()); } catch (IdUnusedException e) { log.error("getGroupsWithMember: " + e.getMessage(), e); return participants; } Collection<Group> groups = site.getGroups(); for (Iterator<Entry<String, Profile>> iter = profilesMap.entrySet().iterator(); iter.hasNext();) { Entry<String, Profile> entry = iter.next(); String userId = entry.getKey(); Profile profile = entry.getValue(); UserRole userRole = userMap.get(userId); // Profiles may exist for users that have been removed. If there's a profile // for a missing user, skip the profile. See SAK-10936 if (userRole == null || userRole.user == null) { log.warn("A profile exists for non-existent user " + userId); continue; } String groupsString = ""; StringBuffer sb = new StringBuffer(); for (Group group : groups) { Member member = group.getMember(userId); if (member != null) { sb.append(group.getTitle() + ", "); } } if (sb.length() > 0) { int endIndex = sb.lastIndexOf(", "); if (endIndex > 0) { groupsString = sb.substring(0, endIndex); } else { groupsString = sb.toString(); } } participants.add(new ParticipantImpl(userRole.user, profile, userRole.role, groupsString)); } return participants; }
From source file:net.mlw.vlh.adapter.jdbc.util.ConfigurableStatementBuilder.java
/** * @see net.mlw.vlh.adapter.jdbc.util.StatementBuilder#generate(java.sql.Connection, java.lang.StringBuffer, java.util.Map, boolean) *///from w w w . j av a 2s. com public PreparedStatement generate(Connection conn, StringBuffer query, Map whereClause, boolean scrollable) throws SQLException, ParseException { if (!init) { init(); } if (whereClause == null) { whereClause = Collections.EMPTY_MAP; } for (Iterator iter = textManipulators.iterator(); iter.hasNext();) { TextManipulator manipulator = (TextManipulator) iter.next(); manipulator.manipulate(query, whereClause); } LinkedList arguments = new LinkedList(); // Replace any "{key}" with the value in the whereClause Map, // then placing the value in the partameters list. for (int i = 0, end = 0, start; ((start = query.toString().indexOf('{', end)) >= 0); i++) { end = query.toString().indexOf('}', start); String key = query.substring(start + 1, end); Object value = whereClause.get(key); if (value == null) { throw new NullPointerException("Property '" + key + "' was not provided."); } arguments.add(new NamedPair(key, value)); Setter setter = getSetter(key); query.replace(start, end + 1, setter.getReplacementString(value)); end -= (key.length() + 2); } PreparedStatement statement = null; if (scrollable) { statement = conn.prepareStatement(query.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } else { statement = conn.prepareStatement(query.toString()); } int index = 1; // Now set all the patameters on the statement. for (Iterator iter = arguments.iterator(); iter.hasNext();) { NamedPair namedPair = (NamedPair) iter.next(); Setter setter = getSetter(namedPair.getName()); try { index = setter.set(statement, index, namedPair.getValue()); } catch (RuntimeException e) { String message = "Cannot set value of " + namedPair.getName() + " (setter = " + setter + ")"; LOGGER.error(message, e); throw new RuntimeException(message, e); } } return statement; }
From source file:org.etudes.ambrosia.impl.UiPropertyReference.java
/** * Write the value for FileItem (commons file upload) values. * /* w ww.ja v a 2 s .co m*/ * @param entity * The entity to write to. * @param property * The property to set. * @param value * The value to write. */ protected void setFileValue(Object entity, String property, FileItem value) { // form a "setFoo()" based setter method name StringBuffer setter = new StringBuffer("set" + property); setter.setCharAt(3, setter.substring(3, 4).toUpperCase().charAt(0)); try { // use this form, providing the setter name and no getter, so we can support properties that are write-only PropertyDescriptor pd = new PropertyDescriptor(property, entity.getClass(), null, setter.toString()); Method write = pd.getWriteMethod(); Object[] params = new Object[1]; Class[] paramTypes = write.getParameterTypes(); if ((paramTypes != null) && (paramTypes.length == 1)) { // single value boolean if (paramTypes[0] != FileItem.class) { M_log.warn( "setFileValue: target not expecting FileItem: " + entity.getClass() + " " + property); return; } params[0] = value; write.invoke(entity, params); } else { M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass() + " : no one parameter setter method defined"); } } catch (IntrospectionException ie) { M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass() + " : " + ie); } catch (IllegalAccessException ie) { M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass() + " :" + ie); } catch (IllegalArgumentException ie) { M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass() + " :" + ie); } catch (InvocationTargetException ie) { M_log.warn("setFileValue: method: " + property + " object: " + entity.getClass() + " :" + ie); } }
From source file:org.openadaptor.auxil.convertor.delimited.AbstractDelimitedStringConvertor.java
/** * Splits a string using a literal string delimiter. Does not preserve blocks of characters * between quoteChars./* w ww . ja v a 2 s.c o m*/ * * @param delimitedString * @param delimiter * @return extracted tokens resulting from split operation. */ protected String[] extractValuesLiteralString(String delimitedString, String delimiter) { char[] chars = delimitedString.toCharArray(); List strings = new ArrayList(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < chars.length; i++) { buffer.append(chars[i]); if (buffer.toString().endsWith(delimiter)) { strings.add(buffer.substring(0, buffer.length() - delimiter.length())); buffer.setLength(0); } } strings.add(buffer.toString()); return (String[]) strings.toArray(new String[strings.size()]); }
From source file:ctrus.pa.bow.java.JavaFileTokenizer.java
@SuppressWarnings("unchecked") public void tokenize(List<String> sourceTextLines) { // initialize if not done earlier if (!_init)/*from www. j a va 2 s. c o m*/ _init(); // Processing a new file, reset tokens _classTokens.clear(); _positionObserver = new IdentifiersPosition(); // Normalize single line comments to block comments StringBuffer sourceText = _preProcessSourceText(sourceTextLines); // Extract all identifiers from java source text _javaParser.setSource(sourceText.toString().toCharArray()); _cu = (CompilationUnit) _javaParser.createAST(null); _cu.accept(this); // Extract all comments from java source text // and merge them with their corresponding identifiers if (!_ignoreComments && !_stateAnalysis) { // Extract List<Comment> comments = (List<Comment>) _cu.getCommentList(); for (Comment comment : comments) { int start = comment.getStartPosition(); int end = start + comment.getLength(); String identifierOfComment = _positionObserver.getIdentifierForPosition(start, end); String commentText = sourceText.substring(start, end).replaceAll("[\\t\\n\\r]", " "); // Do filtering of comments if (!_considerCopyright) { if (commentText.toLowerCase().contains("copyright") || commentText.toLowerCase().contains("license")) continue; } // More filtering rules...TBD IdentifierTokens it = getTokens(identifierOfComment); it.addCommentToken(commentText); } } // Add package information if (!_stateAnalysis) { for (ClassTokens c : _classTokens) c.addToken(_packageName); } }
From source file:org.etudes.ambrosia.impl.UiPropertyReference.java
/** * Read the configured selector value from the entity. * /*from w w w .jav a2s.c o m*/ * @param context * The context. * @param entity * The entity to read from. * @param selector * The selector name. * @return The selector value object found, or null if not. */ protected Object getValue(Context context, Object entity, String property) { // if no selector named, just use the entity if (property == null) return entity; // if the property is an index reference if (property.startsWith("[") && property.endsWith("]")) { return getIndexValue(entity, decode(property.substring(1, property.length() - 1))); } // another form of index, taking the index value from the nested references if (property.startsWith("{") && property.endsWith("}")) { try { String propertiesIndex = property.substring(1, property.length() - 1); int i = Integer.parseInt(propertiesIndex); PropertyReference ref = this.properties.get(i); String index = ref.read(context, entity); return getIndexValue(entity, index); } catch (NumberFormatException e) { } catch (IndexOutOfBoundsException e) { } } // form a "getFoo()" based getter method name StringBuffer getter = new StringBuffer("get" + property); getter.setCharAt(3, getter.substring(3, 4).toUpperCase().charAt(0)); try { // use this form, providing the getter name and no setter, so we can support properties that are read-only PropertyDescriptor pd = new PropertyDescriptor(property, entity.getClass(), getter.toString(), null); Method read = pd.getReadMethod(); Object value = read.invoke(entity, (Object[]) null); return value; } catch (IntrospectionException ie) { M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie); return null; } catch (IllegalAccessException ie) { M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie); return null; } catch (IllegalArgumentException ie) { M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie); return null; } catch (InvocationTargetException ie) { M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie); return null; } }