Java Code Examples for jcifs.smb.SmbFile

The following examples show how to use jcifs.smb.SmbFile. These examples are extracted from open source projects. 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 Project: PowerFileExplorer   Source File: HFile.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @deprecated use {@link #length(Context)} to handle content resolvers
 * @return
 */
public long length() {
    long s = 0L;
    switch (mode) {
        case SMB:
            SmbFile smbFile = getSmbFile();
            if (smbFile != null)
                try {
                    s = smbFile.length();
                } catch (SmbException e) {
                }
            return s;
        case FILE:
            s = new File(path).length();
            return s;
        case ROOT:
            BaseFile baseFile = generateBaseFileFromParent();
            if (baseFile != null) return baseFile.size;
            break;
    }
    return s;
}
 
Example 2
Source Project: PowerFileExplorer   Source File: HFile.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @deprecated use {@link #getName(Context)}
 * @return
 */
public String getName() {
    String name = null;
    switch (mode) {
        case SMB:
            SmbFile smbFile = getSmbFile();
            if (smbFile != null)
                return smbFile.getName();
            break;
        case FILE:
            return new File(path).getName();
        case ROOT:
            return new File(path).getName();
        default:
            //StringBuilder builder = new StringBuilder(path);
            name = path.substring(path.lastIndexOf("/") + 1, path.length());
    }
    return name;
}
 
Example 3
@Test
public void testRenameDirectory () throws CIFSException, MalformedURLException, UnknownHostException {
    try ( SmbFile defaultShareRoot = getDefaultShareRoot();
          SmbFile d = createTestDirectory();
          SmbResource d1 = new SmbFile(defaultShareRoot, makeRandomDirectoryName());
          SmbFile d2 = new SmbFile(d, makeRandomDirectoryName()) ) {
        d1.mkdir();
        boolean renamed = false;
        try {
            d1.renameTo(d2);
            try {
                assertTrue(d2.exists());
                renamed = true;
            }
            finally {
                d2.delete();
            }
        }
        finally {
            if ( !renamed && d1.exists() ) {
                d1.delete();
            }
            d.delete();
        }
    }
}
 
Example 4
private void runReadWriteTest ( int bufSize, long length ) throws MalformedURLException, UnknownHostException, SmbException, IOException {
    try ( SmbFile f = createTestFile() ) {
        try {
            try ( OutputStream os = f.getOutputStream() ) {
                writeRandom(bufSize, length, os);
            }

            assertEquals("File size matches", length, f.length());

            try ( InputStream is = f.getInputStream() ) {
                verifyRandom(bufSize, length, is);
            }

        }
        finally {
            f.delete();
        }
    }
}
 
Example 5
@Test
public void testRenameFile () throws CIFSException, MalformedURLException, UnknownHostException {
    try ( SmbFile defaultShareRoot = getDefaultShareRoot();
          SmbResource f = new SmbFile(defaultShareRoot, makeRandomName());
          SmbFile f2 = new SmbFile(defaultShareRoot, makeRandomName()) ) {
        f.createNewFile();
        boolean renamed = false;
        try {
            f.renameTo(f2);
            try {
                assertTrue(f2.exists());
                renamed = true;
            }
            finally {
                f2.delete();
            }
        }
        finally {
            if ( !renamed && f.exists() ) {
                f.delete();
            }
        }
    }
}
 
Example 6
@Test
public void testMoveDirectory () throws CIFSException, MalformedURLException, UnknownHostException {
    try ( SmbFile defaultShareRoot = getDefaultShareRoot();
          SmbResource d1 = new SmbFile(defaultShareRoot, makeRandomDirectoryName());
          SmbFile d2 = new SmbFile(defaultShareRoot, makeRandomDirectoryName()) ) {
        d1.mkdir();
        boolean renamed = false;
        try {
            d1.renameTo(d2);
            try {
                assertTrue(d2.exists());
                renamed = true;
            }
            finally {
                d2.delete();
            }
        }
        finally {
            if ( !renamed && d1.exists() ) {
                d1.delete();
            }
        }
    }
}
 
Example 7
Source Project: jcifs   Source File: WatchTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testWatchModified () throws InterruptedException, ExecutionException, IOException {
    // samba 4 starting with some version does not seem to handle this correctly :(
    try ( SmbWatchHandle w = this.base
            .watch(FileNotifyInformation.FILE_NOTIFY_CHANGE_ATTRIBUTES | FileNotifyInformation.FILE_NOTIFY_CHANGE_LAST_WRITE, false) ) {
        try ( SmbFile cr = new SmbFile(this.base, "modified") ) {
            cr.createNewFile();
            setupWatch(w);
            try ( OutputStream os = cr.getOutputStream() ) {
                os.write(new byte[] {
                    1, 2, 3, 4
                });
            }
            assertNotified(w, FileNotifyInformation.FILE_ACTION_MODIFIED, "modified", null);
        }
    }
    catch ( TimeoutException e ) {
        log.info("Timeout waiting", e);
        fail("Did not recieve notification");
    }
}
 
Example 8
Source Project: DanDanPlayForAndroid   Source File: JCIFS_NGController.java    License: MIT License 6 votes vote down vote up
@Override
public List<SmbFileInfo> getSelfList() {
    if (isRootDir())
        return rootFileList;

    List<SmbFileInfo> fileInfoList = new ArrayList<>();
    try {
        SmbFile smbFile = new SmbFile(mAuthUrl + mPath, cifsContext);
        if (smbFile.isDirectory() && smbFile.canRead()) {
            fileInfoList.addAll(getFileInfoList(smbFile.listFiles()));
        }
    } catch (MalformedURLException | SmbException e) {
        e.printStackTrace();
    }

    return fileInfoList;
}
 
Example 9
Source Project: jcifs   Source File: EnumTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testEmptyEnum () throws CIFSException, MalformedURLException, UnknownHostException {
    try ( SmbFile f = createTestDirectory() ) {
        try {
            SmbFile[] files = f.listFiles(new DosFileFilter("*.txt", 0));
            assertNotNull(files);
            assertEquals(0, files.length);

            files = f.listFiles();
            assertNotNull(files);
            assertEquals(0, files.length);
        }
        finally {
            f.delete();
        }
    }
}
 
Example 10
Source Project: elexis-3-core   Source File: JCifsTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void createDeleteNonExistingDirectory() throws IOException{
	assumeTrue(servicesAreReachable);
	URL url = new URL(prefixUrl + "test/");
	if (url.getUserInfo() == null) {
		// not authenticated
		thrown.expect(SmbAuthException.class);
	}
	URLConnection openConnection = url.openConnection();
	try (SmbFile smbFile = (SmbFile) openConnection) {
		assertFalse(smbFile.exists());
		smbFile.mkdir();
		assertTrue(smbFile.exists());
		smbFile.delete();
		assertFalse(smbFile.exists());
	}
}
 
Example 11
Source Project: jcifs   Source File: NetworkExplorer.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void doFile ( HttpServletRequest req, HttpServletResponse resp, SmbFile file ) throws IOException {
    byte[] buf = new byte[8192];

    @SuppressWarnings ( "resource" )
    ServletOutputStream out = resp.getOutputStream();
    String url;
    int n;
    try ( SmbFileInputStream in = new SmbFileInputStream(file) ) {
        url = file.getLocator().getPath();
        resp.setContentType("text/plain");
        resp.setContentType(URLConnection.guessContentTypeFromName(url));
        resp.setHeader("Content-Length", file.length() + "");
        resp.setHeader("Accept-Ranges", "Bytes");

        while ( ( n = in.read(buf) ) != -1 ) {
            out.write(buf, 0, n);
        }
    }
}
 
Example 12
@Test
public void testDfsReferralChildResource () throws MalformedURLException, CIFSException {
    try ( SmbResource p = new SmbFile("smb://1.2.3.4/share/foo/", getContext()) ) {
        DfsReferralData dr = new TestDfsReferral("1.2.3.5", "other", "", 0);
        String reqPath = "\\foo\\";
        SmbResourceLocator fl = p.getLocator();
        assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl ).handleDFSReferral(dr, reqPath));

        assertEquals("1.2.3.4", fl.getServer());
        assertEquals("1.2.3.5", fl.getServerWithDfs());
        assertEquals("other", fl.getShare());
        assertEquals("\\foo\\", fl.getUNCPath());
        // this intentionally sticks to the old name
        assertEquals("/share/foo/", fl.getURLPath());

        try ( SmbResource c = p.resolve("bar/") ) {
            SmbResourceLocator fl2 = c.getLocator();
            reqPath = fl2.getUNCPath();
            assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl2 ).handleDFSReferral(dr, reqPath));
        }
    }
}
 
Example 13
Source Project: Mizuu   Source File: SmbTvShow.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void addToResults(SmbFile file, TreeSet<String> results) {
    if (MizLib.checkFileTypes(file.getCanonicalPath())) {
        try {
            if (file.length() < getFileSizeLimit())
                return;
        } catch (SmbException e) {
            return;
        }

        if (!clearLibrary())
            if (existingEpisodes.get(file.getCanonicalPath()) != null) return;

        //Add the file if it reaches this point
        results.add(file.getCanonicalPath());
    }
}
 
Example 14
@Test
public void testReadOnly () throws IOException {
    try ( SmbFile f = createTestFile() ) {
        try {
            try ( SmbFileOutputStream os = f.openOutputStream() ) {
                os.write(new byte[] {
                    0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7
                });
            }

            byte[] buf = new byte[4];
            try ( SmbRandomAccessFile raf = new SmbRandomAccessFile(f, "r") ) {
                raf.seek(4);
                raf.readFully(buf);
            }

            Assert.assertArrayEquals(new byte[] {
                0x4, 0x5, 0x6, 0x7
            }, buf);
        }
        finally {
            f.delete();
        }
    }
}
 
Example 15
Source Project: Mizuu   Source File: SmbMovie.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void addToResults(SmbFile file, TreeSet<String> results) {
	if (MizLib.checkFileTypes(file.getCanonicalPath())) {
		try {
			if (file.length() < getFileSizeLimit() && !file.getName().equalsIgnoreCase("video_ts.ifo"))
				return;
		} catch (SmbException e) {
			return;
		}

		if (!clearLibrary())
			if (existingMovies.get(file.getCanonicalPath()) != null) return;

		String tempFileName = file.getName().substring(0, file.getName().lastIndexOf("."));
		if (tempFileName.toLowerCase(Locale.ENGLISH).matches(".*part[2-9]|cd[2-9]")) return;

		//Add the file if it reaches this point
		results.add(file.getCanonicalPath());
	}
}
 
Example 16
Source Project: jcifs   Source File: ConcurrencyTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testOpenLocked () throws IOException {
    String fname = makeRandomName();
    try ( SmbFile sr = getDefaultShareRoot();
          SmbResource exclFile = new SmbFile(sr, fname) ) {

        try ( OutputStream s = exclFile.openOutputStream(false, SmbConstants.FILE_NO_SHARE);
              InputStream is = exclFile.openInputStream(SmbConstants.FILE_NO_SHARE) ) {
            fail("No sharing violation");
        }
        catch ( SmbException e ) {
            if ( e.getNtStatus() == NtStatus.NT_STATUS_SHARING_VIOLATION ) {
                return;
            }
            throw e;
        }
        finally {
            exclFile.delete();
        }
    }
}
 
Example 17
Source Project: jcifs   Source File: ConcurrencyTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testOpenReadLocked () throws IOException {
    String fname = makeRandomName();
    try ( SmbFile sr = getDefaultShareRoot();
          SmbResource exclFile = new SmbFile(sr, fname) ) {

        exclFile.createNewFile();
        try {
            try ( InputStream is = exclFile.openInputStream(SmbConstants.FILE_NO_SHARE);
                  InputStream is2 = exclFile.openInputStream(SmbConstants.FILE_NO_SHARE) ) {
                fail("No sharing violation");
            }
            catch ( SmbException e ) {
                if ( e.getNtStatus() == NtStatus.NT_STATUS_SHARING_VIOLATION ) {
                    return;
                }
                throw e;
            }
        }
        finally {
            exclFile.delete();
        }
    }
}
 
Example 18
@Test
public void testSetAttributes () throws CIFSException, MalformedURLException, UnknownHostException {
    try ( SmbFile f = createTestFile() ) {
        try {
            int attrs = f.getAttributes() ^ SmbConstants.ATTR_ARCHIVE ^ SmbConstants.ATTR_HIDDEN ^ SmbConstants.ATTR_READONLY;
            f.setAttributes(attrs);
            assertEquals(attrs, f.getAttributes());
        }
        catch ( SmbUnsupportedOperationException e ) {
            Assume.assumeTrue("No Ntsmbs", false);
        }
        finally {
            f.delete();
        }
    }
}
 
Example 19
@Test
public void testLargeReadWrite () throws IOException {
    try ( SmbFile f = createTestFile() ) {
        try {
            int bufSize = 64 * 1024 + 512;
            int l = bufSize;
            try ( SmbRandomAccess raf = f.openRandomAccess("rw") ) {
                writeRandom(bufSize, l, raf);
            }

            try ( SmbRandomAccess raf = f.openRandomAccess("rw") ) {
                verifyRandom(bufSize, l, raf);
            }
        }
        finally {
            f.delete();
        }
    }
}
 
Example 20
@Test
public void testSetAttributes () throws CIFSException, MalformedURLException, UnknownHostException {
    try ( SmbFile f = createTestFile() ) {
        try {
            int attrs = f.getAttributes() ^ SmbConstants.ATTR_ARCHIVE ^ SmbConstants.ATTR_HIDDEN ^ SmbConstants.ATTR_READONLY;
            f.setAttributes(attrs);
            assertEquals(attrs, f.getAttributes());
        }
        catch ( SmbUnsupportedOperationException e ) {
            Assume.assumeTrue("No Ntsmbs", false);
        }
        finally {
            f.delete();
        }
    }
}
 
Example 21
@Test
public void testDfsReferralChildResource () throws MalformedURLException, CIFSException {
    try ( SmbResource p = new SmbFile("smb://1.2.3.4/share/foo/", getContext()) ) {
        DfsReferralData dr = new TestDfsReferral("1.2.3.5", "other", "", 0);
        String reqPath = "\\foo\\";
        SmbResourceLocator fl = p.getLocator();
        assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl ).handleDFSReferral(dr, reqPath));

        assertEquals("1.2.3.4", fl.getServer());
        assertEquals("1.2.3.5", fl.getServerWithDfs());
        assertEquals("other", fl.getShare());
        assertEquals("\\foo\\", fl.getUNCPath());
        // this intentionally sticks to the old name
        assertEquals("/share/foo/", fl.getURLPath());

        try ( SmbResource c = p.resolve("bar/") ) {
            SmbResourceLocator fl2 = c.getLocator();
            reqPath = fl2.getUNCPath();
            assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl2 ).handleDFSReferral(dr, reqPath));
        }
    }
}
 
Example 22
private List<Info> list(SmbFile parent, ListParameters params) throws IOException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	if (!parent.exists()) {
		throw new FileNotFoundException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.file_not_found"), parent.toString())); //$NON-NLS-1$
	}
	if (!parent.isDirectory()) {
		return Arrays.asList(info(parent));
	}
	SmbFile[] children = ensureTrailingSlash(parent).listFiles();
	if (children != null) {
		List<Info> result = new ArrayList<Info>();
		for (SmbFile child: children) {
			result.add(info(child));
			if (params.isRecursive() && child.isDirectory()) {
				result.addAll(list(child, params));
			}
		}
		return result;
	}
	return new ArrayList<Info>(0);
}
 
Example 23
Source Project: Amphitheatre   Source File: GetFilesTask.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onPostExecute(List<SmbFile> files) {
    try {
        final int cpuCount = Runtime.getRuntime().availableProcessors();
        final int maxPoolSize = cpuCount * 2 + 1;
        final int partitionSize = files.size() < maxPoolSize ? files.size() : (files.size() / maxPoolSize);

        List<List<SmbFile>> subSets = ListUtils.partition(files, partitionSize);

        mNumOfSets = subSets.size();

        for (List<SmbFile> subSet : subSets) {
            if (mIsMovie) {
                new DownloadMovieTask(mContext, mConfig, subSet, this)
                        .executeOnExecutor(THREAD_POOL_EXECUTOR);
            } else {
                new DownloadTvShowTask(mContext, mConfig, subSet, this)
                        .executeOnExecutor(THREAD_POOL_EXECUTOR);
            }
        }
    } catch (Exception e) {
        if (mCallback != null) {
            mCallback.failure();
        }
    }
}
 
Example 24
@Test
public void testLargeBufSmallWrite () throws IOException {
    try ( SmbFile f = createTestFile() ) {
        try {
            int bufSize = 65535;
            long length = 1024;
            try ( OutputStream os = f.getOutputStream() ) {
                writeRandom(bufSize, length, os);
            }

            try ( InputStream is = f.getInputStream() ) {
                verifyRandom(bufSize, length, is);
            }

        }
        finally {
            f.delete();
        }
    }
}
 
Example 25
Source Project: jcifs-ng   Source File: WatchTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testWatchModified () throws InterruptedException, ExecutionException, IOException {
    // samba 4 starting with some version does not seem to handle this correctly :(
    try ( SmbWatchHandle w = this.base
            .watch(FileNotifyInformation.FILE_NOTIFY_CHANGE_ATTRIBUTES | FileNotifyInformation.FILE_NOTIFY_CHANGE_LAST_WRITE, false) ) {
        try ( SmbFile cr = new SmbFile(this.base, "modified") ) {
            cr.createNewFile();
            setupWatch(w);
            try ( OutputStream os = cr.getOutputStream() ) {
                os.write(new byte[] {
                    1, 2, 3, 4
                });
            }
            assertNotified(w, FileNotifyInformation.FILE_ACTION_MODIFIED, "modified", null);
        }
    }
    catch ( TimeoutException e ) {
        log.info("Timeout waiting", e);
        fail("Did not recieve notification");
    }
}
 
Example 26
@Test
public void testCopyEmpty () throws IOException {
    try ( SmbFile f = createTestFile() ) {
        try ( SmbFile d1 = createTestDirectory();
              SmbFile t = new SmbFile(d1, makeRandomName()) ) {
            try {
                f.copyTo(t);
                assertTrue(f.exists());
                assertEquals(f.length(), t.length());
                assertEquals(f.getAttributes(), t.getAttributes());
            }
            finally {
                d1.delete();
            }
        }
        finally {
            f.delete();
        }
    }
}
 
Example 27
Source Project: iaf   Source File: Samba1FileSystem.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void open() throws FileSystemException {
	try {
		smbContext = new SmbFile(getShare(), auth);
		smbContext.connect();
	} catch (IOException e) {
		throw new FileSystemException(e);
	}

}
 
Example 28
/**
 * Similar to SmbFile.getName(), but removes trailing slash (in case of directories).
 */
public static String getName(SmbFile file) {
	String name = file.getName();
	if (name.endsWith("/")) {
		name = name.substring(0, name.length() - 1);
	}
	return name;
}
 
Example 29
Source Project: PowerFileExplorer   Source File: HFile.java    License: GNU General Public License v3.0 5 votes vote down vote up
public SmbFile getSmbFile(int timeout) {
    try {
        SmbFile smbFile = new SmbFile(path);
        smbFile.setConnectTimeout(timeout);
        return smbFile;
    } catch (MalformedURLException e) {
        return null;
    }
}
 
Example 30
Source Project: jcifs   Source File: TimeoutTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings ( "resource" )
@Test
public void testIdleTimeout () throws IOException, InterruptedException {
    // use separate context here as the settings stick to the transport
    CIFSContext ctx = fastIdle(withTestNTLMCredentials(getNewContext()));
    try ( SmbFile r = new SmbFile(getTestShareURL(), ctx);
          SmbFile f = new SmbFile(r, makeRandomName()) ) {
        int soTimeout = ctx.getConfig().getSoTimeout();
        f.createNewFile();
        try {
            SmbTransportInternal t;
            try ( SmbTreeHandleInternal th = (SmbTreeHandleInternal) f.getTreeHandle();
                  SmbSessionInternal session = th.getSession().unwrap(SmbSessionInternal.class);
                  SmbTransportInternal trans = session.getTransport().unwrap(SmbTransportInternal.class) ) {
                t = trans;
            }
            f.close();

            Thread.sleep(2 * soTimeout);

            // connection should be closed by now
            assertTrue("Transport is still connected", t.isDisconnected());
            assertFalse("Connection is still in the pool", ( (SmbTransportPoolImpl) ctx.getTransportPool() ).contains(t));
        }
        finally {
            f.delete();
        }
    }

}