List of usage examples for javax.swing.text StyledDocument getText
public String getText(int offset, int length) throws BadLocationException;
From source file:Main.java
public static void main(String args[]) throws BadLocationException { JTextPane textPane1 = new JTextPane(); MutableAttributeSet black = new SimpleAttributeSet(); MutableAttributeSet red = new SimpleAttributeSet(); StyleConstants.setForeground(black, Color.black); StyleConstants.setForeground(red, Color.red); textPane1.setEditorKit(new StyledEditorKit()); doc1 = textPane1.getDocument();/*from w w w. ja v a 2s . c o m*/ append1("This is a Test!\n"); attribute = red; append1("Hello world! Hello Stackoverflow\n"); attribute = black; append1("the text is black again\n"); StyledDocument styledDocument = textPane1.getStyledDocument(); Element element; JTextPane textPane2 = new JTextPane(); textPane2.setEditorKit(new StyledEditorKit()); doc2 = textPane2.getDocument(); for (int i = 0; i < styledDocument.getLength(); i++) { element = styledDocument.getCharacterElement(i); AttributeSet attributeNew = element.getAttributes(); System.out.println(i); append2(styledDocument.getText(i, 1), attributeNew); } JFrame frame1 = new JFrame(); frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.setSize(400, 300); frame1.getContentPane().add(new JScrollPane(textPane1), BorderLayout.CENTER); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setSize(400, 300); frame2.setLocation(300, 0); frame2.getContentPane().add(new JScrollPane(textPane2), BorderLayout.CENTER); frame2.setVisible(true); }
From source file:com.keevosh.springframework.boot.netbeans.SpringBootConfigurationCompletionProvider.java
static int getRowFirstNonWhite(StyledDocument doc, int offset) throws BadLocationException { Element lineElement = doc.getParagraphElement(offset); int start = lineElement.getStartOffset(); while (start + 1 < lineElement.getEndOffset()) { try {//from w w w . j a va 2s.c om if (doc.getText(start, 1).charAt(0) != ' ') { break; } } catch (BadLocationException ex) { throw (BadLocationException) new BadLocationException( "calling getText(" + start + ", " + (start + 1) + ") on doc of length: " + doc.getLength(), start).initCause(ex); } start++; } return start; }
From source file:ParenMatcher.java
public void run() { StyledDocument doc = getStyledDocument(); String text = ""; int len = doc.getLength(); try {/*from ww w . jav a2 s . c o m*/ text = doc.getText(0, len); } catch (BadLocationException ble) { } java.util.Stack stack = new java.util.Stack(); for (int j = 0; j < text.length(); j += 1) { char ch = text.charAt(j); if (ch == '(' || ch == '[' || ch == '{') { int depth = stack.size(); stack.push("" + ch + j); // push a String containg the char and // the offset AttributeSet aset = matchAttrSet[depth % matchAttrSet.length]; doc.setCharacterAttributes(j, 1, aset, false); } if (ch == ')' || ch == ']' || ch == '}') { String peek = stack.empty() ? "." : (String) stack.peek(); if (matches(peek.charAt(0), ch)) { // does it match? stack.pop(); int depth = stack.size(); AttributeSet aset = matchAttrSet[depth % matchAttrSet.length]; doc.setCharacterAttributes(j, 1, aset, false); } else { // mismatch doc.setCharacterAttributes(j, 1, badAttrSet, false); } } } while (!stack.empty()) { // anything left in the stack is a mismatch String pop = (String) stack.pop(); int offset = Integer.parseInt(pop.substring(1)); doc.setCharacterAttributes(offset, 1, badAttrSet, false); } }
From source file:eu.ggnet.dwoss.util.HtmlDialog.java
private void search() { try {/*from ww w.j a v a2s . c om*/ Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED); documentTextPane.getHighlighter().removeAllHighlights(); StyledDocument styledDocument = documentTextPane.getStyledDocument(); String text = styledDocument.getText(0, styledDocument.getLength()); if (StringUtils.isBlank(text) || StringUtils.isBlank(searchField.getText())) return; int indexOf = text.indexOf(searchField.getText()); if (indexOf == -1) JOptionPane.showMessageDialog(this, "Nichts gefunden."); while (indexOf != -1) { try { documentTextPane.getHighlighter().addHighlight(indexOf, indexOf + searchField.getText().length(), painter); indexOf = text.indexOf(searchField.getText(), indexOf + 1); } catch (BadLocationException ex) { Logger.getLogger(HtmlDialog.class.getName()).log(Level.SEVERE, null, ex); } } } catch (BadLocationException ex) { Logger.getLogger(HtmlDialog.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:blue.orchestra.editor.blueSynthBuilder.BSBCompletionProvider.java
@Override public CompletionTask createTask(int queryType, JTextComponent component) { if (queryType != CompletionProvider.COMPLETION_QUERY_TYPE || bsbInterface == null) { return null; }/* w ww .ja va 2s.c o m*/ return new AsyncCompletionTask(new AsyncCompletionQuery() { @Override protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) { String filter = null; int startOffset = caretOffset - 1; try { final StyledDocument bDoc = (StyledDocument) document; final int lineStartOffset = getRowFirstNonWhite(bDoc, caretOffset); final char[] line = bDoc.getText(lineStartOffset, caretOffset - lineStartOffset).toCharArray(); final int whiteOffset = indexOfWhite(line); filter = new String(line, whiteOffset + 1, line.length - whiteOffset - 1); if (whiteOffset > 0) { startOffset = lineStartOffset + whiteOffset + 1; } else { startOffset = lineStartOffset; } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } if (filter != null && !filter.equals("")) { int index = filter.indexOf("<"); if (index >= 0) { filter = filter.substring(index + 1); Iterator<BSBObject> bsbObjects = bsbInterface.iterator(); while (bsbObjects.hasNext()) { BSBObject bsbObj = bsbObjects.next(); String[] keys = bsbObj.getReplacementKeys(); if (keys == null) { continue; } for (String key : keys) { if (StringUtils.containsWhitespace(key)) { continue; } if (filter.isEmpty() || key.startsWith(filter)) { completionResultSet.addItem(new BSBCompletionItem(bsbObj, key)); } } } } } completionResultSet.finish(); } }, component); }
From source file:Main.java
private void initComponents() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextPane textPane = new JTextPane(); ((AbstractDocument) textPane.getDocument()).addDocumentListener(new DocumentListener() { @Override// w ww. j a va2 s. c o m public void insertUpdate(final DocumentEvent de) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { StyledDocument doc = (StyledDocument) de.getDocument(); int start = Utilities.getRowStart(textPane, Math.max(0, de.getOffset() - 1)); int end = Utilities.getWordStart(textPane, de.getOffset() + de.getLength()); String text = doc.getText(start, end - start); for (String emoticon : imageTokens) { int i = text.indexOf(emoticon); while (i >= 0) { final SimpleAttributeSet attrs = new SimpleAttributeSet( doc.getCharacterElement(start + i).getAttributes()); if (StyleConstants.getIcon(attrs) == null) { switch (emoticon) { case imageToken: StyleConstants.setIcon(attrs, anImage); break; } doc.remove(start + i, emoticon.length()); doc.insertString(start + i, emoticon, attrs); } i = text.indexOf(emoticon, i + emoticon.length()); } } } catch (BadLocationException ex) { ex.printStackTrace(); } } }); } @Override public void removeUpdate(DocumentEvent e) { } @Override public void changedUpdate(DocumentEvent e) { } }); JScrollPane scrollPane = new JScrollPane(textPane); scrollPane.setPreferredSize(new Dimension(300, 300)); frame.add(scrollPane); frame.pack(); frame.setVisible(true); }
From source file:com.keevosh.springframework.boot.netbeans.SpringBootConfigurationCompletionProvider.java
@Override public CompletionTask createTask(int queryType, JTextComponent jtc) { if (queryType != CompletionProvider.COMPLETION_QUERY_TYPE) { return null; }// www.j a v a2 s. co m final TopComponent activeTC = TopComponent.getRegistry().getActivated(); if (null == activeTC) { return null; } final FileObject fileObject = activeTC.getLookup().lookup(FileObject.class); if (null == fileObject) { return null; } final ClassPath cp = ClassPath.getClassPath(fileObject, ClassPath.EXECUTE); if (null == cp) { return null; } try { cp.getClassLoader(false) .loadClass("org.springframework.boot.context.properties.ConfigurationProperties"); } catch (ClassNotFoundException ex) { return null; } final List<FileObject> configurationMetaFiles = cp .findAllResources("META-INF/spring-configuration-metadata.json"); final List<ConfigurationMetadata> configurationMetas = new ArrayList<ConfigurationMetadata>( configurationMetaFiles.size()); final JsonMarshaller jsonMarsaller = new JsonMarshaller(); for (FileObject configurationMetaFile : configurationMetaFiles) { try { configurationMetas.add(jsonMarsaller.read(configurationMetaFile.getInputStream())); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } return new AsyncCompletionTask(new AsyncCompletionQuery() { @Override protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) { String filter = null; int startOffset = caretOffset - 1; try { final StyledDocument bDoc = (StyledDocument) document; final int lineStartOffset = getRowFirstNonWhite(bDoc, caretOffset); final char[] line = bDoc.getText(lineStartOffset, caretOffset - lineStartOffset).toCharArray(); final int whiteOffset = indexOfWhite(line); filter = new String(line, whiteOffset + 1, line.length - whiteOffset - 1); if (whiteOffset > 0) { startOffset = lineStartOffset + whiteOffset + 1; } else { startOffset = lineStartOffset; } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } for (ConfigurationMetadata configurationMeta : configurationMetas) { for (ItemMetadata item : configurationMeta.getItems()) { if (item.isOfItemType(ItemMetadata.ItemType.PROPERTY) && !item.getName().equals("") && item.getName().startsWith(filter)) { completionResultSet.addItem( new SpringBootConfigurationCompletionItem(item, cp, startOffset, caretOffset)); } } } completionResultSet.finish(); } }, jtc); }
From source file:com.github.alexfalappa.nbspringboot.cfgprops.completion.CfgPropsCompletionProvider.java
@Override public CompletionTask createTask(int queryType, JTextComponent jtc) { if (queryType != CompletionProvider.COMPLETION_QUERY_TYPE) { return null; }//from w ww . ja va 2s .co m Project prj = Utilities.actionsGlobalContext().lookup(Project.class); if (prj == null) { return null; } logger.log(FINE, "Completing within context of prj {0}", FileUtil.getFileDisplayName(prj.getProjectDirectory())); final SpringBootService sbs = prj.getLookup().lookup(SpringBootService.class); if (sbs == null) { return null; } logger.fine("Creating completion task"); return new AsyncCompletionTask(new AsyncCompletionQuery() { @Override protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) { final StyledDocument styDoc = (StyledDocument) document; Element lineElement = styDoc.getParagraphElement(caretOffset); int lineStartOffset = lineElement.getStartOffset(); try { String lineToCaret = styDoc.getText(lineStartOffset, caretOffset - lineStartOffset); logger.log(FINER, "Completion on line to caret: {0}", lineToCaret); if (!lineToCaret.contains("#")) { String[] parts = lineToCaret.split("="); //property name extraction from part before = Matcher matcher = PATTERN_PROP_NAME.matcher(parts[0]); String propPrefix = null; int propPrefixOffset = 0; while (matcher.find()) { propPrefix = matcher.group(); propPrefixOffset = matcher.start(); } // check which kind of completion final int equalSignOffset = lineToCaret.indexOf('='); if (parts.length > 1) { //value completion String valPrefix = parts[1].trim(); completePropValue(sbs, completionResultSet, propPrefix, valPrefix, lineStartOffset + lineToCaret.indexOf(valPrefix, equalSignOffset), caretOffset); } else if (equalSignOffset >= 0) { //value completion with empty filter completePropValue(sbs, completionResultSet, propPrefix, null, lineStartOffset + equalSignOffset + 1, caretOffset); } else { // property completion completePropName(sbs, completionResultSet, propPrefix, lineStartOffset + propPrefixOffset, caretOffset); } } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } completionResultSet.finish(); } }, jtc); }
From source file:com.github.alexfalappa.nbspringboot.cfgprops.completion.CfgPropCompletionItem.java
@Override public void defaultAction(JTextComponent jtc) { try {//from w w w . ja v a2s. co m StyledDocument doc = (StyledDocument) jtc.getDocument(); // calculate the amount of chars to remove (by default from property start up to caret position) int lenToRemove = caretOffset - propStartOffset; if (overwrite) { // NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed // the document state here is different from when the completion was invoked thus we have to // find again the offset of the equal sign in the line Element lineElement = doc.getParagraphElement(caretOffset); String line = doc.getText(lineElement.getStartOffset(), lineElement.getEndOffset() - lineElement.getStartOffset()); int equalSignIndex = line.indexOf('='); if (equalSignIndex >= 0) { // from property start to equal sign lenToRemove = lineElement.getStartOffset() + equalSignIndex - propStartOffset; } else { // from property start to end of line (except line terminator) lenToRemove = lineElement.getEndOffset() - 1 - propStartOffset; } } // remove characters from the property name start offset doc.remove(propStartOffset, lenToRemove); doc.insertString(propStartOffset, getText(), null); // close the code completion box Completion.get().hideAll(); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } }
From source file:org.debux.webmotion.netbeans.completion.WebMotionCompletion.java
@Override public CompletionTask createTask(int queryType, JTextComponent component) { if (queryType != CompletionProvider.COMPLETION_QUERY_TYPE) { return null; }/* w w w . j a v a 2 s . c o m*/ return new AsyncCompletionTask(new AsyncCompletionQuery() { @Override protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) { String filter = null; int startOffset = caretOffset - 1; int column = 0; try { // Get filter StyledDocument doc = (StyledDocument) document; int lineStartOffset = Utils.getRowFirstNonWhite(doc, caretOffset); char[] line = doc.getText(lineStartOffset, caretOffset - lineStartOffset).toCharArray(); int whiteOffset = Utils.indexOfWhite(line); filter = new String(line, whiteOffset + 1, line.length - whiteOffset - 1); if (whiteOffset > 0) { startOffset = lineStartOffset + whiteOffset + 1; } else { startOffset = lineStartOffset; } // Get position Element lineElement = doc.getParagraphElement(caretOffset); String lineValue = doc.getText(lineElement.getStartOffset(), caretOffset - lineElement.getStartOffset()); Pattern pattern = Pattern.compile("\\s+"); Matcher matcher = pattern.matcher(lineValue); while (matcher.find()) { column++; } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } // Get section Section section = LexerUtils.getSection(document, caretOffset); // Get the package in configuration String packageBase = Utils.getPackageValue("package.base", null); String packageTarget = null; String filterSuperClass = null; String separator = "/"; boolean onlyFolder = false; String onlyMimeType = null; String[] keywords = {}; if (section != null) { if (section == Section.CONFIG) { keywords = KEYWORDS_CONFIG; } else if (section == Section.ERRORS && column % 2 == 0) { keywords = KEYWORDS_ERROR; packageTarget = ""; filterSuperClass = "java.lang.Exception"; } else if (section == Section.ERRORS && column % 2 == 1) { keywords = KEYWORDS_ERROR_ACTION; if (filter.startsWith("view:")) { packageTarget = Utils.getPackageValue("package.views", null); } else if (filter.startsWith("action:") || !filter.contains(":")) { packageTarget = Utils.getPackageValue("package.errors", packageBase); filterSuperClass = "org.debux.webmotion.server.WebMotionController"; } } else if (section == Section.EXTENSIONS && column % 2 == 0) { keywords = KEYWORDS_EXTENSION; } else if (section == Section.EXTENSIONS && column % 2 == 1) { packageTarget = ""; onlyMimeType = WebMotionLanguage.MIME_TYPE; } else if (section == Section.FILTERS && column % 3 == 0) { keywords = KEYWORDS_METHODS; } else if (section == Section.FILTERS && column % 3 == 1) { keywords = KEYWORDS_FILTER; } else if (section == Section.FILTERS && column % 3 == 2) { keywords = KEYWORDS_FILTER_ACTION; packageTarget = Utils.getPackageValue("package.filters", packageBase); filterSuperClass = "org.debux.webmotion.server.WebMotionFilter"; } else if (section == Section.ACTIONS && column % 3 == 0) { keywords = KEYWORDS_METHODS; } else if (section == Section.ACTIONS && column % 3 == 1) { keywords = KEYWORDS_ACTION; } else if (section == Section.ACTIONS && column % 3 == 2) { keywords = KEYWORDS_ACTION_ACTION; if (filter.startsWith("view:")) { packageTarget = Utils.getPackageValue("package.views", null); } else if (filter.startsWith("action:") || !filter.contains(":")) { packageTarget = Utils.getPackageValue("package.actions", packageBase); filterSuperClass = "org.debux.webmotion.server.WebMotionController"; } } else if (section == Section.PROPERTIES) { keywords = KEYWORDS_SECTIONS; } } else { keywords = KEYWORDS_SECTIONS; } // Keywords if (keywords == KEYWORDS_METHODS && filter.contains(",")) { keywords = KEYWORDS_METHOD; startOffset += StringUtils.substringBeforeLast(filter, ",").length(); filter = StringUtils.substringAfterLast(filter, ","); } else if (keywords == KEYWORDS_ERROR && filter.contains("code:")) { keywords = KEYWORDS_ERROR_CODE; startOffset += "code:".length(); filter = filter.substring("code:".length()); packageTarget = null; } else if (filter.startsWith("javac.debug=") || filter.startsWith("server.async=") || filter.startsWith("server.static.autodetect=")) { keywords = KEYWORDS_CONFIG_BOOLEAN; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("server.error.page=")) { keywords = KEYWORDS_CONFIG_ERROR; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("server.controller.scope=")) { keywords = KEYWORDS_CONFIG_SCOPE; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("package.base=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "=").replaceAll("\\.", "/"); packageTarget = ""; filterSuperClass = null; separator = "."; onlyFolder = true; } else if (filter.startsWith("package.views=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "=").replaceAll("\\.", "/"); packageTarget = ""; filterSuperClass = null; separator = "/"; onlyFolder = true; } else if (filter.startsWith("server.listener.class=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); packageTarget = ""; filterSuperClass = "org.debux.webmotion.server.WebMotionServerListener"; } else if (filter.startsWith("server.main.handler.class=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); packageTarget = ""; filterSuperClass = "org.debux.webmotion.server.WebMotionHandler"; } else if (filter.startsWith("default.render=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); packageTarget = ""; filterSuperClass = "org.debux.webmotion.server.render.Render"; } else if (filter.startsWith("package.actions=") || filter.startsWith("package.filters=") || filter.startsWith("package.errors=")) { keywords = KEYWORDS_EMPTY; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); packageTarget = Utils.getPackageValue("package.base", null); filterSuperClass = null; separator = "."; onlyFolder = true; } else if (filter.startsWith("server.encoding=")) { keywords = KEYWORDS_CONFIG_ENCODING; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("server.secret=")) { keywords = new String[] { RandomStringUtils.random(31, true, true) }; startOffset += StringUtils.substringBefore(filter, "=").length() + 1; filter = StringUtils.substringAfter(filter, "="); } else if (filter.startsWith("javac.debug") || filter.startsWith("server.async") || filter.startsWith("server.static.autodetect") || filter.startsWith("server.error.page") || filter.startsWith("server.controller.scope") || filter.startsWith("package.base") || filter.startsWith("package.views") || filter.startsWith("server.listener.class") || filter.startsWith("server.main.handler.class") || filter.startsWith("package.actions") || filter.startsWith("package.filters") || filter.startsWith("package.errors") || filter.startsWith("server.encoding") || filter.startsWith("server.secret")) { keywords = KEYWORDS_CONFIG_EQUAL; startOffset += StringUtils.substringBefore(filter, "=").length(); filter = ""; } for (String keyword : keywords) { if (keyword.startsWith(filter)) { completionResultSet.addItem(new WebMotionCompletionItem(keyword, startOffset, caretOffset)); } } if (packageTarget != null) { // File if (filterSuperClass == null) { String path = packageTarget.replaceAll("\\.", "/"); String filterFile = filter; int startOffsetFile = startOffset; Set<String> names = new HashSet<String>(); if (filter.startsWith("view:")) { filterFile = filter.replaceFirst("view:", ""); startOffsetFile += "view:".length(); } if (filterFile.contains("/")) { String current = StringUtils.substringBeforeLast(filterFile, "/"); path += current; startOffsetFile += current.length() + 1; filterFile = StringUtils.substringAfterLast(filterFile, "/"); } else if (packageTarget.isEmpty() && separator.equals("/")) { String fileName = "WEB-INF"; names.add(fileName); if (fileName.startsWith(filterFile)) { if (!fileName.equals(filterFile)) { completionResultSet.addItem( new WebMotionCompletionItem(fileName, startOffsetFile, caretOffset)); } else { completionResultSet.addItem(new WebMotionCompletionItem(separator, startOffsetFile + fileName.length(), caretOffset)); } } } GlobalPathRegistry registry = GlobalPathRegistry.getDefault(); List<ClassPath> paths = new ArrayList<ClassPath>(); paths.addAll(registry.getPaths(ClassPath.BOOT)); paths.addAll(registry.getPaths(ClassPath.COMPILE)); paths.addAll(registry.getPaths(ClassPath.SOURCE)); for (ClassPath classPath : paths) { FileObject resource = classPath.findResource(path); if (resource != null) { FileObject[] children = resource.getChildren(); for (FileObject child : children) { String fileName = child.getNameExt(); if ((!onlyFolder || onlyFolder && child.isFolder()) && (onlyMimeType == null || child.isFolder() || onlyMimeType != null && child.getMIMEType().equals(onlyMimeType)) && fileName.startsWith(filterFile) && !fileName.startsWith(".")) { if (!names.contains(fileName)) { if (!fileName.equals(filterFile)) { completionResultSet.addItem(new WebMotionCompletionItem(fileName, startOffsetFile, caretOffset)); } else { completionResultSet.addItem(new WebMotionCompletionItem(separator, startOffsetFile + fileName.length(), caretOffset)); } names.add(fileName); } } } } } completionResultSet.finish(); } else { // Class if (filter.contains(":") && !filter.startsWith("code:")) { startOffset += StringUtils.substringBefore(filter, ":").length() + 1; filter = StringUtils.substringAfter(filter, ":"); } int startOffsetClass = startOffset; if (filter.contains(".")) { startOffsetClass += StringUtils.substringBeforeLast(filter, ".").length() + 1; } String fullName = packageTarget + filter; String rootPackage = ""; String filerPackage = fullName; if (fullName.contains(".")) { rootPackage = StringUtils.substringBeforeLast(fullName, "."); filerPackage = StringUtils.substringAfterLast(fullName, "."); } String folderPackage = rootPackage.replaceAll("\\.", "/"); FileObject fo = Utils.getFO(document); ClassPath bootCp = ClassPath.getClassPath(fo, ClassPath.BOOT); ClassPath compileCp = ClassPath.getClassPath(fo, ClassPath.COMPILE); ClassPath sourcePath = ClassPath.getClassPath(fo, ClassPath.SOURCE); ClasspathInfo info = ClasspathInfo.create(bootCp, compileCp, sourcePath); JavaSource src = JavaSource.create(info); final String filterSuperJavaClass = filterSuperClass; final CompletionResultSet completionResultSetClass = completionResultSet; final int startOffsetJavaClass = startOffsetClass; final int caretOffsetClass = caretOffset; // Package names List<FileObject> folders = new ArrayList<FileObject>(); folders.addAll(bootCp.findAllResources(folderPackage)); folders.addAll(compileCp.findAllResources(folderPackage)); folders.addAll(sourcePath.findAllResources(folderPackage)); final String rootPackageFilter = rootPackage; final String filterPackageFilter = filerPackage; final Set<String> names = new HashSet<String>(); for (final FileObject folder : folders) { try { src.runUserActionTask(new CancellableTask<CompilationController>() { @Override public void cancel() { } @Override public void run(CompilationController cu) throws Exception { Types types = cu.getTypes(); Elements elements = cu.getElements(); TypeElement superElement = elements.getTypeElement(filterSuperJavaClass); TypeMirror superType = null; if (superElement != null) { superType = superElement.asType(); } FileObject[] children = folder.getChildren(); for (FileObject child : children) { String name = child.getName(); if (!name.startsWith(".") && name.startsWith(filterPackageFilter)) { if (!names.contains(name)) { names.add(name); TypeElement element; if (rootPackageFilter.isEmpty()) { element = elements.getTypeElement(name); } else { element = elements .getTypeElement(rootPackageFilter + "." + name); } if (name.equals(filterPackageFilter)) { if (element == null || element.getKind() != ElementKind.CLASS || element.getKind() == ElementKind.CLASS && (filterSuperJavaClass.equals( "org.debux.webmotion.server.WebMotionFilter") || filterSuperJavaClass.equals( "org.debux.webmotion.server.WebMotionController"))) { WebMotionCompletionItem item = new WebMotionCompletionItem( ".", startOffsetJavaClass + name.length(), caretOffsetClass); completionResultSetClass.addItem(item); } } else if (child.isFolder()) { WebMotionCompletionItem item = new WebMotionCompletionItem( name, startOffsetJavaClass, caretOffsetClass); completionResultSetClass.addItem(item); } else if (element != null) { Set<Modifier> modifiers = element.getModifiers(); ElementKind kind = element.getKind(); TypeMirror resolveType = element.asType(); if (kind == ElementKind.CLASS && modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.ABSTRACT) && superType != null && types.isSubtype(resolveType, superType)) { WebMotionCompletionItem item = new WebMotionCompletionItem( name, cu, element, startOffsetJavaClass, caretOffsetClass); completionResultSetClass.addItem(item); } } } } } } }, false); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } // Method if (filter.contains(".") && (filterSuperJavaClass .equals("org.debux.webmotion.server.WebMotionFilter") || filterSuperJavaClass.equals("org.debux.webmotion.server.WebMotionController"))) { final String className = StringUtils.substringBeforeLast(filter, "."); final String fullClassName = packageTarget + className; final String filterMethod = StringUtils.substringAfterLast(filter, "."); final CompletionResultSet completionResultSetJavaSource = completionResultSet; final int startOffsetJavaSource = startOffset + className.length() + 1; final int caretOffesetJavaSource = caretOffset; try { src.runUserActionTask(new CancellableTask<CompilationController>() { @Override public void cancel() { } @Override public void run(CompilationController cu) throws Exception { cu.toPhase(JavaSource.Phase.PARSED); Elements elements = cu.getElements(); TypeElement classElement = elements.getTypeElement(fullClassName); if (classElement != null) { List<? extends javax.lang.model.element.Element> members = elements .getAllMembers(classElement); for (javax.lang.model.element.Element member : members) { if (member.getKind() == ElementKind.METHOD) { Set<Modifier> modifiers = member.getModifiers(); String methodName = member.getSimpleName().toString(); String className = member.getEnclosingElement().getSimpleName() .toString(); if (!"Object".equals(className) && !"WebMotionController".equals(className) && !"WebMotionFilter".equals(className) && modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.STATIC) && methodName.startsWith(filterMethod)) { WebMotionCompletionItem item = new WebMotionCompletionItem( methodName, cu, member, startOffsetJavaSource, caretOffesetJavaSource); completionResultSetJavaSource.addItem(item); } } } } completionResultSetJavaSource.finish(); } }, false); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } else { completionResultSet.finish(); } } } else { completionResultSet.finish(); } } }, component); }