/** * This is for debug only: print out training matrices in a CSV type format so that the matrices * can be examined in a spreadsheet program for debugging purposes. */ private void WriteCSVfile( List<String> rowNames, List<String> colNames, float[][] buf, String fileName) { p("tagList.size()=" + tagList.size()); try { FileWriter fw = new FileWriter(fileName + ".txt"); PrintWriter bw = new PrintWriter(new BufferedWriter(fw)); // write the first title row: StringBuffer sb = new StringBuffer(500); for (int i = 0, size = colNames.size(); i < size; i++) { sb.append("," + colNames.get(i)); } bw.println(sb.toString()); // loop on remaining rows: for (int i = 0, size = buf.length; i < size; i++) { sb.delete(0, sb.length()); sb.append(rowNames.get(i)); for (int j = 0, size2 = buf[i].length; j < size2; j++) { sb.append("," + buf[i][j]); } bw.println(sb.toString()); } bw.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
private void traverseToLeaves( final PackageDependenciesNode treeNode, final StringBuffer denyRules, final StringBuffer allowRules) { final Enumeration enumeration = treeNode.breadthFirstEnumeration(); while (enumeration.hasMoreElements()) { PsiElement childPsiElement = ((PackageDependenciesNode) enumeration.nextElement()).getPsiElement(); if (myIllegalDependencies.containsKey(childPsiElement)) { final Map<DependencyRule, Set<PsiFile>> illegalDeps = myIllegalDependencies.get(childPsiElement); for (final DependencyRule rule : illegalDeps.keySet()) { if (rule.isDenyRule()) { if (denyRules.indexOf(rule.getDisplayText()) == -1) { denyRules.append(rule.getDisplayText()); denyRules.append("\n"); } } else { if (allowRules.indexOf(rule.getDisplayText()) == -1) { allowRules.append(rule.getDisplayText()); allowRules.append("\n"); } } } } } }
/** * create a 1-d String array from a network, for easy transmission to R. triples (source, * edgeType, target) are filled in to an array of length 3 * # of interactions * * @param network a gaggle network * @return the edge attributes of the network as a string array */ protected String[] networkEdgeAttributesToStringArray(Network network) { Interaction[] interactions = network.getInteractions(); String source, target, type; String[] attributeNames = network.getEdgeAttributeNames(); ArrayList<String> list = new ArrayList<String>(); for (Interaction interaction : interactions) { source = interaction.getSource(); type = interaction.getType(); target = interaction.getTarget(); String edgeName = source + " (" + type + ") " + target; String terseEdgeName = source + "::" + target + "::" + type; for (String name : attributeNames) { HashMap hash = network.getEdgeAttributes(name); if (hash.containsKey(edgeName)) { Object value = hash.get(edgeName); StringBuffer sb = new StringBuffer(); sb.append(terseEdgeName); sb.append("::"); sb.append(name); sb.append("::"); sb.append(value.toString()); list.add(sb.toString()); } else { System.out.println("no " + name + " attribute for " + edgeName); } } // for a } // for r return list.toArray(new String[0]); } // networkEdgeAttributesToStringArray
/** * Returns a String representation of the <code><saml:Attribute></code> element. * * @param includeNS Determines whether or not the namespace qualifier is prepended to the Element * when converted * @param declareNS Determines whether or not the namespace is declared within the Element. * @return A string containing the valid XML for this element */ public String toString(boolean includeNS, boolean declareNS) { StringBuffer result = new StringBuffer(1000); String prefix = ""; String uri = ""; if (includeNS) { prefix = SAMLConstants.ASSERTION_PREFIX; } if (declareNS) { uri = SAMLConstants.assertionDeclareStr; } result .append("<") .append(prefix) .append("Attribute") .append(uri) .append(" AttributeName=\"") .append(_attributeName) .append("\" AttributeNamespace=\"") .append(_attributeNameSpace) .append("\">\n"); Iterator iter = _attributeValue.iterator(); while (iter.hasNext()) { result.append(XMLUtils.printAttributeValue((Element) iter.next(), prefix)).append("\n"); } result.append("</").append(prefix).append("Attribute>\n"); return result.toString(); }
/** * convert email address mapping<br> * <code>user-</code> will be replace by the email address of the user as stored in the user * repository <code>group-</code> will */ public String convertEmailList(String mailTo) { StringBuffer ret = new StringBuffer(); String[] list = mailTo.split(";"); if (list == null) { return ""; } for (int i = 0; i < list.length; i++) { // for each item String userName = list[i]; if (i != 0) { ret.append("\n"); } if (userName.startsWith(MailConstants.PREFIX_USER)) { userName = StringUtils.removeStart(userName, MailConstants.PREFIX_USER); if (log.isDebugEnabled()) { log.debug("username =" + userName); } ret.append(getUserMail(userName)); } else if (userName.startsWith(MailConstants.PREFIX_GROUP)) { } else if (userName.startsWith(MailConstants.PREFIX_ROLE)) { } else { // none of the above, just add the mail to the list ret.append(userName); } } return ret.toString(); }
private String addNewInteraction(String fingerprint, BiologicalInteraction interaction) throws SQLException { String sql = String.format( "INSERT IGNORE INTO interaction (fingerprint) VALUES (%s)", SqlUtil.toSqlVarchar(fingerprint)); if (1 != DBUtil.update(sql)) { System.out.println("SQL update failed? " + sql); } String interaction_id = DBUtil.querySingle("SELECT LAST_INSERT_ID()"); Iterator<BiologicalEntity> iter = interaction.getEntityIterator(); StringBuffer sb = new StringBuffer( "INSERT IGNORE INTO interaction_pool (interaction_id, gene_id, entity_src_table, role) VALUES "); while (iter.hasNext()) { BiologicalEntity entity = iter.next(); sb.append("(") .append(interaction_id) .append(", ") .append(SqlUtil.toSqlVarchar(entity.getId())) .append(", '") .append(srcTableLookup.get(entity.getId_src())) .append("', '") .append(entity.getRole()) .append("')"); if (iter.hasNext()) sb.append(", "); } if (DBUtil.update(sb.toString()) != interaction.getEnvolvedEntityCount()) { System.out.println("SQL update failed? " + sb); } return interaction_id; }
static String compress(String str) { int size; int strLength = str.length(); size = compressCount(str, strLength); if (size > strLength) { return str; } StringBuffer sb = new StringBuffer(); char newChar = str.charAt(0); int count = 1; for (int i = 1; i < strLength; i++) { if (str.charAt(i) == newChar) { count++; } else { sb.append(newChar); sb.append(count); newChar = str.charAt(i); count = 1; } } sb.append(newChar); sb.append(count); return sb.toString(); }
public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Phase: " + getPhaseAlias() + " SubPhase: " + getSubPhaseAlias()); sb.append( "Leader: " + getLeader().getAlias() + " sel: " + getLeader().getButton().getSelection() + " enabled: " + getLeader().getButton().isEnabled() + "\n"); if (getControls() != null) { Iterator it = getControls().iterator(); while (it.hasNext()) { ISootOptionWidget next = (ISootOptionWidget) it.next(); sb.append("control: " + next.getId() + "\n"); if (next instanceof BooleanOptionWidget) { sb.append( "control is boolean and enable state: " + ((BooleanOptionWidget) next).getButton().isEnabled() + "\n"); } } } return sb.toString(); }
private Pair<MutableTextRange, StringBuffer> getFragmentByRange(int start, final int length) { final StringBuffer fragmentBuffer = new StringBuffer(); int end = start + length; // restoring buffer and remove all subfragments from the list int documentOffset = 0; int effectiveOffset = 0; Iterator<Pair<MutableTextRange, StringBuffer>> iterator = myAffectedFragments.iterator(); while (iterator.hasNext() && effectiveOffset <= end) { final Pair<MutableTextRange, StringBuffer> pair = iterator.next(); final MutableTextRange range = pair.getFirst(); final StringBuffer buffer = pair.getSecond(); int effectiveFragmentEnd = range.getStartOffset() + buffer.length(); if (range.getStartOffset() <= start && effectiveFragmentEnd >= end) return pair; if (effectiveFragmentEnd >= start) { final int effectiveStart = Math.max(effectiveOffset, start); if (range.getStartOffset() > start) { fragmentBuffer.append( myDocument.getCharsSequence(), effectiveStart - effectiveOffset + documentOffset, Math.min(range.getStartOffset(), end) - effectiveOffset + documentOffset); } if (end >= range.getStartOffset()) { fragmentBuffer.append(buffer); end = end > effectiveFragmentEnd ? end - (buffer.length() - range.getLength()) : range.getEndOffset(); effectiveFragmentEnd = range.getEndOffset(); start = Math.min(start, range.getStartOffset()); iterator.remove(); } } documentOffset += range.getEndOffset() - effectiveOffset; effectiveOffset = effectiveFragmentEnd; } if (effectiveOffset < end) { final int effectiveStart = Math.max(effectiveOffset, start); fragmentBuffer.append( myDocument.getCharsSequence(), effectiveStart - effectiveOffset + documentOffset, end - effectiveOffset + documentOffset); } MutableTextRange newRange = new MutableTextRange(start, end); final Pair<MutableTextRange, StringBuffer> pair = new Pair<MutableTextRange, StringBuffer>(newRange, fragmentBuffer); for (Pair<MutableTextRange, StringBuffer> affectedFragment : myAffectedFragments) { MutableTextRange range = affectedFragment.getFirst(); assert end <= range.getStartOffset() || range.getEndOffset() <= start : "Range :" + range + "; Added: " + newRange; } myAffectedFragments.add(pair); return pair; }
public String toString() { StringBuffer sb = new StringBuffer(url.length() + 17); sb.append("[MyMockCachedUrl: "); sb.append(url); sb.append("]"); return sb.toString(); }
/** Sets LOV. */ public void setListOfValues(List listOfValues) { if (listOfValues.size() > 0) { StringBuffer buf = new StringBuffer(); buf.append(" java.util.ArrayList lov = new ArrayList();\n"); Iterator iter = listOfValues.iterator(); while (iter.hasNext()) { ListOfValuesXMLEntity e = (ListOfValuesXMLEntity) iter.next(); String value = e.getValue(); if (!e.getValue().startsWith("new")) { if (type == T_TEXT) value = "\"" + e.getValue() + "\""; else if (type == T_NUMERIC) { if (jrfColumnClassName.equals("java.lang.Long")) value = "new Long(" + e.getValue() + ")"; else if (jrfColumnClassName.equals("java.lang.Short")) value = "new Short(" + e.getValue() + ")"; else if (jrfColumnClassName.equals("java.lang.Integer")) value = "new Integer(" + e.getValue() + ")"; else if (jrfColumnClassName.equals("java.lang.Double")) value = "new Double(" + e.getValue() + ")"; else if (jrfColumnClassName.equals("java.lang.Float")) value = "new Float(" + e.getValue() + ")"; else throw new IllegalArgumentException( this + ": Unsupported list of value number type (long,short,double,float and integer supported)"); } else throw new IllegalArgumentException( this + ": Unsupported list of value literal; use 'new X.."); } buf.append(" lov.add(" + value + ");\n"); } super.transientKeys.put("listOfValues", "lov"); super.transientKeys.put("listOfValuesAdd", buf.toString()); } }
public void run() { int i; String cmdToLookFor = getServerProperty("pidHint"); if (cmdToLookFor == null) { StringBuffer buf = new StringBuffer(); for (i = 0; i < mExecArgs.length; i++) { if (i > 0) { buf.append(" "); } buf.append(mExecArgs[i]); } cmdToLookFor = buf.toString(); } mLogger.finer("Looking for pid for command: " + cmdToLookFor); i = 0; do { try { Thread.sleep(1000); } catch (InterruptedException ie) { } mPid = UnixStdlib.getProcessID(cmdToLookFor); } while (mPid == 0 && ++i < 300); // up to 5 minutes if (mPid == 0) { mLogger.warning("Giving up on trying to identify pid"); } else { mLogger.finer("Serverpid server=" + mName + " pid=" + mPid); } }
protected void prepare() throws Exception { try { List execCommand = buildExecCommand(); if (execCommand == null) { mLogger.severe("No command property was specified; disabling server"); synchronized (this) { changeState(STATE_DISABLED); } return; } else { mExecArgs = (String[]) execCommand.toArray(new String[0]); StringBuffer printableCmd = new StringBuffer(4096); int index = 0; for (; index < mExecArgs.length - 1; index++) { printableCmd.append(mExecArgs[index]).append(" "); } printableCmd.append(mExecArgs[index]); mPrintableCommand = printableCmd.toString(); if (useOptimizeIt()) { System.err.println(mPrintableCommand); } } } catch (Exception ex) { mLogger.severe("Failed In preparing execargs"); throw ex; } }
public Properties internalToProperties() { Properties props = new Properties(); StringBuffer st = new StringBuffer(); st.append(" "); for (int i = 0; i < visibleViewIds.size(); i++) { st.append(" " + Constants.cpNames[((Integer) visibleViewIds.elementAt(i)).intValue()]); } // System.out.println(" visibleViewIds: " + st.toString()); props.setProperty("ndedit.visibleViewIds", st.toString()); props.setProperty("ndedit.cutPanelSizeW", (new Integer(cutPanelSize.width).toString())); props.setProperty("ndedit.cutPanelSizeH", (new Integer(cutPanelSize.height).toString())); props.setProperty("ndedit.cutPanelWMin", (new Integer(cutPanelMinSize.width).toString())); props.setProperty("ndedit.cutPanelHMin", (new Integer(cutPanelMinSize.height).toString())); props.setProperty("ndedit.cutPanelWMax", (new Integer(cutPanelMaxSize.width).toString())); props.setProperty("ndedit.cutPanelHMax", (new Integer(cutPanelMaxSize.height).toString())); props.setProperty("ndedit.lonReference", (new Double(lonReference).toString())); props.setProperty("ndedit.geoDisplayFormat", (new Integer(geoDisplayFormat).toString())); props.setProperty("ndedit.timeDisplayFormat", (new Integer(timeDisplayFormat).toString())); props.setProperty("ndedit.timeAxisMode", (new Integer(timeAxisMode).toString())); props.setProperty("ndedit.timeAxisReference", (new Double(timeAxisReference).toString())); String dpa = new Boolean(displayPanelAxes).toString(); props.setProperty("ndedit.displayPanelAxes", dpa); dpa = new Boolean(independentHandles).toString(); props.setProperty("ndedit.independentHandles", dpa); return props; }
/** * Get a string from the underlying resource bundle and format it with the given set of arguments. * * @param key * @param args */ public String getString(String key, Object[] args) { String iString; String value = getString(key); // this check for the runtime exception is some pre 1.1.6 // VM's don't do an automatic toString() on the passed in // objects and barf out try { // ensure the arguments are not null so pre 1.2 VM's don't barf if (args == null) { args = new Object[1]; } Object[] nonNullArgs = args; for (int i = 0; i < args.length; i++) { if (args[i] == null) { if (nonNullArgs == args) { nonNullArgs = args.clone(); } nonNullArgs[i] = "null"; } } if (value == null) value = key; iString = MessageFormat.format(value, nonNullArgs); } catch (IllegalArgumentException iae) { StringBuffer buf = new StringBuffer(); buf.append(value); for (int i = 0; i < args.length; i++) { buf.append(" arg[").append(i).append("]=").append(args[i]); } iString = buf.toString(); } return iString; }
// Serialize the bean using the specified namespace prefix & uri public String serialize(Object bean) throws IntrospectionException, IllegalAccessException { // Use the class name as the name of the root element String className = bean.getClass().getName(); String rootElementName = null; if (bean.getClass().isAnnotationPresent(ObjectXmlAlias.class)) { AnnotatedElement annotatedElement = bean.getClass(); ObjectXmlAlias aliasAnnotation = annotatedElement.getAnnotation(ObjectXmlAlias.class); rootElementName = aliasAnnotation.value(); } // Use the package name as the namespace URI Package pkg = bean.getClass().getPackage(); nsURI = pkg.getName(); // Remove a trailing semi-colon (;) if present (i.e. if the bean is an array) className = StringUtils.deleteTrailingChar(className, ';'); StringBuffer sb = new StringBuffer(className); String objectName = sb.delete(0, sb.lastIndexOf(".") + 1).toString(); domDocument = createDomDocument(objectName); document = domDocument.getDocument(); Element root = document.getDocumentElement(); // Parse the bean elements getBeanElements(root, rootElementName, className, bean); StringBuffer xml = new StringBuffer(); if (prettyPrint) xml.append(domDocument.serialize(lineSeperator, indentChars, includeXmlProlog)); else xml.append(domDocument.serialize(includeXmlProlog)); if (!includeTypeInfo) { int index = xml.indexOf(root.getNodeName()); xml.delete(index - 1, index + root.getNodeName().length() + 2); xml.delete(xml.length() - root.getNodeName().length() - 4, xml.length()); } return xml.toString(); }
/** ** Reads/returns the specified CompileTime template file */ private static String readTemplate(File tf, String pkgName) { /* read template data */ byte templData[] = FileTools.readFile(tf); if (templData == null) { Print.errPrintln("\nUnable to read Input/Template file: " + tf); return null; } else if (templData.length == 0) { Print.errPrintln("\nInput/Template file is empty: " + tf); return null; } /* return template String */ String templateText = StringTools.toStringValue(templData); if (!StringTools.isBlank(pkgName) && !StringTools.isBlank(templateText)) { String lines[] = StringTools.split(templateText, '\n', false); for (int i = 0; i < lines.length; i++) { if (lines[i].trim().startsWith(JAVA_PACKAGE_)) { lines[i] = CompiletimeVars.packageLine(pkgName); return StringTools.join(lines, '\n') + "\n"; } } StringBuffer sb = new StringBuffer(); sb.append(CompiletimeVars.packageLine(pkgName)).append("\n"); sb.append(templateText); return sb.toString(); } else { return templateText; } }
/** * Computes previous revision or <code>null</code> for initial. * * @param revision num.dot revision or <code>null</code> */ public static String previousRevision(String revision) { if (revision == null) return null; String[] nums = revision.split("\\."); // NOI18N assert (nums.length % 2) == 0 : "File revisions must consist from even tokens: " + revision; // NOI18N // eliminate branches int lastIndex = nums.length - 1; boolean cutoff = false; while (lastIndex > 1 && "1".equals(nums[lastIndex])) { // NOI18N lastIndex -= 2; cutoff = true; } if (lastIndex <= 0) { return null; } else if (lastIndex == 1 && "1".equals(nums[lastIndex])) { // NOI18N return null; } else { int rev = Integer.parseInt(nums[lastIndex]); if (!cutoff) rev--; StringBuffer sb = new StringBuffer(nums[0]); for (int i = 1; i < lastIndex; i++) { sb.append('.').append(nums[i]); // NOI18N } sb.append('.').append(rev); // NOI18N return sb.toString(); } }
/** * ************************************************************************ Lineas de Remesa * * @param whereClause where clause or null (starting with AND) * @return lines */ public MRemesaLine[] getLines(String whereClause, String orderClause) { ArrayList list = new ArrayList(); StringBuffer sql = new StringBuffer("SELECT * FROM C_RemesaLine WHERE C_Remesa_ID=? "); if (whereClause != null) sql.append(whereClause); if (orderClause != null) sql.append(" ").append(orderClause); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql.toString(), get_TrxName()); pstmt.setInt(1, getC_Remesa_ID()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) list.add(new MRemesaLine(getCtx(), rs)); rs.close(); pstmt.close(); pstmt = null; } catch (Exception e) { log.saveError("getLines - " + sql, e); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { } pstmt = null; } // MRemesaLine[] lines = new MRemesaLine[list.size()]; list.toArray(lines); return lines; } // getLines
public String pairClusters2string( ArrayList<Record> pair1, ArrayList<Record> pair2, boolean left) { StringBuffer bf = new StringBuffer(); for (int i = 0; i < pair1.size(); i++) { for (int j = 0; j < pair2.size(); j++) { if (pair1.get(i).isInsertionPair(pair2.get(j), left)) { bf.append(pair1.get(i) + "\n" + pair2.get(j) + "\n\n"); pair1.remove(i); pair2.remove(j); i--; j--; break; } } } if ((pair1.size() + pair2.size()) > 0) { bf.append("***** UNPAIRED *****\n"); for (int i = 0; i < pair1.size(); i++) { bf.append(pair1.get(i) + "\n"); } for (int j = 0; j < pair2.size(); j++) { bf.append(pair2.get(j) + "\n"); } bf.append("**** END OF UNPAIRED ****\n"); } // bf.append("\n"); return bf.toString(); }
// ---------------------------------------------------------------------- // for "SrvTypeRqst" // get the list of service types for specified scope & naming authority // ---------------------------------------------------------------------- public synchronized String getServiceTypeList(String na, String scope) { Vector typelist = new Vector(5); Iterator values = table.values().iterator(); while (values.hasNext()) { Entry e = (Entry) values.next(); if (!e.getDeleted() && // nor deleted scope.equalsIgnoreCase(e.getScope()) && // match scope (na.equals("*") || // NA wildcard na.equalsIgnoreCase(e.getNA())) && // match NA !typelist.contains(e.getType())) { typelist.addElement(e.getType()); } } StringBuffer tl = new StringBuffer(); for (int i = 0; i < typelist.size(); i++) { String s = (String) typelist.elementAt(i); if (tl.length() > 0) tl.append(","); tl.append(s); } return tl.toString(); }
/** @return nick(id) */ public String getNickAndId() { StringBuffer sb = new StringBuffer(getNick()); sb.append('('); sb.append(Long.toString(getId())); sb.append(')'); return sb.toString(); }
private String quoteTimeStampChars(String input) { // put single quotes around text that isn't a supported dateformat char StringBuffer result = new StringBuffer(); // ok to default to false because we also check for index zero below boolean lastCharIsDateFormat = false; for (int i = 0; i < input.length(); i++) { String thisVal = input.substring(i, i + 1); boolean thisCharIsDateFormat = VALID_DATEFORMAT_CHARS.contains(thisVal); // we have encountered a non-dateformat char if (!thisCharIsDateFormat && (i == 0 || lastCharIsDateFormat)) { result.append("'"); } // we have encountered a dateformat char after previously encountering a non-dateformat char if (thisCharIsDateFormat && i > 0 && !lastCharIsDateFormat) { result.append("'"); } lastCharIsDateFormat = thisCharIsDateFormat; result.append(thisVal); } // append an end single-quote if we ended with non-dateformat char if (!lastCharIsDateFormat) { result.append("'"); } return result.toString(); }
/** * Starts a new column, possibly closing the current column if needed * * @param ret the output buffer to put LaTeX into * @param p the properties from the <code><td></code> tag */ public void startCol(StringBuffer ret, Properties p) { endCol(ret); int span = hasNumProp("colspan", p); if (colcnt > 0) { ret.append(" & "); } String align = hasProp("align", p); if (align != null && span < 0) span = 1; if (span > 0) { ret.append("\\multicolumn{" + span + "}{"); if (border && colcnt == 0) ret.append("|"); String cc = "" + (char) ('a' + (colcnt / (26 * 26))) + (char) ((colcnt / 26) + 'a') + (char) ((colcnt % 26) + 'a'); if (align != null) { String h = align.substring(0, 1); if ("rR".indexOf(h) >= 0) ret.append("r"); else if ("lL".indexOf(h) >= 0) ret.append("p{\\tbl" + tc + "c" + cc + "w}"); else if ("cC".indexOf(h) >= 0) ret.append("p{\\tbl" + tc + "c" + cc + "w}"); } else ret.append("p{\\tbl" + tc + "c" + cc + "w}"); if (border) ret.append("|"); ret.append("}"); } String wid = p.getProperty("texwidth"); ret.append("{"); if (wid != null) { ret.append("\\parbox{" + wid + "}{\\vskip 1ex "); parboxed = true; } colcnt++; colopen = true; }
public static String reportKillData() { HashMap hm = getKillHashMap(); ArrayList al = new ArrayList(hm.keySet()); Collections.sort(al); StringBuffer sb = new StringBuffer(); sb.append("You have killed the following creatures:\n"); sb.append("\n"); boolean uniques = true; for (Iterator it = al.iterator(); it.hasNext(); ) { String name = (String) it.next(); // display line after uniques if (uniques && (!Character.isUpperCase(name.charAt(0)))) { uniques = false; sb.append("\n"); } Integer count = (Integer) (hm.get(name)); String g = Text.centrePad(name, count.toString(), 60); sb.append(g + "\n"); } return sb.toString(); }
private static String[] getSuggestionsByValue(final String stringValue) { List<String> result = new ArrayList<String>(); StringBuffer currentWord = new StringBuffer(); boolean prevIsUpperCase = false; for (int i = 0; i < stringValue.length(); i++) { final char c = stringValue.charAt(i); if (Character.isUpperCase(c)) { if (currentWord.length() > 0 && !prevIsUpperCase) { result.add(currentWord.toString()); currentWord = new StringBuffer(); } currentWord.append(c); } else if (Character.isLowerCase(c)) { currentWord.append(Character.toUpperCase(c)); } else if (Character.isJavaIdentifierPart(c) && c != '_') { if (Character.isJavaIdentifierStart(c) || currentWord.length() > 0 || !result.isEmpty()) { currentWord.append(c); } } else { if (currentWord.length() > 0) { result.add(currentWord.toString()); currentWord = new StringBuffer(); } } prevIsUpperCase = Character.isUpperCase(c); } if (currentWord.length() > 0) { result.add(currentWord.toString()); } return ArrayUtil.toStringArray(result); }
/** * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string * buffer to use ** @throws IOException if an error occurs or the server has stopped */ protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb) throws IOException { if (socket != null) { int dataLen = 0; StringBuffer data = (sb != null) ? sb : new StringBuffer(); InputStream input = socket.getInputStream(); while ((maxLen < 0) || (maxLen > dataLen)) { int ch = input.read(); // Print.logInfo("ReadLine char: " + ch); if (ch < 0) { // this means that the server has stopped throw new IOException("End of input"); } else if (ch == LineTerminatorChar) { // include line terminator in String data.append((char) ch); dataLen++; break; } else { // append character data.append((char) ch); dataLen++; } } return data.toString(); } else { return null; } }
/* * Filters strings from a line of text and formats them properly. */ private String stringFilter(String line) { if (line == null || line.equals("")) { return ""; } StringBuffer buf = new StringBuffer(); if (!line.contains("\"")) { return keywordFilter(line); } int start = 0; int startStringIndex = -1; int endStringIndex; int tempIndex; // Keep moving through String characters until we want to stop... while ((tempIndex = line.indexOf("\"")) > -1) { // We found the beginning of a string if (startStringIndex == -1) { startStringIndex = 0; buf.append(stringFilter(line.substring(start, tempIndex))); buf.append(stringStart).append("\""); line = line.substring(tempIndex + 1); } // Must be at the end else { startStringIndex = -1; endStringIndex = tempIndex; buf.append(line.substring(0, endStringIndex + 1)); buf.append(stringEnd); line = line.substring(endStringIndex + 1); } } buf.append(keywordFilter(line)); return buf.toString(); }
/* * Filters keywords from a line of text and formats them properly. */ private String keywordFilter(String line) { if (line == null || line.equals("")) { return ""; } StringBuffer buf = new StringBuffer(); Map<String, String> usedReservedWords = new HashMap<String, String>(); // >= Java2 only (not thread-safe) // Hashtable usedReservedWords = new Hashtable(); // < Java2 (thread-safe) int i = 0; char ch; StringBuffer temp = new StringBuffer(); while (i < line.length()) { temp.setLength(0); ch = line.charAt(i); // 65-90, uppercase letters // 97-122, lowercase letters while (i < line.length() && ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))) { temp.append(ch); i++; if (i < line.length()) { ch = line.charAt(i); } } String tempString = temp.toString(); if (RESERVED_WORDS.containsKey(tempString) && !usedReservedWords.containsKey(tempString)) { usedReservedWords.put(tempString, tempString); line = replace(line, tempString, (reservedWordStart + tempString + reservedWordEnd)); i += (reservedWordStart.length() + reservedWordEnd.length()); } else { i++; } } buf.append(line); return buf.toString(); }
public String toString() { StringBuffer s = new StringBuffer(); s.append("ed:"); for (int i = 0; i < count; i++) s.append(" " + args[i]); if (size != null) s.append(" (" + size + ")"); return s.toString(); }