/*
 * Copyright (c) 2019 Schibsted Media Group.
 *
 * 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.netflix.spinnaker.orca.clouddriver.tasks.providers.aws.cloudformation;

import com.netflix.spinnaker.orca.OverridableTimeoutRetryableTask;
import com.netflix.spinnaker.orca.TaskResult;
import com.netflix.spinnaker.orca.clouddriver.CloudDriverCacheService;
import com.netflix.spinnaker.orca.clouddriver.tasks.AbstractCloudProviderAwareTask;
import com.netflix.spinnaker.orca.pipeline.model.Stage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CloudFormationForceCacheRefreshTask extends AbstractCloudProviderAwareTask
    implements OverridableTimeoutRetryableTask {
  static final String REFRESH_TYPE = "CloudFormation";

  @Autowired CloudDriverCacheService cacheService;

  private final long backoffPeriod = TimeUnit.SECONDS.toMillis(10);
  private final long timeout = TimeUnit.MINUTES.toMillis(5);

  @Override
  public TaskResult execute(@Nonnull Stage stage) {
    String cloudProvider = getCloudProvider(stage);

    Map<String, Object> data = new HashMap<>();

    String credentials = getCredentials(stage);
    if (credentials != null) {
      data.put("credentials", credentials);
    }

    List<String> regions = (List<String>) stage.getContext().get("regions");
    if (regions != null && !regions.isEmpty()) {
      data.put("region", regions);
    }

    String stackName = (String) stage.getContext().get("stackName");
    if (stackName != null) {
      data.put("stackName", stackName);
    }

    cacheService.forceCacheUpdate(cloudProvider, REFRESH_TYPE, data);

    return TaskResult.SUCCEEDED;
  }

  @Override
  public long getBackoffPeriod() {
    return backoffPeriod;
  }

  @Override
  public long getTimeout() {
    return timeout;
  }
}

@@ -1264,16 +1264,47 @@
 mponent;
+%0Aimport retrofit.RetrofitError;
 %0A%0A@Compo
@@ -2288,24 +2288,36 @@
 me);%0A    %7D%0A%0A
+    try %7B%0A  
     cacheSer
@@ -2374,16 +2374,86 @@
  data);%0A
+    %7D catch (RetrofitError e) %7B%0A      return TaskResult.RUNNING;%0A    %7D
 %0A    ret

Return RUNNING if an error occurred (#3210)