jcifs.smb.SmbFile Java Examples

The following examples show how to use jcifs.smb.SmbFile. 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: FileLocationTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 7 votes vote down vote up
@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 #2
Source File: FileOperationsTest.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #3
Source File: FileOperationsTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #4
Source File: WatchTest.java    From jcifs with 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 #5
Source File: HFile.java    From PowerFileExplorer with 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 #6
Source File: ReadWriteTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #7
Source File: FileOperationsTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #8
Source File: FileOperationsTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #9
Source File: JCIFS_NGController.java    From DanDanPlayForAndroid with 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 #10
Source File: EnumTest.java    From jcifs with 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 #11
Source File: JCifsTest.java    From elexis-3-core with 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 #12
Source File: NetworkExplorer.java    From jcifs with 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 #13
Source File: SmbTvShow.java    From Mizuu with 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
Source File: SmbMovie.java    From Mizuu with 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 #15
Source File: HFile.java    From PowerFileExplorer with 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 #16
Source File: WatchTest.java    From jcifs-ng with 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 #17
Source File: ReadWriteTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #18
Source File: GetFilesTask.java    From Amphitheatre with 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 #19
Source File: SMBOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #20
Source File: FileLocationTest.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #21
Source File: FileAttributesTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #22
Source File: RandomAccessFileTest.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #23
Source File: FileAttributesTest.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #24
Source File: ConcurrencyTest.java    From jcifs with 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 #25
Source File: ConcurrencyTest.java    From jcifs with 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 #26
Source File: RandomAccessFileTest.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #27
Source File: SmbFileTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimple() throws Exception{

	String path = "smb://administrator:[email protected]\\install\\ftp\\新建文本文档.txt";
	try {
		FileUtils.readAsString(path);
		Assert.fail("path is error, must error");
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	TimeCounter t = new TimeCounter("217");
	t.start();
	path = "smb://administrator:[email protected]/install/ftp/新建文本文档.txt";
	SmbFile smbf = new SmbFile(path);
	InputStream in = new SmbFileInputStream(smbf);
	List<String> list = FileUtils.readAsList(in);
	for(String str : list){
		System.out.println(str);
	}
	t.stop();
	
	/*t.restart("local");
	String baseDir = "smb://administrator:[email protected]/share/";
	path = "/新建文本文档.txt";
	in = FileUtils.newInputStream(baseDir, path);
	list = FileUtils.readAsList(in, "GBK");
	for(String str : list){
		System.out.println(str);
	}
	t.stop();*/
}
 
Example #28
Source File: SambaFileSystemTestHelper.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public void _createFolder(String filename) throws IOException {
	try {
		if(_folderExists(filename)) {
			throw new FileSystemException("Create directory for [" + filename + "] has failed. Directory already exists.");
		}
		new SmbFile(context, filename).mkdir();
	} catch (Exception e) {
		throw new IOException(e);
	}
}
 
Example #29
Source File: HFile.java    From PowerFileExplorer with 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 File: TimeoutTest.java    From jcifs with 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();
        }
    }

}