Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.guvnor.structure.backend.config;
  
  import java.util.Date;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
 
 import  org.guvnor.structure.server.config.ConfigGroup;
 import  org.guvnor.structure.server.config.ConfigType;
 import  org.guvnor.structure.server.config.ConfigurationService;
 import  org.uberfire.commons.async.DescriptiveRunnable;
 import  org.uberfire.io.IOService;
 import  org.uberfire.java.nio.IOException;
 import  org.uberfire.java.nio.base.WatchContext;
 import  org.uberfire.java.nio.base.options.CommentedOption;
 import  org.uberfire.java.nio.file.DirectoryStream;
 import  org.uberfire.java.nio.file.FileSystem;
 import  org.uberfire.java.nio.file.Files;
 import  org.uberfire.java.nio.file.Path;
 import  org.uberfire.java.nio.file.StandardWatchEventKind;
 import  org.uberfire.java.nio.file.WatchEvent;
 import  org.uberfire.java.nio.file.WatchKey;
 import  org.uberfire.java.nio.file.WatchService;
 
 import static org.uberfire.backend.server.util.Paths.*;
 
 public class ConfigurationServiceImpl implements ConfigurationService,
                                                  AsyncWatchServiceCallback {
 
     private static final String MONITOR_DISABLED = "org.uberfire.sys.repo.monitor.disabled";
     //    private static final String MONITOR_CHECK_INTERVAL = "org.uberfire.sys.repo.monitor.interval";
     // mainly for windows as *NIX is based on POSIX but escape always to keep it consistent
     private static final String INVALID_FILENAME_CHARS = "[\\,/,:,*,?,\",<,>,|]";
 
     @Inject
     @Named("system")
     private org.guvnor.structure.repositories.Repository systemRepository;
 
     @Inject
     private ConfigGroupMarshaller marshaller;
 
     @Inject
     private User identity;
 
     //Cache of ConfigGroups to avoid reloading them from file
     private final Map<ConfigType, List<ConfigGroup>> configuration = new ConcurrentHashMap<ConfigType, List<ConfigGroup>>();
     private AtomicLong localLastModifiedValue = new AtomicLong( -1 );
 
     @Inject
     @Named("configIO")
     private IOService ioService;
 
     // monitor capabilities
     @Inject
     @Repository
     @Inject
     @OrgUnit
     @Inject
 
     private final ExecutorService executorService = Executors.newSingleThreadExecutor();
 
     private final Set<Future<?>> jobs = new CopyOnWriteArraySet<Future<?>>();
 
     private ConfigServiceWatchServiceExecutor executor = null;
 
     private CheckConfigurationUpdates configUpdates = null;
 
     private WatchService watchService = null;
 
     @Inject
     @Named("systemFS")
     private FileSystem fs;
 
    public void setup() {
        Path defaultRoot = .getRootDirectories().iterator().next();
        for ( final Path path : .getRootDirectories() ) {
            if ( path.toUri().toString().contains( "/master@" ) ) {
                defaultRoot = path;
                break;
            }
        }
        .setRoot( convert( defaultRoot ) );
        // enable monitor by default
        if ( System.getProperty ) == null ) {
             = .newWatchService();
             = new CheckConfigurationUpdates );
            final ConfigServiceWatchServiceExecutor configServiceWatchServiceExecutor = getWatchServiceExecutor();
            .add.submitnew DescriptiveRunnable() {
                @Override
                public String getDescription() {
                    return .getDescription();
                }
                @Override
                public void run() {
                    .executeconfigServiceWatchServiceExecutor );
                }
            } ) );
        }
    }
    @PreDestroy
    public void shutdown() {
        if (  != null ) {
            .deactivate();
        }
        if (  != null ) {
            .close();
        }
        for ( Future<?> job :  ) {
            if ( !job.isCancelled() && !job.isDone() ) {
                job.canceltrue );
            }
        }
        .shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if ( !.awaitTermination( 60, . ) ) {
                .shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if ( !.awaitTermination( 60, . ) ) {
                    ..println"Pool did not terminate" );
                }
            }
        } catch ( InterruptedException ie ) {
            // (Re-)Cancel if current thread also interrupted
            .shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }
    @Override
    public List<ConfigGroup> getConfigurationfinal ConfigType type ) {
        if ( .containsKey( type ) ) {
            return .get( type );
        }
        final List<ConfigGroup> configGroups = new ArrayList<ConfigGroup>();
        final DirectoryStream<Path> foundConfigs = .newDirectoryStream( .get( .getUri() ),
                                                                                 new DirectoryStream.Filter<Path>() {
                                                                                     @Override
                                                                                     public boolean accept( final Path entry ) throws IOException {
                                                                                         if ( !Files.isDirectory( entry ) &&
                                                                                                 !entry.getFileName().toString().startsWith( "." ) &&
                                                                                                 entry.getFileName().toString().endsWith( type.getExt() ) ) {
                                                                                             return true;
                                                                                         }
                                                                                         return false;
                                                                                     }
                                                                                 }
                                                                               );
        //Only load and cache if a file was found!
        final Iterator<Path> it = foundConfigs.iterator();
        if ( it.hasNext() ) {
            while ( it.hasNext() ) {
                final String content = .readAllString( it.next() );
                final ConfigGroup configGroup = .unmarshallcontent );
                configGroups.add( configGroup );
            }
            .put( typeconfigGroups );
        }
        return configGroups;
    }
    @Override
    public boolean addConfigurationfinal ConfigGroup configGroup ) {
        String filename = configGroup.getName().replaceAll( "_" );
        final Path filePath = .get( .getUri() ).resolve( filename + configGroup.getType().getExt() );
        // avoid duplicated writes to not cause cyclic cluster sync
        if ( .exists( filePath ) ) {
            return true;
        }
        final CommentedOption commentedOption = new CommentedOption( getIdentityName(),
                                                                     "Created config " + filePath.getFileName() );
        try {
            .startBatch( filePath.getFileSystem() );
            .write( filePath.marshallconfigGroup ), commentedOption );
            updateLastModified();
        } catch ( Exception ex ) {
            throw new RuntimeExceptionex );
        } finally {
            .endBatch();
        }
        //Invalidate cache if a new item has been created; otherwise cached value is stale
        .remove( configGroup.getType() );
        return true;
    }
    @Override
    public boolean updateConfiguration( ConfigGroup configGroup ) {
        String filename = configGroup.getName().replaceAll( "_" );
        final Path filePath = .get( .getUri() ).resolve( filename + configGroup.getType().getExt() );
        final CommentedOption commentedOption = new CommentedOption( getIdentityName(),
                                                                     "Updated config " + filePath.getFileName() );
        try {
            .startBatch( filePath.getFileSystem() );
            .write( filePath.marshallconfigGroup ), commentedOption );
            updateLastModified();
        } catch ( Exception ex ) {
            throw new RuntimeExceptionex );
        } finally {
            .endBatch();
        }
        //Invalidate cache if a new item has been created; otherwise cached value is stale
        .remove( configGroup.getType() );
        return true;
    }
    @Override
    public boolean removeConfigurationfinal ConfigGroup configGroup ) {
        //Invalidate cache if an item has been removed; otherwise cached value is stale
        .remove( configGroup.getType() );
        String filename = configGroup.getName().replaceAll( "_" );
        final Path filePath = .get( .getUri() ).resolve( filename + configGroup.getType().getExt() );
        // avoid duplicated writes to not cause cyclic cluster sync
        if ( !.exists( filePath ) ) {
            return true;
        }
        boolean result;
        try {
            .startBatch( filePath.getFileSystem() );
            result = .deleteIfExists( filePath );
            if ( result ) {
                updateLastModified();
            }
        } catch ( Exception ex ) {
            throw new RuntimeExceptionex );
        } finally {
            .endBatch();
        }
        return result;
    }
    protected String getIdentityName() {
        try {
            return .getIdentifier();
        } catch ( Exception e ) {
            return "unknown";
        }
    }
    protected long getLastModified() {
        final Path lastModifiedPath = .get( .getUri() ).resolve( LAST_MODIFIED_MARKER_FILE );
        return .getLastModifiedTime( lastModifiedPath ).toMillis();
    }
    protected void updateLastModified() {
        final Path lastModifiedPath = .get( .getUri() ).resolve( LAST_MODIFIED_MARKER_FILE );
        final CommentedOption commentedOption = new CommentedOption( "system""system repo updated" );
        .write( lastModifiedPathnew Date().toString().getBytes(), commentedOption );
        // update the last value to avoid to be retriggered byt the monitor
    }
    @Override
    public void callbacklong value ) {
        .setvalue );
        // invalidate cached values as system repo has changed
        .clear();
    }
    private class CheckConfigurationUpdates implements AsyncConfigWatchService {
        private final WatchService ws;
        private boolean active = true;
        public CheckConfigurationUpdatesfinal WatchService watchService ) {
            this. = watchService;
        }
        public void deactivate() {
            this. = false;
        }
        @Override
        public void executefinal ConfigServiceWatchServiceExecutor wsExecutor ) {
            while (  ) {
                try {
                    final WatchKey wk;
                    try {
                        wk = .take();
                    } catch ( final Exception ex ) {
                        break;
                    }
                    final List<WatchEvent<?>> events = wk.pollEvents();
                    boolean markerFileModified = false;
                    for ( final WatchEvent<?> event : events ) {
                        final WatchContext context = (WatchContext) event.context();
                        if ( event.kind().equals( StandardWatchEventKind.ENTRY_MODIFY ) ) {
                            if ( context.getOldPath().getFileName().toString().equals( LAST_MODIFIED_MARKER_FILE ) ) {
                                markerFileModified = true;
                                break;
                            }
                        } else if ( event.kind().equals( StandardWatchEventKind.ENTRY_CREATE ) ) {
                            if ( context.getPath().getFileName().toString().equals( LAST_MODIFIED_MARKER_FILE ) ) {
                                markerFileModified = true;
                                break;
                            }
                        } else if ( event.kind().equals( StandardWatchEventKind.ENTRY_RENAME ) ) {
                            if ( context.getOldPath().getFileName().toString().equals( LAST_MODIFIED_MARKER_FILE ) ) {
                                markerFileModified = true;
                                break;
                            }
                        } else if ( event.kind().equals( StandardWatchEventKind.ENTRY_DELETE ) ) {
                            if ( context.getOldPath().getFileName().toString().equals( LAST_MODIFIED_MARKER_FILE ) ) {
                                markerFileModified = true;
                                break;
                            }
                        }
                    }
                    if ( markerFileModified ) {
                        wsExecutor.executewk.get(), ConfigurationServiceImpl.this );
                    }
                    boolean valid = wk.reset();
                    if ( !valid ) {
                        break;
                    }
                } catch ( final Exception ignored ) {
                }
            }
        }
        @Override
        public String getDescription() {
            return "Config File Watch Service";
        }
    }
        if (  == null ) {
            ConfigServiceWatchServiceExecutor _executor = null;
            try {
                _executor = InitialContext.doLookup"java:module/ConfigServiceWatchServiceExecutorImpl" );
            } catch ( final Exception ignored ) {
            }
            if ( _executor == null ) {
                _executor = new ConfigServiceWatchServiceExecutorImpl();
            }
             = _executor;
        }
        return ;
    }
New to GrepCode? Check out our FAQ X