private void runJavaProcessInProject( TmcProjectInfo projectInfo, ClassPath classPath, String taskName, List<String> args, InputOutput inOut, BgTaskListener<ProcessResult> listener) { FileObject projectDir = projectInfo.getProjectDir(); JavaPlatform platform = JavaPlatform.getDefault(); // Should probably use project's configured platform instead FileObject javaExe = platform.findTool("java"); if (javaExe == null) { throw new IllegalArgumentException(); } // TMC server packages this with every exercise for our convenience. // True even for Maven exercises, at least until NB's Maven API is published. ClassPath testRunnerClassPath = getTestRunnerClassPath(projectInfo); if (testRunnerClassPath != null) { classPath = ClassPathSupport.createProxyClassPath(classPath, testRunnerClassPath); } String[] command = new String[3 + args.size()]; command[0] = FileUtil.toFile(javaExe).getAbsolutePath(); command[1] = "-cp"; command[2] = classPath.toString(ClassPath.PathConversionMode.WARN); System.arraycopy(args.toArray(new String[args.size()]), 0, command, 3, args.size()); log.info(StringUtils.join(command, ' ')); ProcessRunner runner = new ProcessRunner(command, FileUtil.toFile(projectDir), inOut); BgTask.start(taskName, runner, listener); }
public static boolean containsPackage(ClassPath classPath, String fullPackageName) { for (FileObject cpRoot : classPath.getRoots()) { FileObject fo = FileObjectUtils.getPackageFileObject(cpRoot, fullPackageName); if (fo != null) { return true; } } return false; }
public void testQuery() throws Exception { JavaPlatform platform = JavaPlatform.getDefault(); ClassPath cp = platform.getBootstrapLibraries(); FileObject pfo = cp.getRoots()[0]; URL u = URLMapper.findURL(pfo, URLMapper.EXTERNAL); URL urls[] = JavadocForBinaryQuery.findJavadoc(u).getRoots(); assertEquals(1, urls.length); assertTrue(urls[0].toString(), urls[0].toString().startsWith("http://download.oracle.com/")); List<URL> l = new ArrayList<URL>(); File javadocFile = getBaseDir(); File api = new File(javadocFile, "api"); File index = new File(api, "index-files"); FileUtil.toFileObject(index); index.mkdirs(); l.add(Utilities.toURI(javadocFile).toURL()); J2SEPlatformImpl platformImpl = (J2SEPlatformImpl) platform; platformImpl.setJavadocFolders(l); urls = JavadocForBinaryQuery.findJavadoc(u).getRoots(); assertEquals(1, urls.length); assertEquals(Utilities.toURI(api).toURL(), urls[0]); }
public static Collection<JavaPackage> getPackages( final ClassPath classPath, final boolean includeRootPackage) { Collection<JavaPackage> packages = new TreeSet<JavaPackage>(); for (FileObject root : classPath.getRoots()) { addPackages(classPath, root, includeRootPackage, packages); // JavaPackage pack = new JavaPackage(classPath, root); // if ((pack.isRoot() && includeRootPackage) || !pack.hasSubPackage() || // pack.hasFileChildren()) { // packages.add(pack); // } // for (FileObject subPkg : pack.getChildren()) { // addPackages(classPath, subPkg, packages); // } } return packages; }
public void computeTypeNames(TypeProvider.Context context, TypeProvider.Result res) { isCanceled = false; String text = context.getText(); SearchType searchType = context.getSearchType(); // boolean hasBinaryOpen = Lookup.getDefault().lookup(BinaryElementOpen.class) != null; final ClassIndex.NameKind nameKind; switch (searchType) { case EXACT_NAME: nameKind = ClassIndex.NameKind.SIMPLE_NAME; break; case CASE_INSENSITIVE_EXACT_NAME: nameKind = ClassIndex.NameKind.CASE_INSENSITIVE_REGEXP; break; case PREFIX: nameKind = ClassIndex.NameKind.PREFIX; break; case CASE_INSENSITIVE_PREFIX: nameKind = ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX; break; case REGEXP: nameKind = ClassIndex.NameKind.REGEXP; break; case CASE_INSENSITIVE_REGEXP: nameKind = ClassIndex.NameKind.CASE_INSENSITIVE_REGEXP; break; case CAMEL_CASE: nameKind = ClassIndex.NameKind.CAMEL_CASE; break; default: throw new RuntimeException("Unexpected search type: " + searchType); // NOI18N } long time = 0; long cp, gss, gsb, sfb, gtn, add, sort; cp = gss = gsb = sfb = gtn = add = sort = 0; Future<Project[]> openProjectsTask = OpenProjects.getDefault().openProjects(); Project[] projs = new Project[0]; try { projs = openProjectsTask.get(); } catch (InterruptedException ex) { LOGGER.fine(ex.getMessage()); } catch (ExecutionException ex) { LOGGER.fine(ex.getMessage()); } if (cache == null) { Set<CacheItem> sources = new HashSet<CacheItem>(); Set<FileObject> roots = new HashSet<FileObject>(); for (Project project : projs) { if (!(project instanceof VisageProject)) continue; VisageProject jfxp = (VisageProject) project; ClassPath pcp = jfxp.getClassPathProvider().getProjectSourcesClassPath(ClassPath.SOURCE); for (FileObject root : pcp.getRoots()) { if (roots.add(root)) { ClassPath src = org.netbeans.spi.java.classpath.support.ClassPathSupport.createClassPath(root); ClasspathInfo ci = ClasspathInfo.create(EMPTY_CLASSPATH, EMPTY_CLASSPATH, src); if (isCanceled) return; sources.add(new CacheItem(root, ci, false)); } } } if (isCanceled) return; cache = sources; } ArrayList<VisageTypeDescription> types = new ArrayList<VisageTypeDescription>(); res.setMessage(null); // no startup scanning yet. final String textForQuery; switch (nameKind) { case REGEXP: case CASE_INSENSITIVE_REGEXP: // text = removeNonJavaChars(text); String pattern = searchType == SearchType.CASE_INSENSITIVE_EXACT_NAME ? text : text + "*"; // NOI18N pattern = pattern.replace("*", ".*").replace('?', '.'); textForQuery = pattern; break; default: textForQuery = text; } LOGGER.fine("Text For Query '" + textForQuery + "'."); for (final CacheItem ci : cache) { @SuppressWarnings("unchecked") final Set<ElementHandle<TypeElement>> names = ci.classpathInfo .getClassIndex() .getDeclaredTypes( textForQuery, nameKind, EnumSet.of( ci.isBinary ? ClassIndex.SearchScope.DEPENDENCIES : ClassIndex.SearchScope.SOURCE)); for (ElementHandle<TypeElement> name : names) { VisageTypeDescription td = new VisageTypeDescription(ci, name); types.add(td); if (isCanceled) { return; } } } if (isCanceled) return; res.addResult(types); }
public void reparse(Snapshot snapshot, String content) throws ParseException { LOG.warning("Thread id " + Thread.currentThread().getId()); LOG.warning("Parsing document " + (count++)); this.snapshot = snapshot; // mirahParser = new mirah.impl.MirahParser (); // mirahParser.parse(snapshot.getText().toString()); diag = new MirahParseDiagnostics(); Mirahc compiler = new Mirahc(); // Project proj = snapshot.getSource().getFileObject().getLookup().lookup(Project.class); FileObject src = snapshot.getSource().getFileObject(); // LOG.warning("Source file is "+src); ClassPath compileClassPath = ClassPath.getClassPath(src, ClassPath.COMPILE); // LOG.warning("Project directory is "+proj.getProjectDirectory().getName()); // LOG.warning("Parsing classpath is "+compileClassPath.toString()); ClassPath buildClassPath = ClassPath.getClassPath(src, ClassPath.EXECUTE); // LOG.warning("Execute classapth is "+buildClassPath.toString()); ClassPath srcClassPath = ClassPath.getClassPath(src, ClassPath.SOURCE); // LOG.warning("Src classapth is "+srcClassPath.toString()); compiler.setDestination(buildClassPath.toString()); compiler.setDiagnostics(diag); List<String> paths = new ArrayList<String>(); if (!"".equals(srcClassPath.toString())) { paths.add(srcClassPath.toString()); } if (!"".equals(buildClassPath.toString())) { paths.add(buildClassPath.toString()); } if (!"".equals(compileClassPath.toString())) { paths.add(compileClassPath.toString()); } StringBuilder classPath = new StringBuilder(); for (String path : paths) { classPath.append(path); classPath.append(File.pathSeparator); } String cp = "."; if (classPath.length() >= 1) { cp = classPath.toString().substring(0, classPath.length() - 1); } compiler.setClasspath(cp); DocumentDebugger debugger = new DocumentDebugger(); compiler.setDebugger(debugger); ClassPath bootClassPath = ClassPath.getClassPath(src, ClassPath.BOOT); if (!"".equals(bootClassPath.toString())) { compiler.setBootClasspath(bootClassPath.toString()); } String srcText = content; compiler.addFakeFile(src.getPath(), srcText); try { compiler.compile(new String[0]); } catch (Exception ex) { ex.printStackTrace(); } LOG.warning("Finished parsing document"); synchronized (documentDebuggers) { LOG.warning("Inside sync documentDebuggers"); Document doc = snapshot.getSource().getDocument(true); LOG.warning("Resolved types " + debugger.resolvedTypes); if (debugger.resolvedTypes.size() > 0) { debugger.compiler = compiler; LOG.warning("NEW DOCUMENT DEBUGGER ADDED"); documentDebuggers.put(doc, debugger); fireOnParse(doc); } } }
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; }
boolean valid(WizardDescriptor wizard) { // List<Entity> entities = (List<Entity>) // wizard.getProperty(WizardProperties.ENTITY_CLASS); // String controllerPkg = getPackage(); // // boolean filesAlreadyExist = false; // String troubleMaker = ""; // for (Entity entity : entities) { // String entityClass = entity.getClass2(); // String simpleClassName = JSFClientGenerator.simpleClassName(entityClass); // String firstLower = simpleClassName.substring(0, 1).toLowerCase() + // simpleClassName.substring(1); // String folder = jsfFolder.getText().endsWith("/") ? jsfFolder.getText() : // jsfFolder.getText() + "/"; // folder = folder + firstLower; // String controller = controllerPkg + "." + simpleClassName + "Controller"; // String fqn = getPackage().length() > 0 ? getPackage().replace('.', '/') + "/" + // simpleClassName : simpleClassName; // if (getLocationValue().getRootFolder().getFileObject(fqn + "Controller.java") != // null) { // filesAlreadyExist = true; // troubleMaker = controllerPkg + "." + simpleClassName + "Controller.java"; // break; // } // if (getLocationValue().getRootFolder().getFileObject(fqn + "Converter.java") != // null) { // filesAlreadyExist = true; // troubleMaker = controllerPkg + "." + simpleClassName + "Converter.java"; // break; // } // } // if (filesAlreadyExist) { // wizard.putProperty("WizardPanel_errorMessage", // // NOI18N // NbBundle.getMessage(JpaControllerSetupPanelVisual.class, // "MSG_FilesAlreadyExist", troubleMaker)); // return false; // } // wizard.putProperty("WizardPanel_errorMessage", null); // NOI18N if (Util.isContainerManaged(project)) { ClassPath cp = ClassPath.getClassPath(getLocationValue().getRootFolder(), ClassPath.COMPILE); ClassLoader cl = cp.getClassLoader(true); try { Class.forName("javax.transaction.UserTransaction", false, cl); } catch (ClassNotFoundException cnfe) { wizard.putProperty( "WizardPanel_errorMessage", NbBundle.getMessage( JpaControllerSetupPanelVisual.class, "ERR_UserTransactionUnavailable")); return false; } catch (java.lang.UnsupportedClassVersionError err) { // wizard.putProperty("WizardPanel_errorMessage", // NbBundle.getMessage(JpaControllerSetupPanelVisual.class, // "ERR_UserTransactionJavaVersion")); // return false; } } // Sources srcs = (Sources) project.getLookup().lookup(Sources.class); // SourceGroup sgWeb[] = srcs.getSourceGroups("doc_root"); //NOI18N fixme(mbohm): // move into constant // FileObject pagesRootFolder = sgWeb[0].getRootFolder(); // File pagesRootFolderAsFile = FileUtil.toFile(pagesRootFolder); // String jsfFolderText = jsfFolder.getText(); // try { // String canonPath = new File(pagesRootFolderAsFile, // jsfFolderText).getCanonicalPath(); // } // catch (IOException ioe) { // wizard.putProperty("WizardPanel_errorMessage", // NbBundle.getMessage(JpaControllerSetupPanelVisual.class, // "ERR_JsfTargetChooser_InvalidJsfFolder")); // return false; // } String packageName = getPackage(); if (packageName.trim().equals("")) { // NOI18N wizard.putProperty( "WizardPanel_errorMessage", NbBundle.getMessage( JpaControllerSetupPanelVisual.class, "ERR_JavaTargetChooser_CantUseDefaultPackage")); return false; } if (!JavaIdentifiers.isValidPackageName(packageName)) { wizard.putProperty( "WizardPanel_errorMessage", NbBundle.getMessage( JpaControllerSetupPanelVisual.class, "ERR_JavaTargetChooser_InvalidPackage")); // NOI18N return false; } if (!SourceGroups.isFolderWritable(getLocationValue(), packageName)) { wizard.putProperty( "WizardPanel_errorMessage", NbBundle.getMessage( JpaControllerSetupPanelVisual.class, "ERR_JavaTargetChooser_UnwritablePackage")); // NOI18N return false; } wizard.putProperty("WizardPanel_errorMessage", null); // NOI18N return true; }