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

The following examples show how to use org.openide.filesystems.FileObject#getInputStream() . 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: HtmlEditorSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean canDecodeFile(FileObject fo, String encoding) {
    CharsetDecoder decoder = Charset.forName(encoding).newDecoder().onUnmappableCharacter(CodingErrorAction.REPORT).onMalformedInput(CodingErrorAction.REPORT);
    try {
        BufferedInputStream bis = new BufferedInputStream(fo.getInputStream());
        //I probably have to create such big buffer since I am not sure
        //how to cut the file to smaller byte arrays so it cannot happen
        //that an encoded character is divided by the arrays border.
        //In such case it might happen that the method woult return
        //incorrect value.
        byte[] buffer = new byte[(int) fo.getSize()];
        bis.read(buffer);
        bis.close();
        decoder.decode(ByteBuffer.wrap(buffer));
        return true;
    } catch (CharacterCodingException ex) {
        //return false
    } catch (IOException ioe) {
        Logger.getLogger("global").log(Level.WARNING, "Error during charset verification", ioe);
    }
    return false;
}
 
Example 2
Source File: FolderObjTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Test of getInputStream method, of class org.netbeans.modules.masterfs.filebasedfs.fileobjects.FolderObj.
 */
public void testGetInputStream() {
    File f = testFile;
    FileSystem fs = FileBasedFileSystem.getInstance();
    
    FileObject root = fs.getRoot();
    assertNotNull(root);
    
    Enumeration<? extends FileObject> en = root.getFolders(true);
    for (int i = 0; i < 10 && en.hasMoreElements(); i++) {
        FileObject fo = (FileObject) en.nextElement();
        assertTrue(fo.isFolder());
        assertFalse(fo.isData());
        try {
            fo.getInputStream();
            fail ();
        } catch (FileNotFoundException e) {
            
        }

    }
}
 
Example 3
Source File: ModelTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testPersonRevert() throws Exception {
    FileObject fo = getTestFile("testfiles/model/person.js.model");
    BufferedReader reader = new BufferedReader(new InputStreamReader(fo.getInputStream()));
    try {
        Collection<JsObject> obj = Model.readModel(reader, null, null, null);
        assertEquals(1, obj.size());

        final StringWriter sw = new StringWriter();
        Model.Printer p = new Model.Printer() {
            @Override
            public void println(String str) {
                sw.append(str).append("\n");
            }
        };
        Model.writeObject(p, obj.iterator().next(), null);
        assertDescriptionMatches(fo, sw.toString(), false, ".revert", true);
    } finally {
        reader.close();
    }

    // bit hacky check that .model and .model.revert are the same
    String text = fo.asText();
    assertDescriptionMatches("testfiles/model/person.js.model", text, false, ".revert", true);
}
 
Example 4
Source File: FileObjectArchive.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isMultiRelease() {
    Boolean res = multiRelease;
    if (res == null) {
        res = Boolean.FALSE;
        try {
            if (root.getFileSystem() instanceof JarFileSystem) {
                final FileObject manifest = root.getFileObject("META-INF/MANIFEST.MF"); //NOI18N
                if (manifest != null) {
                    try(InputStream in = new BufferedInputStream(manifest.getInputStream())) {
                        res = FileObjects.isMultiVersionArchive(in);
                    }
                }
            }
        } catch (IOException ioe) {
            LOG.log(
                    Level.WARNING,
                    "Cannot read: {0} manifest",    //NOI18N
                    FileUtil.getFileDisplayName(root));
        }
        multiRelease = res;
    }
    return res;
}
 
Example 5
Source File: XmlStaxUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
boolean isTarget(FileObject antScript, String targetName) throws IOException, javax.xml.stream.XMLStreamException {
    InputStream is = antScript.getInputStream();
    XMLStreamReader parser = xmlif.createXMLStreamReader(is);
    boolean found = false;
    int inHeader = 0;
    for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            if ("target".equals(parser.getLocalName()) && targetName.equals(parser.getAttributeValue(null,"name"))) { //NOI18N
                found = true;
                break;
            }
        }
    } // end while
    parser.close();
    is.close();
    return found;
}
 
Example 6
Source File: MavenWhiteListQueryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Manifest getManifest(FileObject root) {
    FileObject manifestFo = root.getFileObject("META-INF/MANIFEST.MF");
    if (manifestFo != null) {
        InputStream is = null;
        try {
            is = manifestFo.getInputStream();
            return new Manifest(is);
        } catch (IOException ex) {
            //Exceptions.printStackTrace(ex);
        } finally {
            IOUtil.close(is);
        }
    }
    return null;

}
 
Example 7
Source File: ProfileSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: AssetsLookupProvider.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Lookup createAdditionalLookup(Lookup lookup) {
    Project prj = lookup.lookup(Project.class);
    project = prj;
    FileObject assetsProperties = prj.getProjectDirectory().getFileObject("nbproject/assets.properties");
    if (assetsProperties == null) {
        assetsProperties = prj.getProjectDirectory().getFileObject("nbproject/project.properties");
    } else {
        Logger.getLogger(AssetsLookupProvider.class.getName()).log(Level.WARNING, "Project is using old assets.properties file");
    }
    if (assetsProperties != null && assetsProperties.isValid()) {
        FileLock lock = null;
        try {
            lock = assetsProperties.lock();
            InputStream in = assetsProperties.getInputStream();
            Properties properties = new Properties();
            properties.load(in);
            in.close();
            String assetsFolderName = properties.getProperty("assets.folder.name", "assets");
            if (prj.getProjectDirectory().getFileObject(assetsFolderName) != null) {
                Logger.getLogger(AssetsLookupProvider.class.getName()).log(Level.INFO, "Valid jMP project, extending with ProjectAssetManager");
                return Lookups.fixed(new ProjectAssetManager(prj, assetsFolderName), openedHook);
            }
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        } finally {
            if (lock != null) {
                lock.releaseLock();
            }
        }
    }

    return Lookups.fixed();
}
 
Example 9
Source File: ImportWorldForgeAction.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void replaceMeshMatName(FileObject file) {
    InputStream stream = null;
    try {
        stream = file.getInputStream();
        Document doc = XMLUtil.parse(new InputSource(stream), false, false, null, null);
        stream.close();
        Element elem = doc.getDocumentElement();
        if (elem == null) {
            throw new IllegalStateException("Cannot find root mesh element");
        }
        Element submeshes = XmlHelper.findChildElement(elem, "submeshes");
        if (submeshes == null) {
            throw new IllegalStateException("Cannot find submeshes element");
        }
        Element submesh = XmlHelper.findChildElement(submeshes, "submesh");
        boolean changed = false;
        while (submesh != null) {
            String matName = submesh.getAttribute("material");
            String newName = removePastUnderScore(matName);
            if (!matName.equals(newName)) {
                Logger.getLogger(ImportWorldForgeAction.class.getName()).log(Level.INFO, "Change material name for {0}", file);
                submesh.setAttribute("material", newName);
                submesh = XmlHelper.findNextSiblingElement(submesh);
                changed = true;
            }
        }
        if (changed) {
            OutputStream out = file.getOutputStream();
            XMLUtil.write(doc, out, "UTF-8");
            out.close();
        }

    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    } finally {
    }
}
 
Example 10
Source File: IndexBuilderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testTitleInJDK8() throws Exception {
    FileObject html = fs.findResource(JDK8_INDEX_PATH + "/index-4.html");

    try (InputStream is = new BufferedInputStream(html.getInputStream(), 1024)) {
        SimpleTitleParser tp = new SimpleTitleParser(is);
        tp.parse();
        String titlestr = tp.getTitle();
        assertEquals("wrong title", "D-Index (Java Platform SE 8 )", titlestr);
    }
}
 
Example 11
Source File: ProjectWhiteListQueryImplementation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Manifest getManifest(FileObject root) {
    FileObject manifestFo = root.getFileObject("META-INF/MANIFEST.MF");
    if (manifestFo != null) {
        InputStream is = null;
        try {
            is = manifestFo.getInputStream();
            return new Manifest(is);
        } catch (IOException ex) {
        }

    }
    return null;
}
 
Example 12
Source File: XmlMultiViewDataObject.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Does this method need to be public ?
 */
public void loadData(FileObject file, FileLock dataLock) throws IOException {
    try {
        BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());
        String encoding = encodingHelper.detectEncoding(inputStream);
        if (!encodingHelper.getEncoding().equals(encoding)) {
            showUsingDifferentEncodingMessage(encoding);
        }
        Reader reader = new InputStreamReader(inputStream, encodingHelper.getEncoding());
        long time;
        StringBuffer sb = new StringBuffer(2048);
        try {
            char[] buf = new char[1024];
            time = file.lastModified().getTime();
            int i;
            while ((i = reader.read(buf,0,1024)) != -1) {
                sb.append(buf,0,i);
            }
        } finally {
            reader.close();
        }
        buffer = null;
        fileTime = time;
        setData(dataLock, sb.toString(), true);
    } finally {
        dataLock.releaseLock();
    }
}
 
Example 13
Source File: ModulesHint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Set<String> readExports(FileObject moduleInfo) {
    Set<String> exported = new HashSet<>();

    try (Reader r = new InputStreamReader(moduleInfo.getInputStream())) {
        StringBuilder content = new StringBuilder();
        int read;

        while ((read = r.read()) != (-1)) {
            content.append((char) read);
        }

        Matcher exportsMatcher = EXPORTS.matcher(content);

        while (exportsMatcher.find()) {
            if (exportsMatcher.group("to") != null) //Ignore qualified exports. How about -Xmodule in @compile?
                continue;

            String pack = exportsMatcher.group(1);

            exported.add(pack);
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }

    return exported;
}
 
Example 14
Source File: IndexBuilderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testTitleInJDK14() throws Exception {
    FileObject html = fs.findResource(JDK14_INDEX_PATH + "/index-4.html");

    try (InputStream is = new BufferedInputStream(html.getInputStream(), 1024)) {
        SimpleTitleParser tp = new SimpleTitleParser(is);
        tp.parse();
        String titlestr = tp.getTitle();
        assertEquals("wrong title", "D-Index (Java 2 Platform SE v1.4.2)", titlestr);
    }
}
 
Example 15
Source File: J2SEJAXWSVersionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public String getJAXWSVersion() {
    String version = "2.1.3"; //NOI18N
    SourceGroup[] srcGroups = ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    if (srcGroups != null && srcGroups.length > 0) {
        ClassPath classpath = ClassPath.getClassPath(srcGroups[0].getRootFolder(), ClassPath.COMPILE);
        FileObject fo = classpath.findResource("com/sun/xml/ws/util/version.properties"); //NOI18N
        if (fo != null) {
            try {
                InputStream is = fo.getInputStream();
                BufferedReader r = new BufferedReader(new InputStreamReader(is, 
                        Charset.forName("UTF-8")));
                String ln = null;
                String ver = null;
                while ((ln=r.readLine()) != null) {
                    String line = ln.trim();
                    if (line.startsWith("major-version=")) { //NOI18N
                        ver = line.substring(14);
                    }
                }
                r.close();
                version = ver;
            } catch (IOException ex) {
                Logger.getLogger(J2SEJAXWSVersionProvider.class.getName()).log(Level.INFO, 
                        "Failed to detect JKAX-WS version", ex); //NOI18N
            }
        } else {
            WSStack<JaxWs> jdkJaxWsStack = JaxWsStackSupport.getJdkJaxWsStack();
            if (jdkJaxWsStack != null) {
                return jdkJaxWsStack.getVersion().toString();
            }
        }
    }
    return version;
}
 
Example 16
Source File: IndexBuilderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testTitleInJDK15() throws Exception {
    FileObject html = fs.findResource(JDK15_INDEX_PATH + "/index-4.html");

    try (InputStream is = new BufferedInputStream(html.getInputStream(), 1024)) {
        SimpleTitleParser tp = new SimpleTitleParser(is);
        tp.parse();
        String titlestr = tp.getTitle();
        assertEquals("wrong title", "D-Index (Java 2 Platform SE 5.0)", titlestr);
    }
}
 
Example 17
Source File: MasterDetailGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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 18
Source File: ProjectExtensionProperties.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void store() throws IOException {
    final FileObject projPropsFO = project.getProjectDirectory().getFileObject(AntProjectHelper.PROJECT_PROPERTIES_PATH);
    if (projPropsFO == null) {
        return;
    }
    final EditableProperties ep = new EditableProperties(true);

    try {
        final InputStream is = projPropsFO.getInputStream();
        ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                try {
                    ep.load(is);
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
                putProperties(properties, ep);
                OutputStream os = null;
                FileLock lock = null;
                try {
                    lock = projPropsFO.lock();
                    os = projPropsFO.getOutputStream(lock);
                    ep.store(os);
                } finally {
                    if (lock != null) {
                        lock.releaseLock();
                    }
                    if (os != null) {
                        os.close();
                    }
                }
                return null;
            }
        });
    } catch (MutexException mux) {
        throw (IOException) mux.getException();
    }

}
 
Example 19
Source File: AntBuildExtender.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void setValueOfProperty(final String propName, final String value, final boolean add) throws IOException {
    try {
        final FileObject projPropsFO = implementation.getOwningProject().getProjectDirectory().getFileObject(AntProjectHelper.PROJECT_PROPERTIES_PATH);
        final InputStream is = projPropsFO.getInputStream();
        ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<Void>() {
            public @Override Void run() throws Exception {
                EditableProperties editableProps = new EditableProperties(true);
                
                try {
                    editableProps.load(is);
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
                
                String libIDs[] = new String[0];
                String savedPropVal = editableProps.getProperty(propName);
                if (savedPropVal != null) {
                    libIDs = savedPropVal.split(",");
                }
                Set<String> libIDSet = new TreeSet<String>(Arrays.asList(libIDs));
                if (add) {
                    libIDSet.add(value);
                } else {
                    libIDSet.remove(value);
                }
                String newLibIDs[] = libIDSet.toArray(new String[libIDSet.size()]);
                StringBuilder propValue = new StringBuilder();
                for (String newLibID : newLibIDs) {
                    propValue.append(newLibID);
                    propValue.append(",");
                }
                propValue.delete(propValue.length() - 1, propValue.length());
                
                editableProps.setProperty(propName, propValue.toString());
                
                OutputStream os = projPropsFO.getOutputStream();
                try {
                    editableProps.store(os);
                } finally {
                    os.close();
                }
                return null;
            }
        });
    } catch (MutexException mux) {
        throw (IOException) mux.getException();
    }
}
 
Example 20
Source File: Util.java    From netbeans with Apache License 2.0 3 votes vote down vote up
/**
 * Convenience method for loading {@link EditableManifest} from a {@link
 * FileObject}.
 *
 * @param manifestFO file representing manifest
 * @exception FileNotFoundException if the file represented by the given
 *            FileObject does not exists, is a folder rather than a regular
 *            file or is invalid. i.e. as it is thrown by {@link
 *            FileObject#getInputStream()}.
 */
public static @NonNull EditableManifest loadManifest(@NonNull FileObject manifestFO) throws IOException {
    InputStream mfIS = manifestFO.getInputStream();
    try {
        return new EditableManifest(mfIS);
    } finally {
        mfIS.close();
    }
}