Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2012 JBoss Inc
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *       http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.uberfire.io.impl;
 
 import java.net.URI;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  org.uberfire.commons.lock.LockService;
 import  org.uberfire.commons.lock.impl.ThreadLockServiceImpl;
 import  org.uberfire.java.nio.IOException;
 import  org.uberfire.java.nio.base.AbstractPath;
 import  org.uberfire.java.nio.base.FileSystemState;
 import  org.uberfire.java.nio.channels.SeekableByteChannel;
 import  org.uberfire.java.nio.file.CopyOption;
 import  org.uberfire.java.nio.file.DirectoryNotEmptyException;
 import  org.uberfire.java.nio.file.DirectoryStream;
 import  org.uberfire.java.nio.file.FileAlreadyExistsException;
 import  org.uberfire.java.nio.file.FileSystem;
 import  org.uberfire.java.nio.file.FileSystemAlreadyExistsException;
 import  org.uberfire.java.nio.file.FileSystemNotFoundException;
 import  org.uberfire.java.nio.file.FileSystems;
 import  org.uberfire.java.nio.file.Files;
 import  org.uberfire.java.nio.file.NoSuchFileException;
 import  org.uberfire.java.nio.file.NotDirectoryException;
 import  org.uberfire.java.nio.file.OpenOption;
 import  org.uberfire.java.nio.file.Option;
 import  org.uberfire.java.nio.file.Path;
 import  org.uberfire.java.nio.file.Paths;
 import  org.uberfire.java.nio.file.ProviderNotFoundException;
 import  org.uberfire.java.nio.file.StandardOpenOption;
 import  org.uberfire.java.nio.file.api.FileSystemProviders;
 import  org.uberfire.java.nio.file.attribute.FileAttribute;
 import  org.uberfire.java.nio.file.attribute.FileTime;
 import  org.uberfire.java.nio.file.spi.FileSystemProvider;
 import  org.uberfire.java.nio.security.SecurityAware;
 import  org.uberfire.security.auth.AuthenticationManager;
 import  org.uberfire.security.authz.AuthorizationManager;
 
 import static org.uberfire.commons.validation.PortablePreconditions.*;
 import static org.uberfire.java.nio.file.StandardOpenOption.*;
 
 public abstract class AbstractIOService implements IOServiceIdentifiable {
 
     private static final Logger logger = LoggerFactory.getLoggerAbstractIOService.class );
 
     protected static final String DEFAULT_SERVICE_NAME = "default";
 
     private static final Set<StandardOpenOption> CREATE_NEW_FILE_OPTIONS = EnumSet.of( CREATE_NEW, WRITE );
 
     protected static final Charset UTF_8 = Charset.forName"UTF-8" );
     public static final FileSystemType DEFAULT_FS_TYPE = new FileSystemType() {
         @Override
         public String toString() {
             return "DEFAULT";
         }
 
         @Override
         public int hashCode() {
             return toString().hashCode();
         }
     };
 
     protected final LockService lockService;
     protected final IOWatchService ioWatchService;
     protected final Map<FileSystemTypeList<FileSystem>> fileSystems = new HashMap<FileSystemTypeList<FileSystem>>();
 
     protected NewFileSystemListener newFileSystemListener = null;
    protected boolean isDisposed = false;
    private String id;
    public AbstractIOService() {
        this. = ;
         = new ThreadLockServiceImpl();
         = null;
    }
    public AbstractIOServicefinal String id ) {
        this. = id;
         = new ThreadLockServiceImpl();
         = null;
    }
    public AbstractIOServicefinal IOWatchService watchService ) {
        this. = ;
         = new ThreadLockServiceImpl();
         = watchService;
    }
    public AbstractIOServicefinal String id,
                              final IOWatchService watchService ) {
        this. = id;
         = new ThreadLockServiceImpl();
         = watchService;
    }
    public AbstractIOServicefinal LockService lockService,
                              final IOWatchService watchService ) {
        this. = ;
        this. = lockService;
        this. = watchService;
    }
    public AbstractIOServicefinal String id,
                              final LockService lockService,
                              final IOWatchService watchService ) {
        this. = id;
        this. = lockService;
        this. = watchService;
    }
    @Override
    public void startBatchfinal Option... options ) {
        .lock();
        if ( !.isEmpty() ) {
            cleanupClosedFileSystems();
            final Path path = .values().iterator().next().get( 0 ).getRootDirectories().iterator().next();
            setAttributepath, FileSystemState.FILE_SYSTEM_STATE_ATTR, FileSystemState.BATCH );
            if ( options != null && options.length == 1 ) {
                setAttributepath, FileSystemState.FILE_SYSTEM_STATE_ATTR, options[ 0 ] );
            }
        }
    }
    @Override
    public void endBatchfinal Option... options ) {
        .unlock();
        if ( !.isEmpty() ) {
            cleanupClosedFileSystems();
            final Path path = .values().iterator().next().get( 0 ).getRootDirectories().iterator().next();
            setAttributepath, FileSystemState.FILE_SYSTEM_STATE_ATTR, FileSystemState.NORMAL );
        }
    }
    private void cleanupClosedFileSystems() {
        for ( final Map.Entry<FileSystemTypeList<FileSystem>> fileSystemTypeListEntry : .entrySet() ) {
            final ArrayList<FileSystem> removeList = new ArrayList<FileSystem>();
            for ( final FileSystem fileSystem : fileSystemTypeListEntry.getValue() ) {
                if ( !fileSystem.isOpen() ) {
                    removeList.add( fileSystem );
                }
            }
            fileSystemTypeListEntry.getValue().removeAll( removeList );
        }
    }
    @Override
    public Path getfinal String first,
                     final String... more ) throws IllegalArgumentException {
        return Paths.get( firstmore );
    }
    @Override
    public Path getfinal URI uri )
            throws IllegalArgumentException, FileSystemNotFoundException, SecurityException {
        return Paths.get( uri );
    }
    @Override
    public Iterable<FileSystem> getFileSystems() {
        return new Iterable<FileSystem>() {
            @Override
            public Iterator<FileSystem> iterator() {
                return new Iterator<FileSystem>() {
                    final Iterator<List<FileSystem>> fsIterator = .values().iterator();
                    Iterator<FileSystem> currentIter;
                    @Override
                    public boolean hasNext() {
                        if (  == null ) {
                            if ( .hasNext() ) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                        if ( !.hasNext() ) {
                             = null;
                            return .hasNext();
                        }
                        return true;
                    }
                    @Override
                    public FileSystem next() {
                        if (  == null ) {
                             = .next().iterator();
                        }
                        return .next();
                    }
                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }
    @Override
    public List<FileSystem> getFileSystemsfinal FileSystemType type ) {
        return .get( type );
    }
    @Override
    public FileSystem getFileSystemfinal URI uri ) {
        try {
            return registerFS( FileSystems.getFileSystem( uri ),  );
        } catch ( final Exception ex ) {
            .warn"Failed to register filesystem " + uri + " with DEFAULT_FS_TYPE. Returning null."ex );
            return null;
        }
    }
    @Override
    public FileSystem newFileSystemfinal URI uri,
                                     final Map<String, ?> env ) throws IllegalArgumentException, FileSystemAlreadyExistsException, ProviderNotFoundException, IOException, SecurityException {
        return newFileSystemurienv );
    }
    @Override
    public FileSystem newFileSystemfinal URI uri,
                                     final Map<String, ?> env,
                                     final FileSystemType type )
            throws IllegalArgumentException, FileSystemAlreadyExistsException, ProviderNotFoundException,
            IOException, SecurityException {
        try {
            final FileSystem fs = FileSystems.newFileSystem( urienv );
            return registerFSfstype );
        } catch ( final FileSystemAlreadyExistsException ex ) {
            registerFS( FileSystems.getFileSystem( uri ), type );
            throw ex;
        }
    }
    @Override
    public void onNewFileSystemfinal NewFileSystemListener listener ) {
        this. = listener;
    }
    private FileSystem registerFSfinal FileSystem fs,
                                   final FileSystemType type ) {
        checkNotNull"type"type );
        if ( fs == null ) {
            return fs;
        }
        if (  != null && !.hasWatchServicefs ) ) {
            .addWatchServicefsfs.newWatchService() );
        }
        synchronized ( this ) {
            List<FileSystem> fsList = .get( type );
            if ( fsList == null ) {
                fsList = new ArrayList<FileSystem>();
                .put( typefsList );
            }
            fsList.add( fs );
        }
        return fs;
    }
    @Override
    public InputStream newInputStreamfinal Path path,
                                       final OpenOption... options )
            throws IllegalArgumentException, NoSuchFileException, UnsupportedOperationException,
            IOException, SecurityException {
        return Files.newInputStream( pathoptions );
    }
    @Override
    public DirectoryStream<Path> newDirectoryStreamfinal Path dir )
            throws IllegalArgumentException, NotDirectoryException, IOException, SecurityException {
        return Files.newDirectoryStream( dir );
    }
    @Override
    public DirectoryStream<Path> newDirectoryStream( final Path dir,
                                                     final DirectoryStream.Filter<Path> filter )
            throws IllegalArgumentException, NotDirectoryException, IOException, SecurityException {
        return Files.newDirectoryStream( dirfilter );
    }
    @Override
    public OutputStream newOutputStreamfinal Path path,
                                         final OpenOption... options )
            IOException, SecurityException {
        return Files.newOutputStream( pathoptions );
    }
    @Override
    public SeekableByteChannel newByteChannelfinal Path path,
                                               final OpenOption... options )
            FileAlreadyExistsException, IOException, SecurityException {
        return Files.newByteChannel( pathoptions );
    }
    @Override
    public Path createDirectoryfinal Path dir,
                                 final Map<String, ?> attrs ) throws IllegalArgumentExceptionUnsupportedOperationException, FileAlreadyExistsException, IOException, SecurityException {
        return createDirectorydirconvertattrs ) );
    }
    @Override
    public Path createDirectoriesfinal Path dir,
                                   final Map<String, ?> attrs ) throws UnsupportedOperationException, FileAlreadyExistsException, IOException, SecurityException {
        return createDirectoriesdirconvertattrs ) );
    }
    @Override
    public Path createTempFilefinal String prefix,
                                final String suffix,
                                final FileAttribute<?>... attrs )
            throws IllegalArgumentExceptionUnsupportedOperationException, IOException, SecurityException {
        return Files.createTempFile( prefixsuffixattrs );
    }
    @Override
    public Path createTempFilefinal Path dir,
                                final String prefix,
                                final String suffix,
                                final FileAttribute<?>... attrs )
            throws IllegalArgumentExceptionUnsupportedOperationException, IOException, SecurityException {
        return Files.createTempFile( dirprefixsuffixattrs );
    }
    @Override
    public Path createTempDirectoryfinal String prefix,
                                     final FileAttribute<?>... attrs )
            throws IllegalArgumentExceptionUnsupportedOperationException, IOException, SecurityException {
        return Files.createTempDirectory( prefixattrs );
    }
    @Override
    public Path createTempDirectoryfinal Path dir,
                                     final String prefix,
                                     final FileAttribute<?>... attrs )
            throws IllegalArgumentExceptionUnsupportedOperationException, IOException, SecurityException {
        return Files.createTempDirectory( dirprefixattrs );
    }
    @Override
    public FileTime getLastModifiedTimefinal Path path )
            throws IllegalArgumentException, IOException, SecurityException {
        return Files.getLastModifiedTime( path );
    }
    @Override
    public Map<StringObjectreadAttributesfinal Path path )
            throws UnsupportedOperationException, NoSuchFileException, IllegalArgumentException,
            IOException, SecurityException {
        return readAttributespath"*" );
    }
    @Override
    public Path setAttributefinal Path path,
                              final String attribute,
                              final Object value )
        Files.setAttribute( pathattributevalue );
        return path;
    }
    @Override
    public Path setAttributesfinal Path path,
                               final Map<StringObjectattrs )
            ClassCastException, IOException, SecurityException {
        return setAttributespathconvertattrs ) );
    }
    @Override
    public long sizefinal Path path )
            throws IllegalArgumentException, IOException, SecurityException {
        return Files.size( path );
    }
    @Override
    public boolean existsfinal Path path )
            throws IllegalArgumentExceptionSecurityException {
        return Files.exists( path );
    }
    @Override
    public boolean notExistsfinal Path path )
            throws IllegalArgumentExceptionSecurityException {
        return Files.notExists( path );
    }
    @Override
    public boolean isSameFilefinal Path path,
                               final Path path2 )
            throws IllegalArgumentException, IOException, SecurityException {
        return Files.isSameFile( pathpath2 );
    }
    @Override
    public synchronized Path createFilefinal Path path,
                                         final FileAttribute<?>... attrs )
            throws IllegalArgumentExceptionUnsupportedOperationException, FileAlreadyExistsException,
            IOException, SecurityException {
        try {
            newByteChannelpathattrs ).close();
        } catch ( java.io.IOException e ) {
            throw new IOException( e );
        }
        return path;
    }
    @Override
    public BufferedReader newBufferedReaderfinal Path path,
                                             final Charset cs )
            throws IllegalArgumentException, NoSuchFileException, IOException, SecurityException {
        return Files.newBufferedReader( pathcs );
    }
    @Override
    public long copyfinal Path source,
                      final OutputStream out )
            throws IOException, SecurityException {
        return Files.copy( sourceout );
    }
    @Override
    public byte[] readAllBytesfinal Path path )
            throws IOException, OutOfMemoryErrorSecurityException {
        return Files.readAllBytes( path );
    }
    @Override
    public List<StringreadAllLinesfinal Path path )
            throws IllegalArgumentException, NoSuchFileException, IOException, SecurityException {
        return readAllLinespath );
    }
    @Override
    public List<StringreadAllLinesfinal Path path,
                                      final Charset cs )
            throws IllegalArgumentException, NoSuchFileException, IOException, SecurityException {
        return Files.readAllLines( pathcs );
    }
    @Override
    public String readAllStringfinal Path path,
                                 final Charset cs ) throws IllegalArgumentException, NoSuchFileException, IOException {
        final byte[] result = Files.readAllBytes( path );
        if ( result == null && result.length < 0 ) {
            return "";
        }
        return new Stringresultcs );
    }
    @Override
    public String readAllStringfinal Path path )
            throws IllegalArgumentException, NoSuchFileException, IOException {
        return readAllStringpath );
    }
    @Override
    public BufferedWriter newBufferedWriterfinal Path path,
                                             final Charset cs,
                                             final OpenOption... options )
            throws IllegalArgumentException, IOException, UnsupportedOperationExceptionSecurityException {
        return Files.newBufferedWriter( pathcsoptions );
    }
    @Override
    public long copyfinal InputStream in,
                      final Path target,
                      final CopyOption... options )
            throws IOException, FileAlreadyExistsException, DirectoryNotEmptyException, UnsupportedOperationExceptionSecurityException {
        return Files.copy( intargetoptions );
    }
    @Override
    public Path writefinal Path path,
                       final byte[] bytes,
                       final OpenOption... options )
            throws IOException, UnsupportedOperationExceptionSecurityException {
        return writepathbytesnew HashSet<OpenOption>( Arrays.asListoptions ) ) );
    }
    @Override
    public Path writefinal Path path,
                       final Iterable<? extends CharSequencelines,
                       final Charset cs,
                       final OpenOption... options ) throws IllegalArgumentException, IOException, UnsupportedOperationExceptionSecurityException {
        return writepathtoByteArraylinescs ), new HashSet<OpenOption>( Arrays.asListoptions ) ) );
    }
    private byte[] toByteArrayfinal Iterable<? extends CharSequencelines,
                                final Charset cs ) {
        final StringBuilder sb = new StringBuilder();
        for ( final CharSequence line : lines ) {
            sb.appendline.toString() );
        }
        return sb.toString().getBytes();
    }
    @Override
    public Path writefinal Path path,
                       final String content,
                       final Charset cs,
                       final OpenOption... options )
            throws IllegalArgumentException, IOException, UnsupportedOperationException {
        return writepathcontent.getBytescs ), new HashSet<OpenOption>( Arrays.asListoptions ) ) );
    }
    @Override
    public Path writefinal Path path,
                       final String content,
                       final OpenOption... options )
            throws IllegalArgumentException, IOException, UnsupportedOperationException {
        return writepathcontentoptions );
    }
    @Override
    public Path writefinal Path path,
                       final String content,
                       final Map<String, ?> attrs,
                       final OpenOption... options )
            throws IllegalArgumentException, IOException, UnsupportedOperationException {
        return writepathcontentattrsoptions );
    }
    @Override
    public Path writefinal Path path,
                       final String content,
                       final Charset cs,
                       final Map<String, ?> attrs,
                       final OpenOption... options )
            throws IllegalArgumentException, IOException, UnsupportedOperationException {
        return writepathcontentcsnew HashSet<OpenOption>( Arrays.asListoptions ) ), convertattrs ) );
    }
    @Override
    public void dispose() {
         = true;
        for ( final FileSystem fileSystem : getFileSystems() ) {
            try {
                fileSystem.dispose();
            } catch ( final Exception ignored ) {
            }
        }
    }
    @Override
    public FileAttribute<?>[] convertfinal Map<String, ?> attrs ) {
        if ( attrs == null || attrs.size() == 0 ) {
            return new FileAttribute<?>[ 0 ];
        }
        final FileAttribute<?>[] attrsArray = new FileAttribute<?>[ attrs.size() ];
        int i = 0;
        for ( final Map.Entry<String, ?> attr : attrs.entrySet() ) {
            attrsArrayi++ ] = new FileAttribute<Object>() {
                @Override
                public String name() {
                    return attr.getKey();
                }
                @Override
                public Object value() {
                    return attr.getValue();
                }
            };
        }
        return attrsArray;
    }
    @Override
    public Path writefinal Path path,
                       final byte[] bytes,
                       final Map<String, ?> attrs,
                       final OpenOption... options ) throws IOException, UnsupportedOperationExceptionSecurityException {
        return writepathbytesnew HashSet<OpenOption>( Arrays.asListoptions ) ), convertattrs ) );
    }
    @Override
    public Path writefinal Path path,
                       final String content,
                       final Set<? extends OpenOption> options,
                       final FileAttribute<?>... attrs )
            throws IllegalArgumentException, IOException, UnsupportedOperationException {
        return writepathcontentoptionsattrs );
    }
    @Override
    public Path writefinal Path path,
                       final String content,
                       final Charset cs,
                       final Set<? extends OpenOption> options,
                       final FileAttribute<?>... attrs )
            throws IllegalArgumentException, IOException, UnsupportedOperationException {
        return writepathcontent.getBytescs ), optionsattrs );
    }
    @Override
    public synchronized Path writefinal Path path,
                                    final byte[] bytes,
                                    final Set<? extends OpenOption> options,
                                    final FileAttribute<?>... attrs ) throws IllegalArgumentException, IOException, UnsupportedOperationException {
        SeekableByteChannel byteChannel;
        try {
            byteChannel = newByteChannelpathbuildOptionsoptions ), attrs );
        } catch ( final FileAlreadyExistsException ex ) {
            ( (AbstractPath) path ).clearCache();
            byteChannel = newByteChannelpathbuildOptionsoptions, TRUNCATE_EXISTING ), attrs );
        }
        try {
            byteChannel.write( ByteBuffer.wrapbytes ) );
            byteChannel.close();
        } catch ( final java.io.IOException e ) {
            throw new IOException( e );
        }
        return path;
    }
    protected abstract Set<? extends OpenOption> buildOptionsfinal Set<? extends OpenOption> options,
                                                               final OpenOption... other );
    @Override
    public String getId() {
        return ;
    }
    @Override
    public void setAuthenticationManagerfinal AuthenticationManager authenticationManager ) {
        for ( final FileSystemProvider fileSystemProvider : FileSystemProviders.installedProviders() ) {
            if ( fileSystemProvider instanceof SecurityAware ) {
                ( (SecurityAware) fileSystemProvider ).setAuthenticationManager( authenticationManager );
            }
        }
    }
    @Override
    public void setAuthorizationManagerfinal AuthorizationManager authorizationManager ) {
        for ( final FileSystemProvider fileSystemProvider : FileSystemProviders.installedProviders() ) {
            if ( fileSystemProvider instanceof SecurityAware ) {
                ( (SecurityAware) fileSystemProvider ).setAuthorizationManager( authorizationManager );
            }
        }
    }
New to GrepCode? Check out our FAQ X