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

The following are Jave code examples for showing how to use getSize() 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: FastMatcher.java   Source Code and License Vote up 6 votes
@Override
    public Def checkMeasuredInternal(FileObject file,
            SearchListener listener) {

        if (trivial) {
            return new Def(file, null, null);
        }

        listener.fileContentMatchingStarted(file.getPath());

        long start = System.currentTimeMillis();
        Def def;
        File f = FileUtil.toFile(file);
        if (file.getSize() > SIZE_LIMIT || f == null) {
//            LOG.log(Level.INFO,
//                    "Falling back to default matcher: {0}, {1} kB", //NOI18N
//                    new Object[]{file.getPath(), file.getSize() / 1024});
//            def = getDefaultMatcher().check(file, listener);
            def = checkBig(file, f, listener);
        } else {
            def = checkSmall(file, f, listener);
        }
        totalTime += System.currentTimeMillis() - start;
        return def;
    }
 
Example 2
Project: incubator-netbeans   File: FolderComparator.java   Source Code and License Vote up 6 votes
/**
 * Sort folders alphabetically first. Then files, biggest to smallest.
 */
private static int compareSize(Object o1, Object o2) {
    boolean f1 = findFileObject(o1).isFolder();
    boolean f2 = findFileObject(o2).isFolder();

    if (f1 != f2) {
        return f1 ? -1 : 1;
    }

    FileObject fo1 = findFileObject(o1);
    FileObject fo2 = findFileObject(o2);
    long s1 = fo1.getSize();
    long s2 = fo2.getSize();
    if (s1 > s2) {
        return -1;
    } else if (s2 > s1) {
        return 1;
    } else {
        return fo1.getNameExt().compareTo(fo2.getNameExt());
    }
}
 
Example 3
Project: incubator-netbeans   File: XMLMIMEComponent.java   Source Code and License Vote up 6 votes
/**
 * Go ahead and retrieve a print or null
 */
protected Smell sniff(FileObject fo) {

    if (fo == null) return null;
    
    if (fo.equals(lastFileObject)) return print;
    
    if (fo.isValid() == false) return null;

    if (fo.getSize() == 0) return null;
    
    print = new Smell();
    errors = 0;
    parse(fo);
    if (this.state == ERROR) {
        return null;
    }
    
    lastFileObject = fo;
    return print;
}
 
Example 4
Project: incubator-netbeans   File: HtmlEditorSupport.java   Source Code and License Vote up 6 votes
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 5
Project: Pogamut3   File: TLDataObject.java   Source Code and License Vote up 6 votes
public TLDataObject(FileObject pf, MultiFileLoader loader) throws DataObjectExistsException, IOException {
    super(pf, loader);
            getCookieSet().assign(SaveCookie.class, saveDB);
            setModified(true);

    if (pf.getSize() > 0) {
        database = getDBFromFile(pf);
    } else {
        database = new TLDatabase();
    }

    CookieSet cookies = getCookieSet();
    cookies.assign(TLDatabase.class, database);
    cookies.add(new TLOpenSupport(this.getPrimaryEntry()));


    cookies.assign(Node.class, this.getNodeDelegate());

    // Set modified if current time of db changes
    database.addDBListener(changeListener);
}
 
Example 6
Project: incubator-netbeans   File: ImageDataObject.java   Source Code and License Vote up 5 votes
/** Gets image data for the image object.
 * @return the image data
 * @deprecated use getImage() instead
 */
private byte[] getImageData() {
    try {
        FileObject fo = getPrimaryFile();
        byte[] imageData = new byte[(int)fo.getSize()];
        BufferedInputStream in = new BufferedInputStream(fo.getInputStream());
        in.read(imageData, 0, (int)fo.getSize());
        in.close();
        return imageData; 
    } catch(IOException ioe) {
        return new byte[0];
    }
}
 
Example 7
Project: incubator-netbeans   File: ContextView.java   Source Code and License Vote up 5 votes
@NbBundle.Messages({
    "TTL_ContextView_showBigFile=Show Big File?",
    "# {0} - file name",
    "# {1} - file size in kilobytes",
    "MSG_ContextView_showBigFile=File {0} is quite big ({1} kB).\n"
    + "Showing it can cause memory and performance problems.\n"
    + "Do you want to show content of this file?",
    "LBL_ContextView_Show=Show",
    "LBL_ContextView_Skip=Do Not Show",
    "LBL_ContextView_ApplyAll=Apply to all big files"
})
private void approveFetchingOfBigFile(final MatchingObject mo,
        final int partIndex) {
    FileObject fo = mo.getFileObject();
    long fileSize = fo.getSize() / 1024;
    JButton showButton = new JButton(Bundle.LBL_ContextView_Show());
    JButton skipButton = new JButton(Bundle.LBL_ContextView_Skip());
    JCheckBox all = new JCheckBox(Bundle.LBL_ContextView_ApplyAll());
    all.setSelected(approveApplyToAllSelected);
    JPanel allPanel = new JPanel();
    allPanel.add(all); //Add to panel not to be handled as standard button.
    NotifyDescriptor nd = new NotifyDescriptor(
            Bundle.MSG_ContextView_showBigFile(
            fo.getNameExt(), fileSize),
            Bundle.TTL_ContextView_showBigFile(),
            NotifyDescriptor.YES_NO_OPTION,
            NotifyDescriptor.WARNING_MESSAGE,
            new Object[]{skipButton, showButton},
            lastApproveOption ? showButton : skipButton);
    nd.setAdditionalOptions(new Object[]{allPanel});
    DialogDisplayer.getDefault().notify(nd);
    boolean app = nd.getValue() == showButton;
    APPROVED_FILES.put(fo, app);
    if (all.isSelected()) {
        allApproved = app;
    }
    approveApplyToAllSelected = all.isSelected();
    lastApproveOption = app;
    displayFile(mo, partIndex);
}
 
Example 8
Project: incubator-netbeans   File: MatchingObject.java   Source Code and License Vote up 5 votes
/**
 * Check validity status of this item.
 * 
 * @return  an invalidity status of this item if it is invalid,
 *          or {@code null} if this item is valid
 * @author  Tim Boudreau
 * @author  Marian Petras
 */
private InvalidityStatus getFreshInvalidityStatus() {
    log(FINER, "getInvalidityStatus()");                            //NOI18N
    FileObject f = getFileObject();
    if (!f.isValid()) {
        log(FINEST, " - DELETED");            
        return InvalidityStatus.DELETED;
    }
    if (f.isFolder()) {
        log(FINEST, " - BECAME_DIR");            
        return InvalidityStatus.BECAME_DIR;
    }
    
    long stamp = f.lastModified().getTime();
    if ((!refreshed && stamp > resultModel.getStartTime())
            || (refreshed && stamp > timestamp)) {
        log(SEVERE, "file's timestamp changed since start of the search");
        if (LOG.isLoggable(FINEST)) {
            final java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.setTimeInMillis(stamp);
            log(FINEST, " - file stamp:           " + stamp + " (" + cal.getTime() + ')');
            cal.setTimeInMillis(resultModel.getStartTime());
            log(FINEST, " - result model created: " + resultModel.getStartTime() + " (" + cal.getTime() + ')');
        }            
        return InvalidityStatus.CHANGED;
    }
    
    if (f.getSize() > Integer.MAX_VALUE) {            
        return InvalidityStatus.TOO_BIG;
    }
    
    if (!f.canRead()) {           
        return InvalidityStatus.CANT_READ;
    }
    
    return null;
}
 
Example 9
Project: incubator-netbeans   File: LayerHandleTest.java   Source Code and License Vote up 5 votes
public void testLayerHandle() throws Exception {
    NbModuleProject project = TestBase.generateStandaloneModule(getWorkDir(), "module");
    LayerHandle handle = LayerHandle.forProject(project);
    FileObject expectedLayerXML = project.getProjectDirectory().getFileObject("src/org/example/module/resources/layer.xml");
    assertNotNull(expectedLayerXML);
    FileObject layerXML = handle.getLayerFile();
    assertNotNull("layer.xml already exists", layerXML);
    assertEquals("right layer file", expectedLayerXML, layerXML);
    FileSystem fs = handle.layer(true);
    assertEquals("initially empty", 0, fs.getRoot().getChildren().length);
    long initialSize = layerXML.getSize();
    fs.getRoot().createData("foo");
    assertEquals("not saved yet", initialSize, layerXML.getSize());
    fs = handle.layer(true);
    assertNotNull("still have in-memory mods", fs.findResource("foo"));
    fs.getRoot().createData("bar");
    handle.save();
    assertTrue("now it is saved", layerXML.getSize() > initialSize);
    String xml =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<!DOCTYPE filesystem PUBLIC \"-//NetBeans//DTD Filesystem 1.2//EN\" \"http://www.netbeans.org/dtds/filesystem-1_2.dtd\">\n" +
            "<filesystem>\n" +
            "    <file name=\"bar\"/>\n" +
            "    <file name=\"foo\"/>\n" +
            "</filesystem>\n";
    assertEquals("right contents too", xml, TestBase.slurp(layerXML));
    // XXX test that nbres: file contents work
}
 
Example 10
Project: incubator-netbeans   File: CustomIconEditor.java   Source Code and License Vote up 5 votes
IconFileItem(FileObject file) {
    this.file = file;
    try {
        try {
            Image image = (file.getSize() < SIZE_LIMIT) ? ImageIO.read(file.getURL()) : null;
            icon = (image != null) ? new ImageIcon(image) : null;
        } catch (IllegalArgumentException iaex) { // Issue 178906
            Logger.getLogger(CustomIconEditor.class.getName()).log(Level.INFO, null, iaex);
            icon = new ImageIcon(file.getURL());
        }
    } catch (IOException ex) {
        Logger.getLogger(CustomIconEditor.class.getName()).log(Level.WARNING, null, ex);
    }
}
 
Example 11
Project: incubator-netbeans   File: DataEditorSupport.java   Source Code and License Vote up 5 votes
/** Obtains the input stream.
* @exception IOException if an I/O error occurs
*/
public InputStream inputStream() throws IOException {
    final FileObject fo = getFileImpl ();
    boolean warned = warnedFiles.contains(fo);
    long size = -1;
    if (!warned && (size = fo.getSize ()) > BIG_FILE_THRESHOLD_MB) {
        throw new ME (size);
    } else if (!sentBigFileInfo && ((size >= 0) ? size : fo.getSize()) > BIG_FILE_THRESHOLD_MB) {
        // warned can contain any file after deserialization
        notifyBigFileLoaded();
    }
    initCanWrite(false);
    InputStream is = getFileImpl ().getInputStream ();
    return is;
}
 
Example 12
Project: incubator-netbeans   File: GsfUtilities.java   Source Code and License Vote up 5 votes
/**
 * Load the document for the given fileObject.
 * @param fileObject the file whose document we want to obtain
 * @param openIfNecessary If true, block if necessary to open the document. If false, will only return the
 *    document if it is already open.
 * @param skipLarge If true, check the file size, and if the file is really large (defined by
 *    openide.loaders), then skip it (otherwise we could end up with a large file warning).
 * @return
 */
public static BaseDocument getDocument(FileObject fileObject, boolean openIfNecessary, boolean skipLarge) {
    if (skipLarge) {
        // Make sure we're not dealing with a huge file!
        // Causes issues like 132306
        // openide.loaders/src/org/openide/text/DataEditorSupport.java
        // has an Env#inputStream method which posts a warning to the user
        // if the file is greater than 1Mb...
        //SG_ObjectIsTooBig=The file {1} seems to be too large ({2,choice,0#{2}b|1024#{3} Kb|1100000#{4} Mb|1100000000#{5} Gb}) to safely open. \n\
        //  Opening the file could cause OutOfMemoryError, which would make the IDE unusable. Do you really want to open it?

        // Apparently there is a way to handle this
        // (see issue http://www.netbeans.org/issues/show_bug.cgi?id=148702 )
        // but for many cases, the user probably doesn't want really large files as indicated
        // by the skipLarge parameter).
        if (fileObject.getSize () > 1024 * 1024) {
            return null;
        }
    }

    try {
        EditorCookie ec = fileObject.isValid() ? DataLoadersBridge.getDefault().getCookie(fileObject, EditorCookie.class) : null;
        if (ec != null) {
            if (openIfNecessary) {
                try {
                    return (BaseDocument) ec.openDocument();
                } catch (UserQuestionException uqe) {
                    uqe.confirmed();
                    return (BaseDocument) ec.openDocument();
                }
            } else {
                return (BaseDocument) ec.getDocument();
            }
        }
    } catch (IOException ex) {
        LOG.log(Level.WARNING, null, ex);
    }

    return null;
}
 
Example 13
Project: incubator-netbeans   File: NbKeymap.java   Source Code and License Vote up 5 votes
/**
 * Traverses shadow files to origin.
 * Returns impl class name if that is obvious (common for SystemAction's);
 * else just returns file path (usual for more modern registrations).
 */
private static String idForFile(FileObject f) {
    if (f.hasExt(SHADOW_EXT)) {
        String path = (String) f.getAttribute("originalFile");
        if (path != null && f.getSize() == 0) {
            f = FileUtil.getConfigFile(path);
            if (f == null) {
                return path; // #169887: some race condition with layer init?
            }
        } else {
            try {
                DataObject d = DataObject.find(f);
                if (d instanceof DataShadow) {
                    f = ((DataShadow) d).getOriginal().getPrimaryFile();
                }
            } catch (DataObjectNotFoundException x) {
                LOG.log(Level.FINE, f.getPath(), x);
            }
        }
    }
    // Cannot actually load instanceCreate methodvalue=... attribute; just want to see if it is there.
    if (f.hasExt("instance") && !Collections.list(f.getAttributes()).contains("instanceCreate")) {
        String clazz = (String) f.getAttribute("instanceClass");
        if (clazz != null) {
            return clazz;
        } else {
            return f.getName().replace('-', '.');
        }
    }
    return f.getPath();
}
 
Example 14
Project: incubator-netbeans   File: SelfSamplerActionTest.java   Source Code and License Vote up 5 votes
@Test
public void testSelfProfileToStream() throws Exception {
    Sampler sampler = Sampler.createManualSampler("testprofile");
    assertTrue("sampler instance", sampler != null);

    sampler.start();
    Thread.sleep(1000);
    assertSamplerThread("sampler-testprofile shall be there", true);

    FileObject fo = FileUtil.createMemoryFileSystem().getRoot().createData("slow.nps");
    OutputStream os = fo.getOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    sampler.stopAndWriteTo(dos);
    dos.close();

    if (fo.getSize() < 100) {
        fail("The file shall have real content: " + fo.getSize());
    }

    DataObject dataObject = DataObject.find(fo);
    assertEquals("Nps DataObject", NpsDataObject.class, dataObject.getClass());
    OpenCookie oc = dataObject.getLookup().lookup(OpenCookie.class);
    assertNotNull("Open cookie exists", oc);

    CharSequence log = Log.enable("", Level.WARNING);
    oc.open();

    if (log.length() > 0) {
        fail("There shall be no warnings:\n" + log);
    }

    assertSamplerThread("no sampler- thread shall be there", false);
}
 
Example 15
Project: incubator-netbeans   File: GeneratedFilesHelper.java   Source Code and License Vote up 5 votes
/** Find (maybe cached) CRC for a file, using a preexisting input stream (not closed by this method). */
private static String getCrc32(InputStream is, FileObject fo) throws IOException {
    URL u = fo.toURL();
    fo.refresh(); // in case was written on disk and we did not notice yet...
    long footprint = fo.lastModified().getTime() ^ fo.getSize();
    String crc = findCachedCrc32(u, footprint);
    if (crc == null) {
        crc = computeCrc32(is);
        cacheCrc32(crc, u, footprint);
    }
    return crc;
}
 
Example 16
Project: incubator-netbeans   File: IndentEngineIntTest.java   Source Code and License Vote up 4 votes
private static String readFile(FileObject fo) throws IOException {
    byte[] arr = new byte[(int)fo.getSize()];
    int len = fo.getInputStream().read(arr);
    assertEquals("Fully read", arr.length, len);
    return new String(arr);
}
 
Example 17
Project: incubator-netbeans   File: PropertiesEncoding.java   Source Code and License Vote up 4 votes
private long getFileSize() {
    FileObject file = getFile();
    return ((file != null) && file.isValid()) ? file.getSize() : 0l;
}
 
Example 18
Project: incubator-netbeans   File: MIMEResolverImpl.java   Source Code and License Vote up 4 votes
public static MIMEResolver forDescriptor(FileObject fo) throws IOException {
    if (fo.getSize() == 0 && !isUserDefined(fo)) {
        return create(fo);
    }
    return forDescriptor(fo, true);
}
 
Example 19
Project: incubator-netbeans   File: SCFTHandlerTest.java   Source Code and License Vote up 4 votes
private static String readFile(FileObject fo) throws IOException {
    byte[] arr = new byte[(int)fo.getSize()];
    int len = fo.getInputStream().read(arr);
    assertEquals("Fully read", arr.length, len);
    return new String(arr);
}
 
Example 20
Project: incubator-netbeans   File: PropertiesProviderTest.java   Source Code and License Vote up 4 votes
private static String readFile(FileObject fo) throws IOException {
    byte[] arr = new byte[(int)fo.getSize()];
    int len = fo.getInputStream().read(arr);
    assertEquals("Fully read", arr.length, len);
    return new String(arr);
}