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

The following examples show how to use org.netbeans.api.java.classpath.ClassPath#getResourceName() . 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: JaxWsUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** This method is called from Create Web Service from WSDL wizard
 */
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
public static void generateJaxWsArtifacts(Project project, 
        FileObject targetFolder, String targetName, URL wsdlURL, 
        String service, String port) throws Exception 
{
    initProjectInfo(project);
    JAXWSSupport jaxWsSupport = JAXWSSupport.getJAXWSSupport(project.getProjectDirectory());
    String artifactsPckg = "service." + targetName.toLowerCase(); //NOI18N
    ClassPath classPath = ClassPath.getClassPath(targetFolder, ClassPath.SOURCE);
    String serviceImplPath = classPath.getResourceName(targetFolder, '.', false);

    boolean jsr109 = true;
    JaxWsModel jaxWsModel = project.getLookup().lookup(JaxWsModel.class);
    if (jaxWsModel != null) {
        jsr109 = isJsr109(jaxWsModel);
    }
    jaxWsSupport.addService(targetName, serviceImplPath + "." + 
            targetName, wsdlURL.toExternalForm(), service, port, artifactsPckg, jsr109, false);
}
 
Example 2
Source File: Util.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Gets classpath that contains the given resource bundle. 
 * In addition to the bundle file, a source must be given that
 * will access the resource at run-time.
 */
public static ClassPath getExecClassPath(FileObject srcFile, FileObject resFile) {
    // try EXECUTE class-path first
    ClassPath ecp = ClassPath.getClassPath( srcFile, ClassPath.EXECUTE );
    if ((ecp != null) && (ecp.getResourceName( resFile, '.',false) != null))
        return ecp;


    // if not directly on EXECUTE, might be on SOURCE
    ClassPath scp = ClassPath.getClassPath( srcFile, ClassPath.SOURCE);
    // try to find  the resource on source class path
    if ((scp != null) && (scp.getResourceName( resFile, '.',false) != null)) 
        return scp; 

    // now try resource owner
    ClassPath rcp = ClassPath.getClassPath( resFile, ClassPath.SOURCE);
    // try to find  the resource on source class path
    if ((rcp!=null) && (rcp.getResourceName( resFile, '.',false) != null))  
            return rcp; 
    

    return null;
}
 
Example 3
Source File: JPDAReload.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String classToSourceURL (FileObject fo) {
    try {
        ClassPath cp = ClassPath.getClassPath (fo, ClassPath.EXECUTE);
        FileObject root = cp.findOwnerRoot (fo);
        String resourceName = cp.getResourceName (fo, '/', false);
        if (resourceName == null) {
            getProject().log("Can not find classpath resource for "+fo+", skipping...", Project.MSG_ERR);
            return null;
        }
        int i = resourceName.indexOf ('$');
        if (i > 0)
            resourceName = resourceName.substring (0, i);
        FileObject[] sRoots = SourceForBinaryQuery.findSourceRoots 
            (root.getURL ()).getRoots ();
        ClassPath sourcePath = ClassPathSupport.createClassPath (sRoots);
        FileObject rfo = sourcePath.findResource (resourceName + ".java");
        if (rfo == null) return null;
        return rfo.getURL ().toExternalForm ();
    } catch (FileStateInvalidException ex) {
        ex.printStackTrace ();
        return null;
    }
}
 
Example 4
Source File: CommonTestsCfgOfCreate.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void updateClassName() {
    if (tfClassName != null) {
        boolean shouldShowClassNameInfo = shouldShowClassNameInfo();
        tfClassName.setVisible(shouldShowClassNameInfo);
        lblClassName.setVisible(shouldShowClassNameInfo);
        if (shouldShowClassNameInfo) {
            FileObject fileObj = activatedFOs[0];

            ClassPath cp = ClassPath.getClassPath(fileObj, ClassPath.SOURCE);
            if (cp != null) {
                String className = cp.getResourceName(fileObj, '.', false);

                String suffix = (selectedTestingFramework != null && selectedTestingFramework.equals(TestCreatorProvider.FRAMEWORK_SELENIUM))
                        || (chkIntegrationTests != null && chkIntegrationTests.isEnabled() && chkIntegrationTests.isSelected()) ? TestCreatorProvider.INTEGRATION_TEST_CLASS_SUFFIX : TestCreatorProvider.TEST_CLASS_SUFFIX;
                String prefilledName = className + getTestingFrameworkSuffix() + suffix;
                tfClassName.setText(prefilledName);
                tfClassName.setDefaultText(prefilledName);
                tfClassName.setCaretPosition(prefilledName.length());
            }
        }
    }
}
 
Example 5
Source File: SetExecutionUriAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isServletFile(WebModule webModule, FileObject javaClass,
        boolean initialScan) 
{
    if (webModule == null ) {
        return false;
    }
    
    ClassPath classPath = ClassPath.getClassPath (javaClass, ClassPath.SOURCE);
    if (classPath == null) {
        return false;
    }
    String className = classPath.getResourceName(javaClass,'.',false);
    if (className == null) {
        return false;
    }
    
    try {
        MetadataModel<WebAppMetadata> metadataModel = webModule
                .getMetadataModel();
        boolean result = false;
        if ( initialScan || metadataModel.isReady()) {
            List<ServletInfo> servlets = WebAppMetadataHelper
                    .getServlets(metadataModel);
            List<String> servletClasses = new ArrayList<String>( servlets.size() );
            for (ServletInfo si : servlets) {
                if (className.equals(si.getServletClass())) {
                    result =  true;
                }
                else {
                    servletClasses.add( si.getServletClass() );
                }
            }
            setServletClasses( servletClasses,  javaClass , initialScan);
        }
        return result;
    } catch (java.io.IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return false;
}
 
Example 6
Source File: ApisupportHyperlinkProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private @CheckForNull FileObject findBundle(FileObject javaFile) {
    ClassPath cp = ClassPath.getClassPath(javaFile, ClassPath.SOURCE);
    if (cp == null) {
        return null;
    }
    String name = cp.getResourceName(javaFile);
    if (name != null) {
        int index = name.lastIndexOf('/');
        name = name.substring(0, index) + "/Bundle.properties"; //NOI18N
        return cp.findResource(name);
    }
    return null;
}
 
Example 7
Source File: OpenTestAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getTestName(ClassPath cp, FileObject selectedFO) {
    String resource = cp.getResourceName(selectedFO, '/', false);        
    String testName = null;
    if (selectedFO.isFolder()) {
    //find Suite for package
        testName = JUnitTestUtil.convertPackage2SuiteName(resource);
    } else {
    // find Test for class
        testName = JUnitTestUtil.convertClass2TestName(resource);
    }
    
    return testName;
}
 
Example 8
Source File: SourcePathProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns relative path for given url.
 *
 * @param url a url of resource file
 * @param directorySeparator a directory separator character
 * @param includeExtension whether the file extension should be included 
 *        in the result
 *
 * @return relative path
 */
@Override
public String getRelativePath (
    String url, 
    char directorySeparator, 
    boolean includeExtension
) {
    // 1) url -> FileObject
    FileObject fo;                                              if (verbose) System.out.println ("SPPI: getRelativePath " + url);
    try {
        fo = URLMapper.findFileObject (new URL (url));          if (verbose) System.out.println ("SPPI:   fo " + fo);
    } catch (MalformedURLException e) {
        //e.printStackTrace ();
        return null;
    }
    if (fo == null) {
        return null;
    }
    String relativePath = smartSteppingSourcePath.getResourceName (
        fo, 
        directorySeparator,
        includeExtension
    );
    if (relativePath == null) {
        // fallback to FileObject's class path
        ClassPath cp = ClassPath.getClassPath (fo, ClassPath.SOURCE);
        if (cp == null) {
            cp = ClassPath.getClassPath (fo, ClassPath.COMPILE);
        }
        if (cp == null) {
            return null;
        }
        relativePath = cp.getResourceName (
            fo, 
            directorySeparator,
            includeExtension
        );
    }
    return relativePath;
}
 
Example 9
Source File: JavaIdentifiers.java    From jeddict 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 fileObject 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(FileObject fileObject){
    Parameters.notNull("fileObject", fileObject); //NOI18N
    ClassPath classPath = ClassPath.getClassPath(fileObject, ClassPath.SOURCE);
    if (classPath != null) {
        return classPath.getResourceName(fileObject, '.', false);
    }
    return null;
}
 
Example 10
Source File: TaskCache.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public boolean isInError(FileObject file, boolean recursive) {
    LOG.log(Level.FINE, "file={0}, recursive={1}", new Object[] {file, Boolean.valueOf(recursive)}); //NOI18N
    
    if (file.isData()) {
        return !getErrors(file, ERR_EXT).isEmpty();
    } else {
        try {
            ClassPath cp = Utilities.getSourceClassPathFor (file);
            
            if (cp == null) {
                return false;
            }
            
            FileObject root = cp.findOwnerRoot(file);
            
            if (root == null) {
                LOG.log(Level.FINE, "file={0} does not have a root on its own source classpath", file); //NOI18N
                return false;
            }
            
            String resourceName = cp.getResourceName(file, File.separatorChar, true);
            File cacheRoot = getCacheRoot(root.toURL(), true);
            
            if (cacheRoot == null) {
                //index does not exist:
                return false;
            }
            
            final File folder = new File(cacheRoot, resourceName);
            
            return folderContainsErrors(folder, recursive);
        } catch (IOException e) {
            LOG.log(Level.WARNING, null, e); //NOI18N
            return false;
        }
    }
}
 
Example 11
Source File: JavaIdentifiers.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 fileObject 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(FileObject fileObject){
    Parameters.notNull("fileObject", fileObject); //NOI18N
    ClassPath classPath = ClassPath.getClassPath(fileObject, ClassPath.SOURCE);
    if (classPath != null) {
        return classPath.getResourceName(fileObject, '.', false);
    }
    return null;
}
 
Example 12
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 13
Source File: CopyClassesUI.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()); //NOI18N
        return f.getName();
    }
}
 
Example 14
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 15
Source File: RefactoringInfo.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String getTargetName(MoveRefactoring refactoring, String fileName) {
    URL targetURL = refactoring.getTarget().lookup(URL.class);
    File f = null;
    try {
        if (targetURL != null) {
            f = FileUtil.normalizeFile(new File(targetURL.toURI()));
        }
    } catch (URISyntaxException ex) {
        Exceptions.printStackTrace(ex);
    }
    LinkedList<String> nonExisting = null; // the path to target folder may not exist yet
    while (f != null && !f.exists()) {
        if (nonExisting == null) {
            nonExisting = new LinkedList<String>();
        }
        nonExisting.addFirst(f.getName());
        f = f.getParentFile();
    }
    FileObject targetFolder = (f != null) ? FileUtil.toFileObject(f) : null;
    if (targetFolder != null && targetFolder.isFolder()) {
        ClassPath cp = ClassPath.getClassPath(targetFolder, ClassPath.SOURCE);
        if (cp != null) {
            String pkg = cp.getResourceName(targetFolder, '.', false);
            StringBuilder buf = new StringBuilder();
            if (pkg != null) {
                buf.append(pkg);
                if (buf.length() > 0) {
                    buf.append('.');
                }
            }
            if (nonExisting != null && !nonExisting.isEmpty()) {
                for (String s : nonExisting) {
                    buf.append(s);
                    buf.append('.');
                }
            }
            buf.append(fileName);
            return buf.toString();
        }
    }
    return null;
}
 
Example 16
Source File: JaxWsServiceCreator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void generateWebServiceFromEJB(String wsName, FileObject pkg, 
        ProjectInfo projectInfo, Node[] nodes) 
        throws IOException, ServiceAlreadyExistsExeption, PropertyVetoException 
{

    if (nodes != null && nodes.length == 1) {

        EjbReference ejbRef = nodes[0].getLookup().lookup(EjbReference.class);
        if (ejbRef != null) {

            DataFolder df = DataFolder.findFolder(pkg);
            FileObject template = Templates.getTemplate(wiz);
            FileObject templateParent = template.getParent();
            if ((Boolean)wiz.getProperty(WizardProperties.IS_STATELESS_BEAN)) { //EJB Web Service
                template = templateParent.getFileObject("EjbWebServiceNoOp", 
                        "java"); //NOI18N
            } else {
                template = templateParent.getFileObject("WebServiceNoOp", 
                        "java"); //NOI18N
            }
            DataObject dTemplate = DataObject.find(template);
            DataObject dobj = dTemplate.createFromTemplate(df, wsName);
            FileObject createdFile = dobj.getPrimaryFile();
            createdFile.setAttribute("jax-ws-service", java.lang.Boolean.TRUE);     // NOI18N
            dobj.setValid(false);
            dobj = DataObject.find(createdFile);

            ClassPath classPath = getClassPathForFile(projectInfo.getProject(), 
                    createdFile);
            if (classPath != null) {
                String serviceImplPath = classPath.getResourceName(createdFile, 
                        '.', false);
                generateDelegateMethods(createdFile, ejbRef);

                final JaxWsModel jaxWsModel = projectInfo.getProject().
                    getLookup().lookup(JaxWsModel.class);
                if (jaxWsModel != null) {
                    jaxWsModel.addService(wsName, serviceImplPath);
                    ProjectManager.mutex().writeAccess(new Runnable() {

                        public void run() {
                            try {
                                jaxWsModel.write();
                            } catch (IOException ex) {
                                ErrorManager.getDefault().notify(ex);
                            }
                        }
                    });
                }
            }
            JaxWsUtils.openFileInEditor(dobj);
            displayDuplicityWarning(createdFile);
        }
    }
}
 
Example 17
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 18
Source File: I18nPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void setDefaultResource(DataObject dataObject) {
        if (dataObject != null) {
            // look for peer Bundle.properties
            FileObject fo = dataObject.getPrimaryFile();
            ClassPath cp = ClassPath.getClassPath(fo, ClassPath.SOURCE);

            if (cp != null) {
                FileObject folder = cp.findResource(cp.getResourceName(fo.getParent()));

                while (folder != null && cp.contains(folder)) {
                
                    String rn = cp.getResourceName(folder) + "/Bundle.properties"; // NOI18N
                
                    FileObject peer = cp.findResource(rn);
                    if (peer == null) {
                        //Try to find any properties file
                        Enumeration<? extends FileObject> data = Enumerations.filter(folder.getData(false), new Enumerations.Processor(){
                            public Object process(Object obj, Collection alwaysNull) {
                                if (obj instanceof FileObject &&
                                        "properties".equals( ((FileObject)obj).getExt())){ //NOI18N
                                    return obj;
                                } else {
                                    return null;
                                }
                            }
                        });
                        if (data.hasMoreElements()) {
                            peer = data.nextElement();
                        }
                    }
                    if (peer != null) {
                        try {
                            DataObject peerDataObject = DataObject.find(peer);
//                          ((ResourcePanel)resourcePanel).setResource(peerDataObject);
                            propertyPanel.setResource(peerDataObject);
                            return;
                        } catch (IOException ex) {
                            // no default resource
                        }
                    }
                    folder = folder.getParent();
                }
            }
        }
    }
 
Example 19
Source File: GsfDataLoader.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected MultiDataObject.Entry createPrimaryEntry (MultiDataObject obj, FileObject primaryFile) {
    FileEntry.Format entry = new FileEntry.Format(obj, primaryFile) {
        @Override
        protected java.text.Format createFormat (FileObject target, String n, String e) {
            ClassPath cp = ClassPath.getClassPath(target, ClassPath.SOURCE);
            String resourcePath = "";
            if (cp != null) {
                resourcePath = cp.getResourceName(target);
                if (resourcePath == null) {
                    resourcePath = ""; // NOI18N
                }
            } else {
                ErrorManager.getDefault().log(ErrorManager.WARNING, "No classpath was found for folder: "+target);
            }
            Map<String,String> m = new HashMap<String,String>();
            m.put("NAME", n ); //NOI18N
            String capitalizedName;
            if (n.length() > 1) {
                capitalizedName = Character.toUpperCase(n.charAt(0))+n.substring(1);
            } else if (n.length() == 1) {
                capitalizedName = ""+Character.toUpperCase(n.charAt(0));
            } else {
                capitalizedName = "";
            }
            m.put("CAPITALIZEDNAME", capitalizedName); //NOI18N
            m.put("LOWERNAME", n.toLowerCase()); //NOI18N
            m.put("UPPERNAME", n.toUpperCase()); //NOI18N

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < n.length(); i++) {
                char c = n.charAt(i);
                if (Character.isJavaIdentifierPart(c)) {
                    sb.append(c);
                }
            }
            String identifier = sb.toString();
            m.put("IDENTIFIER", identifier); // NOI18N
            sb.setCharAt(0, Character.toUpperCase(identifier.charAt(0)));
            m.put("CAPITALIZEDIDENTIFIER", sb.toString()); // NOI18N
            m.put("LOWERIDENTIFIER", identifier.toLowerCase()); //NOI18N
            
            // Yes, this is package sans filename (target is a folder).
            String packageName = resourcePath.replace('/', '.');
            m.put("PACKAGE", packageName); // NOI18N
            String capitalizedPkgName;
            if (packageName == null || packageName.length() == 0) {
                packageName = "";
                capitalizedPkgName = "";
            } else if (packageName.length() > 1) {
                capitalizedPkgName = Character.toUpperCase(packageName.charAt(0))+packageName.substring(1);
            } else {
                capitalizedPkgName = ""+Character.toUpperCase(packageName.charAt(0));
            }
            m.put("CAPITALIZEDPACKAGE", capitalizedPkgName); // NOI18N
            m.put("PACKAGE_SLASHES", resourcePath); // NOI18N
            // Fully-qualified name:
            if (target.isRoot ()) {
                m.put ("PACKAGE_AND_NAME", n); // NOI18N
                m.put ("PACKAGE_AND_NAME_SLASHES", n); // NOI18N
            } else {
                m.put ("PACKAGE_AND_NAME", resourcePath.replace('/', '.') + '.' + n); // NOI18N
                m.put ("PACKAGE_AND_NAME_SLASHES", resourcePath + '/' + n); // NOI18N
            }
            m.put("DATE", DateFormat.getDateInstance(DateFormat.LONG).format(new Date())); // NOI18N
            m.put("TIME", DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date())); // NOI18N
            MapFormat f = new MapFormat(m);
            f.setLeftBrace( "__" ); //NOI18N
            f.setRightBrace( "__" ); //NOI18N
            f.setExactMatch(false);

            return f;
        }
    };
    return entry;
}
 
Example 20
Source File: ActionProviderImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public String convert(ClassPath sourceCP, FileObject file) {
    return sourceCP.getResourceName(file, '.', false);
}