/** * Trim leading and trailing whitespace from the given String. * * @param str the String to check * @return the trimmed String * @see Character#isWhitespace */ public static String trimWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { sb.deleteCharAt(0); } while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); }
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { StringBuilder builder = new StringBuilder(string); for (int i = builder.length() - 1; i >= 0; i--) { int cp = builder.codePointAt(i); if (!Character.isDigit(cp) && cp != '-') { builder.deleteCharAt(i); if (Character.isSupplementaryCodePoint(cp)) { i--; builder.deleteCharAt(i); } } } super.insertString(fb, offset, builder.toString(), attr); }
// 过滤整数字符,把所有非0~9的字符全部删除 private void filterInt(StringBuilder builder) { for (int i = builder.length() - 1; i >= 0; i--) { int cp = builder.codePointAt(i); if (cp > '9' || cp < '0') { builder.deleteCharAt(i); } } }
public static OMElement serializeHandlerConfiguration(HandlerConfigurationBean bean) { OMFactory factory = OMAbstractFactory.getOMFactory(); OMElement handler = factory.createOMElement("handler", null); handler.addAttribute(factory.createOMAttribute("class", null, bean.getHandlerClass())); if (bean.getTenant() != null) { handler.addAttribute(factory.createOMAttribute("tenant", null, bean.getTenant())); } StringBuilder sb = new StringBuilder(); for (String method : bean.getMethods()) { if (method != null && method.length() > 0) { sb.append(method).append(","); } } // Remove last "," if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); handler.addAttribute(factory.createOMAttribute("methods", null, sb.toString())); } for (String property : bean.getPropertyList()) { OMElement temp = factory.createOMElement("property", null); temp.addAttribute(factory.createOMAttribute("name", null, property)); OMElement xmlProperty = bean.getXmlProperties().get(property); if (xmlProperty != null) { // The serialization happens by adding the whole XML property value to the // bean. // Therefore if it is a XML property, we take that whole element. handler.addChild(xmlProperty); } else { String nonXMLProperty = bean.getNonXmlProperties().get(property); if (nonXMLProperty != null) { temp.setText(nonXMLProperty); handler.addChild(temp); } } } OMElement filter = factory.createOMElement("filter", null); filter.addAttribute( factory.createOMAttribute("class", null, bean.getFilter().getFilterClass())); for (String property : bean.getFilter().getPropertyList()) { OMElement temp = factory.createOMElement("property", null); temp.addAttribute(factory.createOMAttribute("name", null, property)); OMElement xmlProperty = bean.getFilter().getXmlProperties().get(property); if (xmlProperty != null) { temp.addAttribute(factory.createOMAttribute("type", null, "xml")); temp.addChild(xmlProperty); filter.addChild(temp); } else { String nonXMLProperty = bean.getFilter().getNonXmlProperties().get(property); if (nonXMLProperty != null) { temp.setText(nonXMLProperty); filter.addChild(temp); } } } handler.addChild(filter); return handler; }
@Contract("null, _, _ -> null") private static String toCanonicalPath( @Nullable String path, char separatorChar, boolean removeLastSlash) { if (path == null || path.isEmpty()) { return path; } else if (".".equals(path)) { return ""; } path = path.replace(separatorChar, '/'); if (path.indexOf('/') == -1) { return path; } int start = pathRootEnd(path) + 1, dots = 0; boolean separator = true; StringBuilder result = new StringBuilder(path.length()); result.append(path, 0, start); for (int i = start; i < path.length(); ++i) { char c = path.charAt(i); if (c == '/') { if (!separator) { processDots(result, dots, start); dots = 0; } separator = true; } else if (c == '.') { if (separator || dots > 0) { ++dots; } else { result.append('.'); } separator = false; } else { if (dots > 0) { StringUtil.repeatSymbol(result, '.', dots); dots = 0; } result.append(c); separator = false; } } if (dots > 0) { processDots(result, dots, start); } int lastChar = result.length() - 1; if (removeLastSlash && lastChar >= 0 && result.charAt(lastChar) == '/' && lastChar > start) { result.deleteCharAt(lastChar); } return result.toString(); }
/** * Trim all occurrences of the supplied trailing character from the given String. * * @param str the String to check * @param trailingCharacter the trailing character to be trimmed * @return the trimmed String */ public static String trimTrailingCharacter(String str, char trailingCharacter) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); }
public static String concatSortedPercentEncodedParams(Map<String, String> params) { StringBuilder target = new StringBuilder(); for (String key : params.keySet()) { target.append(key); target.append(PAIR_SEPARATOR); target.append(params.get(key)); target.append(PARAM_SEPARATOR); } return target.deleteCharAt(target.length() - 1).toString(); }
/** * @param source Source string * @param chars Symbols to be trimmed * @return string without all specified chars at the end. For example, * <code>chopTrailingChars("c:\\my_directory\\//\\",new char[]{'\\'}) is <code>"c:\\my_directory\\//"</code>, * <code>chopTrailingChars("c:\\my_directory\\//\\",new char[]{'\\','/'}) is <code>"c:\my_directory"</code>. * Actually this method can be used to normalize file names to chop trailing separator chars. */ public static String chopTrailingChars(String source, char[] chars) { StringBuilder sb = new StringBuilder(source); while (true) { boolean atLeastOneCharWasChopped = false; for (int i = 0; i < chars.length && sb.length() > 0; i++) { if (sb.charAt(sb.length() - 1) == chars[i]) { sb.deleteCharAt(sb.length() - 1); atLeastOneCharWasChopped = true; } } if (!atLeastOneCharWasChopped) { break; } } return sb.toString(); }
public StringBuilder findLocations(Document doc, StringBuilder sb) { for (Tag tag : doc.tags) { StringBuilder nb = new StringBuilder(); for (int i = tag.begin; i < tag.end; i++) { nb.append(doc.terms.get(i) + " "); } if (!(nb.lastIndexOf(" ") == -1)) { nb.deleteCharAt(nb.lastIndexOf(" ")); } String name = nb.toString(); sb.append(name); sb.append(","); sb.append(doc.name); sb.append("\n"); } return sb; }
/** Return the next element of the json document */ private String getNextNode() { final int popState; switch (states.peek()) { case ARRAY: switch (rand.nextInt(9)) { case 0: // String case final String val = "stepha" + this.getWhitespace() + "n" + this.getWhitespace() + "e"; this.addToLastNode(1); nodes.add(IntsRef.deepCopyOf(curNodePath)); images.add(val); types.add(ExtendedJsonTokenizer.getTokenTypes()[LITERAL]); incr.add(1); datatypes.add(XSDDatatype.XSD_STRING); return "\"" + val + "\"" + this.getWhitespace() + ","; case 1: // DOUBLE case this.addToLastNode(1); nodes.add(IntsRef.deepCopyOf(curNodePath)); images.add("34.560e-9"); types.add(ExtendedJsonTokenizer.getTokenTypes()[NUMBER]); incr.add(1); datatypes.add(XSDDatatype.XSD_DOUBLE); return "34.560e-9" + this.getWhitespace() + ","; case 2: // LONG case this.addToLastNode(1); nodes.add(IntsRef.deepCopyOf(curNodePath)); images.add("34560e-9"); types.add(ExtendedJsonTokenizer.getTokenTypes()[NUMBER]); incr.add(1); datatypes.add(XSDDatatype.XSD_LONG); return "34560e-9" + this.getWhitespace() + ","; case 3: // true case this.addToLastNode(1); nodes.add(IntsRef.deepCopyOf(curNodePath)); images.add("true"); types.add(ExtendedJsonTokenizer.getTokenTypes()[TRUE]); incr.add(1); datatypes.add(XSDDatatype.XSD_BOOLEAN); return "true" + this.getWhitespace() + ","; case 4: // false case this.addToLastNode(1); nodes.add(IntsRef.deepCopyOf(curNodePath)); images.add("false"); types.add(ExtendedJsonTokenizer.getTokenTypes()[FALSE]); incr.add(1); datatypes.add(XSDDatatype.XSD_BOOLEAN); return "false" + this.getWhitespace() + ","; case 5: // null case this.addToLastNode(1); nodes.add(IntsRef.deepCopyOf(curNodePath)); images.add("null"); types.add(ExtendedJsonTokenizer.getTokenTypes()[NULL]); incr.add(1); datatypes.add(XSDDatatype.XSD_STRING); return "null" + this.getWhitespace() + ","; case 6: // nested array case if (states.size() <= MAX_DEPTH) { this.addToLastNode(1); this.incrNodeObjectPath(); states.add(ARRAY); return "["; } return ""; case 7: // nested object case if (states.size() <= MAX_DEPTH) { this.addToLastNode(1); this.incrNodeObjectPath(); states.add(ARRAY_OBJECT); return "{"; } return ""; case 8: // closing array case this.decrNodeObjectPath(); popState = states.pop(); if (popState != ARRAY) { shouldFail = true; } // Remove previous comma, this is not allowed final int comma = sb.lastIndexOf(","); if (comma != -1 && sb.substring(comma + 1).matches("\\s*")) { sb.deleteCharAt(comma); } return "],"; } case ARRAY_OBJECT: case OBJECT_ATT: switch (rand.nextInt(3)) { case 0: // new object field types.add(ExtendedJsonTokenizer.getTokenTypes()[LITERAL]); images.add("ste ph ane"); incr.add(1); this.addToLastNode(1); nodes.add(IntsRef.deepCopyOf(curNodePath)); datatypes.add(JSONDatatype.JSON_FIELD); states.push(OBJECT_VAL); return "\"ste ph ane\"" + this.getWhitespace() + ":"; case 1: // close object if (states.peek() == OBJECT_ATT && nestedObjs > 0) { this.decrNodeObjectPath(); nestedObjs--; } this.decrNodeObjectPath(); popState = states.pop(); if (popState != OBJECT_ATT && popState != ARRAY_OBJECT) { shouldFail = true; } // Remove previous comma, this is not allowed final int comma = sb.lastIndexOf(","); if (comma != -1 && sb.substring(comma + 1).matches("\\s*")) { sb.deleteCharAt(comma); } return states.empty() ? "}" : "},"; case 2: // Datatype if (getLastNode() >= 0) { // this nested object cannot be a datatype object because other things have been added // to it return ""; } final String field; if (states.isEmpty()) { // datatype object at the root are not possible shouldFail = true; field = "{"; } else if (states.peek() == OBJECT_ATT) { // field name this.addToLastNode(1); field = "\"field\":{"; types.add(ExtendedJsonTokenizer.getTokenTypes()[LITERAL]); images.add("field"); incr.add(1); nodes.add(IntsRef.deepCopyOf(curNodePath)); datatypes.add(JSONDatatype.JSON_FIELD); // value this.incrNodeObjectPath(); this.setLastNode(0); } else if (states.peek() == ARRAY) { this.addToLastNode(1); field = "{"; } else if (states.peek() == ARRAY_OBJECT) { this.decrNodeObjectPath(); field = ""; } else { // should not happen throw new IllegalStateException("Received unknown state=" + states.peek()); } types.add(ExtendedJsonTokenizer.getTokenTypes()[LITERAL]); images.add("Luke Skywalker"); incr.add(1); nodes.add(IntsRef.deepCopyOf(curNodePath)); datatypes.add("jedi"); // close datatype object if (states.peek() == ARRAY_OBJECT) { popState = states.pop(); } else { this.decrNodeObjectPath(); } return field + this.getWhitespace() + "\"" + ExtendedJsonTokenizer.DATATYPE_LABEL + "\":" + this.getWhitespace() + "\"jedi\"," + "\"" + ExtendedJsonTokenizer.DATATYPE_VALUES + "\":" + this.getWhitespace() + "\"Luke Skywalker\"" + this.getWhitespace() + "},"; } case OBJECT_VAL: switch (rand.nextInt(8)) { case 0: // String return this.doValString( "stepha" + this.getWhitespace() + "n" + this.getWhitespace() + "e"); case 1: // DOUBLE case images.add("34.560e-9"); types.add(ExtendedJsonTokenizer.getTokenTypes()[NUMBER]); incr.add(1); this.incrNodeObjectPath(); this.setLastNode(0); nodes.add(IntsRef.deepCopyOf(curNodePath)); this.decrNodeObjectPath(); datatypes.add(XSDDatatype.XSD_DOUBLE); states.pop(); // remove OBJECT_VAL state return "34.560e-9" + this.getWhitespace() + ","; case 2: // LONG case images.add("34560e-9"); types.add(ExtendedJsonTokenizer.getTokenTypes()[NUMBER]); incr.add(1); this.incrNodeObjectPath(); this.setLastNode(0); nodes.add(IntsRef.deepCopyOf(curNodePath)); this.decrNodeObjectPath(); datatypes.add(XSDDatatype.XSD_LONG); states.pop(); // remove OBJECT_VAL state return "34560e-9" + this.getWhitespace() + ","; case 3: // True images.add("true"); types.add(ExtendedJsonTokenizer.getTokenTypes()[TRUE]); incr.add(1); this.incrNodeObjectPath(); this.setLastNode(0); nodes.add(IntsRef.deepCopyOf(curNodePath)); this.decrNodeObjectPath(); datatypes.add(XSDDatatype.XSD_BOOLEAN); states.pop(); // remove OBJECT_VAL state return "true" + this.getWhitespace() + ","; case 4: // False images.add("false"); types.add(ExtendedJsonTokenizer.getTokenTypes()[FALSE]); incr.add(1); this.incrNodeObjectPath(); this.setLastNode(0); nodes.add(IntsRef.deepCopyOf(curNodePath)); this.decrNodeObjectPath(); datatypes.add(XSDDatatype.XSD_BOOLEAN); states.pop(); // remove OBJECT_VAL state return "false" + this.getWhitespace() + ","; case 5: // NULL images.add("null"); types.add(ExtendedJsonTokenizer.getTokenTypes()[NULL]); incr.add(1); this.incrNodeObjectPath(); this.setLastNode(0); nodes.add(IntsRef.deepCopyOf(curNodePath)); this.decrNodeObjectPath(); datatypes.add(XSDDatatype.XSD_STRING); states.pop(); // remove OBJECT_VAL state return "null" + this.getWhitespace() + ","; case 6: // New array if (states.size() <= MAX_DEPTH) { states.pop(); // remove OBJECT_VAL state this.incrNodeObjectPath(); states.add(ARRAY); return "["; } return this.doValString(""); case 7: // new Object if (states.size() <= MAX_DEPTH) { states.pop(); // remove OBJECT_VAL state // Two incrementations, because the object introduce a "blank" node nestedObjs++; this.incrNodeObjectPath(); this.setLastNode(0); this.incrNodeObjectPath(); states.add(OBJECT_ATT); return "{"; } return this.doValString(""); } default: throw new IllegalStateException("Got unknown lexical state: " + states.peek()); } }
public static int serDiccGroupByToWriter( ResultSet rs, Writer writer, int maxRows, String idPor, String[] idAcumulados, String campoAcumuladoNombre) { int rowsCount = 0; try { ArrayList<String> acumulado = null; String idActual = null; StringBuilder reg = null; reg = new StringBuilder(); String value = ""; if (rs != null) { ResultSetMetaData rsm = rs.getMetaData(); int countCol = rsm.getColumnCount(); String name = ""; for (int i = 1; i <= countCol; i++) { name = rsm.getColumnName(i); reg.append(name.toLowerCase()).append("\t"); } reg.append(campoAcumuladoNombre); writer.write(reg.toString() + EOL); while (rs.next()) { if (idActual == null) { reg = new StringBuilder(); acumulado = new ArrayList<String>(); idActual = rs.getString(idPor); for (int i = 1; i <= countCol; i++) { reg.append(rs.getString(i)).append("\t"); } for (String id : idAcumulados) { value = rs.getString(id); if (!rs.wasNull()) { acumulado.add(rs.getString(id)); } } } else { if (idActual.equals(rs.getString(idPor))) { for (String id : idAcumulados) { value = rs.getString(id); if (!rs.wasNull()) { acumulado.add(rs.getString(id)); } } } else { if (acumulado.size() > 0) { for (String str : acumulado) { reg.append(str).append(","); } reg.deleteCharAt(reg.length() - 1); } reg.append(EOL); writer.write(reg.toString()); rowsCount++; if (maxRows == rowsCount) { break; } idActual = rs.getString(idPor); reg = new StringBuilder(); acumulado = new ArrayList<String>(); for (int i = 1; i <= countCol; i++) { reg.append(rs.getString(i)).append("\t"); } for (String id : idAcumulados) { value = rs.getString(id); if (!rs.wasNull()) { acumulado.add(rs.getString(id)); } } } } } if (acumulado.size() > 0) { for (String str : acumulado) { reg.append(str).append(","); } reg.deleteCharAt(reg.length() - 1); } reg.append(EOL); writer.write(reg.toString()); rowsCount++; } } catch (SQLException e) { logm("ERR", 1, "Error al escribir registros", e); } catch (IOException e) { logm("ERR", 1, "Error al escribir registros", e); } return rowsCount; }
private String trimLeadingSlash(String path) { StringBuilder builder = new StringBuilder(path); while (builder.length() > 0) { if (builder.charAt(0) == '/') { builder.deleteCharAt(0); } else { break; } } return builder.toString(); }
static void recursive( List<String> list, StringBuilder combo, String digits, String[] map, int[] start) { if (combo.length() == 0) return; if (combo.length() == digits.length()) { list.add(new String(combo)); combo.deleteCharAt(combo.length() - 1); start[0]--; return; } String next = map[digits.charAt(start[0]) - 48]; for (int i = 0; i < next.length(); i++) { combo.append(next.charAt(i)); start[0]++; recursive(list, combo, digits, map, start); } combo.deleteCharAt(combo.length() - 1); start[0]--; }
/** * Generates a JavaScript command to update the JavaScript agent's parameter names. Follows this * format: <code>agent.updateParameterNames({serial: 'XXXX', parameter: 'YYYY'});</code> * * @return A JavaScript Command. */ public String generateCommand(String type, Map<String, ?> props) { StringBuilder buff = new StringBuilder(agentName); buff.append(".update").append(type).append("({"); for (Entry<String, ?> entry : props.entrySet()) { if (entry.getValue() instanceof String) { buff.append(entry.getKey()).append(": '").append(entry.getValue()).append("',"); } else { buff.append(entry.getKey()).append(": ").append(entry.getValue()).append(","); } } buff.deleteCharAt(buff.length() - 1); buff.append("});"); return buff.toString(); }
@Override public void constructIndex() throws IOException { String corpusFile = _options._corpusPrefix + "/"; System.out.println("Construct index from: " + corpusFile); chooseFiles cf = new chooseFiles(_options); int times = cf.writeTimes(); System.out.println(times); FileOps filewriter = new FileOps(_options._indexPrefix + "/"); for (int i = 0; i < times; i++) { Vector<String> files = cf.loadFile(i); for (String name : files) { String filepath = corpusFile + name; File file = new File(filepath); time = new Date().getTime(); String content = ProcessHtml.process(file); totalTime += new Date().getTime() - time; if (content != null) processDocument(content, name); } // System.out.println("Times here : " + i); // System.out.println("processes:" + totalTime); String name = "temp" + i + ".txt"; Map<String, String> content = new HashMap<String, String>(); for (String term : _index.keySet()) { StringBuilder builder = new StringBuilder(); for (Integer x : _index.get(term)) { builder.append(x + "|"); } builder.deleteCharAt(builder.length() - 1); content.put(term, builder.toString()); } filewriter.write(name, content); _index.clear(); _terms.clear(); } String corpus_statistics = _options._indexPrefix + "/" + "statistics"; BufferedWriter outsta = new BufferedWriter(new FileWriter(corpus_statistics)); // the first line in the corpus_statistics is the number of docs in the corpus outsta.write(_numDocs + "\n"); outsta.write(String.valueOf(_totalTermFrequency) + "\n"); outsta.close(); String[] files = new String[times]; for (int count = 0; count < times; count++) { files[count] = "temp" + count + ".txt"; } filewriter.merge(files, "index.txt", "|"); }
public static String joinString(Iterable<String> lines, String separator) { StringBuilder sb = new StringBuilder(); for (String line : lines) { if (line != null) { sb.append(line); sb.append(separator); } } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); return sb.toString(); } else { return ""; } }
/** * Indexes a set of reports, using Start and End tags output is a list of entries of the form: A: * time1,time2,time3 * * <p>If no matches, will return an empty array */ @SuppressWarnings("unchecked") public static Text[] indexGraph(Map<String, Report> reports) { org.apache.commons.collections.MultiMap index = new org.apache.commons.collections.MultiHashMap(); // map from start tag to opIds of nodes containing the ends for (Map.Entry<String, Report> report : reports.entrySet()) { Report start = report.getValue(); List<String> starts = start.get("Start"); if (starts != null) { for (String s : starts) { Report end = findMatchingEnd(reports, start, s); if (end == null) continue; List<String> endTL = end.get("Timestamp"); List<String> staTL = start.get("Timestamp"); if (staTL != null && endTL != null && staTL.size() > 0 && endTL.size() > 0) { // FIXME: perhaps parse more cleverly? double startT = Double.parseDouble(staTL.get(0)); double endT = Double.parseDouble(endTL.get(0)); Long diff = new Long((long) (1000 * (endT - startT))); index.put(s, diff); } } } } Text[] out = new Text[index.size()]; int i = 0; for (Object k : index.keySet()) { StringBuilder sb = new StringBuilder(); sb.append(k.toString()); sb.append(' '); Collection coll = (Collection) index.get(k); for (Object v : coll) { assert v instanceof Long : "how did a non-Long get into my collection?"; sb.append(v.toString()); sb.append(","); } sb.deleteCharAt(sb.length() - 1); Text t = new Text(sb.toString()); out[i++] = t; } return out; }
// Returns params string only, e.g. // application_id=774&auth_key=aY7WwSRmu2-GbfA&nonce=1451135156 private String getEncodedParamsOnlyString(boolean encoded) { StringBuilder paramsOnly = new StringBuilder(); if (parameters.size() > 0) { for (String key : parameters.keySet()) { String value = parameters.get(key); if (value != null) { String encodedValue = encoded ? URLEncoder.encode(value) : value; paramsOnly.append(String.format("%s=%s&", key, encodedValue)); } } // remove last '&' paramsOnly.deleteCharAt(paramsOnly.length() - 1); } return paramsOnly.toString(); }
/** * Create NGMON log namespace which will contain all calls for this logs. This method sets * granularity level of NGMON log messages. If original packageName length is longer then * applicationNamespaceLength property, make it shorter. * * @param packageName string to change * @return shortened packageName from NGMON length rules */ private static String createNamespace(String packageName) { int numberOfDots = Utils.countOfSymbolInText(packageName, "."); if (numberOfDots < Utils.getApplicationNamespaceLength()) { return packageName; } else { StringBuilder newPackageName = new StringBuilder(); String[] pckgs = packageName.split("\\.", Utils.getApplicationNamespaceLength() + 1); pckgs[pckgs.length - 1] = ""; for (String p : pckgs) { if (!p.equals("")) newPackageName.append(p).append("."); } // remove last extra dot newPackageName.deleteCharAt(newPackageName.length() - 1); return newPackageName.toString(); } }
public List<String> removeInvalidParentheses(String s) { // 由于是去掉最少的括号,所以以去掉括号的个数为BFS的层数.通过记录的方式减少不必要的访问(重复的访问子树),缩短时间的关键是备忘memorized // 标记在某一level是否已经找到一个合法的string,且其值表示在哪一level找到 int flag = -1; // 全局hashset,用作去重 Set<String> gset = new HashSet<String>(); Set<String> output = new HashSet<String>(); // 初始化BFS的队列Q Deque<Node> q = new ArrayDeque<Node>(); Node root = new Node(s, 0); q.addLast(root); while (!q.isEmpty()) { Node u = q.removeFirst(); String subs = u.s; // 说明已经找到全部,返回结果即可,这里很巧妙 if ((u.depth == (flag + 1)) && flag != -1) { break; } if (checkValid(subs) == 0) { // 说明合法,结束本次循环,并不检测深一层的子树,但要检测完同一level的所有节点 if (flag == -1) flag = u.depth; output.add(subs); continue; } else { // u.s无效,分两种情况讨论:a.flag==-1,说明还没找到合适的,所以要将子树都填加 b.flag!=-1,说明在该level已经找到,不必再添加子树 if (flag != -1) { continue; } else { for (int i = 0; i < subs.length(); i++) { StringBuilder sb = new StringBuilder(subs); sb.deleteCharAt(i); String ssubs = sb.toString(); if (!gset.contains(ssubs)) { gset.add(ssubs); Node n = new Node(ssubs, u.depth + 1); q.addLast(n); } } } } } return new ArrayList<String>(output); }
public static void list( JsonArray attributes, Integer skip, Integer limit, TransactionHelper transactionHelper) { StringBuilder query = new StringBuilder("MATCH (s:Structure) "); JsonObject params = new JsonObject(); if (attributes != null && attributes.size() > 0) { query.append("RETURN DISTINCT"); for (Object attribute : attributes) { query.append(" s.").append(attribute).append(" as ").append(attribute).append(","); } query.deleteCharAt(query.length() - 1); query.append(" "); } else { query.append("RETURN DISTINCT s "); } if (skip != null && limit != null) { query.append("ORDER BY externalId ASC " + "SKIP {skip} " + "LIMIT {limit} "); params.putNumber("skip", skip); params.putNumber("limit", limit); } transactionHelper.add(query.toString(), params); }
public void getHelp(Caller caller, Workspace workspace, LinkedList<String> tokens) { WorkspaceService service = plugin.getWorkspaceService(); String source = service.getWorkspaceName(caller.getSender()); String firstToken = tokens.pollFirst(); if (firstToken == null) firstToken = ""; MetaClass callerScriptMetaClass = InvokerHelper.getMetaClass(CallerScript.class); MetaClass workspaceMetaClass = InvokerHelper.getMetaClass(Workspace.class); Map workspaceVars = null; if (workspace != null) workspaceVars = workspace.getBinding().getVariables(); Map globalVars = service.getBinding().getVariables(); PreparedScriptProperties properties = new PreparedScriptProperties(); properties.setCaller(caller); properties.setServer(plugin.getServer()); properties.setWorkspace(workspace); if (tokens.isEmpty()) { // get current method or class if (firstToken.equals("_")) { Object result = caller.getLastResult(); String type = "null"; if (result != null) type = result.getClass().getName(); caller.sendPrintMessage("Last result: " + AQUA + type + RESET, source); return; } MetaProperty prop = callerScriptMetaClass.getMetaProperty(firstToken); if (prop != null) { caller.sendPrintMessage( String.format( "Script property %s: %s", YELLOW + prop.getName() + RESET, AQUA + prop.getType().getName() + RESET), source); return; } Class compClass = service.getImportTabCompleteClasses().get(firstToken); if (compClass != null) { String type = "Class"; if (compClass.isInterface()) type = "Interface"; else if (compClass.isEnum()) type = "Enum class"; StringBuilder buf = new StringBuilder(); Class superClass = compClass.getSuperclass(); buf.append(type).append(" ").append(YELLOW).append(compClass.getName()).append(RESET); if (superClass != null) { buf.append(" extends ").append(AQUA).append(superClass.getName()).append(RESET); } caller.sendPrintMessage(buf, source); return; } for (MetaMethod metaMethod : callerScriptMetaClass.getMetaMethods()) { String name = metaMethod.getName(); String methodEnd = "("; if (metaMethod.isValidMethod(new Class[] {Closure.class})) methodEnd = "{"; else if (metaMethod.getParameterTypes().length == 0) methodEnd = "()"; if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) { StringBuilder buf = new StringBuilder(); buf.append("Script meta method ") .append(YELLOW) .append(metaMethod.getName()) .append(RESET); buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName()); buf.append(RESET).append('\n'); Class[] types = metaMethod.getNativeParameterTypes(); buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n'); for (Class type : types) buf.append(AQUA).append(type.getName()).append('\n').append(RESET); buf.deleteCharAt(buf.length() - 1); caller.sendPrintMessage(buf, source); } int args = metaMethod.getParameterTypes().length; if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1) && name.length() > 3) { String propertyName = getPropertyName(name); if (propertyName != null && propertyName.equals(firstToken)) { caller.sendPrintMessage( String.format( "Script meta getter %s returns %s", YELLOW + name + "()" + RESET, AQUA + metaMethod.getReturnType().getName() + RESET), source); } } } for (MetaMethod metaMethod : workspaceMetaClass.getMetaMethods()) { String name = metaMethod.getName(); String methodEnd = "("; if (metaMethod.isValidMethod(new Class[] {Closure.class})) methodEnd = "{"; else if (metaMethod.getParameterTypes().length == 0) methodEnd = "()"; if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) { StringBuilder buf = new StringBuilder(); buf.append("Workspace meta method ") .append(YELLOW) .append(metaMethod.getName()) .append(RESET); buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName()); buf.append(RESET).append('\n'); Class[] types = metaMethod.getNativeParameterTypes(); buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n'); for (Class type : types) buf.append(AQUA).append(type.getName()).append(RESET).append('\n'); buf.deleteCharAt(buf.length() - 1); caller.sendPrintMessage(buf, source); } } for (Method method : CallerScript.class.getMethods()) { String name = method.getName(); String methodEnd = "("; Class<?>[] params = method.getParameterTypes(); if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{"; else if (params.length == 0) methodEnd = "()"; if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) { StringBuilder buf = new StringBuilder(); buf.append("Script method ").append(YELLOW).append(method.getName()).append(RESET); buf.append(" returns ").append(AQUA).append(method.getReturnType().getName()); buf.append(RESET).append('\n'); buf.append("arguments: ").append(YELLOW).append(params.length).append(RESET).append('\n'); for (Class<?> type : params) buf.append(AQUA).append(type.getName()).append(RESET).append('\n'); buf.deleteCharAt(buf.length() - 1); caller.sendPrintMessage(buf, source); } int args = params.length; if ((name.startsWith("get") && args == 0 || name.startsWith("set") && args == 1) && name.length() > 3) { String propertyName = getPropertyName(name); if (propertyName != null && propertyName.equals(firstToken)) { caller.sendPrintMessage( String.format( "Script getter %s returns %s", YELLOW + name + "()" + RESET, AQUA + method.getReturnType().getName() + RESET), source); } } } for (Method method : Workspace.class.getMethods()) { String name = method.getName(); String methodEnd = "("; Class<?>[] params = method.getParameterTypes(); if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{"; else if (params.length == 0) methodEnd = "()"; if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) { StringBuilder buf = new StringBuilder(); buf.append("Workspace method ").append(YELLOW).append(method.getName()).append(RESET); buf.append(" returns ").append(AQUA).append(method.getReturnType().getName()); buf.append(RESET).append('\n'); buf.append("arguments: ").append(YELLOW).append(params.length).append(RESET).append('\n'); for (Class<?> type : params) buf.append(AQUA).append(type.getName()).append(RESET).append('\n'); buf.deleteCharAt(buf.length() - 1); caller.sendPrintMessage(buf, source); } } if (workspaceVars != null) { Object result = workspaceVars.get(firstToken); if (result != null || workspaceVars.containsKey(firstToken)) { caller.sendPrintMessage( String.format( "Workspace variable %s: %s", YELLOW + firstToken + RESET, AQUA + (result == null ? "null" : result.getClass().getName()) + RESET), source); return; } } if (globalVars != null) { Object result = globalVars.get(firstToken); if (result != null || globalVars.containsKey(firstToken)) { caller.sendPrintMessage( String.format( "Workspace variable %s: %s", YELLOW + firstToken + RESET, AQUA + (result == null ? "null" : result.getClass().getName()) + RESET), source); return; } } for (GroovyObject modifier : CallerScript.getDynamicModifiers()) { Object[] params = {properties}; try { Map<?, ?> map = (Map) modifier.getMetaClass().invokeMethod(modifier, "getPropertyMapFor", params); Object result = map.get(firstToken); if (result != null || map.containsKey(firstToken)) { Class resultClass = result instanceof Class ? (Class) result : null; caller.sendPrintMessage( String.format( "Dynamic variable %s: %s", YELLOW + firstToken + RESET, AQUA + (resultClass == null ? "unknown type" : resultClass.getName()) + RESET), source); } } catch (Exception ignored) { } try { Map<?, ?> map = (Map) modifier.getMetaClass().invokeMethod(modifier, "getMethodMapFor", params); String funToken = firstToken; if (funToken.endsWith("(")) funToken = firstToken.substring(0, funToken.length() - 1); Object result = map.get(funToken); if (result != null || map.containsKey(funToken)) { Class resultClass = result instanceof Class ? (Class) result : null; caller.sendPrintMessage( String.format( "Dynamic function %s: %s", YELLOW + firstToken + RESET, AQUA + (resultClass == null ? "unknown type" : resultClass.getName()) + RESET), source); } } catch (Exception ignored) { } } return; } MetaClass metaClass = getFirstTokenMeta( caller, firstToken, caller.getSender(), service, callerScriptMetaClass, workspaceMetaClass, workspace, workspaceVars, globalVars, properties); boolean classHook = tokens.size() <= 1 && service.getImportTabCompleteClasses().containsKey(firstToken); metaClass = skipTokens(tokens, metaClass); if (metaClass == null) return; // select property or method of last metaclass String token = tokens.pollFirst(); Class theClass = metaClass.getTheClass(); MetaProperty metaProperty = metaClass.getMetaProperty(token); if (metaProperty != null) { caller.sendPrintMessage( String.format( "Meta property %s: %s", YELLOW + token + RESET, AQUA + metaProperty.getType().getName() + RESET), source); } for (MetaMethod metaMethod : metaClass.getMetaMethods()) { String name = metaMethod.getName(); String methodEnd = "("; Class<?>[] params = metaMethod.getNativeParameterTypes(); if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{"; else if (params.length == 0) methodEnd = "()"; if (token.equals(name) || token.equals(name + methodEnd)) { StringBuilder buf = new StringBuilder(); buf.append("Meta method ").append(YELLOW).append(metaMethod.getName()).append(RESET); buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName()); buf.append(RESET).append('\n'); Class[] types = metaMethod.getNativeParameterTypes(); buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n'); for (Class type : types) buf.append(AQUA).append(type.getName()).append(RESET).append('\n'); buf.deleteCharAt(buf.length() - 1); caller.sendPrintMessage(buf, source); } int args = params.length; if (name.startsWith("get") && args == 0 && name.length() > 3) { String propertyName = getPropertyName(name); if (propertyName != null && propertyName.equals(token)) { caller.sendPrintMessage( String.format( "Meta getter %s returns %s", YELLOW + name + "()" + RESET, AQUA + metaMethod.getReturnType().getName() + RESET), source); } } } for (Method method : theClass.getMethods()) { String name = method.getName(); String methodEnd = "("; Class<?>[] params = method.getParameterTypes(); if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{"; else if (params.length == 0) methodEnd = "()"; if (token.equals(name) || token.equals(name + methodEnd)) { StringBuilder buf = new StringBuilder(); buf.append("Method ").append(YELLOW).append(method.getName()).append(RESET); buf.append(" returns ").append(AQUA).append(method.getReturnType().getName()); buf.append(RESET).append('\n'); Class[] types = method.getParameterTypes(); buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n'); for (Class type : types) buf.append(AQUA).append(type.getName()).append(RESET).append('\n'); buf.deleteCharAt(buf.length() - 1); caller.sendPrintMessage(buf, source); } int args = params.length; if (name.startsWith("get") && args == 0 && name.length() > 3) { String propertyName = getPropertyName(name); if (propertyName != null && propertyName.equals(token)) { caller.sendPrintMessage( String.format( "Getter %s returns %s", YELLOW + name + "()" + RESET, AQUA + method.getReturnType().getName() + RESET), source); } } } if (Enum.class.isAssignableFrom(theClass)) { Enum[] enumValues = getEnumValues(theClass); if (enumValues != null) for (Enum anEnum : enumValues) { String name = anEnum.name(); if (name.equals(token)) { caller.sendPrintMessage( String.format( "Enum value %s: %s", YELLOW + name + RESET, AQUA + theClass.getName() + RESET), source); } } } if (classHook) { MetaProperty property = InvokerHelper.getMetaClass(Class.class).getMetaProperty(token); if (property != null) { caller.sendPrintMessage( String.format( "Meta property %s: %s", YELLOW + token + RESET, AQUA + property.getType().getName() + RESET), source); } for (MetaMethod metaMethod : InvokerHelper.getMetaClass(Class.class).getMetaMethods()) { String name = metaMethod.getName(); String methodEnd = "("; Class<?>[] params = metaMethod.getNativeParameterTypes(); if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{"; else if (params.length == 0) methodEnd = "()"; if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) { StringBuilder buf = new StringBuilder(); buf.append("Method ").append(YELLOW).append(metaMethod.getName()).append(RESET); buf.append(" returns ").append(AQUA).append(metaMethod.getReturnType().getName()); buf.append(RESET).append('\n'); Class[] types = metaMethod.getNativeParameterTypes(); buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n'); for (Class type : types) buf.append(AQUA).append(type.getName()).append(RESET).append('\n'); buf.deleteCharAt(buf.length() - 1); caller.sendPrintMessage(buf, source); } } for (Method method : Class.class.getMethods()) { String name = method.getName(); String methodEnd = "("; Class<?>[] params = method.getParameterTypes(); if (params.length == 1 && Closure.class.isAssignableFrom(params[0])) methodEnd = "{"; else if (params.length == 0) methodEnd = "()"; if (firstToken.equals(name) || firstToken.equals(name + methodEnd)) { StringBuilder buf = new StringBuilder(); buf.append("Method ").append(YELLOW).append(method.getName()).append(RESET); buf.append(" returns ").append(AQUA).append(method.getReturnType().getName()); buf.append(RESET).append('\n'); Class[] types = method.getParameterTypes(); buf.append("arguments: ").append(YELLOW).append(types.length).append(RESET).append('\n'); for (Class type : types) buf.append(AQUA).append(type.getName()).append(RESET).append('\n'); buf.deleteCharAt(buf.length() - 1); caller.sendPrintMessage(buf, source); } } } }