Java Code Examples for org.netbeans.api.java.classpath.ClassPath#getClassPath()

The following examples show how to use org.netbeans.api.java.classpath.ClassPath#getClassPath() . 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: GeneratedSourceRootTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testFirstGenSrcAddedDynamically() throws Exception {
    Project p = createTestProject(false);
    FileObject d = p.getProjectDirectory();
    FileObject src = d.getFileObject("src");
    URL classes = new URL(d.toURL(), "build/classes/");
    URL distJar = FileUtil.getArchiveRoot(BaseUtilities.toURI(FileUtil.normalizeFile(
            new File(FileUtil.toFile(d), "dist/x.jar".replace('/', File.separatorChar)))).toURL()); //NOI18N
    ClassPath sourcePath = ClassPath.getClassPath(src, ClassPath.SOURCE);
    assertEquals(Arrays.asList(src), Arrays.asList(sourcePath.getRoots()));
    assertEquals(Arrays.asList(src), Arrays.asList(SourceForBinaryQuery.findSourceRoots(classes).getRoots()));
    // now add the first gensrc root:
    FileObject stuff = FileUtil.createFolder(d, "build/generated-sources/stuff");
    FileObject xgen = FileUtil.createData(stuff, "net/nowhere/XGen.java");
    assertEquals(Arrays.asList(src, stuff), Arrays.asList(sourcePath.getRoots()));
    assertEquals(ClassPath.getClassPath(src, ClassPath.COMPILE), ClassPath.getClassPath(stuff, ClassPath.COMPILE));
    assertEquals(Arrays.asList(src, stuff), Arrays.asList(SourceForBinaryQuery.findSourceRoots(classes).getRoots()));
    assertEquals(Arrays.asList(classes, distJar), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(stuff.toURL()).getRoots()));
    FileBuiltQuery.Status status = FileBuiltQuery.getStatus(xgen);
    assertNotNull(status);
    assertFalse(status.isBuilt());
    FileUtil.createData(d, "build/classes/net/nowhere/XGen.class");
    assertTrue(status.isBuilt());
}
 
Example 2
Source File: RestUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static boolean isAnnotationConfigAvailable(Project project) throws IOException {
    RestSupport restSupport = project.getLookup().lookup(RestSupport.class);
    if ( restSupport!= null ){
        if ( restSupport.hasSpringSupport()){
            return false;
        }
    }
    
    if (MiscUtilities.isJavaEE6AndHigher(project)) {
        SourceGroup[] sourceGroups = SourceGroupSupport
                .getJavaSourceGroups(project);
        if (sourceGroups.length > 0) {
            ClassPath cp = ClassPath.getClassPath(
                    sourceGroups[0].getRootFolder(), ClassPath.COMPILE);
            if (cp!=null && cp.findResource(
                    "javax/ws/rs/ApplicationPath.class") != null      // NOI18N
                    && cp.findResource(
                            "javax/ws/rs/core/Application.class") != null)// NOI18N
            { 
                return true;
            }
        }
    }
    return false;
}
 
Example 3
Source File: JavaTemplateAttributesProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Map<String,?> attributesFor(DataObject template, DataFolder target, String name) {
    FileObject templateFO = template.getPrimaryFile();
    if (!JavaDataLoader.JAVA_EXTENSION.equals(templateFO.getExt()) || templateFO.isFolder()) {
        return null;
    }
    
    FileObject targetFO = target.getPrimaryFile();
    Map<String,Object> result = new HashMap<String,Object>();
    
    ClassPath cp = ClassPath.getClassPath(targetFO, ClassPath.SOURCE);
    if (cp == null) {
        LOG.warning("No classpath was found for folder: " + target.getPrimaryFile()); // NOI18N
    }
    else {
        result.put("package", cp.getResourceName(targetFO, '.', false)); // NOI18N
    }
    
    String sourceLevel = SourceLevelQuery.getSourceLevel(targetFO);
    if (sourceLevel != null) {
        result.put("javaSourceLevel", sourceLevel); // NOI18N
        if (isJava15orLater(sourceLevel))
            result.put("java15style", Boolean.TRUE); // NOI18N
    }
    
    return result;
}
 
Example 4
Source File: IconEditor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static NbImageIcon iconFromResourceName(String resName, FileObject srcFile) {
    ClassPath cp = ClassPath.getClassPath(srcFile, ClassPath.SOURCE);
    FileObject fo = cp.findResource(resName);
    if (fo == null) {
        cp = ClassPath.getClassPath(srcFile, ClassPath.EXECUTE);
        fo = cp.findResource(resName);
    }
    if (fo != null) {
        try {
            try {
                Image image = ImageIO.read(fo.getURL());
                if (image != null) { // issue 157546
                    return new NbImageIcon(TYPE_CLASSPATH, resName, new ImageIcon(image));
                }
            } catch (IllegalArgumentException iaex) { // Issue 178906
                Logger.getLogger(IconEditor.class.getName()).log(Level.INFO, null, iaex);
                return new NbImageIcon(TYPE_CLASSPATH, resName, new ImageIcon(fo.getURL()));
            }
        } catch (IOException ex) { // should not happen
            Logger.getLogger(IconEditor.class.getName()).log(Level.WARNING, null, ex);
        }
    }
    return null;
}
 
Example 5
Source File: RenamePackagePlugin.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public RenameNonRecursiveFolder(FileObject folder) {
    this.folder = folder;
    ClassPath classPath = ClassPath.getClassPath(folder, ClassPath.SOURCE);

    if (classPath != null) {
        this.currentName = classPath.getResourceName(folder, '.', false); //NOI18N
        this.oldName = this.currentName;
        this.root = classPath.findOwnerRoot(folder);
    }
}
 
Example 6
Source File: MoveClassesUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getDOPackageName(FileObject f) {
    ClassPath cp = ClassPath.getClassPath(f, ClassPath.SOURCE);
    if (cp!=null) {
        return cp.getResourceName(f, '.', false);
    } else {
        Logger.getLogger("org.netbeans.modules.refactoring.java").info("Cannot find classpath for " + f.getPath());
        return f.getName();
    }
}
 
Example 7
Source File: IdentifiersUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the fully qualified name for the given <code>fileObject</code>. If it
 * represents a java package, returns the name of the package (with dots as separators).
 *
 * @param fo the file object whose FQN is to be get; must not be null.
 * @return the FQN for the given file object or null.
 */
public static String getQualifiedName(final FileObject fo){
    Parameters.notNull("fileObject", fo); // NOI18N
    ClassPath classPath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
    if (classPath != null) {
        return classPath.getResourceName(fo, '.', false);
    }
    return null;
}
 
Example 8
Source File: SourcePathProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the source root (if any) for given url.
 *
 * @param url a url of resource file
 *
 * @return the source root or <code>null</code> when no source root was found.
 */
@Override
public synchronized String getSourceRoot(String url) {
    FileObject fo;
    try {
        fo = URLMapper.findFileObject(new java.net.URL(url));
    } catch (java.net.MalformedURLException ex) {
        fo = null;
    }
    FileObject[] roots = null;
    if (fo != null && fo.canRead()) {
        ClassPath cp = ClassPath.getClassPath(fo, ClassPath.SOURCE);
        if (cp != null) {
            roots = cp.getRoots();
        }
    }
    if (roots == null) {
        roots = originalSourcePath.getRoots();
    }
    for (FileObject fileObject : roots) {
        String rootURL = fileObject.toURL().toString();
        if (url.startsWith(rootURL)) {
            String root = getRoot(fileObject);
            if (root != null) {
                return root;
            }
        }
    }
    return null; // not found
}
 
Example 9
Source File: Utils.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the execute {@code ClassPath} object for the given project.
 *
 * @param proj the project
 * @return found ClassPath object or null
 */
public static ClassPath execClasspathForProj(Project proj) {
    Sources srcs = ProjectUtils.getSources(proj);
    SourceGroup[] srcGroups = srcs.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    if (srcGroups.length > 0) {
        return ClassPath.getClassPath(srcGroups[0].getRootFolder(), ClassPath.EXECUTE);
    } else {
        logger.log(WARNING, "No sources found for project: {0}", new Object[]{proj.toString()});
    }
    return null;
}
 
Example 10
Source File: PersistenceXmlPackageRename.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Problem prepare(RefactoringElementsBag refactoringElementsBag) {
    if (isPackage()){
        FileObject pkg = renameRefactoring.getRefactoringSource().lookup(NonRecursiveFolder.class).getFolder();
        String oldPackageName = JavaIdentifiers.getQualifiedName(pkg);
        
        return doPrepare(refactoringElementsBag, pkg, oldPackageName, renameRefactoring.getNewName());
    } else if (isFolder()){
        FileObject folder = renameRefactoring.getRefactoringSource().lookup(FileObject.class);
        ClassPath classPath = ClassPath.getClassPath(folder, ClassPath.SOURCE);
        if(classPath == null){
            return null;//it may happens for folders in php and similar projects, see #181611
        }
        FileObject root = classPath.findOwnerRoot(folder);
        // issue 62320. By JavaDoc, ClassPath.fineOwnerRoot can return null
        if(root == null ) {
            return null;
        }
        String prefix = FileUtil.getRelativePath(root, folder.getParent());
        // #249491
        if (prefix == null) {
            return null;
        }
        prefix = prefix.replace('/','.'); // NOI18N
        String oldName = buildName(prefix, folder.getName());
        // the new package name
        String newName = buildName(prefix, renameRefactoring.getNewName());
        
        return doPrepare(refactoringElementsBag, folder, oldName, newName);
    }
    return null;
}
 
Example 11
Source File: TestUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Determines source level of the given file.
 * 
 * @param  file  file whose source level is to be determined
 * @return  string denoting source level of the given file
 *          (e.g. <code>&quot;1.5&quot;</code>)
 *          or {@code null} if the source level could not be determined
 */
static String getSourceLevel(FileObject file) {
    ClassPath srcCP = ClassPath.getClassPath(file, ClassPath.SOURCE);
    if (srcCP == null) {
        return null;
    }
    
    FileObject srcRoot = srcCP.findOwnerRoot(file);
    if (srcRoot == null) {
        return null;
    }
    
    return SourceLevelQuery.getSourceLevel(srcRoot);
}
 
Example 12
Source File: ActivatorIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Set<DataObject> instantiate () throws IOException/*, IllegalStateException*/ {
    // Here is the default plain behavior. Simply takes the selected
    // template (you need to have included the standard second panel
    // in createPanels(), or at least set the properties targetName and
    // targetFolder correctly), instantiates it in the provided
    // position, and returns the result.
    // More advanced wizards can create multiple objects from template
    // (return them all in the result of this method), populate file
    // contents on the fly, etc.
   
    org.openide.filesystems.FileObject dir = Templates.getTargetFolder( wiz );
    DataFolder df = DataFolder.findFolder( dir );
    
    FileObject template = Templates.getTemplate( wiz );
    
    DataObject dTemplate = DataObject.find( template );                
    final DataObject dobj = dTemplate.createFromTemplate( df, Templates.getTargetName( wiz )  );

    //this part might be turned pluggable once we have also ant based osgi projects. if..
    Project project = Templates.getProject( wiz );
    ClassPath cp = ClassPath.getClassPath(dobj.getPrimaryFile(), ClassPath.SOURCE);
    final String path = cp.getResourceName(dobj.getPrimaryFile(), '.', false);

    final NbMavenProject prj = project.getLookup().lookup(NbMavenProject.class);
    if (prj != null) {
        Utilities.performPOMModelOperations(project.getProjectDirectory().getFileObject("pom.xml"),
                Collections.<ModelOperation<POMModel>>singletonList(
                    new ModelOperation<POMModel>() {
            @Override
                       public void performOperation(POMModel model) {
                           addActivator(prj, model, path);
                       }
                }
        ));
    }

    return Collections.singleton(dobj);
}
 
Example 13
Source File: PersistenceHelper.java    From jeddict with Apache License 2.0 5 votes vote down vote up
public static boolean hasResource(Project project, String resource) {
    SourceGroup[] sgs = ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    if (sgs.length < 1) {
        return false;
    }
    FileObject sourceRoot = sgs[0].getRootFolder();
    ClassPath classPath = ClassPath.getClassPath(sourceRoot, ClassPath.COMPILE);
    if (classPath == null) {
        return false;
    }
    FileObject resourceFile = classPath.findResource(resource);
    return resourceFile != null;
}
 
Example 14
Source File: WsitProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public boolean isWsitRtOnClasspath() {
    SourceGroup[] sgs = ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    if ((sgs != null) && (sgs.length > 0)) {
        ClassPath classPath = ClassPath.getClassPath(sgs[0].getRootFolder(),ClassPath.COMPILE);
        FileObject rtFO = classPath.findResource("com/sun/xml/wss/impl/callback/SAMLCallback.class"); // NOI18N
        if ((rtFO != null)) {
            return true;
        }
    }
    return false;
}
 
Example 15
Source File: PersistenceUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the persistence unit(s) the given entity class belongs to. Since
 * an entity class can belong to any persistence unit, this returns all
 * persistence units in all persistence.xml files in the project which owns
 * the given entity class.
 *
 * @return an array of PersistenceUnit's; never null.
 * @throws NullPointerException if <code>sourceFile</code> is null.
 */
public static PersistenceUnit[] getPersistenceUnits(FileObject sourceFile) throws IOException {
    if (sourceFile == null) {
        throw new NullPointerException("The sourceFile parameter cannot be null"); // NOI18N
    }
    
    Project project = FileOwnerQuery.getOwner(sourceFile);
    if (project == null) {
        return new PersistenceUnit[0];
    }
    
    List<PersistenceUnit> result = new ArrayList<PersistenceUnit>();
    ClassPath cp = ClassPath.getClassPath(sourceFile, ClassPath.SOURCE);
    for (PersistenceScope persistenceScope : getPersistenceScopes(project, cp != null ? cp.findOwnerRoot(sourceFile) : null)) {
        Persistence persistence = null;
        try{
            persistence = PersistenceMetadata.getDefault().getRoot(persistenceScope.getPersistenceXml());
        } catch (RuntimeException ex) {// must catch RTE (thrown by schema2beans when document is not valid)
            LOG.log(Level.INFO, null, ex);
        }
        if(persistence != null) {
            result.addAll(Arrays.asList(persistence.getPersistenceUnit()));
        }
    }
    
    return (PersistenceUnit[])result.toArray(new PersistenceUnit[result.size()]);
}
 
Example 16
Source File: PageIterator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean isJSF20(WebModule wm) {
    ClassPath classpath = ClassPath.getClassPath(wm.getDocumentBase(), ClassPath.COMPILE);
    return classpath != null && classpath.findResource("javax/faces/application/ProjectStage.class") != null; //NOI18N
}
 
Example 17
Source File: CurrentPackageScopeProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
    public boolean initialize(Lookup context, AtomicBoolean cancel) {
        FileObject file = context.lookup(FileObject.class);
        if (file == null) {
            return false;
        }
        final FileObject packageFolder;
        final String packageName;
        ClassPath sourceCP = ClassPath.getClassPath(file, ClassPath.SOURCE);
        if (sourceCP != null) {
//            TreePathHandle path = context.lookup(TreePathHandle.class);
//            if (path != null) {
//                final ExpressionTree packageName1 = path.getCompilationUnit().getPackageName();
//                packageName = packageName1 == null ? "<default package>" : packageName1.toString(); //NOI18N
//                if (packageName1 == null) {
//                    packageFolder = sourceCP.findOwnerRoot(file);
//                } else {
//                    packageFolder = sourceCP.findResource(packageName.replaceAll("\\.", "/")); //NOI18N
//                }
//            } else {
            packageFolder = file.isFolder()? file : file.getParent();
            String packageName1 = sourceCP.getResourceName(packageFolder, '.', false);
            if(packageName1 == null) {
                return false;
            }
            packageName = packageName1.isEmpty()? "<default package>" : packageName1; //NOI18N
//            }
        } else {
            packageFolder = null;
            packageName = null;
        }

        if (packageFolder != null) {
            detail = packageName;
            scope = Scope.create(null, Arrays.<NonRecursiveFolder>asList(new NonRecursiveFolder() {
                @Override
                public FileObject getFolder() {
                    return packageFolder;
                }
            }), null);
            return true;
        }
        return false;
    }
 
Example 18
Source File: MoveClassUI.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String getPackageName(FileObject file) {
    ClassPath cp = ClassPath.getClassPath(file, ClassPath.SOURCE);
    return cp.getResourceName(file, '.', false);
}
 
Example 19
Source File: WhereUsedPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void setupScope() {
    final FileObject fo = element.getFileObject();
    final String packageName = element.getOwnerNameWithoutPackage();
    final Project p = FileOwnerQuery.getOwner(fo);
    final ClassPath classPath = ClassPath.getClassPath(fo, ClassPath.SOURCE);

    if (classPath != null) {
        if(packageName == null) {
            packageFolder = classPath.findOwnerRoot(fo);
        } else {
            packageFolder = classPath.findResource(packageName.replaceAll("\\.", "/")); //NOI18N
        }
    }

    final JLabel customScope;
    final JLabel currentFile;
    final JLabel currentPackage;
    final JLabel currentProject;
    final JLabel allProjects;
    if (p != null) {
        ProjectInformation pi = ProjectUtils.getInformation(FileOwnerQuery.getOwner(fo));
        DataObject currentFileDo = null;
        try {
            currentFileDo = DataObject.find(fo);
        } catch (DataObjectNotFoundException ex) {
        } // Not important, only for Icon.
        customScope = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_CustomScope"), pi.getIcon(), SwingConstants.LEFT); //NOI18N
        currentFile = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_CurrentFile", fo.getNameExt()), currentFileDo != null ? new ImageIcon(currentFileDo.getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16)) : pi.getIcon(), SwingConstants.LEFT); //NOI18N
        currentPackage = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_CurrentPackage", packageName), ImageUtilities.loadImageIcon(PACKAGE, false), SwingConstants.LEFT); //NOI18N
        currentProject = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_CurrentProject", pi.getDisplayName()), pi.getIcon(), SwingConstants.LEFT); //NOI18N
        allProjects = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_AllProjects"), pi.getIcon(), SwingConstants.LEFT); //NOI18N
    } else {
        customScope = null;
        currentFile = null;
        currentPackage = null;
        currentProject = null;
        allProjects = null;
    }

    if ((element.getKind().equals(ElementKind.VARIABLE) ||
         element.getKind().equals(ElementKind.PARAMETER)) ||
         element.getModifiers().contains(Modifier.PRIVATE)) {
        
        enableScope = false;
    }

    innerPanel.removeAll();
    innerPanel.add(panel, BorderLayout.CENTER);
    panel.setVisible(true);

    if(enableScope && currentProject != null) {
        scope.setModel(new DefaultComboBoxModel(new Object[]{allProjects, currentProject, currentPackage, currentFile, customScope }));
        int defaultItem = (Integer) RefactoringModule.getOption("whereUsed.scope", 0); // NOI18N
        WhereUsedPanel.this.customScope = readScope();
        if(defaultItem == 4 && WhereUsedPanel.this.customScope !=null &&
                WhereUsedPanel.this.customScope.getFiles().isEmpty() &&
                WhereUsedPanel.this.customScope.getFolders().isEmpty() &&
                WhereUsedPanel.this.customScope.getSourceRoots().isEmpty()) {
            scope.setSelectedIndex(0);
        } else {
            scope.setSelectedIndex(defaultItem);
        }
        scope.setRenderer(new JLabelRenderer());
    } else {
        scopePanel.setVisible(false);
    }
}
 
Example 20
Source File: OpenTestAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected void performAction (Node[] nodes) {
    FileObject selectedFO;
    
    for (int i = 0; i < nodes.length; i++) {
        // get test class or suite class file, if it was not such one pointed by the node
        selectedFO = org.netbeans.modules.gsf.testrunner.ui.api.UICommonUtils.getFileObjectFromNode(nodes[i]);
        if (selectedFO == null) {
            JUnitTestUtil.notifyUser(NbBundle.getMessage(OpenTestAction.class, "MSG_file_from_node_failed"));
            continue;
        }
        ClassPath cp = ClassPath.getClassPath(selectedFO, ClassPath.SOURCE);
        if (cp == null) {
            JUnitTestUtil.notifyUser(NbBundle.getMessage(OpenTestAction.class, 
                "MSG_no_project", selectedFO));
            continue;
        }
 
        FileObject packageRoot = cp.findOwnerRoot(selectedFO);            
        URL[] testRoots = UnitTestForSourceQuery.findUnitTests(packageRoot);
        FileObject fileToOpen = null;
        for (int j = 0 ; j < testRoots.length; j++) {
            fileToOpen = findUnitTestInTestRoot(cp, selectedFO, testRoots[j]);
            if (fileToOpen != null) break;
        }
        
        if (fileToOpen != null) {
            openFile(fileToOpen);
        } else {                
            String testClsName = getTestName(cp, selectedFO).replace('/','.');                                                
            String pkgName = cp.getResourceName(selectedFO, '.', false);                
            boolean isPackage = selectedFO.isFolder();
            boolean isDefPkg = isPackage && (pkgName.length() == 0);
            String msgPattern = !isPackage
                   ? "MSG_test_class_not_found"                     //NOI18N
                   : isDefPkg
                     ? "MSG_testsuite_class_not_found_def_pkg"      //NOI18N
                     : "MSG_testsuite_class_not_found";             //NOI18N
                            
            String[] params = isDefPkg ? new String[] { testClsName }
                                       : new String[] { testClsName,
                                                        pkgName };                                                                             
                             
            JUnitTestUtil.notifyUser(NbBundle.getMessage(OpenTestAction.class,
                                                    msgPattern, params),
                                ErrorManager.INFORMATIONAL);
            continue;
        }
    }
}