Java Code Examples for org.openide.util.Utilities#toURI()

The following examples show how to use org.openide.util.Utilities#toURI() . 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: FileOwnerQueryTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testFileOwner() throws Exception {
    assertEquals("correct project from projfile FileObject", p, FileOwnerQuery.getOwner(projfile));
    URI u = Utilities.toURI(FileUtil.toFile(projfile));
    assertEquals("correct project from projfile URI " + u, p, FileOwnerQuery.getOwner(u));
    assertEquals("correct project from projfile2 FileObject", p, FileOwnerQuery.getOwner(projfile2));
    assertEquals("correct project from projfile2 URI", p, FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(projfile2))));
    assertEquals("correct project from projdir FileObject", p, FileOwnerQuery.getOwner(projdir));
    assertEquals("correct project from projdir URI", p, FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(projdir))));
    // Check that it loads the project even though we have not touched it yet:
    Project p2 = FileOwnerQuery.getOwner(subprojfile);
    Project subproj = ProjectManager.getDefault().findProject(subprojdir);
    assertEquals("correct project from subprojdir FileObject", subproj, p2);
    assertEquals("correct project from subprojdir URI", subproj, FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(subprojdir))));
    assertEquals("correct project from subprojfile FileObject", subproj, FileOwnerQuery.getOwner(subprojfile));
    assertEquals("correct project from subprojfile URI", subproj, FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(subprojfile))));
    assertEquals("no project from randomfile FileObject", null, FileOwnerQuery.getOwner(randomfile));
    assertEquals("no project from randomfile URI", null, FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(randomfile))));
    assertEquals("no project in C:\\", null, FileOwnerQuery.getOwner(URI.create("file:/C:/")));
}
 
Example 2
Source File: ProjectOpenedHookImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Set<URI> getProjectExternalSourceRoots(NbMavenProjectImpl project) throws IllegalArgumentException {
    Set<URI> uris = new HashSet<URI>();
    Set<URI> toRet = new HashSet<URI>();
    uris.addAll(Arrays.asList(project.getSourceRoots(false)));
    uris.addAll(Arrays.asList(project.getSourceRoots(true)));
    //#167572 in the unlikely event that generated sources are located outside of
    // the project root.
    uris.addAll(Arrays.asList(project.getGeneratedSourceRoots(false)));
    uris.addAll(Arrays.asList(project.getGeneratedSourceRoots(true)));
    URI rootUri = Utilities.toURI(FileUtil.toFile(project.getProjectDirectory()));
    File rootDir = Utilities.toFile(rootUri);
    for (URI uri : uris) {
        if (FileUtilities.getRelativePath(rootDir, Utilities.toFile(uri)) == null) {
            toRet.add(uri);
        }
    }
    return toRet;
}
 
Example 3
Source File: DelegatingVCS.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public CollocationQueryImplementation2 getCollocationQueryImplementation() {
    if(collocationQuery == null) {
        collocationQuery = new CollocationQueryImplementation2() {
            private CollocationQueryImplementation cqi = getDelegate().getCollocationQueryImplementation();
            @Override
            public boolean areCollocated(URI uri1, URI uri2) {
                return cqi != null && cqi.areCollocated(Utilities.toFile(uri1), Utilities.toFile(uri2));
            }
            @Override
            public URI findRoot(URI uri) {
                File file = cqi != null ? cqi.findRoot(Utilities.toFile(uri)) : null;
                return file != null ? Utilities.toURI(file) : null;
            }
        };
    } 
    return collocationQuery;        
}
 
Example 4
Source File: URLsAreEqualTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testURLsAreEqual() throws Exception {
    final File wd = new File(getWorkDir(), "work#dir");
    wd.mkdirs();
    
    File jar = new File(wd, "default-package-resource.jar");
    
    URL orig = new URL("jar:" + Utilities.toURI(jar) + "!/package/resource.txt");
    URLConnection conn = orig.openConnection();
    assertFalse("JDK connection: " + conn, conn.getClass().getName().startsWith("org.netbeans"));
    
    
    TestFileUtils.writeZipFile(jar, "package/resource.txt:content", "root.txt:empty");
    JarClassLoader jcl = new JarClassLoader(Collections.singletonList(jar), new ProxyClassLoader[0]);

    URL root = jcl.getResource("root.txt");
    URL u = new URL(root, "/package/resource.txt");
    assertNotNull("Resource found", u);
    URLConnection uC = u.openConnection();
    assertTrue("Our connection: " + uC, uC.getClass().getName().startsWith("org.netbeans"));

    assertEquals("Both URLs are equal", u, orig);
    assertEquals("Equality is symetrical", orig, u);
}
 
Example 5
Source File: LayerUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Lists any XML layers defined in a module JAR.
 * May include an explicit layer and/or a generated layer.
 * Layers from platform-specific modules are ignored automatically.
 * @param jar a module JAR file
 * @return from zero to two layer URLs
 */
public static List<URL> layersOf(File jar) throws IOException {
    ManifestManager mm = ManifestManager.getInstanceFromJAR(jar, true);
    for (String tok : mm.getRequiredTokens()) {
        if (tok.startsWith("org.openide.modules.os.")) { // NOI18N
            // Best to exclude platform-specific modules, e.g. ide/applemenu, as they can cause confusion.
            return Collections.emptyList();
        }
    }
    String layer = mm.getLayer();
    String generatedLayer = mm.getGeneratedLayer();
    List<URL> urls = new ArrayList<URL>(2);
    URI juri = Utilities.toURI(jar);
    for (String path : new String[] {layer, generatedLayer}) {
        if (path != null) {
            urls.add(new URL("jar:" + juri + "!/" + path));
        }
    }
    if (layer != null) {
        urls.add(new URL("jar:" + juri + "!/" + layer));
    }
    if (generatedLayer != null) {
        urls.add(new URL("jar:" + juri + "!/" + generatedLayer));
    }
    return urls;
}
 
Example 6
Source File: LayerUtilsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
void store(LayerCacheManager m, List<File> files) throws IOException {
    cacheDir = new File(this.getWorkDir(), "cache");
    assertFalse(cacheDir.exists());
    assertTrue(cacheDir.mkdir());
    System.out.println("Storing external cache into " + cacheDir);

    List<URL> urll = new ArrayList<URL>(Collections.singletonList((URL) null));
    for (int i = 0; i < files.size(); i++) {
        File xf = files.get(i);
        File cf = new File(cacheDir, xf.getName() + ".ser");
        assertFalse(cf.exists());
        assertTrue(cf.createNewFile());
        OutputStream os = new BufferedOutputStream(new FileOutputStream(cf));
        URL url = xf.getName().endsWith(".jar") ? new URL("jar:" + Utilities.toURI(xf) + "!/" + LAYER_PATH_IN_JAR) : Utilities.toURI(xf).toURL();
        urll.set(0, url);
        m.store(null, urll, os);
        os.close();
    }
}
 
Example 7
Source File: DataFolderPasteTypesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testUriFileListPasteTypes() throws ClassNotFoundException, IOException {
    DataFlavor flavor = new DataFlavor( "unsupported/flavor;class=java.lang.Object" );
    FileObject testFO = FileUtil.createData( testFileSystem.getRoot(), "testFile.txt" );
    File testFile = FileUtil.toFile( testFO );
    String uriList = Utilities.toURI(testFile) + "\r\n";
    Transferable t = new MockTransferable( new DataFlavor[] {new DataFlavor("text/uri-list;class=java.lang.String")}, uriList );

    DataFolder.FolderNode node = (DataFolder.FolderNode)folderNode;
    ArrayList list = new ArrayList();
    node.createPasteTypes( t, list );
    assertFalse( list.isEmpty() );
    PasteType paste = (PasteType)list.get( 0 );
    paste.paste();

    FileObject[] children = testFileSystem.getRoot().getFileObject( "testDir" ).getChildren();
    assertEquals( 1, children.length );
    assertEquals( children[0].getNameExt(), "testFile.txt" );
}
 
Example 8
Source File: FileUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static URI getDirURI(@NonNull File root, @NonNull String path) {
    String pth = path.trim();
    pth = pth.replaceFirst("^\\./", ""); //NOI18N
    pth = pth.replaceFirst("^\\.\\\\", ""); //NOI18N
    File src = FileUtilities.resolveFilePath(root, pth);
    return Utilities.toURI(FileUtil.normalizeFile(src));
}
 
Example 9
Source File: AntArtifactProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public URI[] getArtifactLocations() {
    String jarloc = eval.evaluate("${cluster}/${module.jar}"); // NOI18N
    File jar = helper.resolveFile(jarloc); // probably absolute anyway, now
    String reldir = PropertyUtils.relativizeFile(project.getProjectDirectoryFile(), jar);
    if (reldir != null) {
        try {
            return new URI[] {new URI(null, null, reldir, null)};
        } catch (URISyntaxException e) {
            throw new AssertionError(e);
        }
    } else {
        return new URI[] {Utilities.toURI(jar)};
    }
    // XXX should it add in class path extensions?
}
 
Example 10
Source File: ProxyURLStreamHandlerFactoryTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Tests UNC path is correctly treated. On JDK1.5 UNCFileStreamHandler should 
 * be installed in ProxyURLStreamHandlerFactory to workaround JDK bug
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5086147.
 */
public void testUNCFileURLStreamHandler() throws Exception {
    if(!Utilities.isWindows()) {
        return;
    }
    File uncFile = new File("\\\\computerName\\sharedFolder\\a\\b\\c\\d.txt");
    URI uri = Utilities.toURI(uncFile);
    String expectedURI = "file://computerName/sharedFolder/a/b/c/d.txt";
    assertEquals("Wrong URI from File.toURI.", expectedURI, uri.toString());
    URL url = uri.toURL();
    assertEquals("Wrong URL from URI.toURL", expectedURI, url.toString());
    assertEquals("URL.getAuthority must is now computer name.", "computerName", url.getAuthority());
    uri = url.toURI();
    assertEquals("Wrong URI from URL.toURI.", expectedURI, uri.toString());
}
 
Example 11
Source File: FileUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static @NullUnknown URI convertStringToUri(@NullAllowed String str) {
    if (str != null) {
        File fil = new File(str);
        fil = FileUtil.normalizeFile(fil);
        return Utilities.toURI(fil);
    }
    return null;
}
 
Example 12
Source File: SharabilityQueryImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public URI getNodeModulesUri() {
    if (nodeModulesUri == null) {
        nodeModulesUri = Utilities.toURI(packageJson.getNodeModulesDir());
    }
    return nodeModulesUri;
}
 
Example 13
Source File: SharabilityQueryImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private URI getBowerComponentsDir() {
    if (bowerComponentsDir == null) {
        bowerComponentsDir = Utilities.toURI(bowerrcJson.getBowerComponentsDir());
    }
    return bowerComponentsDir;
}
 
Example 14
Source File: JarURLStreamHandlerTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testNbHandler() throws Exception {
    URL root = new URL("jar:" + Utilities.toURI(jar) + "!/");
    URL plain = new URL(root, "/fldr/plain.txt", new JarClassLoader.JarURLStreamHandler(null));
    assertTrue("Contains the plain.txt part: " + plain, plain.toExternalForm().contains("fldr/plain.txt"));
    assertContent("Ahoj", plain);
}
 
Example 15
Source File: EarImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public List<Project> getProjects() {
    MavenProject mp = mavenproject().getMavenProject();
    @SuppressWarnings("unchecked")
    Set<Artifact> artifactSet = mp.getArtifacts();
    @SuppressWarnings("unchecked")
    List<Dependency> deps = mp.getRuntimeDependencies();
    List<Project> toRet = new ArrayList<Project>();
    EarImpl.MavenModule[] mm = readPomModules();
    //#162173 order by dependency list, artifacts is unsorted set.
    for (Dependency d : deps) {
        if ("war".equals(d.getType()) || "ejb".equals(d.getType()) || "app-client".equals(d.getType())) {//NOI18N
            for (Artifact a : artifactSet) {
                if (a.getGroupId().equals(d.getGroupId()) &&
                        a.getArtifactId().equals(d.getArtifactId()) &&
                        StringUtils.equals(a.getClassifier(), d.getClassifier())) {
                    URI uri = Utilities.toURI(FileUtil.normalizeFile(a.getFile()));
                    //#174744 - it's of essence we use the URI based method. items in local repo might not be available yet.
                    Project owner = FileOwnerQuery.getOwner(uri);
                    if (owner != null) {
                        EarImpl.MavenModule m = findMavenModule(a, mm);
                        //#162173 respect order in pom configuration.. shall we?
                        if (m.pomIndex > -1 && toRet.size() > m.pomIndex) {
                            toRet.add(m.pomIndex, owner);
                        } else {
                            toRet.add(owner);
                        }
                        
                    }
                }
            }
        }
    }
    // This might happened if someone calls getProjects() before the EAR childs were actually opened
    // Typically if childs are needed during the project creation
    if (toRet.isEmpty()) {
        FileObject parentFO = project.getProjectDirectory().getParent();
        for (FileObject childFO : parentFO.getChildren()) {
            if (childFO.isData()) {
                continue;
            }
            
            try {
                Project childProject = ProjectManager.getDefault().findProject(childFO);
                if (childProject != null && !childProject.equals(project)) {
                    toRet.add(childProject);
                }
            } catch (IOException | IllegalArgumentException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return toRet;
}
 
Example 16
Source File: URIMapper.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static URI toURI(File webServerBase, boolean includeHostPart) {
    URI webServerBaseURI = Utilities.toURI(webServerBase);
    return createURI(webServerBaseURI.getScheme(), webServerBaseURI.getHost(),
            webServerBaseURI.getPath(), webServerBaseURI.getFragment(),
            includeHostPart, webServerBase.exists() && webServerBase.isDirectory());
}
 
Example 17
Source File: SharabilityQueryImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private URI getVendorDir() {
    if (vendorDir == null) {
        vendorDir = Utilities.toURI(composerJson.getVendorDir());
    }
    return vendorDir;
}
 
Example 18
Source File: TemplateAttributesProviderImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, ?> attributesFor(DataObject template, DataFolder target, String name) {
    Map<String, String> values = new HashMap<String, String>();
    EditableProperties priv  = helper.getProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH);
    EditableProperties props = helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
    String licensePath = priv.getProperty("project.licensePath");
    if (licensePath == null) {
        licensePath = props.getProperty("project.licensePath");
    }
    if (licensePath != null) {
        licensePath = helper.getStandardPropertyEvaluator().evaluate(licensePath);
        if (licensePath != null) {
            File path = FileUtil.normalizeFile(helper.resolveFile(licensePath));
            if (path.exists() && path.isAbsolute()) { //is this necessary? should prevent failed license header inclusion
                URI uri = Utilities.toURI(path);
                licensePath = uri.toString();
                values.put("licensePath", licensePath);
            } else {
                LOG.log(Level.INFO, "project.licensePath value not accepted - " + licensePath);
            }
        }
    }
    String license = priv.getProperty("project.license"); // NOI18N
    if (license == null) {
        license = props.getProperty("project.license"); // NOI18N
    }
    if (license != null) {
        values.put("license", license); // NOI18N
    }
    Charset charset = encodingQuery.getEncoding(target.getPrimaryFile());
    String encoding = (charset != null) ? charset.name() : null;
    if (encoding != null) {
        values.put("encoding", encoding); // NOI18N
    }
    try {
        Project prj = ProjectManager.getDefault().findProject(helper.getProjectDirectory());
        ProjectInformation info = ProjectUtils.getInformation(prj);
        if (info != null) {
            String pname = info.getName();
            if (pname != null) {
                values.put("name", pname);// NOI18N
            }
            String pdname = info.getDisplayName();
            if (pdname != null) {
                values.put("displayName", pdname);// NOI18N
            }
        }
    } catch (Exception ex) {
        //not really important, just log.
        Logger.getLogger(TemplateAttributesProviderImpl.class.getName()).log(Level.FINE, "", ex);
    }

    if (values.isEmpty()) {
        return null;
    } else {
        return Collections.singletonMap("project", values); // NOI18N
    }
}
 
Example 19
Source File: SharabilityQueryImplTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private URI file(String path) {
    return Utilities.toURI(new File(scratchF, path.replace('/', File.separatorChar)));
}
 
Example 20
Source File: VCSFileProxy.java    From netbeans with Apache License 2.0 3 votes vote down vote up
/**
 * Determines this files URI. Depending on its origin it will be either
 * {@link FileObject#toURI()} or {@link File#toURI()}.
 *
 * @return this file URI
 * @see File#toURI()
 * @see FileObject#toURI()
 */
public URI toURI() throws URISyntaxException {
    if (this.proxy == null) {
        return  Utilities.toURI(new File(path));
    } else {
        return proxy.toURI(this);
    }
}