2  * ============LICENSE_START=======================================================
 
   3  *  Copyright (C) 2018 Intel Corp. All rights reserved.
 
   4  *  Copyright (C) 2019 Nordix Foundation.
 
   5  * ================================================================================
 
   6  * Licensed under the Apache License, Version 2.0 (the "License");
 
   7  * you may not use this file except in compliance with the License.
 
   8  * You may obtain a copy of the License at
 
  10  *      http://www.apache.org/licenses/LICENSE-2.0
 
  12  * Unless required by applicable law or agreed to in writing, software
 
  13  * distributed under the License is distributed on an "AS IS" BASIS,
 
  14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  15  * See the License for the specific language governing permissions and
 
  16  * limitations under the License.
 
  18  * SPDX-License-Identifier: Apache-2.0
 
  19  * ============LICENSE_END=========================================================
 
  22 package org.onap.policy.distribution.reception.handling.file;
 
  24 import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
 
  27 import java.io.IOException;
 
  28 import java.nio.file.FileSystems;
 
  29 import java.nio.file.Path;
 
  30 import java.nio.file.Paths;
 
  31 import java.nio.file.WatchEvent;
 
  32 import java.nio.file.WatchKey;
 
  33 import java.nio.file.WatchService;
 
  34 import java.util.concurrent.ExecutorService;
 
  35 import java.util.concurrent.Executors;
 
  36 import java.util.concurrent.TimeUnit;
 
  37 import java.util.zip.ZipFile;
 
  39 import org.onap.policy.common.parameters.ParameterService;
 
  40 import org.onap.policy.distribution.model.Csar;
 
  41 import org.onap.policy.distribution.reception.decoding.PolicyDecodingException;
 
  42 import org.onap.policy.distribution.reception.handling.AbstractReceptionHandler;
 
  43 import org.onap.policy.distribution.reception.statistics.DistributionStatisticsManager;
 
  44 import org.slf4j.Logger;
 
  45 import org.slf4j.LoggerFactory;
 
  48  * Handles reception of inputs from File System which can be used to decode policies.
 
  50 public class FileSystemReceptionHandler extends AbstractReceptionHandler {
 
  52     private static final Logger LOGGER = LoggerFactory.getLogger(FileSystemReceptionHandler.class);
 
  53     private boolean running = false;
 
  59     protected void initializeReception(final String parameterGroupName) {
 
  60         LOGGER.debug("FileSystemReceptionHandler init...");
 
  62             final FileSystemReceptionHandlerConfigurationParameterGroup handlerParameters =
 
  63                     ParameterService.get(parameterGroupName);
 
  64             final FileClientHandler fileClientHandler = new FileClientHandler(this,
 
  65                     handlerParameters.getWatchPath(),
 
  66                     handlerParameters.getMaxThread());
 
  67             final Thread fileWatcherThread = new Thread(fileClientHandler);
 
  68             fileWatcherThread.start();
 
  69         } catch (final Exception ex) {
 
  70             LOGGER.error("FileSystemReceptionHandler initialization failed", ex);
 
  78     public void destroy() {
 
  83      * Method to check the running status of file watcher thread.
 
  85      * @return the running status
 
  87     public boolean isRunning() {
 
  92      * Initialize the file watcher thread.
 
  94      * @param watchPath Path to watch
 
  96     public void initFileWatcher(final String watchPath, final int maxThread) throws IOException {
 
  97         try (final WatchService watcher = FileSystems.getDefault().newWatchService()) {
 
  98             final Path dir = Paths.get(watchPath);
 
  99             dir.register(watcher, ENTRY_CREATE);
 
 100             LOGGER.debug("Watch Service registered for dir: {}", dir.getFileName());
 
 101             startWatchService(watcher, dir, maxThread);
 
 102         } catch (final Exception ex) {
 
 103             LOGGER.error("FileWatcher initialization failed", ex);
 
 104             Thread.currentThread().interrupt();
 
 109      * Method to keep watching the given path for any new file created.
 
 111      * @param watcher the watcher
 
 112      * @param dir the watch directory
 
 113      * @param maxThread the max thread number
 
 114      * @throws InterruptedException if it occurs
 
 116     @SuppressWarnings("unchecked")
 
 117     protected void startWatchService(final WatchService watcher,
 
 118             final Path dir, int maxThread) throws InterruptedException {
 
 120         ExecutorService pool = Executors.newFixedThreadPool(maxThread);
 
 125                 key = watcher.take();
 
 126                 processFileEvents(dir, key, pool);
 
 127                 final boolean valid = key.reset();
 
 129                     LOGGER.error("Watch key no longer valid!");
 
 138     private void processFileEvents(Path dir, WatchKey key, ExecutorService pool) {
 
 139         for (final WatchEvent<?> event : key.pollEvents()) {
 
 140             final WatchEvent<Path> ev = (WatchEvent<Path>) event;
 
 141             final Path fileName = ev.context();
 
 143                 LOGGER.debug("new CSAR found: {}", fileName);
 
 144                 DistributionStatisticsManager.updateTotalDistributionCount();
 
 145                 final String fullFilePath = dir.toString() + File.separator + fileName.toString();
 
 147                     waitForFileToBeReady(fullFilePath);
 
 148                     createPolicyInputAndCallHandler(fullFilePath);
 
 149                     LOGGER.debug("CSAR complete: {}", fileName);
 
 150                 } catch (InterruptedException e) {
 
 151                     LOGGER.error("waitForFileToBeReady interrupted", e);
 
 152                     Thread.currentThread().interrupt();
 
 159      * Method to create policy input & call policy handlers.
 
 161      * @param fileName the filename
 
 163     protected void createPolicyInputAndCallHandler(final String fileName) {
 
 165             final Csar csarObject = new Csar(fileName);
 
 166             DistributionStatisticsManager.updateTotalDownloadCount();
 
 167             inputReceived(csarObject);
 
 168             DistributionStatisticsManager.updateDownloadSuccessCount();
 
 169             DistributionStatisticsManager.updateDistributionSuccessCount();
 
 170         } catch (final PolicyDecodingException ex) {
 
 171             DistributionStatisticsManager.updateDownloadFailureCount();
 
 172             DistributionStatisticsManager.updateDistributionFailureCount();
 
 173             LOGGER.error("Policy creation failed", ex);
 
 177     private void waitForFileToBeReady(final String fullFilePath) throws InterruptedException {
 
 180             TimeUnit.MILLISECONDS.sleep(100);
 
 181             try (ZipFile zipFile = new ZipFile(fullFilePath)) {
 
 183             } catch (final IOException exp) {
 
 184                 LOGGER.error("file is not ready for reading, wait for sometime and try again", exp);