下面列出了怎么用java.io.SyncFailedException的API类实例代码及写法,或者点击链接到github查看源代码。
private void createFolder(final File folder2Create, final String name) throws IOException {
boolean isSupported = new FileInfo(folder2Create).isSupportedFile();
ProvidedExtensions extensions = getProvidedExtensions();
if (!isSupported) {
extensions.createFailure(this, folder2Create.getName(), true);
FSException.io("EXC_CannotCreateFolder", folder2Create.getName(), getPath());// NOI18N
} else if (FileChangedManager.getInstance().exists(folder2Create)) {
extensions.createFailure(this, folder2Create.getName(), true);
SyncFailedException sfe = new SyncFailedException(folder2Create.getAbsolutePath()); // NOI18N
String msg = NbBundle.getMessage(FileBasedFileSystem.class, "EXC_CannotCreateFolder", folder2Create.getName(), getPath()); // NOI18N
Exceptions.attachLocalizedMessage(sfe, msg);
throw sfe;
} else if (!folder2Create.mkdirs()) {
extensions.createFailure(this, folder2Create.getName(), true);
FSException.io("EXC_CannotCreateFolder", folder2Create.getName(), getPath());// NOI18N
}
LogRecord r = new LogRecord(Level.FINEST, "FolderCreated: "+ folder2Create.getAbsolutePath());
r.setParameters(new Object[] {folder2Create});
Logger.getLogger("org.netbeans.modules.masterfs.filebasedfs.fileobjects.FolderObj").log(r);
}
private void createData(final File file2Create) throws IOException {
boolean isSupported = new FileInfo(file2Create).isSupportedFile();
ProvidedExtensions extensions = getProvidedExtensions();
if (!isSupported) {
extensions.createFailure(this, file2Create.getName(), false);
FSException.io("EXC_CannotCreateData", file2Create.getName(), getPath());// NOI18N
} else if (FileChangedManager.getInstance().exists(file2Create)) {
extensions.createFailure(this, file2Create.getName(), false);
SyncFailedException sfe = new SyncFailedException(file2Create.getAbsolutePath()); // NOI18N
String msg = NbBundle.getMessage(FileBasedFileSystem.class, "EXC_CannotCreateData", file2Create.getName(), getPath()); // NOI18N
Exceptions.attachLocalizedMessage(sfe, msg);
throw sfe;
} else if (!file2Create.createNewFile()) {
extensions.createFailure(this, file2Create.getName(), false);
FSException.io("EXC_CannotCreateData", file2Create.getName(), getPath());// NOI18N
}
LogRecord r = new LogRecord(Level.FINEST, "DataCreated: "+ file2Create.getAbsolutePath());
r.setParameters(new Object[] {file2Create});
Logger.getLogger("org.netbeans.modules.masterfs.filebasedfs.fileobjects.FolderObj").log(r);
}
private void syncFileSystem(final FileDescriptor fd) throws SyncFailedException {
// Simple retry a number of times; avoids Repeater to avoid complications of timeouts and separate threads
int maxTries = 3;
SyncFailedException sfe = null;
for (int c = 0 ; c < maxTries ; c++) {
try {
fd.sync();
sfe = null;
break;
} catch (SyncFailedException e) {
sfe = e;
}
}
if (sfe != null) {
throw sfe;
}
}
public static void atomicWriteBytes(final File destinationFile, final byte[] data)
throws SyncFailedException, IOException {
// Create a temporary file in the same directory as the desination file
final File parentDirectory = destinationFile.getParentFile();
parentDirectory.mkdirs();
final File tempFile = new File(parentDirectory,
destinationFile.getName() + UUID.randomUUID().toString() + ".tmp");
try (final FileOutputStream fos = new FileOutputStream(tempFile);) {
// FIXME: Make serialization of state objects more efficient, currently a
// performance problem
// Do everything we can to ensure a flush to storage
fos.write(data);
//fos.getChannel().force(true);
fos.flush();
//fos.getFD().sync();
fos.close();
try {
// Attempt atomic rename
Files.move(Paths.get(tempFile.getAbsolutePath()), Paths.get(destinationFile.getAbsolutePath()),
StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
// Fall back to normal rename (may not be atomic)
System.err.println("Atomic moves not supported on this platform. This can lead to data loss!");
tempFile.renameTo(destinationFile);
}
}
}
@Test
public void flushAndSync() throws Exception {
when(pdf.getFileDescriptor()).thenReturn(fd);
thrown.expect(SyncFailedException.class);
thrown.expectMessage("sync failed");
outputStream.flushAndSync();
verify(out).flush();
}
@Override
public void close() throws IOException
{
try
{
FileDescriptor fd = getFD();
if(fd!=null)
fd.sync();
}
catch(SyncFailedException ignored) {}
super.close();
}
@Override
public List<RemoteDataInfo> getRemoteEntries() throws SyncFailedException {
StringBuilder sb = new StringBuilder();
sb.append(getBaseFilePath());
sb.append(ENTRIES);
List<RemoteDataInfo> dataInfoObjects = new ArrayList<>();
try {
List<DropboxAPI.Entry> dropboxEntries = getFileInfo(sb.toString()).contents;
for (DropboxAPI.Entry entry : dropboxEntries) {
if ( !entry.isDir ) {
RemoteDataInfo infoObject = new RemoteDataInfo();
infoObject.isDirectory = entry.isDir;
infoObject.isDeleted = entry.isDeleted;
infoObject.name = entry.fileName().toUpperCase();
infoObject.modifiedDate = RESTUtility.parseDate(entry.modified).getTime();
infoObject.revision = entry.rev;
dataInfoObjects.add(infoObject);
}
}
} catch (Exception e) {
if (!BuildConfig.DEBUG) Crashlytics.logException(e);
e.printStackTrace();
throw new SyncFailedException(e.getMessage());
}
return dataInfoObjects;
}
@Override
public List<RemoteDataInfo> getRemotePhotos() throws SyncFailedException {
StringBuilder sb = new StringBuilder();
sb.append(getBaseFilePath());
sb.append(PHOTOS);
List<RemoteDataInfo> dataInfoObjects = new ArrayList<>();
try {
List<DropboxAPI.Entry> dropboxEntries = getFileInfo(sb.toString()).contents;
for (DropboxAPI.Entry file : dropboxEntries) {
if ( !file.isDir ) {
RemoteDataInfo infoObject = new RemoteDataInfo();
infoObject.isDirectory = file.isDir;
infoObject.isDeleted = file.isDeleted;
infoObject.name = file.fileName().toLowerCase();
infoObject.modifiedDate = RESTUtility.parseDate(file.modified).getTime();
infoObject.revision = file.rev;
dataInfoObjects.add(infoObject);
}
}
} catch (Exception e) {
if (!BuildConfig.DEBUG) Crashlytics.logException(e);
e.printStackTrace();
throw new SyncFailedException(e.getMessage());
}
return dataInfoObjects;
}
@Override
public List<RemoteDataInfo> getRemoteEntries() throws SyncFailedException {
LogUtil.log(getClass().getSimpleName(), "Files in Narrate Drive AppFolder:");
List<RemoteDataInfo> dataObjects = new ArrayList<>();
try {
List<File> contents = getContents();
if (contents != null) {
Iterator<File> iter = contents.iterator();
File f;
while (iter.hasNext()) {
f = iter.next();
LogUtil.log(getClass().getSimpleName(), f.getTitle());
if (!f.getTitle().equals("photos")) {
RemoteDataInfo info = new RemoteDataInfo();
info.name = f.getTitle();
info.isDirectory = f.getMimeType().equals(FOLDER_MIME);
info.isDeleted = f.getLabels().getTrashed();
info.modifiedDate = f.getModifiedDate().getValue();
info.revision = String.valueOf(f.getVersion());
dataObjects.add(info);
}
}
return dataObjects;
}
} catch (Exception e) {
if (!BuildConfig.DEBUG) Crashlytics.logException(e);
e.printStackTrace();
throw new SyncFailedException(e.getMessage());
}
return null;
}
@Override
public List<RemoteDataInfo> getRemotePhotos() throws SyncFailedException {
LogUtil.log(DriveSyncService.class.getSimpleName(), "getRemotePhotos()");
List<RemoteDataInfo> dataObjects = new ArrayList<>();
try {
List<File> result = getPhotosContents();
LogUtil.log(getClass().getSimpleName(), "Files in Narrate Drive Photos Folder:");
if (result.size() > 0) {
for (File f : result) {
LogUtil.log(getClass().getSimpleName(), f.getTitle());
RemoteDataInfo info = new RemoteDataInfo();
info.name = f.getTitle();
info.isDirectory = f.getMimeType().equals(FOLDER_MIME);
info.isDeleted = f.getLabels().getTrashed();
info.modifiedDate = f.getModifiedDate().getValue();
info.revision = String.valueOf(f.getVersion());
dataObjects.add(info);
}
}
} catch (Exception e) {
if (!BuildConfig.DEBUG) Crashlytics.logException(e);
e.printStackTrace();
throw new SyncFailedException(e.getMessage());
}
return dataObjects;
}
/**
* Guarantee all writes up to the last call to flushLogAccessFile on disk.
* <p>
* A call for clients of LogAccessFile to insure that all data written
* up to the last call to flushLogAccessFile() are written to disk.
* This call will not return until those writes have hit disk.
* <p>
* Note that this routine may block waiting for I/O to complete so
* callers should limit the number of resource held locked while this
* operation is called. It is expected that the caller
* Note that this routine only "writes" the data to the file, this does not
* mean that the data has been synced to disk. The only way to insure that
* is to first call switchLogBuffer() and then follow by a call of sync().
*
**/
public void syncLogAccessFile()
throws IOException, StandardException
{
for( int i=0; ; )
{
// 3311: JVM sync call sometimes fails under high load against NFS
// mounted disk. We re-try to do this 20 times.
try
{
synchronized( this)
{
log.sync( false);
}
// the sync succeed, so return
break;
}
catch( SyncFailedException sfe )
{
i++;
try
{
// wait for .2 of a second, hopefully I/O is done by now
// we wait a max of 4 seconds before we give up
Thread.sleep( 200 );
}
catch( InterruptedException ie )
{ //does not matter weather I get interrupted or not
}
if( i > 20 )
throw StandardException.newException(
SQLState.LOG_FULL, sfe);
}
}
}
/**
* Force any changes out to the persistent store.
*
* @param metaData If true then this method is required to force changes to both the file's
* content and metadata to be written to storage; otherwise, it need only force content changes
* to be written.
*
* @exception IOException If an IO error occurs.
*/
public void sync( boolean metaData) throws IOException
{
try
{
getChannel().force( metaData);
}
catch( ClosedChannelException cce) { throw cce;}
catch( IOException ioe)
{
SyncFailedException sne = new SyncFailedException( ioe.getMessage());
sne.initCause( ioe);
throw sne;
}
}
/**
* Will hint the OS that data read so far will not be accessed again and should hence be dropped from the buffer cache.
* @param fd The file descriptor to drop from buffer cache.
*/
public void dropPartialFileFromCache(FileDescriptor fd, long offset, long len, boolean sync) {
if (sync) {
try {
fd.sync();
} catch (SyncFailedException e) {
logger.warning("Sync failed while dropping cache: " + e.getMessage());
}
}
if (initialized) {
posix_fadvise(getNativeFD(fd), offset, len, POSIX_FADV_DONTNEED);
}
}
/**
* Guarantee all writes up to the last call to flushLogAccessFile on disk.
* <p>
* A call for clients of LogAccessFile to insure that all data written
* up to the last call to flushLogAccessFile() are written to disk.
* This call will not return until those writes have hit disk.
* <p>
* Note that this routine may block waiting for I/O to complete so
* callers should limit the number of resource held locked while this
* operation is called. It is expected that the caller
* Note that this routine only "writes" the data to the file, this does not
* mean that the data has been synced to disk. The only way to insure that
* is to first call switchLogBuffer() and then follow by a call of sync().
*
**/
public void syncLogAccessFile()
throws IOException, StandardException
{
for( int i=0; ; )
{
// 3311: JVM sync call sometimes fails under high load against NFS
// mounted disk. We re-try to do this 20 times.
try
{
synchronized( this)
{
log.sync( false);
}
// the sync succeed, so return
break;
}
catch( SyncFailedException sfe )
{
i++;
try
{
// wait for .2 of a second, hopefully I/O is done by now
// we wait a max of 4 seconds before we give up
Thread.sleep( 200 );
}
catch( InterruptedException ie )
{ //does not matter weather I get interrupted or not
}
if( i > 20 )
throw StandardException.newException(
SQLState.LOG_FULL, sfe);
}
}
}
/**
* Force any changes out to the persistent store.
*
* @param metaData If true then this method is required to force changes to both the file's
* content and metadata to be written to storage; otherwise, it need only force content changes
* to be written.
*
* @exception IOException If an IO error occurs.
*/
public void sync( boolean metaData) throws IOException
{
try
{
getChannel().force( metaData);
}
catch( ClosedChannelException cce) { throw cce;}
catch( IOException ioe)
{
SyncFailedException sne = new SyncFailedException( ioe.getMessage());
sne.initCause( ioe);
throw sne;
}
}
public static void atomicWriteSignedMessage(final File destinationFile, final SignedMessage signedMessage)
throws SyncFailedException, IOException {
byte[] messageData = MessageSerializer.serializeSignedMessage(signedMessage);
atomicWriteBytes(destinationFile, messageData);
}
public static void atomicWriteString(final File destinationFile, final String string)
throws SyncFailedException, IOException {
atomicWriteBytes(destinationFile, string.getBytes(StandardCharsets.UTF_8));
}
@Message(id = 18, value = "copied content does not match expected hash for item: %s")
SyncFailedException wrongCopiedContent(ContentItem item);
public void fsync() throws SyncFailedException {
fileDescriptor.sync();
}
/**
* Test Method to be used only for testing purposes. Gets the underlying File
* object for the Oplog . Oplog class uses this File object to obtain the
* RandomAccessFile object. Before returning the File object , the dat present
* in the buffers of the RandomAccessFile object is flushed. Otherwise, for
* windows the actual file length does not match with the File size obtained
* from the File object
*
* @throws IOException
* @throws SyncFailedException
*/
File getOplogFile() throws SyncFailedException, IOException
{
synchronized (this.crf) {
if (!this.crf.RAFClosed) {
this.crf.raf.getFD().sync();
}
return this.crf.f;
}
}
/**
* Test Method to be used only for testing purposes. Gets the underlying File
* object for the Oplog . Oplog class uses this File object to obtain the
* RandomAccessFile object. Before returning the File object , the dat present
* in the buffers of the RandomAccessFile object is flushed. Otherwise, for
* windows the actual file length does not match with the File size obtained
* from the File object
*
* @throws IOException
* @throws SyncFailedException
*/
File getOplogFile() throws SyncFailedException, IOException
{
synchronized (this.crf) {
if (!this.crf.RAFClosed) {
this.crf.raf.getFD().sync();
}
return this.crf.f;
}
}
/**
* Queries remote sync service for information about the data the service stores (i.e.
* a list of file names, modified date, etc.)
*
* @return list of info objects
*/
public abstract List<RemoteDataInfo> getRemoteEntries() throws SyncFailedException;
/**
* Force the data of an output stream out to the underlying storage.
*
* That is, ensure that it has been made persistent. If the database is to
* be transient, that is, if the database does not survive a restart, then
* the sync method implementation need not do anything.
*
* @param stream The stream to be synchronized.
* @param metaData If true then this method must force both changes to the
* file's contents and metadata to be written to storage;
* if false, it need only force file content changes to be
* written. The implementation is allowed to ignore this
* parameter and always force out metadata changes.
*
* @exception IOException if an I/O error occurs.
* @exception SyncFailedException Thrown when the buffers cannot be flushed,
* or because the system cannot guarantee that all the buffers
* have been synchronized with physical media.
*/
public void sync( OutputStream stream, boolean metaData) throws IOException, SyncFailedException
{
realStorageFactory.sync(stream, metaData);
}
/**
* Force the data of an output stream out to the underlying storage. That is, ensure that
* it has been made persistent. If the database is to be transient, that is, if the database
* does not survive a restart, then the sync method implementation need not do anything.
*
* @param stream The stream to be synchronized.
* @param metaData If true then this method must force both changes to the file's
* contents and metadata to be written to storage; if false, it need only force file content changes
* to be written. The implementation is allowed to ignore this parameter and always force out
* metadata changes.
*
* @exception IOException if an I/O error occurs.
* @exception SyncFailedException Thrown when the buffers cannot be flushed,
* or because the system cannot guarantee that all the buffers have been
* synchronized with physical media.
*/
public void sync( OutputStream stream, boolean metaData) throws IOException, SyncFailedException
{
((FileOutputStream) stream).getFD().sync();
}
/**
* Force the data of an output stream out to the underlying storage. That is, ensure that
* it has been made persistent. If the database is to be transient, that is, if the database
* does not survive a restart, then the sync method implementation need not do anything.
*
* @param stream The stream to be synchronized.
* @param metaData If true then this method must force both changes to the file's
* contents and metadata to be written to storage; if false, it need only force file content changes
* to be written. The implementation is allowed to ignore this parameter and always force out
* metadata changes.
*
* @exception IOException if an I/O error occurs.
* @exception SyncFailedException Thrown when the buffers cannot be flushed,
* or because the system cannot guarantee that all the buffers have been
* synchronized with physical media.
*/
public void sync( OutputStream stream, boolean metaData) throws IOException, SyncFailedException;
/**
* Force the data of an output stream out to the underlying storage.
*
* That is, ensure that it has been made persistent. If the database is to
* be transient, that is, if the database does not survive a restart, then
* the sync method implementation need not do anything.
*
* @param stream The stream to be synchronized.
* @param metaData If true then this method must force both changes to the
* file's contents and metadata to be written to storage;
* if false, it need only force file content changes to be
* written. The implementation is allowed to ignore this
* parameter and always force out metadata changes.
*
* @exception IOException if an I/O error occurs.
* @exception SyncFailedException Thrown when the buffers cannot be flushed,
* or because the system cannot guarantee that all the buffers
* have been synchronized with physical media.
*/
public void sync( OutputStream stream, boolean metaData) throws IOException, SyncFailedException
{
realStorageFactory.sync(stream, metaData);
}
/**
* Force the data of an output stream out to the underlying storage. That is, ensure that
* it has been made persistent. If the database is to be transient, that is, if the database
* does not survive a restart, then the sync method implementation need not do anything.
*
* @param stream The stream to be synchronized.
* @param metaData If true then this method must force both changes to the file's
* contents and metadata to be written to storage; if false, it need only force file content changes
* to be written. The implementation is allowed to ignore this parameter and always force out
* metadata changes.
*
* @exception IOException if an I/O error occurs.
* @exception SyncFailedException Thrown when the buffers cannot be flushed,
* or because the system cannot guarantee that all the buffers have been
* synchronized with physical media.
*/
public void sync( OutputStream stream, boolean metaData) throws IOException, SyncFailedException
{
((FileOutputStream) stream).getFD().sync();
}
/**
* Force the data of an output stream out to the underlying storage. That is, ensure that
* it has been made persistent. If the database is to be transient, that is, if the database
* does not survive a restart, then the sync method implementation need not do anything.
*
* @param stream The stream to be synchronized.
* @param metaData If true then this method must force both changes to the file's
* contents and metadata to be written to storage; if false, it need only force file content changes
* to be written. The implementation is allowed to ignore this parameter and always force out
* metadata changes.
*
* @exception IOException if an I/O error occurs.
* @exception SyncFailedException Thrown when the buffers cannot be flushed,
* or because the system cannot guarantee that all the buffers have been
* synchronized with physical media.
*/
public void sync( OutputStream stream, boolean metaData) throws IOException, SyncFailedException;
/**
* ファイルディスクリプタの同期.
* @param fd ファイルディスクリプタ
* @exception SyncFailedException 同期に失敗
*/
public void sync(FileDescriptor fd) throws SyncFailedException {
fd.sync();
}
/**
* ファイルディスクリプタの同期.
* @param fd ファイルディスクリプタ
* @throws SyncFailedException 同期に失敗
*/
public void sync(FileDescriptor fd) throws SyncFailedException {
fd.sync();
}