private Collection<Token> performTest(String sourceCode, final int offset, boolean[] wasResolved)
      throws Exception {
    FileObject root = makeScratchDir(this);

    FileObject sourceDir = root.createFolder("src");
    FileObject buildDir = root.createFolder("build");
    FileObject cacheDir = root.createFolder("cache");

    source = sourceDir.createFolder("test").createData("Test.java");

    writeIntoFile(source, sourceCode);

    SourceUtilsTestUtil.prepareTest(sourceDir, buildDir, cacheDir, new FileObject[0]);

    DataObject od = DataObject.find(source);
    EditorCookie ec = od.getCookie(EditorCookie.class);
    Document doc = ec.openDocument();

    doc.putProperty(Language.class, JavaTokenId.language());
    doc.putProperty("mimeType", "text/x-java");

    return InstantRenamePerformer.computeChangePoints(
        SourceUtilsTestUtil.getCompilationInfo(JavaSource.forFileObject(source), Phase.RESOLVED),
        offset,
        wasResolved);
  }
  @Override
  public void actionPerformed(PhpModule phpModule) {
    // Check CakePHP project
    if (!CakePhpUtils.isCakePHP(phpModule)) {
      return;
    }

    // get EditorCookie
    Lookup lookup = Utilities.actionsGlobalContext();
    EditorCookie context = lookup.lookup(EditorCookie.class);
    if (context == null) {
      return;
    }

    Document doc = context.getDocument();
    if (doc == null) {
      return;
    }

    reformat(doc);

    // Change line feed
    if (!BaseDocument.LS_LF.equals(doc.getProperty(BaseDocument.READ_LINE_SEPARATOR_PROP))) {
      doc.putProperty(BaseDocument.READ_LINE_SEPARATOR_PROP, BaseDocument.LS_LF);
    }
  }
  /** isDocumentModified */
  public boolean isDocumentModified() throws CollabException {
    boolean isModified = false;
    EditorCookie cookie = getEditorCookie();

    if (cookie != null) {
      isModified = cookie.isModified();
    }

    Debug.log(
        this, "CollabJavaHandler, isModified: " + isModified + " for file " + getName()); // NoI18n

    return isModified;
  }
 public MarkOccurrencesHighlighter(Document doc) {
   rp = new RequestProcessor(MarkOccurrencesHighlighter.class);
   bag = new OffsetsBag(doc);
   weakDoc = new WeakReference<Document>((Document) doc);
   DataObject dobj = NbEditorUtilities.getDataObject(weakDoc.get());
   if (dobj != null) {
     EditorCookie pane = dobj.getLookup().lookup(EditorCookie.class);
     JEditorPane[] panes = pane.getOpenedPanes();
     if (panes != null && panes.length > 0) {
       comp = panes[0];
       comp.addCaretListener(this);
     }
   }
 }
 @Override
 public void actionPerformed(ActionEvent e) {
   if (null == this.context || null == this.context.getDocument()) {
     return;
   }
   final StyledDocument document = context.getDocument();
   DocumentGenerator.RegenerateALL(document);
 }
  /** saveDocument */
  public boolean saveDocument() throws CollabException {
    Debug.log(
        this, // NoI18n
        "CollabJavaHandler, saving document: " + getName()); // NoI18n

    try {
      EditorCookie cookie = getEditorCookie();

      if (cookie != null) {
        cookie.saveDocument();
      }
    } catch (IOException iox) {
      Debug.log(
          this, // NoI18n
          "CollabJavaHandler, Exception occured while saving the document: " // NoI18n
              + getName()); // NoI18n

      return false;
    }

    return true;
  }
  /**
   * return document object for this file
   *
   * @throws CollabException
   * @return document
   */
  public StyledDocument getDocument() throws CollabException {
    try {
      FileObject file = getFileObject();

      // Get the DataObject
      DataObject dataObject = DataObject.find(file);

      if (dataObject == null) {
        throw new IllegalArgumentException("No DataObject found for file \"" + getName() + "\"");
      }

      // Get the Swing document for the file
      EditorCookie cookie = (EditorCookie) dataObject.getCookie(EditorCookie.class);

      StyledDocument document = cookie.openDocument();

      return document;
    } catch (org.openide.loaders.DataObjectNotFoundException notFound) {
      throw new CollabException(notFound);
    } catch (java.io.IOException io) {
      throw new CollabException(io);
    }
  }
Esempio n. 8
0
 public void run() {
   if (lp == null || ec == null) return;
   StyledDocument doc;
   try {
     doc = ec.openDocument();
   } catch (IOException ex) {
     return;
   }
   JEditorPane ep = EditorContextDispatcher.getDefault().getCurrentEditor();
   if (ep == null) return;
   int offset;
   String expression =
       getIdentifier(
           doc,
           ep,
           offset = NbDocument.findLineOffset(doc, lp.getLine().getLineNumber()) + lp.getColumn());
   if (expression == null) return;
   DebuggerEngine currentEngine = DebuggerManager.getDebuggerManager().getCurrentEngine();
   if (currentEngine == null) return;
   JPDADebugger d = currentEngine.lookupFirst(null, JPDADebugger.class);
   if (d == null) return;
   JPDAThread t = d.getCurrentThread();
   if (t == null || !t.isSuspended()) return;
   String toolTipText = null;
   try {
     Variable v = null;
     List<Operation> operations = t.getLastOperations();
     if (operations != null) {
       for (Operation operation : operations) {
         if (!expression.endsWith(operation.getMethodName())) {
           continue;
         }
         if (operation.getMethodStartPosition().getOffset() <= offset
             && offset <= operation.getMethodEndPosition().getOffset()) {
           v = operation.getReturnValue();
         }
       }
     }
     if (v == null) {
       v = d.evaluate(expression);
     }
     String type = v.getType();
     if (v instanceof ObjectVariable)
       try {
         String toString = null;
         try {
           java.lang.reflect.Method toStringMethod =
               v.getClass()
                   .getMethod(
                       "getToStringValue", // NOI18N
                       new Class[] {Integer.TYPE});
           toStringMethod.setAccessible(true);
           toString = (String) toStringMethod.invoke(v, TO_STRING_LENGTH_LIMIT);
         } catch (Exception ex) {
           ex.printStackTrace();
         }
         if (toString == null) {
           toString = ((ObjectVariable) v).getToStringValue();
         }
         toolTipText =
             expression + " = " + (type.length() == 0 ? "" : "(" + type + ") ") + toString;
       } catch (InvalidExpressionException ex) {
         toolTipText =
             expression + " = " + (type.length() == 0 ? "" : "(" + type + ") ") + v.getValue();
       }
     else
       toolTipText =
           expression + " = " + (type.length() == 0 ? "" : "(" + type + ") ") + v.getValue();
   } catch (InvalidExpressionException e) {
     toolTipText = expression + " = >" + e.getMessage() + "<";
   }
   firePropertyChange(PROP_SHORT_DESCRIPTION, null, toolTipText);
 }
Esempio n. 9
0
  public static List<ErrorDescription> runFindBugs(
      CompilationInfo info,
      Preferences customSettings,
      String singleBug,
      FileObject sourceRoot,
      Iterable<? extends String> classNames,
      FindBugsProgress progress,
      SigFilesValidator validator) {
    List<ErrorDescription> result = new ArrayList<ErrorDescription>();

    try {
      Class.forName(
          "org.netbeans.modules.findbugs.NbClassFactory",
          true,
          RunFindBugs.class.getClassLoader()); // NOI18N
      Project p = new Project();
      URL[] binaryRoots =
          CacheBinaryForSourceQuery.findCacheBinaryRoots(sourceRoot.toURL()).getRoots();

      if (classNames == null) {
        for (URL binary : binaryRoots) {
          try {
            p.addFile(new File(binary.toURI()).getAbsolutePath());
          } catch (URISyntaxException ex) {
            Exceptions.printStackTrace(ex);
          }
        }
      } else {
        ClassPath binary = ClassPathSupport.createClassPath(binaryRoots);
        List<FileObject> sigFiles = new ArrayList<FileObject>();

        for (String className : classNames) {
          FileObject classFO = binary.findResource(className.replace('.', '/') + ".sig"); // NOI18N

          if (classFO != null) {
            sigFiles.add(classFO);
          } else {
            LOG.log(
                Level.WARNING,
                "Cannot find sig file for: "
                    + className); // TODO: should probably become FINE eventually
          }
        }

        assert validator != null;

        if (!validator.validate(sigFiles)) return null;

        for (FileObject classFO : sigFiles) {
          p.addFile(new File(classFO.toURI()).getAbsolutePath());
        }

        addCompileRootAsSource(p, sourceRoot);
      }

      ClassPath compile = ClassPath.getClassPath(sourceRoot, ClassPath.COMPILE);

      for (FileObject compileRoot : compile.getRoots()) {
        addCompileRoot(p, compileRoot);
      }

      BugCollectionBugReporter r =
          new BugCollectionBugReporter(p) {
            @Override
            protected void emitLine(String line) {
              LOG.log(Level.FINE, line);
            }
          };

      r.setPriorityThreshold(Integer.MAX_VALUE);
      r.setRankThreshold(Integer.MAX_VALUE);

      FindBugs2 engine = new FindBugs2();

      engine.setProject(p);
      engine.setNoClassOk(true);
      engine.setBugReporter(r);

      if (progress != null) {
        engine.setProgressCallback(progress);
      }

      boolean inEditor = validator != null;
      Preferences settings =
          customSettings != null
              ? customSettings
              : NbPreferences.forModule(RunFindBugs.class).node("global-settings");
      UserPreferences preferences;

      if (singleBug != null) {
        singleBug = singleBug.substring(PREFIX_FINDBUGS.length());
        preferences = forSingleBug(singleBug);
      } else {
        preferences = readPreferences(settings, customSettings != null);
      }

      if (preferences == null) {
        // nothing enabled, stop
        return result;
      }

      engine.setUserPreferences(preferences);
      engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance());

      LOG.log(Level.FINE, "Running FindBugs");

      engine.execute();

      Map<FileObject, List<BugInstance>> file2Bugs = new HashMap<FileObject, List<BugInstance>>();

      for (BugInstance b : r.getBugCollection().getCollection()) {
        if (singleBug != null && !singleBug.equals(b.getBugPattern().getType())) continue;
        if (singleBug == null
            && !settings.getBoolean(
                b.getBugPattern().getType(),
                customSettings == null && isEnabledByDefault(b.getBugPattern()))) {
          continue;
        }

        SourceLineAnnotation sourceLine = b.getPrimarySourceLineAnnotation();
        FileObject sourceFile = null;

        if (sourceLine != null) {
          sourceFile = sourceRoot.getFileObject(sourceLine.getSourcePath());

          if (sourceFile != null) {
            List<BugInstance> bugs = file2Bugs.get(sourceFile);

            if (bugs == null) {
              file2Bugs.put(sourceFile, bugs = new ArrayList<BugInstance>());
            }

            bugs.add(b);
          } else {
            LOG.log(
                Level.WARNING,
                "{0}, location: {1}:{2}",
                new Object[] {b, sourceLine.getSourcePath(), sourceLine.getStartLine()});
          }
        }
      }

      for (Entry<FileObject, List<BugInstance>> e : file2Bugs.entrySet()) {
        int[] lineOffsets = null;
        FileObject sourceFile = e.getKey();
        DataObject d = DataObject.find(sourceFile);
        EditorCookie ec = d.getLookup().lookup(EditorCookie.class);
        Document doc = ec.getDocument();
        JavaSource js = null;

        for (BugInstance b : e.getValue()) {
          SourceLineAnnotation sourceLine = b.getPrimarySourceLineAnnotation();

          if (sourceLine.getStartLine() >= 0) {
            LazyFixList fixes =
                prepareFixes(b, inEditor, sourceFile, sourceLine.getStartLine(), null);

            if (doc != null) {
              result.add(
                  ErrorDescriptionFactory.createErrorDescription(
                      PREFIX_FINDBUGS + b.getType(),
                      Severity.VERIFIER,
                      b.getMessageWithoutPrefix(),
                      b.getBugPattern().getDetailHTML(),
                      fixes,
                      doc,
                      sourceLine.getStartLine()));
            } else {
              if (lineOffsets == null) {
                lineOffsets = computeLineMap(sourceFile, FileEncodingQuery.getEncoding(sourceFile));
              }

              int edLine = 2 * (Math.min(sourceLine.getStartLine(), lineOffsets.length / 2) - 1);

              result.add(
                  ErrorDescriptionFactory.createErrorDescription(
                      PREFIX_FINDBUGS + b.getType(),
                      Severity.VERIFIER,
                      b.getMessageWithoutPrefix(),
                      b.getBugPattern().getDetailHTML(),
                      fixes,
                      sourceFile,
                      lineOffsets[edLine],
                      lineOffsets[edLine + 1]));
            }
          } else {
            if (js == null) {
              js = JavaSource.forFileObject(sourceFile);
            }
            addByElementAnnotation(b, info, sourceFile, js, result, inEditor);
          }
        }
      }
    } catch (ClassNotFoundException ex) {
      Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
      Exceptions.printStackTrace(ex);
    } catch (InterruptedException ex) {
      LOG.log(Level.FINE, null, ex);
    }

    return result;
  }
Esempio n. 10
0
  public static void overwriteFile(Node srcNode, Node destNode) throws IOException {

    DataObject srcDO = srcNode.getLookup().lookup(DataObject.class);
    FileObject srcFO = srcDO.getPrimaryFile();

    DataObject destDO = destNode.getLookup().lookup(DataObject.class);
    FileObject destFO = destDO.getPrimaryFile();

    // To avoid any confusion, save modified source first.
    if (srcDO.isModified()) {
      NotifyDescriptor d =
          new NotifyDescriptor.Confirmation(
              NbBundle.getMessage(
                  FileNodeUtil.class, "MSG_SaveModifiedSource", srcFO.getNameExt()), // NOI18N
              NbBundle.getMessage(FileNodeUtil.class, "TTL_SaveModifiedSource"), // NOI18N
              NotifyDescriptor.OK_CANCEL_OPTION);
      if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.OK_OPTION) {
        EditorCookie srcEditorCookie = srcDO.getCookie(EditorCookie.class);
        srcEditorCookie.saveDocument();
      }
    }
    //        // Alternatively, we could use the in-memory copy of the source file
    //        EditorCookie srcEditorCookie =
    //                (EditorCookie) srcDO.getCookie(EditorCookie.class);
    //        Document srcDocument = srcEditorCookie.getDocument();
    //        if (srcDocument == null) {
    //            Task loadTask = srcEditorCookie.prepareDocument();
    //            new RequestProcessor().post(loadTask);
    //
    //            loadTask.waitFinished();
    //            srcDocument = srcEditorCookie.getDocument();
    //        }
    //        String srcText = srcDocument.getText(0, srcDocument.getLength());

    // From now on, we will only be using the on-disk copy of the source file.

    if (destDO.isModified()) {
      NotifyDescriptor d =
          new NotifyDescriptor.Confirmation(
              NbBundle.getMessage(
                  FileNodeUtil.class,
                  "MSG_OverwriteModifiedDestination",
                  destFO.getNameExt()), // NOI18N
              NbBundle.getMessage(FileNodeUtil.class, "TTL_OverwriteModifiedDestination"), // NOI18N
              NotifyDescriptor.OK_CANCEL_OPTION);
      if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.CANCEL_OPTION) {
        return;
      }

      EditorCookie destEditorCookie = destDO.getCookie(EditorCookie.class);

      InputStream inputStream = null;
      try {
        inputStream = srcFO.getInputStream();
        String srcText = getInputStreamContents(inputStream);

        Document outputDocument = destEditorCookie.getDocument();
        try {
          outputDocument.remove(0, outputDocument.getLength());
        } catch (java.lang.Exception e) {
          // Ignore exception here on purpose.
          // One of the listener from xml module throws NPE:
          // at
          // org.netbeans.modules.xml.text.completion.GrammarManager.isGuarded(GrammarManager.java:170)
          // at
          // org.netbeans.modules.xml.text.completion.GrammarManager.removeUpdate(GrammarManager.java:140)
          // at
          // org.netbeans.lib.editor.util.swing.PriorityDocumentListenerList.removeUpdate(PriorityDocumentListenerList.java:63)
          // at javax.swing.text.AbstractDocument.fireRemoveUpdate(AbstractDocument.java:242)
          // at org.netbeans.editor.BaseDocument.fireRemoveUpdate(BaseDocument.java:1305)
          // at org.netbeans.editor.BaseDocument.remove(BaseDocument.java:737)
        }
        outputDocument.insertString(0, srcText, null);
        destEditorCookie.saveDocument();
      } catch (BadLocationException e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
      } finally {
        try {
          if (inputStream != null) {
            inputStream.close();
          }
        } catch (Exception e) {;
        }
      }
    } else {
      FileLock lock = destFO.lock();
      InputStream inputStream = null;
      OutputStream outputStream = null;

      try {
        outputStream = destFO.getOutputStream(lock);
        inputStream = srcFO.getInputStream();
        FileUtil.copy(inputStream, outputStream);
      } finally {
        try {
          if (inputStream != null) {
            inputStream.close();
          }
          if (outputStream != null) {
            outputStream.close();
          }

          lock.releaseLock();
        } catch (Exception e) {;
        }
      }
    }
  }
Esempio n. 11
0
 public static Project GetProjectFromActivatedNodes(Node[] activatedNodes) {
   EditorCookie ec = activatedNodes[0].getLookup().lookup(EditorCookie.class);
   return GetProjectFromDocument(ec.getDocument());
 }