<commit_before>/*
 * Copyright (c) 2016 Open Baton (http://www.openbaton.org)
 *
 * 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 org.openbaton.nfvo.core.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
import javax.persistence.EntityManager;
import org.openbaton.catalogue.api.DeployNSRBody;
import org.openbaton.catalogue.mano.common.DeploymentFlavour;
import org.openbaton.catalogue.mano.common.Ip;
import org.openbaton.catalogue.mano.descriptor.*;
import org.openbaton.catalogue.mano.record.*;
import org.openbaton.catalogue.nfvo.*;
import org.openbaton.catalogue.nfvo.messages.Interfaces.NFVMessage;
import org.openbaton.catalogue.nfvo.messages.OrVnfmGenericMessage;
import org.openbaton.catalogue.nfvo.messages.OrVnfmHealVNFRequestMessage;
import org.openbaton.catalogue.nfvo.messages.OrVnfmStartStopMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrHealedMessage;
import org.openbaton.catalogue.nfvo.networks.Network;
import org.openbaton.catalogue.nfvo.viminstances.BaseVimInstance;
import org.openbaton.catalogue.nfvo.viminstances.OpenstackVimInstance;
import org.openbaton.catalogue.security.Key;
import org.openbaton.exceptions.*;
import org.openbaton.nfvo.common.internal.model.EventNFVO;
import org.openbaton.nfvo.common.utils.viminstance.VimInstanceUtils;
import org.openbaton.nfvo.core.interfaces.DependencyManagement;
import org.openbaton.nfvo.core.interfaces.EventDispatcher;
import org.openbaton.nfvo.core.interfaces.ResourceManagement;
import org.openbaton.nfvo.core.interfaces.VimManagement;
import org.openbaton.nfvo.core.utils.NSDUtils;
import org.openbaton.nfvo.core.utils.NSRUtils;
import org.openbaton.nfvo.repositories.*;
import org.openbaton.nfvo.vim_interfaces.vim.VimBroker;
import org.openbaton.vnfm.interfaces.manager.VnfmManager;
import org.openbaton.vnfm.interfaces.state.VnfStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
@ConfigurationProperties
@SuppressWarnings({"unsafe", "unchecked"})
public class NetworkServiceRecordManagement
    implements org.openbaton.nfvo.core.interfaces.NetworkServiceRecordManagement {

  private final Logger log = LoggerFactory.getLogger(this.getClass());
  @Autowired private ThreadPoolTaskExecutor executor;
  @Autowired private EventDispatcher publisher;
  @Autowired private NetworkServiceRecordRepository nsrRepository;
  @Autowired private NetworkServiceDescriptorRepository nsdRepository;
  @Autowired private VNFDRepository vnfdRepository;
  @Autowired private VNFRRepository vnfrRepository;
  @Autowired private VNFRecordDependencyRepository vnfRecordDependencyRepository;
  @Autowired private NSDUtils nsdUtils;
  @Autowired private VnfmManager vnfmManager;
  @Autowired private VnfStateHandler vnfStateHandler;
  @Autowired private ResourceManagement resourceManagement;
  @Autowired private DependencyManagement dependencyManagement;
  @Autowired private VNFCRepository vnfcRepository;
  @Autowired private VduRepository vduRepository;
  @Autowired private VimRepository vimInstanceRepository;
  @Autowired private VnfmEndpointRepository vnfmManagerEndpointRepository;
  @Autowired private VimBroker vimBroker;
  @Autowired private EntityManager entityManager;
  @Autowired private KeyRepository keyRepository;
  @Autowired private VnfPackageRepository vnfPackageRepository;
  @Autowired private VimManagement vimManagement;

  @Value("${nfvo.delete.vnfr.wait.timeout:60}")
  private int timeout;

  @Value("${nfvo.delete.vnfr.wait:true}")
  private boolean removeAfterTimeout;

  @Value("${nfvo.delete.all-status:true}")
  private boolean deleteInAllStatus;

  @Value("${nfvo.quota.check:true}")
  private boolean isQuotaCheckEnabled;

  @Value("${nfvo.quota.check.failOnException:true}")
  private boolean failingQuotaCheckOnException;

  @Override
  public NetworkServiceRecord onboard(
      String idNsd,
      String projectID,
      List keys,
      Map<String, Set<String>> vduVimInstances,
      Map<String, Configuration> configurations,
      String monitoringIp)
      throws VimException, NotFoundException, PluginException, BadRequestException, IOException,
          AlreadyExistingException, BadFormatException, ExecutionException, InterruptedException {
    log.info("Looking for NetworkServiceDescriptor with ID: " + idNsd);
    NetworkServiceDescriptor networkServiceDescriptor =
        nsdRepository.findFirstByIdAndProjectId(idNsd, projectID);
    if (networkServiceDescriptor == null) {
      throw new NotFoundException("NSD with ID " + idNsd + " was not found");
    }

    // Detach instance of NSD to stop persistence
    if (networkServiceDescriptor.getId() != null) {
      entityManager.detach(networkServiceDescriptor);
    }

    DeployNSRBody body = new DeployNSRBody();
    body.setVduVimInstances(vduVimInstances);
    if (configurations == null) {
      body.setConfigurations(new HashMap());
    } else {
      body.setConfigurations(configurations);
    }
    if (keys == null) {
      body.setKeys(null);
    } else {
      Set<Key> keys1 = new LinkedHashSet<>();
      for (Object k : keys) {
        log.debug("Looking for keyname: " + k);
        Key key = keyRepository.findKey(projectID, (String) k);
        if (key == null) {
          throw new NotFoundException("No key found with name: " + k);
        }
        keys1.add(key);
      }
      body.setKeys(keys1);
      log.debug("Found keys: " + body.getKeys());
    }
    return deployNSR(networkServiceDescriptor, projectID, body, monitoringIp);
  }

  @Override
  public NetworkServiceRecord scaleOutNsr(
      String nsrId,
      String vnfdId,
      String projectId,
      List keys,
      Map vduVimInstances,
      Map configurations)
      throws NotFoundException, BadRequestException, MissingParameterException {
    //Check if the NSR exists
    log.info("Looking for NetworkServiceRecord with id: " + nsrId);
    NetworkServiceRecord nsr = nsrRepository.findFirstById(nsrId);
    if (nsr == null) {
      throw new NotFoundException("NSR with id " + nsrId + " was not found");
    }
    //Check if the NSR belongs to the current project
    if (!nsr.getProjectId().equals(projectId)) {
      throw new UnauthorizedUserException(
          "NSD " + nsrId + " not under the project (" + projectId + ") chosen ...");
    }
    //Check if the VNFD exists
    VirtualNetworkFunctionDescriptor vnfd = vnfdRepository.findFirstById(vnfdId);
    if (vnfd == null) {
      throw new NotFoundException("VNFD with id " + vnfdId + " was not found");
    }
    //Check if the VNFD belongs the current project
    if (!vnfd.getProjectId().equals(projectId)) {
      throw new UnauthorizedUserException(
          "VNFD " + vnfdId + " not under the project (" + projectId + ") chosen ...");
    }

    DeployNSRBody body = new DeployNSRBody();
    body.setVduVimInstances(vduVimInstances);
    if (configurations == null) {
      body.setConfigurations(new HashMap());
    } else {
      body.setConfigurations(configurations);
    }
    if (keys == null) {
      body.setKeys(null);
    } else {
      Set<Key> keys1 = new LinkedHashSet<>();<commit_msg>optimized check if nsr exists<commit_after>/*
 * Copyright (c) 2016 Open Baton (http://www.openbaton.org)
 *
 * 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 org.openbaton.nfvo.core.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.regex.Pattern;
import javax.persistence.EntityManager;
import org.openbaton.catalogue.api.DeployNSRBody;
import org.openbaton.catalogue.mano.common.DeploymentFlavour;
import org.openbaton.catalogue.mano.common.Ip;
import org.openbaton.catalogue.mano.descriptor.*;
import org.openbaton.catalogue.mano.record.*;
import org.openbaton.catalogue.nfvo.*;
import org.openbaton.catalogue.nfvo.messages.Interfaces.NFVMessage;
import org.openbaton.catalogue.nfvo.messages.OrVnfmGenericMessage;
import org.openbaton.catalogue.nfvo.messages.OrVnfmHealVNFRequestMessage;
import org.openbaton.catalogue.nfvo.messages.OrVnfmStartStopMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrHealedMessage;
import org.openbaton.catalogue.nfvo.networks.Network;
import org.openbaton.catalogue.nfvo.viminstances.BaseVimInstance;
import org.openbaton.catalogue.nfvo.viminstances.OpenstackVimInstance;
import org.openbaton.catalogue.security.Key;
import org.openbaton.exceptions.*;
import org.openbaton.nfvo.common.internal.model.EventNFVO;
import org.openbaton.nfvo.common.utils.viminstance.VimInstanceUtils;
import org.openbaton.nfvo.core.interfaces.DependencyManagement;
import org.openbaton.nfvo.core.interfaces.EventDispatcher;
import org.openbaton.nfvo.core.interfaces.ResourceManagement;
import org.openbaton.nfvo.core.interfaces.VimManagement;
import org.openbaton.nfvo.core.utils.NSDUtils;
import org.openbaton.nfvo.core.utils.NSRUtils;
import org.openbaton.nfvo.repositories.*;
import org.openbaton.nfvo.vim_interfaces.vim.VimBroker;
import org.openbaton.vnfm.interfaces.manager.VnfmManager;
import org.openbaton.vnfm.interfaces.state.VnfStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
@ConfigurationProperties
@SuppressWarnings({"unsafe", "unchecked"})
public class NetworkServiceRecordManagement
    implements org.openbaton.nfvo.core.interfaces.NetworkServiceRecordManagement {

  private final Logger log = LoggerFactory.getLogger(this.getClass());
  @Autowired private ThreadPoolTaskExecutor executor;
  @Autowired private EventDispatcher publisher;
  @Autowired private NetworkServiceRecordRepository nsrRepository;
  @Autowired private NetworkServiceDescriptorRepository nsdRepository;
  @Autowired private VNFDRepository vnfdRepository;
  @Autowired private VNFRRepository vnfrRepository;
  @Autowired private VNFRecordDependencyRepository vnfRecordDependencyRepository;
  @Autowired private NSDUtils nsdUtils;
  @Autowired private VnfmManager vnfmManager;
  @Autowired private VnfStateHandler vnfStateHandler;
  @Autowired private ResourceManagement resourceManagement;
  @Autowired private DependencyManagement dependencyManagement;
  @Autowired private VNFCRepository vnfcRepository;
  @Autowired private VduRepository vduRepository;
  @Autowired private VimRepository vimInstanceRepository;
  @Autowired private VnfmEndpointRepository vnfmManagerEndpointRepository;
  @Autowired private VimBroker vimBroker;
  @Autowired private EntityManager entityManager;
  @Autowired private KeyRepository keyRepository;
  @Autowired private VnfPackageRepository vnfPackageRepository;
  @Autowired private VimManagement vimManagement;

  @Value("${nfvo.delete.vnfr.wait.timeout:60}")
  private int timeout;

  @Value("${nfvo.delete.vnfr.wait:true}")
  private boolean removeAfterTimeout;

  @Value("${nfvo.delete.all-status:true}")
  private boolean deleteInAllStatus;

  @Value("${nfvo.quota.check:true}")
  private boolean isQuotaCheckEnabled;

  @Value("${nfvo.quota.check.failOnException:true}")
  private boolean failingQuotaCheckOnException;

  @Override
  public NetworkServiceRecord onboard(
      String idNsd,
      String projectID,
      List keys,
      Map<String, Set<String>> vduVimInstances,
      Map<String, Configuration> configurations,
      String monitoringIp)
      throws VimException, NotFoundException, PluginException, BadRequestException, IOException,
          AlreadyExistingException, BadFormatException, ExecutionException, InterruptedException {
    log.info("Looking for NetworkServiceDescriptor with ID: " + idNsd);
    NetworkServiceDescriptor networkServiceDescriptor =
        nsdRepository.findFirstByIdAndProjectId(idNsd, projectID);
    if (networkServiceDescriptor == null) {
      throw new NotFoundException("NSD with ID " + idNsd + " was not found");
    }

    // Detach instance of NSD to stop persistence
    if (networkServiceDescriptor.getId() != null) {
      entityManager.detach(networkServiceDescriptor);
    }

    DeployNSRBody body = new DeployNSRBody();
    body.setVduVimInstances(vduVimInstances);
    if (configurations == null) {
      body.setConfigurations(new HashMap());
    } else {
      body.setConfigurations(configurations);
    }
    if (keys == null) {
      body.setKeys(null);
    } else {
      Set<Key> keys1 = new LinkedHashSet<>();
      for (Object k : keys) {
        log.debug("Looking for keyname: " + k);
        Key key = keyRepository.findKey(projectID, (String) k);
        if (key == null) {
          throw new NotFoundException("No key found with name: " + k);
        }
        keys1.add(key);
      }
      body.setKeys(keys1);
      log.debug("Found keys: " + body.getKeys());
    }
    return deployNSR(networkServiceDescriptor, projectID, body, monitoringIp);
  }

  @Override
  public NetworkServiceRecord scaleOutNsr(
      String nsrId,
      String vnfdId,
      String projectId,
      List keys,
      Map vduVimInstances,
      Map configurations)
      throws NotFoundException, BadRequestException, MissingParameterException {
    //Check if the NSR exists
    log.info("Looking for NetworkServiceRecord with id: " + nsrId);
    NetworkServiceRecord nsr = nsrRepository.findFirstByIdAndProjectId(nsrId, projectId);
    if (nsr == null) {
      throw new NotFoundException(
          "NSR with id " + nsrId + " was not found in the project with id " + projectId);
    }
    //Check if the VNFD exists
    VirtualNetworkFunctionDescriptor vnfd = vnfdRepository.findFirstById(vnfdId);
    if (vnfd == null) {
      throw new NotFoundException("VNFD with id " + vnfdId + " was not found");
    }
    //Check if the VNFD belongs the current project
    if (!vnfd.getProjectId().equals(projectId)) {
      throw new UnauthorizedUserException(
          "VNFD " + vnfdId + " not under the project (" + projectId + ") chosen ...");
    }

    DeployNSRBody body = new DeployNSRBody();
    body.setVduVimInstances(vduVimInstances);
    if (configurations == null) {
      body.setConfigurations(new HashMap());
    } else {
      body.setConfigurations(configurations);
    }
    if (keys == null) {
      body.setKeys(null);
    } else {
      Set<Key> keys1 = new LinkedHashSet<>();
{'fraction_non_alphanumeric': 0.09435536746736603, 'fraction_numerical': 0.0020265840138284554, 'mean_word_length': 4.670158837445083, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '684590', 'n_tokens_mistral': 4919, 'n_tokens_neox': 4943, 'n_words': 1101}