@RequestMapping(
      value = "/{topologyId}/workflows/{workflowName}",
      method = RequestMethod.POST,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public RestResponse<Workflow> renameWorkflow(
      @PathVariable String topologyId,
      @PathVariable String workflowName,
      @RequestParam String newName) {

    Topology topology = topologyServiceCore.getMandatoryTopology(topologyId);
    topologyService.checkEditionAuthorizations(topology);
    topologyService.throwsErrorIfReleased(topology);

    if (topology.getWorkflows().containsKey(newName)) {
      throw new AlreadyExistException(
          String.format("The workflow named '%s' already exists", newName));
    }
    Workflow wf = topology.getWorkflows().remove(workflowName);
    if (wf.isStandard()) {
      throw new RuntimeException("standard wf can not be renamed");
    }
    wf.setName(newName);
    topology.getWorkflows().put(newName, wf);
    alienDAO.save(topology);
    return RestResponseBuilder.<Workflow>builder().data(wf).build();
  }
  /**
   * Create a new instance of the {@link PaaSProviderPollingMonitor} to monitor the given paas
   * provider.
   *
   * @param paaSProvider The paas provider to monitor.
   */
  @SuppressWarnings("rawtypes")
  public PaaSProviderPollingMonitor(
      IGenericSearchDAO dao,
      IGenericSearchDAO monitorDAO,
      IPaaSProvider paaSProvider,
      List<IPaasEventListener> listeners,
      String cloudId) {
    this.cloudId = cloudId;
    this.dao = dao;
    this.monitorDAO = monitorDAO;
    this.paaSProvider = paaSProvider;
    this.listeners = listeners;
    Set<Class<?>> eventClasses = Sets.newHashSet();
    try {
      eventClasses = TypeScanner.scanTypes("alien4cloud.paas.model", AbstractMonitorEvent.class);
    } catch (ClassNotFoundException e) {
      log.info("No event class derived from {} found", AbstractMonitorEvent.class.getName());
    }
    Map<String, String[]> filter = Maps.newHashMap();
    filter.put("cloudId", new String[] {this.cloudId});
    // sort by filed date DESC
    SearchQueryHelperBuilder searchQueryHelperBuilder =
        monitorDAO
            .getQueryHelper()
            .buildSearchQuery("deploymentmonitorevents")
            .types(eventClasses.toArray(new Class<?>[eventClasses.size()]))
            .filters(filter)
            .fieldSort("date", true);

    // the first one is the one with the latest date
    GetMultipleDataResult lastestEventResult = monitorDAO.search(searchQueryHelperBuilder, 0, 1);
    if (lastestEventResult.getData().length > 0) {
      AbstractMonitorEvent lastEvent = (AbstractMonitorEvent) lastestEventResult.getData()[0];
      Date lastEventDate = new Date(lastEvent.getDate());
      log.info(
          "Recovering events from the last in elasticsearch {} of type {}",
          lastEventDate,
          lastEvent.getClass().getName());
      this.lastPollingDate = lastEventDate;
    } else {
      this.lastPollingDate = new Date();
      log.debug(
          "No monitor events found, the last polling date will be current date {}",
          this.lastPollingDate);
    }
    paaSEventsCallback = new PaaSEventsCallback();
  }
 /**
  * Get events for a specific deployment from an environment
  *
  * @param applicationEnvironmentId The environment we want to get events from
  * @param from The initial position of the events to get (based on time desc sorting)
  * @param size The number of events to get.
  * @return A result that contains all events.
  */
 public GetMultipleDataResult<?> getDeploymentEvents(
     String applicationEnvironmentId, int from, int size) {
   Deployment deployment = deploymentService.getActiveDeploymentOrFail(applicationEnvironmentId);
   String index = alienMonitorDao.getIndexForType(AbstractMonitorEvent.class);
   QueryHelper.SearchQueryHelperBuilder searchQueryHelperBuilder =
       queryHelper
           .buildSearchQuery(index)
           .types(
               PaaSDeploymentStatusMonitorEvent.class,
               PaaSInstanceStateMonitorEvent.class,
               PaaSMessageMonitorEvent.class,
               PaaSInstancePersistentResourceMonitorEvent.class)
           .filters(
               MapUtil.newHashMap(
                   new String[] {"deploymentId"},
                   new String[][] {new String[] {deployment.getId()}}))
           .fieldSort("_timestamp", true);
   return alienMonitorDao.search(searchQueryHelperBuilder, from, size);
 }
 public TopologyTemplate searchTopologyTemplateByName(String name) {
   Map<String, String[]> filters =
       MapUtil.newHashMap(new String[] {"name"}, new String[][] {new String[] {name}});
   GetMultipleDataResult<TopologyTemplate> result =
       alienDAO.find(TopologyTemplate.class, filters, Integer.MAX_VALUE);
   if (result.getTotalResults() > 0) {
     return result.getData()[0];
   }
   return null;
 }
  @RequestMapping(
      value = "/{topologyId}/workflows",
      method = RequestMethod.POST,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public RestResponse<Workflow> createWorkflow(@PathVariable String topologyId) {

    Topology topology = topologyServiceCore.getMandatoryTopology(topologyId);
    topologyService.checkEditionAuthorizations(topology);
    topologyService.throwsErrorIfReleased(topology);

    Workflow wf = workflowBuilderService.ceateWorkflow(topology);
    alienDAO.save(topology);
    return RestResponseBuilder.<Workflow>builder().data(wf).build();
  }
  @RequestMapping(
      value = "/{topologyId}/workflows/{workflowName}/steps/{stepId}",
      method = RequestMethod.DELETE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public RestResponse<Workflow> removeStep(
      @PathVariable String topologyId,
      @PathVariable String workflowName,
      @PathVariable String stepId) {
    Topology topology = topologyServiceCore.getMandatoryTopology(topologyId);
    topologyService.checkEditionAuthorizations(topology);
    topologyService.throwsErrorIfReleased(topology);

    Workflow wf = workflowBuilderService.removeStep(topology, workflowName, stepId, false);
    alienDAO.save(topology);
    return RestResponseBuilder.<Workflow>builder().data(wf).build();
  }
  private Deployment getActiveDeployment() {
    Deployment deployment = null;

    GetMultipleDataResult<Deployment> dataResult =
        dao.search(
            Deployment.class,
            null,
            MapUtil.newHashMap(
                new String[] {"cloudId", "endDate"},
                new String[][] {new String[] {cloudId}, new String[] {null}}),
            1);
    if (dataResult.getData() != null && dataResult.getData().length > 0) {
      deployment = dataResult.getData()[0];
    }
    return deployment;
  }
 /**
  * Get the detailed status for each instance of each node template.
  *
  * @param deployment The deployment for witch to get the instance informations.
  * @param callback callback on witch to send the map of node template's id to map of instance's id
  *     to instance information.
  * @throws alien4cloud.paas.exception.OrchestratorDisabledException In case the cloud selected for
  *     the topology is disabled.
  */
 public void getInstancesInformation(
     final Deployment deployment,
     IPaaSCallback<Map<String, Map<String, InstanceInformation>>> callback)
     throws OrchestratorDisabledException {
   Map<String, Map<String, InstanceInformation>> instancesInformation = Maps.newHashMap();
   if (deployment == null) {
     callback.onSuccess(instancesInformation);
     return;
   }
   DeploymentTopology runtimeTopology =
       alienMonitorDao.findById(DeploymentTopology.class, deployment.getId());
   PaaSTopologyDeploymentContext deploymentContext =
       deploymentContextService.buildTopologyDeploymentContext(
           deployment, deploymentTopologyService.getLocations(runtimeTopology), runtimeTopology);
   IOrchestratorPlugin orchestratorPlugin =
       orchestratorPluginService.getOrFail(deployment.getOrchestratorId());
   orchestratorPlugin.getInstancesInformation(deploymentContext, callback);
 }
  @RequestMapping(
      value = "/{topologyId}/workflows/{workflowName}",
      method = RequestMethod.DELETE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public RestResponse<Void> removeWorkflow(
      @PathVariable String topologyId, @PathVariable String workflowName) {

    Topology topology = topologyServiceCore.getMandatoryTopology(topologyId);
    topologyService.checkEditionAuthorizations(topology);
    topologyService.throwsErrorIfReleased(topology);

    Workflow wf = topology.getWorkflows().remove(workflowName);
    if (wf.isStandard()) {
      throw new RuntimeException("standard wf can not be removed");
    }
    alienDAO.save(topology);
    return new RestResponse<Void>();
  }
  @RequestMapping(
      value = "/{topologyId}/workflows/{workflowName}/activities",
      method = RequestMethod.POST,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public RestResponse<Workflow> addActivity(
      @PathVariable String topologyId,
      @PathVariable String workflowName,
      @RequestBody TopologyWorkflowAddActivityRequest activityRequest) {

    Topology topology = topologyServiceCore.getMandatoryTopology(topologyId);
    topologyService.checkEditionAuthorizations(topology);
    topologyService.throwsErrorIfReleased(topology);

    Workflow wf =
        workflowBuilderService.addActivity(
            topology,
            workflowName,
            activityRequest.getRelatedStepId(),
            activityRequest.isBefore(),
            activityRequest.getActivity());
    alienDAO.save(topology);
    return RestResponseBuilder.<Workflow>builder().data(wf).build();
  }
 /**
  * Get the deployed (runtime) topology of an application on a cloud
  *
  * @param topologyId id of the topology for which to get deployed topology.
  * @param orchestratorId targeted cloud id
  * @return the DeploymentTopology requested if found
  */
 public DeploymentTopology getRuntimeTopologyFromEnvironment(
     String topologyId, String orchestratorId) {
   Deployment deployment = deploymentService.getActiveDeploymentOrFail(topologyId, orchestratorId);
   return alienMonitorDao.findById(DeploymentTopology.class, deployment.getId());
 }
 /**
  * Get the deployed (runtime) topology of an application from the deployment's id
  *
  * @param deploymentId
  * @return
  */
 public DeploymentTopology getRuntimeTopology(String deploymentId) {
   return alienMonitorDao.findById(DeploymentTopology.class, deploymentId);
 }
 /**
  * Get the deployed (runtime) topology of an application from the environment id
  *
  * @param applicationEnvironmentId id of the environment
  * @return the DeploymentTopology requested if found
  */
 public DeploymentTopology getRuntimeTopologyFromEnvironment(String applicationEnvironmentId) {
   Deployment deployment = deploymentService.getActiveDeploymentOrFail(applicationEnvironmentId);
   return alienMonitorDao.findById(DeploymentTopology.class, deployment.getId());
 }
 public Topology getTopology(String topologyId) {
   return alienDAO.findById(Topology.class, topologyId);
 }
  public void updateSubstitutionType(final Topology topology) {
    if (!topology.getDelegateType().equalsIgnoreCase(TopologyTemplate.class.getSimpleName())) {
      return;
    }
    if (topology.getSubstitutionMapping() == null
        || topology.getSubstitutionMapping().getSubstitutionType() == null) {
      return;
    }
    IndexedNodeType nodeType =
        csarRepoSearchService.getElementInDependencies(
            IndexedNodeType.class,
            topology.getSubstitutionMapping().getSubstitutionType().getElementId(),
            topology.getDependencies());

    TopologyTemplate topologyTemplate =
        alienDAO.findById(TopologyTemplate.class, topology.getDelegateId());
    TopologyTemplateVersion topologyTemplateVersion =
        topologyTemplateVersionService.getByTopologyId(topology.getId());

    Set<CSARDependency> inheritanceDependencies = Sets.newHashSet();
    inheritanceDependencies.add(
        new CSARDependency(nodeType.getArchiveName(), nodeType.getArchiveVersion()));

    // we have to search for the eventually existing CSar to update it' deps
    // actually, the csar is not renamed when the topology template is renamed (this is not quite
    // simple to rename a csar if it
    // is used in topologies ....). So we have to search the csar using the topology id.
    Csar csar = csarService.getTopologySubstitutionCsar(topology.getId());
    if (csar == null) {
      // the csar can not be found, we create it
      String archiveName = topologyTemplate.getName();
      String archiveVersion = topologyTemplateVersion.getVersion();
      csar = new Csar(archiveName, archiveVersion);
      csar.setSubstitutionTopologyId(topology.getId());
    }
    csar.setDependencies(inheritanceDependencies);
    csar.getDependencies().addAll(topology.getDependencies());
    csarService.save(csar);

    IndexedNodeType topologyTemplateType = new IndexedNodeType();
    topologyTemplateType.setArchiveName(csar.getName());
    topologyTemplateType.setArchiveVersion(csar.getVersion());
    topologyTemplateType.setElementId(csar.getName());
    topologyTemplateType.setDerivedFrom(Lists.newArrayList(nodeType.getElementId()));
    topologyTemplateType.setSubstitutionTopologyId(topology.getId());
    List<CapabilityDefinition> capabilities = Lists.newArrayList();
    topologyTemplateType.setCapabilities(capabilities);
    List<RequirementDefinition> requirements = Lists.newArrayList();
    topologyTemplateType.setRequirements(requirements);
    // inputs from topology become properties of type
    topologyTemplateType.setProperties(topology.getInputs());
    // output attributes become attributes for the type
    Map<String, IValue> attributes = Maps.newHashMap();
    topologyTemplateType.setAttributes(attributes);
    Map<String, Set<String>> outputAttributes = topology.getOutputAttributes();
    if (outputAttributes != null) {
      for (Entry<String, Set<String>> oae : outputAttributes.entrySet()) {
        String nodeName = oae.getKey();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        IndexedNodeType nodeTemplateType =
            csarRepoSearchService.getRequiredElementInDependencies(
                IndexedNodeType.class, nodeTemplate.getType(), topology.getDependencies());
        for (String attributeName : oae.getValue()) {
          IValue ivalue = nodeTemplateType.getAttributes().get(attributeName);
          // we have an issue here : if several nodes have the same attribute name, there is a
          // conflict
          if (ivalue != null && !attributes.containsKey(attributeName)) {
            attributes.put(attributeName, ivalue);
          }
        }
      }
    }
    // output properties become attributes for the type
    Map<String, Set<String>> outputProperties = topology.getOutputProperties();
    if (outputProperties != null) {
      for (Entry<String, Set<String>> ope : outputProperties.entrySet()) {
        String nodeName = ope.getKey();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        IndexedNodeType nodeTemplateType =
            csarRepoSearchService.getRequiredElementInDependencies(
                IndexedNodeType.class, nodeTemplate.getType(), topology.getDependencies());
        for (String propertyName : ope.getValue()) {
          PropertyDefinition pd = nodeTemplateType.getProperties().get(propertyName);
          // we have an issue here : if several nodes have the same attribute name, there is a
          // conflict
          if (pd != null && !attributes.containsKey(propertyName)) {
            attributes.put(propertyName, pd);
          }
        }
      }
    }
    // output capabilities properties also become attributes for the type
    Map<String, Map<String, Set<String>>> outputCapabilityProperties =
        topology.getOutputCapabilityProperties();
    if (outputCapabilityProperties != null) {
      for (Entry<String, Map<String, Set<String>>> ocpe : outputCapabilityProperties.entrySet()) {
        String nodeName = ocpe.getKey();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        for (Entry<String, Set<String>> cpe : ocpe.getValue().entrySet()) {
          String capabilityName = cpe.getKey();
          String capabilityTypeName = nodeTemplate.getCapabilities().get(capabilityName).getType();
          IndexedCapabilityType capabilityType =
              csarRepoSearchService.getRequiredElementInDependencies(
                  IndexedCapabilityType.class, capabilityTypeName, topology.getDependencies());
          for (String propertyName : cpe.getValue()) {
            PropertyDefinition pd = capabilityType.getProperties().get(propertyName);
            // we have an issue here : if several nodes have the same attribute name, there is a
            // conflict
            if (pd != null && !attributes.containsKey(propertyName)) {
              attributes.put(propertyName, pd);
            }
          }
        }
      }
    }

    // capabilities substitution
    if (topology.getSubstitutionMapping().getCapabilities() != null) {
      for (Entry<String, SubstitutionTarget> e :
          topology.getSubstitutionMapping().getCapabilities().entrySet()) {
        String key = e.getKey();
        String nodeName = e.getValue().getNodeTemplateName();
        String capabilityName = e.getValue().getTargetId();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        IndexedNodeType nodeTemplateType =
            csarRepoSearchService.getRequiredElementInDependencies(
                IndexedNodeType.class, nodeTemplate.getType(), topology.getDependencies());
        CapabilityDefinition capabilityDefinition =
            IndexedModelUtils.getCapabilityDefinitionById(
                nodeTemplateType.getCapabilities(), capabilityName);
        capabilityDefinition.setId(key);
        topologyTemplateType.getCapabilities().add(capabilityDefinition);
      }
    }
    // requirement substitution
    if (topology.getSubstitutionMapping().getRequirements() != null) {
      for (Entry<String, SubstitutionTarget> e :
          topology.getSubstitutionMapping().getRequirements().entrySet()) {
        String key = e.getKey();
        String nodeName = e.getValue().getNodeTemplateName();
        String requirementName = e.getValue().getTargetId();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        IndexedNodeType nodeTemplateType =
            csarRepoSearchService.getRequiredElementInDependencies(
                IndexedNodeType.class, nodeTemplate.getType(), topology.getDependencies());
        RequirementDefinition requirementDefinition =
            IndexedModelUtils.getRequirementDefinitionById(
                nodeTemplateType.getRequirements(), requirementName);
        requirementDefinition.setId(key);
        topologyTemplateType.getRequirements().add(requirementDefinition);
      }
    }
    indexerService.indexInheritableElement(
        csar.getName(), csar.getVersion(), topologyTemplateType, inheritanceDependencies);
  }