protected Map<String, String> getAttributes() { if (attributes != null) { return attributes; } attributes = new HashMap<String, String>(); matcher = ADDITIONAL_ATTRIBUTES_PATTERN.matcher(firstLine); if (matcher.find()) { String s; Matcher attributeMatcher; s = matcher.group(2); attributeMatcher = ADDITIONAL_ATTRIBUTE_PATTERN.matcher(s); while (attributeMatcher.find()) { String key; String value; key = attributeMatcher.group(1); value = attributeMatcher.group(2); attributes.put(key.toLowerCase(Locale.ENGLISH), value); } } return attributes; }
/** * Takes a line and looks for an archive request tag. If one is found, the information from the * tag is returned as an <CODE>ArchiveRequest</CODE>. If a tag is found, the data in the tag is * stored in the <CODE>HashMap</CODE> provided. * * @param currentLine The line in which to look for the archive tag. * @param group The <CODE>ArchiveGroup</CODE> to which to add the <CODE>ArchiveRequest</CODE>. Can * be <CODE>null</CODE>. * @param template The <CODE>Template</CODE> to which the <CODE>ArchiveRequest</CODE> belongs. * @return The archive request tag data as an instance of <CODE>ArchiveRequest</CODE>, <CODE>null * </CODE> if the line passed in does not contain an arFile tag. */ private ArchiveRequest parseArchiveRequestTag( String currentLine, ArchiveGroup group, Template template) { ArchiveRequest archiveTag; Matcher currentMatcher = archiveRequestPattern.matcher(currentLine); if (currentMatcher.find()) { String fileName = currentMatcher.group(1); archiveTag = template.getArchiveRequest(fileName); if (archiveTag == null) { archiveTag = new ArchiveRequest(fileName); template.addArchiveRequest(archiveTag); } if (group != null) { // Creating a new request object because the requests // in the groups flagged as not in database will mean the // group - request association is not in database. Requests // in the archiveRequests map flagged as not in database // means the request record is not there. String requestFileName = archiveTag.getFileName(); String requestFileLocation = archiveTag.getFileLocation(); ArchiveRequest groupRequest = new ArchiveRequest(requestFileLocation, requestFileName); group.addArchiveRequest(groupRequest); } } else archiveTag = null; return archiveTag; }
@Override public void actionPerformed(ActionEvent e) { if (td.getTabCount() > 0) { TextDocument ta = (TextDocument) td.getComponentAt(td.getSelectedIndex()); Pattern pn = Pattern.compile(tf1.getText()); Matcher mt = pn.matcher(ta.getText()); if (e.getSource() == jb2) { // 取代 ta.setText(mt.replaceAll(tf2.getText())); } else if (e.getSource() == jb1) { // 尋找 Highlighter hl = ta.getHighlighter(); hl.removeAllHighlights(); while (mt.find()) { try { hl.addHighlight( mt.start(), mt.end(), new DefaultHighlighter.DefaultHighlightPainter(null)); } catch (Exception ex) { } } // 開啟及關閉介面 } else if (e.getSource() == replace_searchMenuItem) { System.out.println("Replace/Search is show:" + !show); if (show) { getContentPane().remove(jp); show = false; } else { getContentPane().add(jp, BorderLayout.SOUTH); show = true; } validate(); // 刷新容器 } } else if (e.getSource() == replace_searchMenuItem) { JOptionPane.showMessageDialog( null, "尚無檔案,無法使用!", "Repace/Search error", JOptionPane.ERROR_MESSAGE); } }
private InstanceList readFile() throws IOException { String NL = System.getProperty("line.separator"); Scanner scanner = new Scanner(new FileInputStream(fileName), encoding); ArrayList<Pipe> pipeList = new ArrayList<Pipe>(); pipeList.add(new CharSequence2TokenSequence(Pattern.compile("\\p{L}\\p{L}+"))); pipeList.add(new TokenSequence2FeatureSequence()); InstanceList testing = new InstanceList(new SerialPipes(pipeList)); try { while (scanner.hasNextLine()) { String text = scanner.nextLine(); text = text.replaceAll("\\x0d", ""); Pattern patten = Pattern.compile("^(.*?),(.*?),(.*)$"); Matcher matcher = patten.matcher(text); if (matcher.find()) { docIds.add(matcher.group(1)); testing.addThruPipe(new Instance(matcher.group(3), null, "test instance", null)); } } } finally { scanner.close(); } return testing; }
public static void main(String[] args) throws IOException { // Get input html StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (String str = in.readLine(); str != null; str = in.readLine()) { sb.append("\n" + str); } String html = sb.toString(); // Match all the questions Matcher matcher = Pattern.compile( "<\\s*div\\s+class\\s*=\\s*\"question-summary\"\\s*id\\s*=\\s*\"question-summary-(?<id>\\d+)\"\\s*>" + ".*?<\\s*div\\s+class\\s*=\\s*\"summary\"\\s*>" + ".*?<\\s*a\\s+.*?class\\s*=\\s*\"question-hyperlink\"\\s*>" + "(?<title>.*?)" + "</\\s*a\\s*>.*?<\\s*div\\s+class\\s*=\\s*\"user-action-time\"\\s*>" + ".*?<\\s*span\\s+.*?>(?<time>.*?)</\\s*span\\s*>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL) .matcher(html); // Output the information while (matcher.find()) { String id = matcher.group("id"); String title = matcher.group("title"); String time = matcher.group("time"); System.out.println(id + ";" + title + ";" + time); } }
/** * Get dependencies of a source file. * * @param path The canonical path of source file. * @return Path of dependencies. */ private ArrayList<String> getDependencies(String path) { if (!dependenceMap.containsKey(path)) { ArrayList<String> dependencies = new ArrayList<String>(); Matcher m = PATTERN_REQUIRE.matcher(read(path, charset)); while (m.find()) { // Decide which root path to use. // Path wrapped in <> is related to root path. // Path wrapped in "" is related to parent folder of the source file. String root = null; if (m.group(1).equals("<")) { root = this.root; } else { root = new File(path).getParent(); } // Get path of required file. String required = m.group(2); File f = new File(root, required); if (f.exists()) { dependencies.add(canonize(f)); } else { App.exit("Cannot find required file " + required + " in " + path); } } dependenceMap.put(path, dependencies); } return dependenceMap.get(path); }
public synchronized String format(String message) { Matcher matcher = variablePattern.matcher(message); while (matcher.find()) { String variable = matcher.group(); variable = variable.substring(1); if (variable.startsWith("{") && variable.endsWith("}")) variable = variable.substring(1, variable.length() - 1); String value = variables.get(variable); if (value == null) value = ""; message = message.replaceFirst(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value)); } matcher = colorPattern.matcher(message); while (matcher.find()) message = message.substring(0, matcher.start()) + "\247" + message.substring(matcher.end() - 1); return message; }
public BasicSpellChecker(String file) throws IOException { BufferedReader in = new BufferedReader(new FileReader(file)); Pattern p = Pattern.compile("\\w+"); for (String temp = ""; temp != null; temp = in.readLine()) { Matcher m = p.matcher(temp.toLowerCase()); while (m.find()) nWords.put((temp = m.group()), nWords.containsKey(temp) ? nWords.get(temp) + 1 : 1); } in.close(); }
public int getStatus() { if (status != null) { return status; } matcher = STATUS_PATTERN.matcher(firstLine); if (matcher.find()) { status = Integer.parseInt(matcher.group(1)); } return status; }
public String getResult() { if (result != null) { return result; } matcher = RESULT_PATTERN.matcher(firstLine); if (matcher.find()) { result = matcher.group(1); } return result; }
private static List<String> loadAccounts(String fileName) { List<String> accounts = new ArrayList<String>(); try { Pattern pattern = Pattern.compile("[\\w]{1,16}"); BufferedReader reader = new BufferedReader(new FileReader(new File(fileName))); String line; while ((line = reader.readLine()) != null) { Matcher matcher = pattern.matcher(line); if (!matcher.find()) continue; String username = matcher.group(); if (!matcher.find()) continue; String password = matcher.group(); accounts.add(username + ":" + password); } reader.close(); } catch (Exception exception) { throw new RuntimeException(exception); } System.out.println("Loaded " + accounts.size() + " accounts."); return accounts; }
void findRemoveDirectives(boolean clean) { // if ( clean ) editor.startCompoundEdit(); Sketch sketch = editor.getSketch(); for (int i = 0; i < sketch.getCodeCount(); i++) { SketchCode code = sketch.getCode(i); String program = code.getProgram(); StringBuffer buffer = new StringBuffer(); Matcher m = pjsPattern.matcher(program); while (m.find()) { String mm = m.group(); // TODO this urgently needs tests .. /* remove framing */ mm = mm.replaceAll("^\\/\\*\\s*@pjs", "").replaceAll("\\s*\\*\\/\\s*$", ""); /* fix multiline nice formatting */ mm = mm.replaceAll("[\\s]*([^;\\s\\n\\r]+)[\\s]*,[\\s]*[\\n\\r]+", "$1,"); /* fix multiline version without semicolons */ mm = mm.replaceAll("[\\s]*([^;\\s\\n\\r]+)[\\s]*[\\n\\r]+", "$1;"); mm = mm.replaceAll("\n", " ").replaceAll("\r", " "); // System.out.println(mm); if (clean) { m.appendReplacement(buffer, ""); } else { String[] directives = mm.split(";"); for (String d : directives) { // System.out.println(d); parseDirective(d); } } } if (clean) { m.appendTail(buffer); // TODO: not working! code.setProgram(buffer.toString()); code.setModified(true); } } if (clean) { // editor.stopCompoundEdit(); editor.setText(sketch.getCurrentCode().getProgram()); sketch.setModified(false); sketch.setModified(true); } }
/** * Takes a line and looks for an archive group tag. If one is found, the information from the tag * is returned as an <CODE>ArchiveGroup</CODE>. If a tag is found, the data in the tag is stored * in the <CODE>HashMap</CODE> provided. * * @param currentLine The line in which to look for the archive tag. * @param template The <CODE>Template</CODE> to which the <CODE>ArchiveGroup</CODE> belongs. * @return The archive request tag data as an instance of <CODE>ArchiveGroup</CODE>, <CODE>null * </CODE> if the line passed in does not contain an arFile tag. */ private ArchiveGroup parseArchiveGroupTag(String currentLine, Template template) { ArchiveGroup archiveTag; Matcher currentMatcher = archiveRequestPattern.matcher(currentLine); if (currentMatcher.find()) { String fileName = currentMatcher.group(1); archiveTag = template.getArchiveGroup(fileName); if (archiveTag == null) { File groupFile = new File(fileName); archiveTag = new ArchiveGroup(groupFile.getParent(), groupFile.getName()); template.addArchiveGroup(archiveTag); } } else archiveTag = null; return archiveTag; }
public void run() { // each file is processed into a local hash table and then merged with the global results // this will cause much less contention on the global table, but still avoids a sequential // update Hashtable<String, Integer> local_results = new Hashtable<String, Integer>(WordCountJ.HASH_SIZE, WordCountJ.LF); // grab a file to work on String cf; while ((cf = files.poll()) != null) { try { BufferedReader input = new BufferedReader(new FileReader(cf)); String text; // well go line-by-line... maybe this is not the fastest while ((text = input.readLine()) != null) { // parse words Matcher matcher = pattern.matcher(text); while (matcher.find()) { String word = matcher.group(1); if (local_results.containsKey(word)) { local_results.put(word, 1 + local_results.get(word)); } else { local_results.put(word, 1); } } } input.close(); } catch (Exception e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); return; } // merge local hashmap with shared one,could have a // seperate thread do this but that might be cheating Iterator<Map.Entry<String, Integer>> updates = local_results.entrySet().iterator(); while (updates.hasNext()) { Map.Entry<String, Integer> kv = updates.next(); String k = kv.getKey(); Integer v = kv.getValue(); synchronized (results) { if (results.containsKey(k)) { results.put(k, v + results.get(k)); } else { results.put(k, v); } } } local_results.clear(); } }
/** Set this news object using the news specified by newsFile */ public void setNews(String newsFile) throws IOException { Pattern pDocId = Pattern.compile("<DOC-ID>(.*)</DOC-ID>"); Pattern pTitle = Pattern.compile("<TITLE>(.*)</TITLE>"); Pattern pTimestamp = Pattern.compile("<TIMESTAMP>(.*)</TIMESTAMP>"); Pattern pContent = Pattern.compile("<CONTENT>(.*)</CONTENT>"); Matcher m = null; BufferedReader br = new BufferedReader(new FileReader(newsFile)); String line = ""; String news = ""; while ((line = br.readLine()) != null) { news += line; } // get news metadata and content m = pDocId.matcher(news); if (m.find()) { this.docId = m.group(1); } m = pTitle.matcher(news); if (m.find()) { this.title = m.group(1); } m = pTimestamp.matcher(news); if (m.find()) { this.timestamp = m.group(1); } m = pContent.matcher(news); if (m.find()) { this.content = m.group(1); } }
public static void t1986main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder reg = new StringBuilder(); reg.append(in.readLine()); String sent; Pattern pattern = Pattern.compile(reg.toString()); Matcher matcher; while (in.ready()) { sent = in.readLine(); matcher = pattern.matcher(sent); if (matcher.find()) System.out.println("YES"); else System.out.println("NO"); } System.exit(0); }
public static void main(String[] args) throws IOException { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); if (args.length != 1) { System.err.println("Usage: MatchLines pattern"); System.exit(1); } Pattern patt = Pattern.compile(args[0]); Matcher matcher = patt.matcher(""); String line = null; while ((line = is.readLine()) != null) { matcher.reset(line); if (matcher.find()) { System.out.println("MATCH: " + line); } } }
private void processResponse(InputStream response) throws IOException { Pattern p = Pattern.compile("<cdbId>\\s*(\\d+)"); BufferedReader in = new BufferedReader(new InputStreamReader(response)); String line = in.readLine(); while (line != null) { System.out.println(line); Matcher m = p.matcher(line); if (m.find()) { String idText = m.group(1); if (idText != null) { cdbId = Integer.parseInt(idText); } } line = in.readLine(); } }
public String getExtra() { if (getStatus() != SC_SUCCESS) { return null; } if (extraCreated) { return extra; } matcher = PARENTHESIS_PATTERN.matcher(firstLine); if (matcher.find()) { extra = matcher.group(1); } extraCreated = true; return extra; }
/** * Takes a line and looks for an archive tag. If one is found, the information from the tag is * returned as a <CODE>Signal</CODE>. If a signal ID is given in the tag, the data in the tag is * stored in the <CODE>HashMap</CODE> provided. * * @param currentLine The line in which to look for the archive tag. * @return The archive tag data as an instance of <CODE>Signal</CODE>, <CODE>null</CODE> if the * line passed in does not contain an arReq tag. */ private Signal parseArchiveTag(String currentLine) { Signal archiveTag; Matcher currentMatcher = archivePattern.matcher(currentLine); if (currentMatcher.find()) { archiveTag = new Signal(currentMatcher.group(1)); String frequency = currentMatcher.group(2); BigDecimal frequencyValue; if (frequency == null) frequencyValue = null; else frequencyValue = new BigDecimal(frequency); archiveTag.setArchiveFrequency(frequencyValue); String type = currentMatcher.group(3); if (type == null) type = "Monitor"; archiveTag.setArchiveType(type); archiveTag.setArchiveIndicator("Y"); } else archiveTag = null; return archiveTag; }
/** * Checks the specified template and adds a variable. * * @param tmp template string * @param type allowed type * @param declared variable declaration flags * @return resulting variable * @throws QueryException query exception */ private QNm checkVariable(final String tmp, final Type type, final boolean[] declared) throws QueryException { final Var[] args = function.args; final Matcher m = TEMPLATE.matcher(tmp); if (!m.find()) error(INV_TEMPLATE, tmp); final byte[] vn = token(m.group(1)); if (!XMLToken.isQName(vn)) error(INV_VARNAME, vn); final QNm qnm = new QNm(vn, context); int r = -1; while (++r < args.length && !args[r].name.eq(qnm)) ; if (r == args.length) error(UNKNOWN_VAR, vn); if (declared[r]) error(VAR_ASSIGNED, vn); final SeqType st = args[r].declaredType(); if (args[r].checksType() && !st.type.instanceOf(type)) error(INV_VARTYPE, vn, type); declared[r] = true; return qnm; }
private void addNonTerminal(String EBNF) { String p = "<([\\w-]+)>[\\s]*::=(" + "([\\s]*(<[\\w-]+>|(\"[^\"]*\")|[|\\[\\]{}])" + ")+)"; Matcher m = Pattern.compile(p).matcher(EBNF); m.find(); NonTerminal nt = new NonTerminal(m.group(1)); List<? extends EBNFBranch> branches = EBNFBranch.getBranches(m.group(2)); assert (branches.size() > 0); if (nonTerminals.size() == 0) { startSymbol = nt; } nonTerminals.put(nt, branches); }
public void addAllNonTerminals(File file) { String s = MyFileReader.read(file); // some more checking need to be added String p = "<[\\w-]+>[\\s]*::=(" + // where EBNF is diff from BNF "[\\s]*(<[\\w-]+>|(\"[^\"]*\")|[|\\[\\]{}])" + ")+" + "(?=(([\\s]*<[\\w-]+>[\\s]*::=)|[\\s]*\\z))"; Matcher m = Pattern.compile(p).matcher(s); while (m.find()) { addNonTerminal(m.group()); } }
public static void main(String args[]) { // System.out.println( "Starting Jinan..." ); LineNumberReader in = null; BufferedWriter out = null; try { in = new LineNumberReader(new FileReader("Jinan.txt")); out = new BufferedWriter(new FileWriter("format.txt")); } catch (IOException e) { System.out.println(e); System.exit(-1); } String line; // 下面的表达式为:以K或没有K开头,接着是若干数字,然后是“路”字。 // 注意()表示group,以便提取其中的信息 Pattern p = Pattern.compile("^([Kk]?\\d+路).*$"); Matcher m; boolean flag = true; try { while (true) { line = in.readLine(); if (line == null) break; else if (line.equals("")) continue; m = p.matcher(line); if (flag != m.find()) // 这里必须先用find()触发匹配过程,才能开始使用 throw new RuntimeException("File format error: " + in.getLineNumber()); if (flag == true) { out.write(m.group(1)); // group(0) is the entire string, group(1) is the right one out.write(" "); flag = false; } else { out.write(line); out.newLine(); flag = true; } } in.close(); out.close(); } catch (IOException e) { System.out.println(e); System.exit(-1); } }
public String getSynopsis() { if (getStatus() != SC_INVALID_COMMAND_SYNTAX) { return null; } if (synopsis == null) { if (lines.size() > 1) { String secondLine; Matcher synopsisMatcher; secondLine = lines.get(1); synopsisMatcher = SYNOPSIS_PATTERN.matcher(secondLine); if (synopsisMatcher.find()) { synopsis = synopsisMatcher.group(1); } } } return synopsis; }
protected void getDimensionsFromLogFile(BufferedReader reader, PicText text) { if (reader == null) { return; } String line = ""; // il rale si j'initialise pas ... boolean finished = false; while (!finished) { try { line = reader.readLine(); } catch (IOException ioex) { ioex.printStackTrace(); return; } if (line == null) { System.out.println("Size of text not found in log file..."); return; } System.out.println(line); Matcher matcher = LogFilePattern.matcher(line); if (line != null && matcher.find()) { System.out.println("FOUND :" + line); finished = true; try { text.setDimensions( 0.3515 * Double.parseDouble(matcher.group(1)), // height, pt->mm (1pt=0.3515 mm) 0.3515 * Double.parseDouble(matcher.group(2)), // width 0.3515 * Double.parseDouble(matcher.group(3))); // depth areDimensionsComputed = true; } catch (NumberFormatException e) { System.out.println("Logfile number format problem: $line" + e.getMessage()); } catch (IndexOutOfBoundsException e) { System.out.println("Logfile regexp problem: $line" + e.getMessage()); } } } return; }
/** * Replace occurrences of "%ab" with the character represented by the hex value. Strings of * escaped characters are treated as UTF-8 byte sequences and decoded appropriately. */ private static String decode(String s) { int length = s.length(); StringBuilder str = new StringBuilder(length); Matcher matcher = PATTERN.matcher(s); int offset = 0; byte[] bb = null; while (matcher.find(offset)) { int count = matcher.groupCount(); for (int i = 0; i < count; i++) { String match = matcher.group(0); int num = match.length() / 3; if (bb == null || bb.length < num) { bb = new byte[num]; } for (int j = 0; j < num; j++) { int head = j * 3 + 1; int tail = head + 2; bb[j] = (byte) Integer.parseInt(match.substring(head, tail), 16); } try { String text = new String(bb, "UTF-8"); str.append(s.substring(offset, matcher.start())); str.append(text); } catch (UnsupportedEncodingException e) { // NOTE: This should *never* be thrown because all // JVMs are required to support UTF-8. I mean, // the strings in the .class file are all in // a modified UTF-8, for pete's sake! :) } } offset = matcher.end(); } if (offset < length) { str.append(s.substring(offset)); } return str.toString(); }
private static boolean contains_exactly_one(String string, Pattern pattern) { Matcher m = pattern.matcher(string); // return true if first call returns true and second returns false return (m.find() && !m.find()); }
public CreateCplusplusHeader(GNode n) { classTree = n; /*Debug**/ // p1.println(classTree.size()); final PrintWriter p1; final GNode[] containsRelevantClasses; final ArrayList<String> stringClasses = new ArrayList<String>(); final ArrayList<Integer> countClasses = new ArrayList<Integer>(); final ArrayList<Integer> countChildren = new ArrayList<Integer>(); final GNode stac = GNode.create("Holder"); File headerFile; File newDirectory; try { newDirectory = new File("cplusplusfiles"); newDirectory.mkdir(); headerFile = new File("cplusplusfiles", "Header.h"); headerFile.createNewFile(); p1 = new PrintWriter(headerFile); /*Remove comments below to Debug**/ // p1.println(classTree.size()); // p1.println(containsRelevantClasses.size()); // p1.println(countClasses); // p1.println(countChildren); p1.println("// Ankit Goel's Header"); p1.println("#pragma once"); p1.println(); p1.println("#include <stdint.h>"); p1.println("#include <string>"); p1.println(); p1.println("using namespace java::lang;"); p1.println("// Foward Declarations "); p1.println(); /* Remove comments below to Debug**/ // String s = classTree.getNode(1).getNode(0).getNode(0).getName(); // p1.println(s); // p1.flush(); // p1.close(); new Visitor() { int counter22 = 0; public void visitClass(GNode n) { counter22++; countChildren.add(n.size()); countClasses.add(counter22); visit(n); } public void visitClassHeaderDeclaration(GNode n) { stac.add(n); /*Remove comments below to Debug**/ // p1.println(n.getNode(0).getName()); // containsRelevantClasses[counter22] = (GNode) n; } public void visit(Node n) { for (Object o : n) if (o instanceof Node) dispatch((Node) o); } }.dispatch(classTree); /*Remove comments below to Debug**/ // p1.println(stac.size()); String globalVariableArrayCheck; for (int b = 4; b < stac.size(); b++) { createCplusplusHeader = (GNode) stac.getNode(b); GNode vMethods = (GNode) createCplusplusHeader.getNode(0); // p1.println(createCplusplusHeader.getName()); /*Remove comments below to Debug**/ // p1.println(vMethods.getName()); // We need a mapping of methodName to accessibility final HashMap<String, String> mNAccess = new HashMap<String, String>(); /*Remove comments below to Debug**/ // We need a mapping to methodName to whetherItsStatic // p1.println(mNAccess); // p1.println(mNAccess.get("goel")); final GNode constructorPrinter = GNode.create("ConstructorPrinter"); final ArrayList<Integer> getCounter = new ArrayList<Integer>(); new Visitor() { int counter2 = 0; public void visitVirtualMethodDeclaration(GNode n) { counter2++; getCounter.add(counter2); } public void visit(Node n) { for (Object o : n) if (o instanceof Node) dispatch((Node) o); } }.dispatch(vMethods); int startHere = getCounter.get(getCounter.size() - 1) + 1; /*Remove comments below to Debug**/ // p1.println(startHere); final String className = vMethods.getNode(startHere).getNode(4).getNode(0).getString(0); final String plainClassName = className.substring(2, className.length()); final GNode ARRAYTRACKER = GNode.create("ArrayTracker"); // Need another dispatch for constructor heeader node new Visitor() { public void visitConstructorHeader(GNode n) { // Add each node if (n.getString(0).equals(plainClassName)) constructorPrinter.add(n); } public void visitCustomArrayDeclaration(GNode n) { ARRAYTRACKER.add(n); } public void visit(Node n) { for (Object o : n) if (o instanceof Node) dispatch((Node) o); } }.dispatch(createCplusplusHeader); // p1.println(constructorPrinter.size()); // Find out when the virtual method declarations ends /*Remove comments below to Debug**/ // p1.println(getCounter); p1.println("struct __" + plainClassName + ";"); p1.println(); p1.println("struct __" + plainClassName + "_VT;"); p1.println(); p1.println("typedef __rt::Ptr<" + "__" + plainClassName + "> " + plainClassName + ";"); p1.println(); p1.println("struct __" + plainClassName + " { "); p1.println(); p1.println(" // The data layout for java.lang.plainClassName"); p1.println(" " + "__" + plainClassName + "_VT* __vptr;"); // Get the Field Decl in this final GNode fields = GNode.create("Fields"); new Visitor() { public void visitDataLayoutDeclaration(GNode n) { visit(n); } public void visitDataFieldList(GNode n) { fields.add(n); } public void visit(Node n) { for (Object o : n) if (o instanceof Node) dispatch((Node) o); } }.dispatch(createCplusplusHeader); // p1.println(fields.size()); final ArrayList<String> privateOrpublic = new ArrayList<String>(); final ArrayList<String> PrimitiveType = new ArrayList<String>(); final ArrayList<String> Decl = new ArrayList<String>(); new Visitor() { public void visitDataFieldList(GNode n) { visit(n); } public void visitFieldDeclaration(GNode n) { // if (n.getNode(0).size() > 0 ) // privateOrpublic.add(n.getNode(0).getNode(0).getString(0)); /* if (n.getNode(0).getNode(0).getString(0).equals("static") && n.getNode(1).getNode(0).getString(0).equals("int") ) PrimitiveType.add("static const int32_t "); **/ if (n.getNode(1).getNode(0).getString(0).equals("int") && n.toString().contains("static")) PrimitiveType.add(" static int32_t"); else PrimitiveType.add(n.getNode(1).getNode(0).getString(0)); Decl.add(n.getNode(2).getNode(0).getString(0)); /* else Decl.add(n.getNode(2).getNode(0).getString(0) + " = " + n.getNode(2).getNode(0).getNode(2).getString(0)); **/ } public void visit(Node n) { for (Object o : n) if (o instanceof Node) dispatch((Node) o); } }.dispatch(fields); // Print out the Data Fields for (int c = 0; c < Decl.size(); c++) { p1.println(); p1.println(" " + PrimitiveType.get(c) + " " + Decl.get(c) + ";"); } List<String> typeOfParameter = new ArrayList<String>(); List<String> DECLARATOR = new ArrayList<String>(); // p1.println(constructorPrinter); for (int ccd = 0; ccd < constructorPrinter.size(); ccd++) { // There is more than one parameter if (constructorPrinter.getNode(ccd).getNode(1).size() >= 1) { GNode GETPARAMS = GNode.create("GETPARAMS"); GETPARAMS.add(constructorPrinter.getNode(ccd).getNode(1)); // p1.println(GETPARAMS); // Now Go through the Formal Parameters for (int dcc = 0; dcc < GETPARAMS.size(); dcc++) { typeOfParameter.add( GETPARAMS.getNode(0).getNode(dcc).getNode(1).getNode(0).getString(0)); DECLARATOR.add(GETPARAMS.getNode(0).getNode(dcc).getString(3)); } } else { p1.println(); p1.println(" " + className + "();"); } } if (DECLARATOR.size() >= 1 && typeOfParameter.size() >= 1) { p1.print(className + "( "); for (int goela = 0; goela < typeOfParameter.size(); goela++) { if (goela != typeOfParameter.size() - 1) p1.print(typeOfParameter.get(goela) + " " + DECLARATOR.get(goela) + ","); else p1.print(typeOfParameter.get(goela) + " " + DECLARATOR.get(goela) + ");"); } } p1.println(); if ((constructorPrinter.size() == 0)) { p1.println(); p1.println(" " + "// The Constructor"); p1.println(); p1.println(" " + "__" + plainClassName + "(); "); } // Find Instance Methods of the class Basically go through vtMethodPointersList and // go through its children and check if the qualified identifier is the same as the clas // name // Store the names in a Arraylist type final List<String> names = new ArrayList<String>(); List<String> types2 = new ArrayList<String>(); final List<Integer> indexx = new ArrayList<Integer>(); final HashMap<Integer, String> checkForOtherSuperClass = new HashMap<Integer, String>(); // final HashMap<String,String> checkForPredefinedMethods = new HashMap<String,String>(); // Basically You need to consider this fact there will be however so many Constructors and // you need to keep a tally to start it like that and // Ignore those indices final List<Integer> constuctorIndex = new ArrayList<Integer>(); final GNode constructors = GNode.create("CONSTRUCTOR"); final String constructorNameGetter = plainClassName; // p1.println(constructors.size()); // p1.println(constructorNameGetter); // Lets find out which methods are unique new Visitor() { public int counter = 0; public void visitVTConstructorDeclaration(GNode n) { visit(n); } public void visitvtMethodPointersList(GNode n) { visit(n); } public void visitvtMethodPointer(GNode n) { counter++; if (!(n.getNode(1).getString(1).equals("__Object")) && !(n.getString(0).equals("main_String"))) { // constructorIndex.add(counter); // p1.println(n.getString(0)); indexx.add(counter); names.add(n.getString(0)); // There needs to be a check for the other than __Object && __SuperClass checkForOtherSuperClass.put(counter, n.getNode(1).getString(1)); // checkForPredefinedMethods.put(n.getString(0), n.getNode(1).getString(1)); } else { checkForOtherSuperClass.put(counter, n.getNode(1).getString(1)); // constructors.add(n); } } public void visit(Node n) { for (Object o : n) if (o instanceof Node) dispatch((Node) o); } }.dispatch(vMethods); // p1.println(names); // p1.println("Constructors" + constructors.size()); // p1.println(checkForOtherSuperClass); // System.out.println("ARRAY CONTENTS" + names); // Now lets get the type of the method and store it in Types arraylist // Visit the Method Declarations of the Java AST and store the types in order into an array. // Then // store the corresponding names of the methods in another array then do matching to // determine the // the types of the method // p1.println(checkForOtherSuperClass); for (int i = 0; i < indexx.size(); i++) { if (vMethods.getNode(indexx.get(i)).getGeneric(0) != null) { if (vMethods.getNode(indexx.get(i)).getNode(0).getName().equals("Type")) { // I think there only needs to be one check for a bool value the rest translate as is if (vMethods .getNode(indexx.get(i)) .getNode(0) .getNode(0) .getString(0) .equals("boolean")) types2.add("bool"); else types2.add(vMethods.getNode(indexx.get(i)).getNode(0).getNode(0).getString(0)); } else types2.add("void"); } else { types2.add(" "); } } // p1.println(types2); // p1.println(names); // params are appended to the methods name List<String> specialnames = new ArrayList<String>(); // A single method name which is a string could essential map to however many Strings Map<String, String> parameters = new HashMap<String, String>(); // Remove anything after _ in the method these are the parameters that are appended to it for (int i = 0; i < names.size(); i++) { Pattern p = Pattern.compile("_"); Matcher m = p.matcher(names.get(i)); if (m.find()) { // p1.println("FOUND"); // p1.println(m.start()); // ****** Changed // specialnames.add(names.get(i).substring(0,m.start())); specialnames.add(names.get(i)); // Money.add(names.get(i)); parameters.put( specialnames.get(i), names.get(i).substring(m.start(), names.get(i).length())); } else { specialnames.add(names.get(i)); // The hashmap needs to be consistent parameters.put(names.get(i), "ZeroParams"); } } // p1.println(names); // p1.println(parameters); // p1.println(types2); // p1.println(parameters); // Now print the instance methods using the types and names p1.println(" // The instance methods of java.lang.plainClassName"); // p1.println(specialnames); // Constructor Initializeer p1.println(" static " + plainClassName + " init_Construct( " + plainClassName + "); "); for (int i = 0; i < types2.size(); i++) { if (parameters.get(specialnames.get(i)).equals("ZeroParams") && !(specialnames.get(i).equals(plainClassName))) p1.println( " " + "static " + types2.get(i) + " " + specialnames.get(i) + "( " + plainClassName + ")" + ";"); else { if (!(specialnames.get(i).equals(plainClassName))) { ArrayList<Integer> getTheParameters = new ArrayList<Integer>(); p1.print( " " + "static " + types2.get(i) + " " + specialnames.get(i) + "( " + plainClassName + " , "); Pattern pp = Pattern.compile("_"); Matcher mm = pp.matcher(parameters.get(specialnames.get(i))); while (mm.find()) { getTheParameters.add(mm.start()); } for (int cc = 0; cc < getTheParameters.size(); cc++) { if (cc != getTheParameters.size() - 1) { p1.print( parameters .get(specialnames.get(i)) .substring(getTheParameters.get(cc) + 1, getTheParameters.get(cc + 1)) + " , "); } else { int length = parameters.get(specialnames.get(i)).length(); p1.print( parameters .get(specialnames.get(i)) .substring(getTheParameters.get(cc) + 1, length) + ");"); } } p1.println(); } } } p1.println(); p1.println( " // The Function returning the class Object representing java.lang.plainClassName "); p1.println(" static Class __class(); "); p1.println(" static void init( " + "__" + plainClassName + "*" + " );"); p1.println(); // Changes for Command line arguements if (plainClassName.contains("Test")) { p1.println(" static void main(__rt::Ptr<__rt::Array<String> > args);"); } p1.println(" static __" + plainClassName + "_" + "VT " + "__vtable;"); p1.println(); p1.println(" };"); p1.println(); // Now print the Constructor taking into account which ones are implemented by the given // class p1.println("struct __" + plainClassName + "_" + "VT" + "{"); p1.println(" Class __isa;"); // Introduce some logic to differentiate between new methods and predefined inherited method // from Object List<String> arr1 = new ArrayList<String>(); arr1.add("hashcode"); arr1.add("equals"); arr1.add("getClass"); arr1.add("toString"); arr1.add("getName"); arr1.add("getSuperClass"); arr1.add("isInstance"); // Basically iterate through map and add any methods that have a type not equal to the // You need to add the inherited types p1.println(" void (*__delete)(__" + plainClassName + "*);"); p1.println(" int32_t (*hashCode)(" + plainClassName + ");"); p1.println(" bool (*equals)(" + plainClassName + " , " + "Object);"); p1.println(" Class (*getClass)(" + plainClassName + ");"); p1.println(" String (*toString) (" + plainClassName + ");"); for (int i = 0; i < names.size(); i++) { if (!(arr1.contains(names.get(i)))) { p1.println(); ArrayList<Integer> getTheParameters = new ArrayList<Integer>(); if (parameters.get(specialnames.get(i)).equals("ZeroParams") && !(specialnames.get(i).equals(plainClassName))) p1.println( " " + types2.get(i) + " (*" + specialnames.get(i) + ") (" + plainClassName + ");"); else { if (!(specialnames.get(i).equals(plainClassName))) { Pattern pp = Pattern.compile("_"); Matcher mm = pp.matcher(parameters.get(specialnames.get(i))); while (mm.find()) { getTheParameters.add(mm.start()); } p1.print( " " + types2.get(i) + " (*" + specialnames.get(i) + ") (" + plainClassName + " , "); for (int cc = 0; cc < getTheParameters.size(); cc++) { if (cc != getTheParameters.size() - 1) { p1.print( parameters .get(specialnames.get(i)) .substring( getTheParameters.get(cc) + 1, getTheParameters.get(cc + 1)) + " , "); } else { int length = parameters.get(specialnames.get(i)).length(); p1.print( parameters .get(specialnames.get(i)) .substring(getTheParameters.get(cc) + 1, length) + ");"); } } } // p1.println(getTheParameters); } } } p1.println(); p1.println(); // Now the constructor initilization inlined in the header p1.println(" __" + plainClassName + "_VT()"); p1.println(" : __isa(__" + plainClassName + "::__class()),"); List<String> getImplementation = new ArrayList<String>(); int COUNT = 0; // Are there any instance methods for (int i = 0; i < specialnames.size(); i++) { if (!(specialnames.equals(plainClassName))) COUNT++; } // p1.println(COUNT); for (int i = 0; i < arr1.size(); i++) { if (names.contains(arr1.get(i))) { // Suppose a super class defines an Object method then this is wrong so add an // additional check // if(checkForPredefinedMethods.get(arr1.get(i)).equals("__" + plainClassName)) getImplementation.add(plainClassName); // else // getImplementation.add(checkForPredefinedMethods.get(arr1.get(i))); } else { getImplementation.add("Object"); } } // Remove comment to Debug // p1.println(getImplementation); p1.println(" __delete(&__rt::__delete<__" + plainClassName + ">),"); // Hardcoded May Need to Change in the final Phase if (getImplementation.get(0).equals("Object")) p1.println( " hashCode((int32_t(*)(" + plainClassName + "))" + "&__" + getImplementation.get(0) + "::hashCode),"); else p1.println(" hashCode(&__" + plainClassName + "::hashCode),"); if (getImplementation.get(1).equals("Object")) p1.println( " equals((bool(*)(" + plainClassName + " , Object)) &__" + getImplementation.get(1) + "::equals), "); else p1.println(" equals(&__" + plainClassName + "::equals"); if (getImplementation.get(2).equals("Object")) p1.println( " getClass((Class(*)(" + plainClassName + ")) &__" + getImplementation.get(2) + "::getClass), "); else p1.println(" getClass(&__" + plainClassName + ")"); // Remember to Take care of the comma issue if (getImplementation .get(3) .equals("Object") /*|| !(getImplementation.get(3).equals("__" + plainClassName))**/) { if (COUNT != 0) p1.println( " toString((String(*)(" + plainClassName + ")) &__" + getImplementation.get(3) + "::toString), "); else p1.println( " toString((String(*)(" + plainClassName + ")) &__" + getImplementation.get(3) + "::toString) { "); } else { int x = names.size(); boolean bat = false; if ((x == 1) && (names.get(0).equals("toString"))) bat = true; if (COUNT != 0 && !(bat)) p1.println(" toString(&__" + getImplementation.get(3) + "::toString),"); else p1.println(" toString(&__" + getImplementation.get(3) + "::toString) {"); } // p1.println(names); // for (int uniqueNames = 0; uniqueNames < names.size(); uniqueNames++) { // Remove Unnecessary Methods if (arr1.contains(names.get(uniqueNames))) { names.remove(uniqueNames); specialnames.remove(uniqueNames); types2.remove(uniqueNames); } } // p1.println(types2); // p1.println(names); // ADD Remaining Methods to implementation for (int i = 0; i < names.size(); i++) { if (!(arr1.contains(specialnames.get(i))) && checkForOtherSuperClass.get(i + 6).equals(className) && (i == names.size() - 1) && !(specialnames.get(i).equals(plainClassName))) { // Remember to Fix this later p1.println(); p1.println( " " + specialnames.get(i) + "(&__" + plainClassName + "::" + specialnames.get(i) + ") {"); } // Finally Add Parameters Here else { if (parameters.get(specialnames.get(i)).equals("ZeroParams") && !(specialnames.get(i).equals(plainClassName)) && !(arr1.contains(specialnames.get(i)))) { if (i != names.size() - 1) p1.println( " " + specialnames.get(i) + "((" + types2.get(i) + "(*)" + "(" + plainClassName + "))" + "&" + checkForOtherSuperClass.get(i + 6) + "::" + specialnames.get(i) + "),"); else p1.println( " " + specialnames.get(i) + "((" + types2.get(i) + "(*)" + "(" + plainClassName + "))" + "&" + checkForOtherSuperClass.get(i + 6) + "::" + specialnames.get(i) + ") {"); p1.println(); } else { if (!(specialnames.get(i).equals(plainClassName)) && !(arr1.contains(specialnames.get(i)))) { ArrayList<Integer> getTheParameters = new ArrayList<Integer>(); p1.print( " " + specialnames.get(i) + "((" + types2.get(i) + "(*)" + "(" + plainClassName + " , "); Pattern pp = Pattern.compile("_"); Matcher mm = pp.matcher(parameters.get(specialnames.get(i))); while (mm.find()) { getTheParameters.add(mm.start()); } for (int cc = 0; cc < getTheParameters.size(); cc++) { if (cc != getTheParameters.size() - 1) { p1.print( parameters .get(specialnames.get(i)) .substring( getTheParameters.get(cc) + 1, getTheParameters.get(cc + 1)) + " , "); } else { int length = parameters.get(specialnames.get(i)).length(); p1.print( parameters .get(specialnames.get(i)) .substring(getTheParameters.get(cc) + 1, length)); if (i != names.size() - 1) p1.print( "))" + "&" + checkForOtherSuperClass.get(i + 6) + "::" + specialnames.get(i) + "),"); else p1.print( "))" + "&" + checkForOtherSuperClass.get(i + 6) + "::" + specialnames.get(i) + ") {"); p1.println(); } } // p1.println(getTheParameters); } } } } p1.println(" }"); p1.println("};"); p1.println(); p1.println(); p1.println(); /*Remove comments below to Debug**/ } // p1.println(names); p1.flush(); p1.close(); } catch (Exception e) { } }
private static boolean handleURL(String address) { Main.status(String.format("Processing page \"%s\".", address)); try { NodeList posts = getPosts(address); if (posts.toNodeArray().length == 0) { return false; } for (Node post_node : posts.toNodeArray()) { if (post_node instanceof TagNode) { TagNode post = (TagNode) post_node; Post new_post = new Post(Long.parseLong(post.getAttribute("id").substring(5))); if (!Main.post_post_hash.containsKey(new_post)) { NodeList photo_posts = getPhotoPosts(post.getChildren()); NodeList remarks = getRemarks(photo_posts); for (Node node : remarks.toNodeArray()) { Matcher matcher = lores.matcher(node.getText()); String media_url = ""; if (matcher.find()) { media_url = matcher.group(); media_url = media_url.substring(17, media_url.length() - 1); } String thumb = media_url.replace( media_url.substring(media_url.lastIndexOf("_"), media_url.lastIndexOf(".")), "_75sq"); URL thumb_url = new URL(thumb); new_post.pictures.add(new Picture(new URL(media_url), thumb_url)); } NodeList photoset_posts = getPhotosetPosts(post.getChildren()); NodeList iframes = getIFrames(photoset_posts); for (Node node : iframes.toNodeArray()) { if (node instanceof TagNode) { String iframe_url = ((TagNode) node).getAttribute("src"); Parser parser2 = new Parser(iframe_url); NodeList a_list = parser2.extractAllNodesThatMatch(new TagNameFilter("a")); Node[] a_array = a_list.toNodeArray(); Node[] img_array = a_list.extractAllNodesThatMatch(new TagNameFilter("img"), true).toNodeArray(); String media_url; for (int i = 0; i < a_array.length; i++) { media_url = ((TagNode) img_array[i]).getAttribute("src"); String thumb = media_url.replace( media_url.substring( media_url.lastIndexOf("_"), media_url.lastIndexOf(".")), "_75sq"); URL thumb_url = new URL(thumb); new_post.pictures.add(new Picture(new URL(media_url), thumb_url)); } } } Main.handlePost(new_post); } else { new_post = post_post_hash.get(new_post); handleNonDownloadPost(new_post); } } } } catch (Exception ex) { ex.printStackTrace(); Main.status("Error handling post."); } return true; }