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

The following examples show how to use org.openide.util.Utilities#toFile() . 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: GlobalSourceForBinaryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected String resolveRelativePath(URL sourceRoot) throws IOException {
    // TODO C.P cache root + cnb -> relpath? dig into library wrappers?
    File srPath = Utilities.toFile(URI.create(sourceRoot.toExternalForm()));
    File moduleSrc = new File(srPath, "src");    // NOI18N
    if (moduleSrc.exists()) {   // src root is module project root directly
        return "src/";    // NOI18N
    }
    File prjProp = new File(srPath, "nbproject/project.properties");    // NOI18N
    if (prjProp.exists()) {
        // maybe suite root
        EditableProperties ep = Util.loadProperties(FileUtil.toFileObject(prjProp));
        String prjName = ep.get("project." + cnb);    // NOI18N
        if (prjName != null) {
            return prjName + "/src/";
        }
    }
    // either artificially composed sources without nbproject - not supported -
    // or (part of) NB.org source tree, which should have been resolved against NbPlatform
    return null;
}
 
Example 2
Source File: SharabilityQueryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Sharability getSharability(URI uri) {
    final File file = Utilities.toFile(uri);
    if (file == null) {
        return Sharability.NOT_SHARABLE;
    }
    final String simpleName = getSimpleName(file);
    if (simpleName.endsWith(SHARABLE_SUFFIX)) {
        return Sharability.SHARABLE;
    } else if (simpleName.endsWith(NON_SHARABLE_SUFFIX)) {
        return Sharability.NOT_SHARABLE;
    } else {
        return file.isDirectory() ? Sharability.MIXED
                                  : Sharability.SHARABLE;
    }
}
 
Example 3
Source File: DataShadowTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testBrokenShadow55115 () throws Exception {
    FileObject brokenShadow = FileUtil.createData(FileUtil.getConfigRoot(),"brokenshadows/brokon.shadow");
    assertNotNull (brokenShadow);
    // intentionally not set attribute "originalFile" to let that shadow be broken 
    //brokenShadow.setAttribute("originalFile", null);
    BrokenDataShadow bds = (BrokenDataShadow)DataObject.find(brokenShadow);
    assertNotNull (bds);
    URL url = bds.getUrl();
    //this call proves #55115 - but just in case if there is reachable masterfs 
    // - probably unwanted here
    bds.refresh(); 
    
    //If masterfs isn't reachable - second test crucial for URL,File, FileObject conversions
    // not necessary to be able to convert - but at least no IllegalArgumentException is expected
    if ("file".equals(url.getProtocol())) {
        Utilities.toFile(URI.create(url.toExternalForm()));
    }
}
 
Example 4
Source File: FreeformSharabilityQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override public Sharability getSharability(URI uri) {
       File file = Utilities.toFile(uri);
String absolutePath = file.getAbsolutePath();

if (absolutePath.equals(nbproject)) {
    return SharabilityQuery.Sharability.MIXED;
}

if (absolutePath.startsWith(nbproject)) {
    return absolutePath.startsWith(nbprojectPrivate) ? SharabilityQuery.Sharability.NOT_SHARABLE : SharabilityQuery.Sharability.SHARABLE;
}

       if (isExported(file)) {
           return SharabilityQuery.Sharability.NOT_SHARABLE;
       }

return SharabilityQuery.Sharability.UNKNOWN;
   }
 
Example 5
Source File: NetigsoActivationWithLookupTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected @Override void setUp() throws Exception {
    Locale.setDefault(Locale.US);
    clearWorkDir();
    File ud = new File(getWorkDir(), "ud");
    ud.mkdirs();
    System.setProperty("netbeans.user", ud.getPath());
    
    data = new File(getDataDir(), "jars");
    jars = new File(getWorkDir(), "jars");
    jars.mkdirs();
    File activate = createTestJAR("activate", null);

    File lkp = Utilities.toFile(Lookup.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    File register = createTestJAR("register", null, lkp);

    registerModule(ud, activate, "org.activate");
    registerModule(ud, register, "org.register");
}
 
Example 6
Source File: LibrariesNodeFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public List<String> keys() {
    List<String> result = new ArrayList<String>();
    result.add(LIBRARIES);
    URL[] testRoots = project.getTestSourceRoots().getRootURLs();
    boolean addTestSources = false;
    for (int i = 0; i < testRoots.length; i++) {
        File f = Utilities.toFile(URI.create(testRoots[i].toExternalForm()));
        if (f.exists()) {
            addTestSources = true;
            break;
        }
    }
    if (addTestSources) {
        result.add(TEST_LIBRARIES);
    }
    return result;
}
 
Example 7
Source File: MySQLDatabaseServerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    Lookup.getDefault().lookup(ModuleInfo.class);

    // We need to set up netbeans.dirs so that the NBInst URLMapper correctly
    // finds the mysql jar file
    File jarFile = Utilities.toFile(JDBCDriverManager.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    File clusterDir = jarFile.getParentFile().getParentFile();
    System.setProperty("netbeans.dirs", clusterDir.getAbsolutePath());

    getProperties();

    server = MySQLDatabaseServer.getDefault();
    server.setUser(getUser());
    server.setPassword(getPassword());
    server.setHost(getHost());
    server.setPort(getPort());
}
 
Example 8
Source File: LocalTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void getAttachementData (final OutputStream os) {
    try {
        File f = Utilities.toFile(new URI(uri));
        FileUtils.copyStreamsCloseAll(os, FileUtils.createInputStream(f));
    } catch (URISyntaxException | IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 9
Source File: GlobalJavadocForBinaryImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Result findForBinaryRoot(final URL binaryRoot) throws MalformedURLException, MalformedURLException {
    URL jar = FileUtil.getArchiveFile(binaryRoot);
    if (!jar.getProtocol().equals("file")) { // NOI18N
        Util.err.log(binaryRoot + " is not an archive file."); // NOI18N
        return null;
    }
    File binaryRootF = Utilities.toFile(URI.create(jar.toExternalForm()));
    // XXX this will only work for modules following regular naming conventions:
    String n = binaryRootF.getName();
    if (!n.endsWith(".jar")) { // NOI18N
        Util.err.log(binaryRootF + " is not a *.jar"); // NOI18N
        return null;
    }
    String cnbdashes = n.substring(0, n.length() - 4);
    NbPlatform supposedPlaf = null;
    for (NbPlatform plaf : NbPlatform.getPlatformsOrNot()) {
        if (binaryRootF.getAbsolutePath().startsWith(plaf.getDestDir().getAbsolutePath() + File.separator)) {
            supposedPlaf = plaf;
            break;
        }
    }
    if (supposedPlaf == null) {
        // try external clusters
        URL[] javadocRoots = ModuleList.getJavadocRootsForExternalModule(binaryRootF);
        if (javadocRoots.length > 0) {
            return findByDashedCNB(cnbdashes, javadocRoots, true);
        }
        Util.err.log(binaryRootF + " does not correspond to a known platform"); // NOI18N
        return null;
    }
    Util.err.log("Platform in " + supposedPlaf.getDestDir() + " claimed to have Javadoc roots "
        + Arrays.asList(supposedPlaf.getJavadocRoots()));
    return findByDashedCNB(cnbdashes, supposedPlaf.getJavadocRoots(), true);
}
 
Example 10
Source File: XMLHintPreferences.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static HintPreferencesProviderImpl from(@NonNull URI settings) {
    Reference<HintPreferencesProviderImpl> ref = uri2Cache.get(settings);
    HintPreferencesProviderImpl cachedResult = ref != null ? ref.get() : null;
    
    if (cachedResult != null) return cachedResult;
    
    Document doc = null;
    File file = Utilities.toFile(settings); //XXX: non-file:// scheme
    
    if (file.canRead()) {
        try(InputStream in = new BufferedInputStream(new FileInputStream(file))) {
            doc = XMLUtil.parse(new InputSource(in), false, false, null, EntityCatalog.getDefault());
        } catch (SAXException | IOException ex) {
            LOG.log(Level.FINE, null, ex);
        }
    }
    
    if (doc == null) {
        doc = XMLUtil.createDocument("configuration", null, "-//NetBeans//DTD Tool Configuration 1.0//EN", "http://www.netbeans.org/dtds/ToolConfiguration-1_0.dtd");
    }
    
    synchronized (uri2Cache) {
        ref = uri2Cache.get(settings);
        cachedResult = ref != null ? ref.get() : null;

        if (cachedResult != null) return cachedResult;
        
        uri2Cache.put(settings, new CleaneableSoftReference(cachedResult = new HintPreferencesProviderImpl(settings, doc), settings));
    }
    
    return cachedResult;
}
 
Example 11
Source File: NbClassLoaderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testFastIsUsedForFileUrl() throws Exception {
    CharSequence log = Log.enable(NbClassLoader.class.getName(), Level.FINE);
    LocalFileSystem lfs = new LocalFileSystem();
    File here = Utilities.toFile(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
    lfs.setRootDirectory(here);
    lfs.setReadOnly(true);
    ClassLoader cl = new NbClassLoader(new FileObject[]{lfs.getRoot()}, ClassLoader.getSystemClassLoader().getParent(), null);
    Class c = cl.loadClass("org.openide.execution.NbClassLoaderTest$User");
    assertFalse(log.toString().contains("NBFS used!"));
}
 
Example 12
Source File: UpdateUnitFactoryTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp () throws IOException, URISyntaxException {
    clearWorkDir ();
    System.setProperty ("netbeans.user", getWorkDirPath ());
    Lookup.getDefault ().lookup (ModuleInfo.class);
    try {
        p = new MyProvider ();
    } catch (Exception x) {
        x.printStackTrace ();
    }
    p.refresh (true);
    URL urlToFile = TestUtils.class.getResource ("data/org-yourorghere-depending.nbm");
    NBM_FILE = Utilities.toFile(urlToFile.toURI ());
    assertNotNull ("data/org-yourorghere-depending.nbm file must found.", NBM_FILE);
}
 
Example 13
Source File: NewClustersRebootTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void invokeNbExecAndCreateCluster(File workDir, StringBuffer sb, String... args) throws Exception {
        URL u = Lookup.class.getProtectionDomain().getCodeSource().getLocation();
        File f = Utilities.toFile(u.toURI());
        assertTrue("file found: " + f, f.exists());
        File nbexec = org.openide.util.Utilities.isWindows() ? new File(f.getParent(), "nbexec.exe") : new File(f.getParent(), "nbexec");
        assertTrue("nbexec found: " + nbexec, nbexec.exists());
        LOG.log(Level.INFO, "nbexec: {0}", nbexec);

        URL tu = NewClustersRebootCallback.class.getProtectionDomain().getCodeSource().getLocation();
        File testf = Utilities.toFile(tu.toURI());
        assertTrue("file found: " + testf, testf.exists());

        LinkedList<String> allArgs = new LinkedList<String>(Arrays.asList(args));
        allArgs.addFirst("-J-Dnetbeans.mainclass=" + NewClustersRebootCallback.class.getName());
        allArgs.addFirst(System.getProperty("java.home"));
        allArgs.addFirst("--jdkhome");
        allArgs.addFirst(getWorkDirPath());
        allArgs.addFirst("--userdir");
        allArgs.addFirst(testf.getPath());
        allArgs.addFirst("-cp:p");
        allArgs.addFirst("--nosplash");

        if (!org.openide.util.Utilities.isWindows()) {
            allArgs.addFirst(nbexec.getPath());
            allArgs.addFirst("-x");
            allArgs.addFirst("/bin/sh");
        } else {
            allArgs.addFirst(nbexec.getPath());
        }
        LOG.log(Level.INFO, "About to execute {0}@{1}", new Object[]{allArgs, workDir});
        Process p = Runtime.getRuntime().exec(allArgs.toArray(new String[0]), new String[0], workDir);
        LOG.log(Level.INFO, "Process created {0}", p);
        int res = readOutput(sb, p);
        LOG.log(Level.INFO, "Output read: {0}", res);
        String output = sb.toString();
//        System.out.println("nbexec output is: " + output);
        assertEquals("Execution is ok: " + output, 0, res);
    }
 
Example 14
Source File: ClassPathProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isReset(PropertyChangeEvent evt) {
    boolean reset = false;            
    if( (NbMavenProject.PROP_RESOURCE.equals(evt.getPropertyName()) && evt.getNewValue() instanceof URI)) {
        File file = Utilities.toFile((URI) evt.getNewValue());
        MavenProject mp = proj.getOriginalMavenProject();
        reset = mp.getCompileSourceRoots().stream().anyMatch((sourceRoot) -> (file.equals(new File(sourceRoot, MODULE_INFO_JAVA)))) ||
                mp.getTestCompileSourceRoots().stream().anyMatch((sourceRoot) -> (file.equals(new File(sourceRoot, MODULE_INFO_JAVA))));                
        if(reset) {
            LOGGER.log(Level.FINER, "TestPathSelector {0} for project {1} resource changed: {2}", new Object[]{logDesc, proj.getProjectDirectory().getPath(), evt});
        }
    }
    return reset;
}
 
Example 15
Source File: CopyResourcesOnSave.java    From netbeans with Apache License 2.0 5 votes vote down vote up
final void refresh() {
    synchronized (resourceUris) {
        List<Resource> resources = new ArrayList<Resource>();
        resources.addAll(nbproject.getMavenProject().getResources());
        resources.addAll(nbproject.getMavenProject().getTestResources());
        Set<File> old = new HashSet<File>(resourceUris);
        Set<File> added = new HashSet<File>();
        
            for (Resource res : resources) {
                String dir = res.getDirectory();
                if (dir == null) {
                    continue;
                }
                URI uri = FileUtilities.getDirURI(project.getProjectDirectory(), dir);
                File file = Utilities.toFile(uri);
                if (!old.contains(file) && !added.contains(file)) { // if a given file is there multiple times, we get assertion back from FileUtil. there can be only one listener+file tuple
                    FileUtil.addRecursiveListener(this, file);
                }
                added.add(file);
            }
        
        old.removeAll(added);
        for (File oldFile : old) {
            FileUtil.removeRecursiveListener(this, oldFile);
        }
        resourceUris.removeAll(old);
        resourceUris.addAll(added);
    }
}
 
Example 16
Source File: SyncUpdateTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSyncRuleElement() throws Exception {
    File originalFC = Utilities.toFile(Util.getResourceURI("faces-config-03.xml"));
    FileObject fc = FileUtil.copyFile(FileUtil.toFileObject(originalFC), FileUtil.toFileObject(getWorkDir()), "faces-config-03.xml");
    ModelSource ms = TestCatalogModel.getDefault().getModelSource(fc.toURI());
    JSFConfigModel model = JSFConfigModelFactory.getInstance().getModel(ms);
    NavigationRule rule = model.getRootComponent().getNavigationRules().get(0);
    assertEquals("afaa", rule.getFromViewId());
    Util.setDocumentContentTo(model, "faces-config-04.xml");
    assertEquals("newafaa", rule.getFromViewId());
}
 
Example 17
Source File: StyledDocumentWriter.java    From editorconfig-netbeans with MIT License 4 votes vote down vote up
public static void writeOnFileWithLines(FileObject fo, Charset charset, List<String> lines)
        throws FileAccessException {
  File file = Utilities.toFile(fo.toURI());
  writeOnFileWithLines(file, charset, lines);
}
 
Example 18
Source File: ManifestManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static ManifestManager getInstanceFromJAR(File jar, boolean withGeneratedLayer) {
    try {
        if (!jar.isFile()) {
            throw new IOException("No such JAR: " + jar); // NOI18N
        }
        JarFile jf = new JarFile(jar, false);
        try {
            Manifest m = jf.getManifest();
            if (m == null) { // #87064
                throw new IOException("No manifest in " + jar); // NOI18N
            }
            withGeneratedLayer = withGeneratedLayer && (jf.getJarEntry(GENERATED_LAYER_PATH) != null);
            ManifestManager mm = ManifestManager.getInstance(m, true, withGeneratedLayer);
            if (Arrays.asList(mm.getProvidedTokens()).contains("org.osgi.framework.launch.FrameworkFactory")) { // NOI18N
                // This looks to be a wrapper for an OSGi container.
                // Add in anything provided by the container itself.
                // Otherwise some bundles might be expressing container dependencies
                // which can actually be resolved at runtime but which look like missing deps.
                String cp = m.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
                if (cp != null) {
                    for (String piece : cp.split("[, ]+")) {
                        if (piece.isEmpty()) {
                            continue;
                        }
                        File ext = Utilities.toFile(Utilities.toURI(jar.getParentFile()).resolve(piece.trim()));
                        if (ext.isFile()) {
                            ManifestManager mm2 = getInstanceFromJAR(ext);
                            List<String> toks = new ArrayList<String>(Arrays.asList(mm.provTokens));
                            toks.addAll(Arrays.asList(mm2.provTokens));
                            mm.provTokens = toks.toArray(new String[toks.size()]);
                        }
                    }
                }
            }
            return mm;
        } finally {
            jf.close();
        }
    } catch (IOException e) {
        LOG.log(Level.INFO, "While opening: " + jar, e);
        return NULL_INSTANCE;
    }
}
 
Example 19
Source File: LibrariesCustomizer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void selectLibrary (Node[] nodes) {
    int tabCount = this.properties.getTabCount();
    for (int i=0; i<tabCount; i++) {
        this.properties.removeTabAt(0);
    }
    this.libraryName.setEnabled(false);
    this.libraryName.setText("");   //NOI18N
    this.jLabel1.setVisible(false);
    this.libraryName.setVisible(false);
    this.properties.setVisible(false);
    this.deleteButton.setEnabled(false);
    if (nodes.length != 1) {
        return;
    }
    LibraryImplementation impl = nodes[0].getLookup().lookup(LibraryImplementation.class);
    if (impl == null) {
        return;
    }
    this.jLabel1.setVisible(true);
    this.libraryName.setVisible(true);
    this.properties.setVisible(true);
    boolean editable = model.isLibraryEditable (impl);
    this.libraryName.setEnabled(editable && LibrariesSupport.supportsDisplayName(impl));
    this.deleteButton.setEnabled(editable);
    this.libraryName.setText (LibrariesSupport.getLocalizedName(impl));
    LibraryTypeProvider provider = nodes[0].getLookup().lookup(LibraryTypeProvider.class);
    if (provider == null) {
        return;
    }
    LibraryCustomizerContextWrapper customizerContext;
    LibraryStorageArea area = nodes[0].getLookup().lookup(LibraryStorageArea.class);
    if (area != LibraryStorageArea.GLOBAL) {
        customizerContext = new LibraryCustomizerContextWrapper(impl, area);
        File f = Utilities.toFile(URI.create(area.getLocation().toExternalForm()));
        this.libraryLocation.setText(f.getPath());
    } else {
        customizerContext = new LibraryCustomizerContextWrapper(impl, null);
        this.libraryLocation.setText(LABEL_Global_Libraries());
    }

    String[] volumeTypes = provider.getSupportedVolumeTypes();
    for (int i=0; i< volumeTypes.length; i++) {
        Customizer c = provider.getCustomizer (volumeTypes[i]);
        if (c instanceof JComponent) {
            c.setObject (customizerContext);
            JComponent component = (JComponent) c;
            component.setEnabled (editable);
            String tabName = component.getName();
            if (tabName == null) {
                tabName = volumeTypes[i];
            }
            this.properties.addTab(tabName, component);
        }
    }        
}
 
Example 20
Source File: J2SEPlatformCustomizer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@NonNull
private static Pair<String,Icon> getDisplayName(@NonNull URL url) {
    IconKind iconKind = IconKind.UNKNOWN;
    try {
        final Pair<URL,String> parsed = NBJRTUtil.parseURI(url.toURI());
        if (parsed != null) {
            String moduleName = parsed.second();
            final int end = moduleName.endsWith(URL_SEPARATOR) ?
                    moduleName.length() - URL_SEPARATOR.length() :
                    moduleName.length();
            int start = end == 0 ? -1 : moduleName.lastIndexOf(URL_SEPARATOR, end - 1);
            start = start < 0 ? 0 : start + URL_SEPARATOR.length();
            moduleName = moduleName.substring(start, end);
            iconKind = IconKind.MODULE;
            return Pair.<String,Icon>of(moduleName, iconKind.getIcon());
        }
    } catch (URISyntaxException e) {
        //pass
    }
    if ("jar".equals(url.getProtocol())) {      //NOI18N
        iconKind = IconKind.ARCHVIVE;
        URL fileURL = FileUtil.getArchiveFile (url);
        if ((fileURL != null) && FileUtil.getArchiveRoot(fileURL).equals(url)) {
            // really the root
            url = fileURL;
        } else {
            // some subdir, just show it as is
            return Pair.of(url.toExternalForm(), iconKind.getIcon());
        }
    }
    if ("file".equals(url.getProtocol())) { //NOI18N
        if (iconKind == IconKind.UNKNOWN) {
            iconKind = IconKind.FOLDER;
        }
        final File f = Utilities.toFile(URI.create(url.toExternalForm()));
        return Pair.of(f.getAbsolutePath(), iconKind.getIcon());
    } else {
        if (url.getProtocol().startsWith("http") || url.getProtocol().startsWith("ftp")) {  //NOI18N
            iconKind = IconKind.NET;
        }
        return Pair.of(url.toExternalForm(), iconKind.getIcon());
    }
}