/*
   Copyright 2015 Cisco Systems

   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 com.cisco.cta.taxii.adapter;

import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import org.apache.log4j.MDC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;

import java.util.List;
import java.util.UUID;

/**
 * Wraps everything what has to be triggered by a scheduler.
 */
public class AdapterTask implements Runnable {
    private static final Logger LOG = LoggerFactory.getLogger(AdapterTask.class);

    private static final String MESSAGE_ID_PREFIX = "tla-";

    private final RequestFactory requestFactory;
    private final ResponseHandler responseHandler;
    private final List<String> feeds;
    private final AdapterStatistics statistics;

    private final TaxiiStatusDao taxiiStatusDao;

    public AdapterTask(RequestFactory requestFactory, ResponseHandler responseHandler, TaxiiServiceSettings settings, AdapterStatistics statistics, TaxiiStatusDao taxiiStatusDao) {
        this.requestFactory = requestFactory;
        this.responseHandler = responseHandler;
        this.feeds = settings.getFeeds();
        this.statistics = statistics;
        this.taxiiStatusDao = taxiiStatusDao;
    }

    private String createMessageId() {
        return MESSAGE_ID_PREFIX + UUID.randomUUID().toString();
    }

    /**
     * Invoked by the scheduler.
     */
    public void run() {
        LOG.trace("triggering task...");
        for (String feed : feeds) {
            try {
                downloadFeed(feed);
            } catch (Exception e) {
                statistics.incrementErrors();
                LOG.error("Error while processing feed " + feed, e);
            }
        }
    }

    private void downloadFeed(String feed) throws Exception {
        TaxiiPollResponse response = null;
        do {
            response = poll(feed, response);
            if (response != null) {
                taxiiStatusDao.update(feed, response);
            }
        }while(hasPendingResultParts(response));
    }

    private boolean hasPendingResultParts(TaxiiPollResponse response) {
        return response != null && response.isMore();
    }

    private TaxiiPollResponse poll(String feed, TaxiiPollResponse previousResponse) throws Exception {
        statistics.incrementPolls();
        try {
            String messageId = createMessageId();
            MDC.put("messageId", messageId);
            ClientHttpRequest request;
            if (previousResponse == null) {
                LOG.trace("creating initial taxii request...");
                request = requestFactory.createInitialRequest(messageId, feed);
            } else {
                LOG.trace("creating fulfillment taxii request - {}", previousResponse.getResultPartNumber() + 1);
                request = requestFactory.createFulfillmentRequest(messageId, feed, previousResponse.getResultId(), previousResponse.getResultPartNumber() + 1);
            }
            try (ClientHttpResponse resp = request.execute()) {
                return responseHandler.handle(feed, resp);
            }
        } finally{
            MDC.clear();
        }
    }

}

@@ -2172,37 +2172,51 @@
 ) %7B%0A            
-try %7B
+downloadFeed(feed);
 %0A               
@@ -2204,32 +2204,50 @@
 d);%0A        
+%7D%0A
     
+%7D%0A%0A
     
+private void 
 downloadFeed
@@ -2239,38 +2239,46 @@
 id downloadFeed(
+String 
 feed)
-;
+ %7B
 %0A            %7D c
@@ -2274,35 +2274,42 @@
     
-    %7D catch (Exception e) %7B
+TaxiiPollResponse response = null;
 %0A   
@@ -2317,111 +2317,190 @@
     
- 
+do %7B%0A
        
-statistics.incrementErrors();%0A                LOG.error(%22Error while processing feed %22 + feed, 
+     try %7B%0A                String messageId = createMessageId();%0A                MDC.put(%22messageId%22, messageId);%0A                response = poll(messageId, feed, respons
 e);%0A
@@ -2515,77 +2515,134 @@
     
-%7D%0A
     
-    %7D%0A    %7D%0A%0A    private void downloadFeed(String feed) throws 
+if (response != null) %7B%0A                    taxiiStatusDao.update(feed, response);%0A                %7D%0A            %7D catch (
 Exce
@@ -2638,32 +2638,35 @@
 catch (Exception
+ e)
  %7B%0A        Taxii
@@ -2664,49 +2664,52 @@
     
-TaxiiPollResponse response = null
+        statistics.incrementErrors()
 ;%0A      
   do
@@ -2696,39 +2696,32 @@
 Errors();%0A      
-  do %7B%0A
             resp
@@ -2718,131 +2718,136 @@
     
-  response = poll(feed, response);%0A            if (response != null) %7B%0A                taxiiStatusDao.update(feed, response
+LOG.error(%22Error while processing feed %22 + feed, e);%0A                return ;%0A%0A            %7D finally%7B%0A                MDC.clear(
 );%0A 
@@ -3086,24 +3086,42 @@
 poll(String 
+messageId, String 
 feed, TaxiiP
@@ -3210,121 +3210,8 @@
 ();%0A
-        try %7B%0A            String messageId = createMessageId();%0A            MDC.put(%22messageId%22, messageId);%0A    
     
@@ -3241,20 +3241,16 @@
 equest;%0A
-    
         
@@ -3285,36 +3285,32 @@
 ) %7B%0A            
-   
- 
 LOG.trace(%22creat
@@ -3337,28 +3337,24 @@
 quest...%22);%0A
-    
             
@@ -3425,20 +3425,16 @@
         
-    
 %7D else %7B
@@ -3438,36 +3438,32 @@
 e %7B%0A            
-   
- 
 LOG.trace(%22creat
@@ -3536,36 +3536,32 @@
 tNumber() + 1);%0A
-    
             requ
@@ -3704,34 +3704,26 @@
 1);%0A        
-    %7D%0A    
+%7D%0A
         try 
@@ -3778,28 +3778,24 @@
             
-    
 return respo
@@ -3837,67 +3837,10 @@
     
-    %7D%0A        %7D finally%7B%0A            MDC.clear();%0A        
 %7D
+%0A
 %0A   

include messageId when logging error