Java Code Examples for org.openide.filesystems.FileObject.getInputStream()

The following are Jave code examples for showing how to use getInputStream() of the org.openide.filesystems.FileObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-netbeans   File: ResultsManager.java   Source Code and License Vote up 6 votes
private LoadedSnapshot loadSnapshotFromFileObject(FileObject selectedFile)
                                           throws IOException {
    DataInputStream dis = null;

    try {
        InputStream is = selectedFile.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        dis = new DataInputStream(bis);

        LoadedSnapshot ls = LoadedSnapshot.loadSnapshot(dis);

        if (ls != null) {
            ls.setFile(FileUtil.toFile(selectedFile));
            ls.setProject(findProjectForSnapshot(selectedFile));
        }

        return ls;
    } finally {
        if (dis != null) {
            dis.close();
        }
    }
}
 
Example 2
Project: incubator-netbeans   File: ProjectImportModel.java   Source Code and License Vote up 6 votes
private boolean readJUnitFileHeader(FileObject fo) throws IOException {
    InputStream is = fo.getInputStream();
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(is, getEncoding()));
        String line;
        int maxLines = 100;
        while (null != (line = input.readLine()) && maxLines > 0) {
            maxLines--;
            if (line.contains("junit.framework.Test") || // NOI18N
                line.contains("org.junit.Test") || // NOI18N
                line.contains("junit.framework.*") || // NOI18N
                line.contains("org.junit.*")) { // NOI18N
                return true;
            }
                
        }
    } finally {
        is.close();
    }
    return false;
}
 
Example 3
Project: incubator-netbeans   File: EncodedReaderFactory.java   Source Code and License Vote up 6 votes
private Reader getReader(FileObject fo, String encoding, FileObject type, String secondFileExt) throws FileNotFoundException {
    if (encoding != null) {
        try {
            return new InputStreamReader(fo.getInputStream(), encoding);
        } catch (UnsupportedEncodingException ueex) {
            ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ueex);
        }
    }
    Reader r = null;
    String ext = type.getExt();
    if (!"java".equalsIgnoreCase(ext) || !ext.equals(secondFileExt)) {// We read the encoding for Java files explicitely
                                        // If it's not defined, read with default encoding from stream (because of guarded blocks)
                                        // But when the extensions of the two files are different (comparing Java files with something else),
                                        // we have to use the Document approach for both due to possible different line-endings.
        r = getReaderFromEditorSupport(fo, type);
        if (r == null) {
            r = getReaderFromKit(null, fo, type.getMIMEType());
        }
    }
    if (r == null) {
        // Fallback, use current encoding
        r = new InputStreamReader(fo.getInputStream());
    }
    return r;
}
 
Example 4
Project: incubator-netbeans   File: Utilities.java   Source Code and License Vote up 6 votes
private static boolean isBuildScriptUpToDate(@NonNull final Project project) {
    final FileObject prjDir = project.getProjectDirectory();
    if (prjDir == null) {
        return false;
    }
    final FileObject remoteBuildScript = prjDir.getFileObject(BUILD_SCRIPT_PATH);
    if (remoteBuildScript == null) {
        return false;
    }
    try {
        final long scriptCRC;
        try (final InputStream in = new BufferedInputStream(remoteBuildScript.getInputStream())) {
            scriptCRC = calculateCRC(in);
        }
        Long templateCRC = templateCRCCache;
        if (templateCRC == null) {
            try (final InputStream in = new BufferedInputStream(
                    RemotePlatformProjectSaver.class.getResourceAsStream(BUILD_SCRIPT_PROTOTYPE))) {
                templateCRCCache = templateCRC = calculateCRC(in);
            }
        }
        return scriptCRC == templateCRC;
    } catch (IOException ioe) {
        return false;
    }
}
 
Example 5
Project: incubator-netbeans   File: AccessQueryImpl.java   Source Code and License Vote up 6 votes
private static List<Pattern> loadPublicPackagesPatterns(Project project) {
    List<Pattern> toRet = new ArrayList<Pattern>();
    String[] params = PluginPropertyUtils.getPluginPropertyList(project, 
            MavenNbModuleImpl.GROUPID_MOJO, MavenNbModuleImpl.NBM_PLUGIN, //NOI18N
            "publicPackages", "publicPackage", "manifest"); //NOI18N
    if (params != null) {
        toRet = prepareMavenPublicPackagesPatterns(params);
    } else {
        FileObject obj = project.getProjectDirectory().getFileObject(MANIFEST_PATH);
        if (obj != null) {
            InputStream in = null;
            try {
                in = obj.getInputStream();
                Manifest man = new Manifest();
                man.read(in);
                String value = man.getMainAttributes().getValue(ATTR_PUBLIC_PACKAGE);
                toRet = prepareManifestPublicPackagesPatterns(value);
            } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
            } finally {
                IOUtil.close(in);
            }
        }
    }
    return toRet;
}
 
Example 6
Project: incubator-netbeans   File: JavaFix.java   Source Code and License Vote up 5 votes
/**Allows access to non-Java resources. The content of this InputStream will
 * include all changes done through {@link #getResourceOutput(org.openide.filesystems.FileObject) }
 * before calling this method.
 *
 * @param file whose content should be returned
 * @return the file's content
 * @throws IOException if something goes wrong while opening the file
 * @throws IllegalArgumentException if {@code file} parameter is null, or
 *                                  if it represents a Java file
 */
public @NonNull InputStream getResourceContent(@NonNull FileObject file) throws IOException, IllegalArgumentException {
    Parameters.notNull("file", file);
    if ("text/x-java".equals(file.getMIMEType("text/x-java")))
        throw new IllegalArgumentException("Cannot access Java files");

    byte[] newContent = resourceContentChanges != null ? resourceContentChanges.get(file) : null;

    if (newContent == null) {
        final Document doc = BatchUtilities.getDocument(file);

        if (doc != null) {
            final String[] result = new String[1];

            doc.render(new Runnable() {
                @Override public void run() {
                    try {
                        result[0] = doc.getText(0, doc.getLength());
                    } catch (BadLocationException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }
            });

            if (result[0] != null) {
                ByteBuffer encoded = FileEncodingQuery.getEncoding(file).encode(result[0]);
                byte[] encodedBytes = new byte[encoded.remaining()];

                encoded.get(encodedBytes);

                return new ByteArrayInputStream(encodedBytes);
            }
        }
        
        return file.getInputStream();
    } else {
        return new ByteArrayInputStream(newContent);
    }
}
 
Example 7
Project: incubator-netbeans   File: PaletteEnvironmentProvider.java   Source Code and License Vote up 5 votes
public synchronized PaletteItemNode getInstance() {

            PaletteItemNode node = refNode.get();
            if (node != null)
                return node;

            FileObject file = xmlDataObject.getPrimaryFile();
            if (file.getSize() == 0L) // item file is empty
                return null;

            PaletteItemHandler handler = new PaletteItemHandler();
            try {
                XMLReader reader = getXMLReader();
                FileObject fo = xmlDataObject.getPrimaryFile();
                String urlString = fo.getURL().toExternalForm();
                InputSource is = new InputSource(fo.getInputStream());
                is.setSystemId(urlString);
                reader.setContentHandler(handler);
                reader.setErrorHandler(handler);
                reader.parse(is);
            }
            catch (SAXException saxe) {
                Logger.getLogger( getClass().getName() ).log( Level.INFO, null, saxe );
                return null;
            } 
            catch (IOException ioe) {
                Logger.getLogger( getClass().getName() ).log( Level.INFO, null, ioe );
                return null;
            }
            if( handler.isError() )
                return null;

            node = createPaletteItemNode(handler);
            refNode = new WeakReference<PaletteItemNode>(node);

            return node;
        }
 
Example 8
Project: incubator-netbeans   File: MasterDetailGenerator.java   Source Code and License Vote up 5 votes
/**
 * Reads the content of the file.
 *
 * @param file file whose content should be read.
 * @return the content of the file.
 * @throws IOException when the reading fails.
 */
private static String read(FileObject file, String encoding) throws IOException {
    InputStream is = file.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
    StringBuilder sb = new StringBuilder();
    try {
        String s;
        while ((s=br.readLine()) != null) {
            sb.append(s).append('\n');
        }
    } finally {
        br.close();
    }
    return sb.toString();
}
 
Example 9
Project: incubator-netbeans   File: PermUITestCase.java   Source Code and License Vote up 5 votes
public void ref(FileObject fo) {
    if (fo.isValid()) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(fo.getInputStream()));
            getRef().println("==>" + fo.getName());
            String s = br.readLine();
            while (s != null) {
                getRef().println(s);
                s = br.readLine();
            }
        } catch (IOException ioe) {
            fail(ioe);
        }
    }
}
 
Example 10
Project: incubator-netbeans   File: ProfileSupport.java   Source Code and License Vote up 5 votes
@NonNull
private Union2<Profile,String> findProfileInManifest(@NonNull URL root) {
    final ArchiveCache ac = context.getArchiveCache();
    Union2<Profile,String> res;
    final ArchiveCache.Key key = ac.createKey(root);
    if (key != null) {
        res = ac.getProfile(key);
        if (res != null) {
            return res;
        }
    }
    String profileName = null;
    final FileObject rootFo = URLMapper.findFileObject(root);
    if (rootFo != null) {
        final FileObject manifestFile = rootFo.getFileObject(RES_MANIFEST);
        if (manifestFile != null) {
            try {
                try (InputStream in = manifestFile.getInputStream()) {
                    final Manifest manifest = new Manifest(in);
                    final Attributes attrs = manifest.getMainAttributes();
                    profileName = attrs.getValue(ATTR_PROFILE);
                }
            } catch (IOException ioe) {
                LOG.log(
                    Level.INFO,
                    "Cannot read Profile attribute from: {0}", //NOI18N
                    FileUtil.getFileDisplayName(manifestFile));
            }
        }
    }
    final Profile profile = Profile.forName(profileName);
    res = profile != null ?
            Union2.<Profile,String>createFirst(profile) :
            Union2.<Profile,String>createSecond(profileName);
    if (key != null) {
        ac.putProfile(key, res);
    }
    return res;
}
 
Example 11
Project: incubator-netbeans   File: CreatedModifiedFilesTest.java   Source Code and License Vote up 5 votes
/** @see "#64273" */
public void testCreateLayerEntryWithoutLocalizingBundle() throws Exception {
    NbModuleProject project = TestBase.generateStandaloneModule(getWorkDir(), "module");
    project.getProjectDirectory().getFileObject("src/org/example/module/resources/Bundle.properties").delete();
    FileObject mf = project.getProjectDirectory().getFileObject("manifest.mf");
    EditableManifest m;
    InputStream is = mf.getInputStream();
    try {
        m = new EditableManifest(is);
    } finally {
        is.close();
    }
    m.removeAttribute("OpenIDE-Module-Localizing-Bundle", null);
    OutputStream os = mf.getOutputStream();
    try {
        m.write(os);
    } finally {
        os.close();
    }
    CreatedModifiedFiles cmf = new CreatedModifiedFiles(project);
    Operation op = cmf.createLayerEntry("f", null, null, "F!", null);
    cmf.add(op);
    cmf.run();
    String[] supposedContent = new String[] {
        "<filesystem>",
        "<file name=\"f\"/>",
        "</filesystem>"
    };
    assertLayerContent(supposedContent, 
            new File(getWorkDir(), "module/src/org/example/module/resources/layer.xml"));
}
 
Example 12
Project: incubator-netbeans   File: URLDataObject.java   Source Code and License Vote up 5 votes
/**
 * Gets a <code>URL</code> string from the underlying .url file.
 * The user is notified if an error occures during reading the file.
 * If there are multiple lines of text in the file, only the first one is
 * returned and no error is reported.
 *
 * @return  <code>URL</code> string stored in the file,
 *          an empty string if the file is empty,
 *          or <code>null</code> if an error occured while reading the file
 */
String getURLString() {
    FileObject urlFile = getPrimaryFile();
    if (!urlFile.isValid()) {
        return null;
    }
    String urlString = null;
    
    InputStream is = null;
    try {
        is = urlFile.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        urlString = findUrlInFileContent(br);
    } catch (FileNotFoundException fne) {
        ErrorManager.getDefault().notify(ErrorManager.WARNING, fne);
        return null;
    } catch (IOException ioe) {
        ErrorManager.getDefault().notify(ErrorManager.WARNING, ioe);
        return null;
    } finally {
        if (is != null) {
            try {
                is.close ();
            } catch (IOException e) {
                ErrorManager.getDefault().notify(
                        ErrorManager.INFORMATIONAL, e);
            }
        }
    }
    
    if (urlString == null) {
        /*
         * If the file is empty, return an empty string.
         * <null> is reserved for notifications of failures.
         */
        urlString = "";                                             //NOI18N
    }
    return urlString;
}
 
Example 13
Project: incubator-netbeans   File: ModuleNames.java   Source Code and License Vote up 5 votes
@CheckForNull
private static String readModuleName(@NonNull FileObject moduleInfo) throws IOException {
    try (final InputStream in = new BufferedInputStream(moduleInfo.getInputStream())) {
        final ClassFile clz = new ClassFile(in, false);
        final Module modle = clz.getModule();
        return modle != null ?
                modle.getName() :
                null;
    }
}
 
Example 14
Project: incubator-netbeans   File: CreatedModifiedFiles.java   Source Code and License Vote up 5 votes
private static void copyByteAfterByte(FileObject content, FileObject target) throws IOException {
    OutputStream os = target.getOutputStream();
    try {
        InputStream is = content.getInputStream();
        try {
            FileUtil.copy(is, os);
        } finally {
            is.close();
        }
    } finally {
        os.close();
    }
}
 
Example 15
Project: incubator-netbeans   File: GeneratorUtilsTest.java   Source Code and License Vote up 5 votes
static String readFromFile(FileObject fo) throws Exception {
    InputStream in = fo.getInputStream();
    
    int s = (int)fo.getSize();
    byte[] arr = new byte[s];
    assertEquals("All read", s, in.read(arr));
    return new String(arr);
}
 
Example 16
Project: incubator-netbeans   File: SCFTHandlerTest.java   Source Code and License Vote up 5 votes
private static String readChars(FileObject fo, Charset set) throws IOException {
    try (InputStream is = fo.getInputStream()) {
        StringBuilder sb = new StringBuilder();
        int read = 0;
        char[] buffer = new char[1024];
        InputStreamReader r = new InputStreamReader(is, set);
        while ((read = r.read(buffer)) > 0) {
            sb.append(buffer, 0, read);
        }
        return sb.toString().replace(System.getProperty("line.separator"), "\n");
    }
}
 
Example 17
Project: incubator-netbeans   File: NbGlobalActionGoalProvider.java   Source Code and License Vote up 5 votes
@Override
public InputStream getActionDefinitionStream() {
    checkListener();
    FileObject fo = FileUtil.getConfigFile(FILE_NAME_PATH);
    resetCache.set(false);
    if (fo != null) {
        try {
            return fo.getInputStream();
        } catch (FileNotFoundException ex) {
            LOG.log(Level.FINE, "File not found: " + FileUtil.getFileDisplayName(fo), ex);
        }
    }
    return null;
}
 
Example 18
Project: incubator-netbeans   File: BaseFileObjectTestHid.java   Source Code and License Vote up 5 votes
public void testDeletedFileDoesNotReturnInputStream() throws Exception {
    final FileObject testFo = FileUtil.createData(root,"testfile.data");
    final File testFile = FileUtil.toFile(testFo);
    final Logger LOGGER = Logger.getLogger(FileObj.class.getName());
    final Handler handler = new Handler() {
        @Override
        public void publish(LogRecord record) {
            if ("FileObj.getInputStream_after_is_valid".equals(record.getMessage())) {
                testFile.delete();
            }
        }
        @Override
        public void flush() {
        }
        @Override
        public void close() throws SecurityException {
        }
    };
    final Level originalLevel = LOGGER.getLevel();
    LOGGER.setLevel(Level.FINEST);
    try {
        LOGGER.addHandler(handler);
        try {
            testFo.getInputStream();
            assertTrue("Exception not thrown by deleted file getInputStream()", false);
        } catch (FileNotFoundException e) {
            //pass - expected exception
        } finally {
            LOGGER.removeHandler(handler);
        }
    } finally {
        LOGGER.setLevel(originalLevel);
    }
}
 
Example 19
Project: incubator-netbeans   File: Utils.java   Source Code and License Vote up 4 votes
public static Reader createReader(FileObject file) throws FileNotFoundException {
    return new InputStreamReader(file.getInputStream(), FileEncodingQuery.getEncoding(file));
}
 
Example 20
Project: incubator-netbeans   File: NbClassLoader.java   Source Code and License Vote up 4 votes
protected Class findClass (final String name) throws ClassNotFoundException {
    if (!fast && name.indexOf ('.') != -1) {
        Logger.getLogger(NbClassLoader.class.getName()).log(Level.FINE, "NBFS used!");
        String pkg = name.substring (0, name.lastIndexOf ('.'));
        if (getPackage (pkg) == null) {
            String resource = name.replace ('.', '/') + ".class"; // NOI18N
            URL[] urls = getURLs ();
            for (int i = 0; i < urls.length; i++) {
                // System.err.println (urls[i].toString ());
                FileObject root = URLMapper.findFileObject(urls[i]);

                if (root == null) {
                    continue;
                }
                try {
                    FileObject fo = root.getFileObject(resource);

                    if (fo != null) {
                        // Got it. If there is an associated manifest, load it.
                        FileObject manifo = root.getFileObject("META-INF/MANIFEST.MF");

                        if (manifo == null)
                            manifo = root.getFileObject("meta-inf/manifest.mf");
                        if (manifo != null) {
                            // System.err.println (manifo.toString () + " " + manifo.getClass ().getName () + " " + manifo.isValid ());
                            Manifest mani = new Manifest();
                            InputStream is = manifo.getInputStream();

                            try {
                                mani.read(is);
                            }
                            finally {
                                is.close();
                            }
                            definePackage(pkg, mani, urls[i]);
                        }
                        break;
                    }
                }
                catch (IOException ioe) {
                    Exceptions.attachLocalizedMessage(ioe,
                                                      urls[i].toString());
                    Exceptions.printStackTrace(ioe);
                    continue;
                }
            }
        }
    }
    return super.findClass (name);
}