Java Code Examples for org.netbeans.api.java.source.JavaSource#forDocument()
The following examples show how to use
org.netbeans.api.java.source.JavaSource#forDocument() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JavaRefactoringGlobalAction.java From netbeans with Apache License 2.0 | 6 votes |
@Override public final void run() { try { JavaSource source = JavaSource.forDocument(textC.getDocument()); source.runUserActionTask(this, false); } catch (IOException ioe) { Exceptions.printStackTrace(ioe); return; } TopComponent activetc = TopComponent.getRegistry().getActivated(); if (ui!=null) { UI.openRefactoringUI(ui, activetc); } else { DialogDescriptor.Message msg = new DialogDescriptor.Message (delegate.getErrorMessage(), DialogDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notify(msg); } }
Example 2
Source File: JavaI18nSupport.java From netbeans with Apache License 2.0 | 6 votes |
/** * Creates a new field which holds a reference to the resource holder * (resource bundle). The field is added to the internationalized file. */ private void createField() { // Check if we have to generate field. if (!isGenerateField()) { return; } final JavaSource javaSource = JavaSource.forDocument(document); try { ModificationResult result = javaSource.runModificationTask(new AddFieldTask(getIdentifier())); result.commit(); } catch (Exception ex) { ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, ex); } }
Example 3
Source File: GoToSuperTypeAction.java From netbeans with Apache License 2.0 | 6 votes |
public void actionPerformed(ActionEvent evt, final JTextComponent target) { final JavaSource js = JavaSource.forDocument(target.getDocument()); if (js == null) { StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(GoToSupport.class, "WARN_CannotGoToGeneric",1)); return; } final int caretPos = target.getCaretPosition(); final AtomicBoolean cancel = new AtomicBoolean(); ProgressUtils.runOffEventDispatchThread(new Runnable() { @Override public void run() { goToImpl(target, js, caretPos, cancel); } }, NbBundle.getMessage(JavaKit.class, "goto-super-implementation"), cancel, false); }
Example 4
Source File: TestSingleMethodSupport.java From netbeans with Apache License 2.0 | 6 votes |
public static SingleMethod getTestMethod(Document doc, int cursor){ SingleMethod sm = null; if (doc != null){ JavaSource js = JavaSource.forDocument(doc); if(js == null) { return null; } TestClassInfoTask task = new TestClassInfoTask(cursor); try { Future<Void> f = js.runWhenScanFinished(task, true); if (f.isDone() && task.getFileObject() != null && task.getMethodName() != null){ sm = new SingleMethod(task.getFileObject(), task.getMethodName()); } } catch (IOException ex) { LOGGER.log(Level.WARNING, null, ex); } } return sm; }
Example 5
Source File: HintAction.java From netbeans with Apache License 2.0 | 6 votes |
private String doPerform() { int[] span = new int[2]; JTextComponent pane = getCurrentFile(span); Document doc = pane != null ? pane.getDocument() : null; if (doc == null) { if (span[0] != span[1]) return "ERR_Not_Selected"; //NOI18N else return "ERR_No_Selection"; //NOI18N } JavaSource js = JavaSource.forDocument(doc); if (js == null) return "ERR_Not_Supported"; //NOI18N perform(js, pane, span); return null; }
Example 6
Source File: HierarchyTopComponent.java From netbeans with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public void actionPerformed(ActionEvent e) { if (refreshButton == e.getSource()) { final JTextComponent lastFocusedComponent = EditorRegistry.lastFocusedComponent(); if (lastFocusedComponent != null) { final JavaSource js = JavaSource.forDocument(Utilities.getDocument(lastFocusedComponent)); if (js != null) { setContext(js, lastFocusedComponent); } } } else if (jdocButton == e.getSource()) { final TopComponent win = JavadocTopComponent.findInstance(); if (win != null && !win.isShowing()) { win.open(); win.requestVisible(); jdocTask.schedule(NOW); } } else if (historyCombo == e.getSource()) { refresh(); } else if (viewTypeCombo == e.getSource()) { refresh(); } }
Example 7
Source File: ShowHierarchyAtCaretAction.java From netbeans with Apache License 2.0 | 5 votes |
private JavaSource getContext(JTextComponent target) { final Document doc = Utilities.getDocument(target); if (doc == null) { return null; } return JavaSource.forDocument(doc); }
Example 8
Source File: ShowMembersAtCaretAction.java From netbeans with Apache License 2.0 | 5 votes |
private JavaSource getContext(JTextComponent target) { final Document doc = Utilities.getDocument(target); if (doc == null) { return null; } return JavaSource.forDocument(doc); }
Example 9
Source File: WebBeansActionHelper.java From netbeans with Apache License 2.0 | 5 votes |
static boolean getClassAtDot( final JTextComponent component , final Object[] subject, final PositionStrategy strategy ) { JavaSource javaSource = JavaSource.forDocument(component.getDocument()); if ( javaSource == null ){ Toolkit.getDefaultToolkit().beep(); return false; } try { javaSource.runUserActionTask( new Task<CompilationController>(){ @Override public void run(CompilationController controller) throws Exception { controller.toPhase( Phase.ELEMENTS_RESOLVED ); int dot = strategy.getOffset(component); TreePath tp = controller.getTreeUtilities() .pathFor(dot); Element element = controller.getTrees().getElement(tp ); if ( element == null ){ StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage( WebBeansActionHelper.class, "LBL_ElementNotFound")); return; } if ( element instanceof TypeElement ){ subject[0] = ElementHandle.create(element); subject[1] = element.getSimpleName(); subject[2] = InspectActionId.CLASS_CONTEXT; } } }, true ); } catch(IOException e ){ Logger.getLogger( WebBeansActionHelper.class.getName()). log( Level.WARNING, e.getMessage(), e); } return subject[0]!=null; }
Example 10
Source File: DelegateMethodGenerator.java From netbeans with Apache License 2.0 | 5 votes |
public static ElementNode.Description getAvailableMethods(final JTextComponent component, final ElementHandle<? extends TypeElement> typeElementHandle, final ElementHandle<? extends VariableElement> fieldHandle) { if (fieldHandle.getKind().isField()) { final JavaSource js = JavaSource.forDocument(component.getDocument()); if (js != null) { final int caretOffset = component.getCaretPosition(); final ElementNode.Description[] description = new ElementNode.Description[1]; final AtomicBoolean cancel = new AtomicBoolean(); ProgressUtils.runOffEventDispatchThread(new Runnable() { @Override public void run() { try { ScanUtils.waitUserActionTask(js, new Task<CompilationController>() { @Override public void run(CompilationController controller) throws IOException { if (controller.getPhase().compareTo(Phase.RESOLVED) < 0) { Phase phase = controller.toPhase(Phase.RESOLVED); if (phase.compareTo(Phase.RESOLVED) < 0) { if (log.isLoggable(Level.SEVERE)) { log.log(Level.SEVERE, "Cannot reach required phase. Leaving without action."); } return; } } if (cancel.get()) { return; } description[0] = getAvailableMethods(controller, caretOffset, typeElementHandle, fieldHandle); } }); } catch (IOException ioe) { Exceptions.printStackTrace(ioe); } } }, NbBundle.getMessage(DelegateMethodGenerator.class, "LBL_Get_Available_Methods"), cancel, false); cancel.set(true); return description[0]; } } return null; }
Example 11
Source File: EqualsHashCodeGenerator.java From netbeans with Apache License 2.0 | 5 votes |
public static void invokeEqualsHashCode(final TreePathHandle handle, final JTextComponent component) { JavaSource js = JavaSource.forDocument(component.getDocument()); if (js != null) { class FillIn implements Task<CompilationController> { EqualsHashCodeGenerator gen; @Override public void run(CompilationController cc) throws Exception { cc.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); Element e = handle.resolveElement(cc); gen = createEqualsHashCodeGenerator(component, cc, e); } public void invoke() { if (gen != null) { gen.invoke(); } } } FillIn fillIn = new FillIn(); try { js.runUserActionTask(fillIn, true); fillIn.invoke(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }
Example 12
Source File: LoggerGenerator.java From netbeans with Apache License 2.0 | 5 votes |
@Override public void invoke() { final int caretOffset = component.getCaretPosition(); JavaSource js = JavaSource.forDocument(component.getDocument()); if (js != null) { try { ModificationResult mr = js.runModificationTask(new Task<WorkingCopy>() { @Override public void run(WorkingCopy copy) throws IOException { copy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); Element e = description.getElementHandle().resolve(copy); TreePath path = e != null ? copy.getTrees().getPath(e) : copy.getTreeUtilities().pathFor(caretOffset); path = copy.getTreeUtilities().getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path); if (path == null) { String message = NbBundle.getMessage(LoggerGenerator.class, "ERR_CannotFindOriginalClass"); //NOI18N org.netbeans.editor.Utilities.setStatusBoldText(component, message); } else { ClassTree cls = (ClassTree) path.getLeaf(); CodeStyle cs = CodeStyle.getDefault(component.getDocument()); Set<Modifier> mods = EnumSet.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL); List<String> names = Utilities.varNamesSuggestions(null, ElementKind.FIELD, mods, "LOG", null, copy.getTypes(), copy.getElements(), e.getEnclosedElements(), cs); VariableTree var = createLoggerField(copy.getTreeMaker(), cls, names.size() > 0 ? names.get(0) : "LOG", mods); //NOI18N copy.rewrite(cls, GeneratorUtils.insertClassMembers(copy, cls, Collections.singletonList(var), caretOffset)); } } }); GeneratorUtils.guardedCommit(component, mr); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }
Example 13
Source File: TextDocumentServiceImpl.java From netbeans with Apache License 2.0 | 5 votes |
private JavaSource getSource(String fileUri) { Document doc = openedDocuments.get(fileUri); if (doc == null) { try { FileObject file = fromUri(fileUri); return JavaSource.forFileObject(file); } catch (MalformedURLException ex) { return null; } } else { return JavaSource.forDocument(doc); } }
Example 14
Source File: ConstructorGenerator.java From netbeans with Apache License 2.0 | 4 votes |
@Override public void invoke() { final List<ElementHandle<? extends Element>> fieldHandles; final List<ElementHandle<? extends Element>> constrHandles; final int caretOffset = component.getCaretPosition(); if (constructorDescription != null || fieldsDescription != null) { ConstructorPanel panel = new ConstructorPanel(constructorDescription, fieldsDescription); DialogDescriptor dialogDescriptor = GeneratorUtils.createDialogDescriptor(panel, NbBundle.getMessage(ConstructorGenerator.class, "LBL_generate_constructor")); //NOI18N Dialog dialog = DialogDisplayer.getDefault().createDialog(dialogDescriptor); dialog.setVisible(true); if (dialogDescriptor.getValue() != dialogDescriptor.getDefaultValue()) { return; } if (constructorHandle == null) { constrHandles = panel.getInheritedConstructors(); } else { constrHandles = null; } fieldHandles = panel.getVariablesToInitialize(); } else { fieldHandles = null; constrHandles = null; } try { if (existingWorkingCopy == null) { JavaSource js = JavaSource.forDocument(component.getDocument()); if (js != null) { ModificationResult mr = js.runModificationTask(new Task<WorkingCopy>() { @Override public void run(WorkingCopy copy) throws IOException { doGenerateConstructor(copy, fieldHandles, constrHandles, caretOffset); } }); GeneratorUtils.guardedCommit(component, mr); } } else { doGenerateConstructor(existingWorkingCopy, fieldHandles, constrHandles, caretOffset); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } }
Example 15
Source File: WebBeansActionHelper.java From netbeans with Apache License 2.0 | 4 votes |
/** * Compilation controller from metamodel could not be used for getting * TreePath via dot because it is not based on one FileObject ( Document ). * So this method is required for searching Element at dot. * If appropriate element is found it's name is placed into list * along with name of containing type. * Resulted element could not be used in metamodel for injectable * access. This is because element was gotten via other Compilation * controller so it is from other model. */ static boolean getVariableElementAtDot( final JTextComponent component, final Object[] variable , final boolean showStatusOnError, final PositionStrategy strategy) { JavaSource javaSource = JavaSource.forDocument(component.getDocument()); if ( javaSource == null ){ Toolkit.getDefaultToolkit().beep(); return false; } try { javaSource.runUserActionTask( new Task<CompilationController>(){ @Override public void run(CompilationController controller) throws Exception { controller.toPhase( Phase.ELEMENTS_RESOLVED ); int dot = strategy.getOffset(component); TreePath tp = controller.getTreeUtilities().pathFor(dot); Element contextElement = controller.getTrees().getElement(tp ); if ( contextElement == null ){ StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage( WebBeansActionHelper.class, "LBL_ElementNotFound")); return; } Element element = getContextElement(contextElement, controller); if ( element == null ){ return; } if ( !( element instanceof VariableElement) && showStatusOnError){ StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage( WebBeansActionHelper.class, "LBL_NotVariableElement", StatusDisplayer.IMPORTANCE_ERROR_HIGHLIGHT)); return; } else { if ( element.getKind() == ElementKind.FIELD ){ ElementHandle<VariableElement> handle = ElementHandle.create((VariableElement)element); variable[0] = handle; variable[1] = element.getSimpleName().toString(); variable[2] = InspectActionId.INJECTABLES_CONTEXT; } else { setVariablePath(variable, controller, element); } } } }, true ); } catch(IOException e ){ Logger.getLogger( GoToInjectableAtCaretAction.class.getName()). log( Level.INFO, e.getMessage(), e); } return variable[1] !=null ; }
Example 16
Source File: ToStringGenerator.java From netbeans with Apache License 2.0 | 4 votes |
@Override public void invoke() { final int caretOffset = component.getCaretPosition(); final ToStringPanel panel = new ToStringPanel(description, useStringBuilder, supportsStringBuilder); DialogDescriptor dialogDescriptor = GeneratorUtils.createDialogDescriptor(panel, NbBundle.getMessage(ToStringGenerator.class, "LBL_generate_tostring")); //NOI18N Dialog dialog = DialogDisplayer.getDefault().createDialog(dialogDescriptor); dialog.setVisible(true); if (dialogDescriptor.getValue() != dialogDescriptor.getDefaultValue()) { return; } JavaSource js = JavaSource.forDocument(component.getDocument()); if (js != null) { try { ModificationResult mr = js.runModificationTask(new Task<WorkingCopy>() { @Override public void run(WorkingCopy copy) throws IOException { copy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); Element e = description.getElementHandle().resolve(copy); TreePath path = e != null ? copy.getTrees().getPath(e) : copy.getTreeUtilities().pathFor(caretOffset); path = copy.getTreeUtilities().getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path); if (path == null) { String message = NbBundle.getMessage(ToStringGenerator.class, "ERR_CannotFindOriginalClass"); //NOI18N org.netbeans.editor.Utilities.setStatusBoldText(component, message); } else { ClassTree cls = (ClassTree) path.getLeaf(); ArrayList<VariableElement> fields = new ArrayList<>(); for (ElementHandle<? extends Element> elementHandle : panel.getVariables()) { VariableElement field = (VariableElement) elementHandle.resolve(copy); if (field == null) { return; } fields.add(field); } MethodTree mth = createToStringMethod(copy, fields, cls.getSimpleName().toString(), panel.useStringBuilder()); copy.rewrite(cls, GeneratorUtils.insertClassMembers(copy, cls, Collections.singletonList(mth), caretOffset)); } } }); GeneratorUtils.guardedCommit(component, mr); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }
Example 17
Source File: ClipboardHandler.java From netbeans with Apache License 2.0 | 4 votes |
@Override public void actionPerformed(final ActionEvent evt, final JTextComponent target) { Document doc = target.getDocument(); JavaSource js = JavaSource.forDocument(doc); final Object lock = new Object(); final AtomicBoolean cancel = new AtomicBoolean(); final AtomicBoolean alreadyRunning = new AtomicBoolean(); if (js != null) { Task<CompilationController> work = new Task<CompilationController>() { @Override public void run(CompilationController parameter) throws Exception { synchronized (lock) { if (cancel.get()) return; alreadyRunning.set(true); } try { target.putClientProperty(RUN_SYNCHRONOUSLY, true); JavaCutAction.super.actionPerformed(evt, target); } finally { target.putClientProperty(RUN_SYNCHRONOUSLY, null); } } }; if (target.getClientProperty(RUN_SYNCHRONOUSLY) == null) { if (!DocumentUtilities.isWriteLocked(doc)) { boolean finished = runQuickly(js, work); if (finished) return; } } else { try { js.runUserActionTask(work, true); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return; } } synchronized (lock) { if (alreadyRunning.get()) return; cancel.set(true); } try { target.putClientProperty(NO_IMPORTS, true); super.actionPerformed(evt, target); } finally { target.putClientProperty(NO_IMPORTS, null); } }
Example 18
Source File: ClipboardHandler.java From netbeans with Apache License 2.0 | 4 votes |
@Override public void actionPerformed(final ActionEvent evt, final JTextComponent target) { Document doc = target.getDocument(); JavaSource js = JavaSource.forDocument(doc); final Object lock = new Object(); final AtomicBoolean cancel = new AtomicBoolean(); final AtomicBoolean alreadyRunning = new AtomicBoolean(); if (js != null && !DocumentUtilities.isWriteLocked(doc)) { boolean finished = runQuickly(js, new Task<CompilationController>() { @Override public void run(CompilationController parameter) throws Exception { synchronized (lock) { if (cancel.get()) { return; } alreadyRunning.set(true); } try { target.putClientProperty(RUN_SYNCHRONOUSLY, true); JavaCutToLineBeginOrEndAction.super.actionPerformed(evt, target); } finally { target.putClientProperty(RUN_SYNCHRONOUSLY, null); } } }); if (finished) { return; } } synchronized (lock) { if (alreadyRunning.get()) { return; } cancel.set(true); } try { target.putClientProperty(NO_IMPORTS, true); super.actionPerformed(evt, target); } finally { target.putClientProperty(NO_IMPORTS, null); } }
Example 19
Source File: GoToDecoratorAtCaretAction.java From netbeans with Apache License 2.0 | 4 votes |
@Override protected boolean findContext( final JTextComponent component, final Object[] context ) { JavaSource javaSource = JavaSource.forDocument(component.getDocument()); if ( javaSource == null ){ Toolkit.getDefaultToolkit().beep(); return false; } try { javaSource.runUserActionTask( new Task<CompilationController>(){ @Override public void run(CompilationController controller) throws Exception { controller.toPhase( Phase.ELEMENTS_RESOLVED ); int dot = component.getCaret().getDot(); TreePath tp = controller.getTreeUtilities().pathFor(dot); Element contextElement = controller.getTrees().getElement(tp ); if ( contextElement == null ){ StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage( WebBeansActionHelper.class, "LBL_ElementNotFound")); return; } context[0] = contextElement; } }, true ); } catch (IOException e) { Logger.getLogger(GoToDecoratorAtCaretAction.class.getName()).log( Level.INFO, e.getMessage(), e); } boolean result = context[0] instanceof TypeElement; if ( !result ){ StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage(GoToDecoratorAtCaretAction.class, "LBL_NotTypeElement"), // NOI18N StatusDisplayer.IMPORTANCE_ERROR_HIGHLIGHT); } else { context[0] = ElementHandle.create( (TypeElement) context[0]); } return result; }
Example 20
Source File: WebBeansActionHelper.java From netbeans with Apache License 2.0 | 4 votes |
static boolean getMethodAtDot( final JTextComponent component , final Object[] subject , final PositionStrategy strategy) { JavaSource javaSource = JavaSource.forDocument(component.getDocument()); if ( javaSource == null ){ Toolkit.getDefaultToolkit().beep(); return false; } try { javaSource.runUserActionTask( new Task<CompilationController>(){ @Override public void run(CompilationController controller) throws Exception { controller.toPhase( Phase.ELEMENTS_RESOLVED ); int dot = strategy.getOffset(component); TreePath tp = controller.getTreeUtilities() .pathFor(dot); Element element = controller.getTrees().getElement(tp ); if ( element == null ){ StatusDisplayer.getDefault().setStatusText( NbBundle.getMessage( WebBeansActionHelper.class, "LBL_ElementNotFound")); return; } if ( element instanceof ExecutableElement ){ subject[0] = ElementHandle.create(element); subject[1] = element.getSimpleName(); subject[2] = InspectActionId.METHOD_CONTEXT; } else if ( element instanceof VariableElement ){ Element enclosingElement = element.getEnclosingElement(); if ( enclosingElement instanceof ExecutableElement && hasAnnotation(element, OBSERVES_ANNOTATION)) { subject[0] = ElementHandle.create(enclosingElement); subject[1] = enclosingElement.getSimpleName(); subject[2] = InspectActionId.METHOD_CONTEXT; } } } }, true ); } catch(IOException e ){ Logger.getLogger( WebBeansActionHelper.class.getName()). log( Level.WARNING, e.getMessage(), e); } return subject[0]!=null; }