<commit_before>package org.ovirt.engine.core.bll.network.dc;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.ovirt.engine.core.bll.CommandBase;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkCluster;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.CustomLogField;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.CustomLogFields;
import org.ovirt.engine.core.utils.ReplacementUtils;

@SuppressWarnings("serial")
@CustomLogFields({ @CustomLogField("NetworkName") })
public abstract class NetworkCommon<T extends AddNetworkStoragePoolParameters> extends CommandBase<T> {
    private List<Network> networks;
    private List<NetworkCluster> clusterAttachments;

    public NetworkCommon(T parameters) {
        super(parameters);
        this.setStoragePoolId(getNetwork().getDataCenterId());
    }

    protected Network getNetwork() {
        return getParameters().getNetwork();
    }

    public String getNetworkName() {
        return getNetwork().getName();
    }

    @Override
    protected void setActionMessageParameters() {
        addCanDoActionMessage(VdcBllMessages.VAR__TYPE__NETWORK);
    }

    protected ValidationResult vmNetworkSetCorrectly() {
        return getNetwork().isVmNetwork() || FeatureSupported.nonVmNetwork(getStoragePool().getcompatibility_version())
                ? ValidationResult.VALID
                : new ValidationResult(VdcBllMessages.NON_VM_NETWORK_NOT_SUPPORTED_FOR_POOL_LEVEL);
    }

    protected ValidationResult stpForVmNetworkOnly() {
        return getNetwork().isVmNetwork() || !getNetwork().getStp()
                ? ValidationResult.VALID
                : new ValidationResult(VdcBllMessages.NON_VM_NETWORK_CANNOT_SUPPORT_STP);
    }

    protected ValidationResult mtuValid() {
        return getNetwork().getMtu() == 0
                || FeatureSupported.mtuSpecification(getStoragePool().getcompatibility_version())
                ? ValidationResult.VALID
                : new ValidationResult(VdcBllMessages.NETWORK_MTU_OVERRIDE_NOT_SUPPORTED);
    }

    protected ValidationResult vlanIsFree() {
        if (getNetwork().getVlanId() != null) {
            for (Network network : getNetworks()) {
                if (network.getVlanId() != null
                        && network.getVlanId().equals(getNetwork().getVlanId())
                        && network.getDataCenterId().equals(getNetwork().getDataCenterId())
                        && !network.getId().equals(getNetwork().getId())) {
                    return new ValidationResult(VdcBllMessages.NETWORK_VLAN_IN_USE,
                            String.format("$vlanId %d", getNetwork().getVlanId()));
                }
            }
        }
        return ValidationResult.VALID;
    }

    protected ValidationResult networkPrefixValid() {
        return getNetworkName().toLowerCase().startsWith("bond")
                ? new ValidationResult(VdcBllMessages.NETWORK_CANNOT_CONTAIN_BOND_NAME)
                : ValidationResult.VALID;
    }

    protected ValidationResult storagePoolExists() {
        return getStoragePool() == null
                ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST)
                : ValidationResult.VALID;
    }

    @Override
    public List<PermissionSubject> getPermissionCheckSubjects() {
        Network network = getNetwork();
        Guid networkId = network == null ? null : network.getId();

        return Collections.singletonList(new PermissionSubject(networkId,
                VdcObjectType.Network,
                getActionType().getActionGroup()));
    }

    protected List<Network> getNetworks() {
        if (networks == null) {
            networks = getNetworkDAO().getAllForDataCenter(getNetwork().getDataCenterId());
        }
        return networks;
    }

    protected ValidationResult networkExists(Network network) {
        return network == null
                ? new ValidationResult(VdcBllMessages.NETWORK_NOT_EXISTS)
                : ValidationResult.VALID;
    }

    protected ValidationResult networkNotUsedByVms(final Network network) {
        List<VM> vms = getVmDAO().getAllForNetwork(network.getId());
        if (vms.isEmpty()) {
            return ValidationResult.VALID;
        }

        Collection<String> replacements = ReplacementUtils.replaceWithNameable("ENTITIES_USING_NETWORK", vms);
        replacements.add(VdcBllMessages.VAR__ENTITIES__VMS.name());
        return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWORK_IN_USE, replacements);
    }

    protected List<NetworkCluster> getClusterAttachments() {
        if (clusterAttachments == null) {
            clusterAttachments = getNetworkClusterDAO().getAllForNetwork(getNetwork().getId());
        }

        return clusterAttachments;
    }

    protected ValidationResult networkNotUsedByHosts(final Network network) {
        List<VDS> hostsWithNetwork = getVdsDAO().getAllForNetwork(network.getId());
        if (hostsWithNetwork.isEmpty()) {
            return ValidationResult.VALID;
        }

        Collection<String> replacements =
                ReplacementUtils.replaceWithNameable("ENTITIES_USING_NETWORK", hostsWithNetwork);
        replacements.add(VdcBllMessages.VAR__ENTITIES__HOSTS.name());
        return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWORK_IN_USE, replacements);
    }

    protected ValidationResult networkNotUsedByTemplates(final Network network) {
        List<VmTemplate> templates = getVmTemplateDAO().getAllForNetwork(network.getId());
        if (templates.isEmpty()) {
            return ValidationResult.VALID;
        }

        Collection<String> replacements = ReplacementUtils.replaceWithNameable("ENTITIES_USING_NETWORK", templates);
        replacements.add(VdcBllMessages.VAR__ENTITIES__VM_TEMPLATES.name());
        return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWORK_IN_USE, replacements);
    }
}
<commit_msg>engine: Extract common code for network used<commit_after>package org.ovirt.engine.core.bll.network.dc;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.ovirt.engine.core.bll.CommandBase;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters;
import org.ovirt.engine.core.common.businessentities.Nameable;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkCluster;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.CustomLogField;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.CustomLogFields;
import org.ovirt.engine.core.utils.ReplacementUtils;

@SuppressWarnings("serial")
@CustomLogFields({ @CustomLogField("NetworkName") })
public abstract class NetworkCommon<T extends AddNetworkStoragePoolParameters> extends CommandBase<T> {
    private List<Network> networks;
    private List<NetworkCluster> clusterAttachments;

    public NetworkCommon(T parameters) {
        super(parameters);
        this.setStoragePoolId(getNetwork().getDataCenterId());
    }

    protected Network getNetwork() {
        return getParameters().getNetwork();
    }

    public String getNetworkName() {
        return getNetwork().getName();
    }

    @Override
    protected void setActionMessageParameters() {
        addCanDoActionMessage(VdcBllMessages.VAR__TYPE__NETWORK);
    }

    protected ValidationResult vmNetworkSetCorrectly() {
        return getNetwork().isVmNetwork() || FeatureSupported.nonVmNetwork(getStoragePool().getcompatibility_version())
                ? ValidationResult.VALID
                : new ValidationResult(VdcBllMessages.NON_VM_NETWORK_NOT_SUPPORTED_FOR_POOL_LEVEL);
    }

    protected ValidationResult stpForVmNetworkOnly() {
        return getNetwork().isVmNetwork() || !getNetwork().getStp()
                ? ValidationResult.VALID
                : new ValidationResult(VdcBllMessages.NON_VM_NETWORK_CANNOT_SUPPORT_STP);
    }

    protected ValidationResult mtuValid() {
        return getNetwork().getMtu() == 0
                || FeatureSupported.mtuSpecification(getStoragePool().getcompatibility_version())
                ? ValidationResult.VALID
                : new ValidationResult(VdcBllMessages.NETWORK_MTU_OVERRIDE_NOT_SUPPORTED);
    }

    protected ValidationResult vlanIsFree() {
        if (getNetwork().getVlanId() != null) {
            for (Network network : getNetworks()) {
                if (network.getVlanId() != null
                        && network.getVlanId().equals(getNetwork().getVlanId())
                        && network.getDataCenterId().equals(getNetwork().getDataCenterId())
                        && !network.getId().equals(getNetwork().getId())) {
                    return new ValidationResult(VdcBllMessages.NETWORK_VLAN_IN_USE,
                            String.format("$vlanId %d", getNetwork().getVlanId()));
                }
            }
        }
        return ValidationResult.VALID;
    }

    protected ValidationResult networkPrefixValid() {
        return getNetworkName().toLowerCase().startsWith("bond")
                ? new ValidationResult(VdcBllMessages.NETWORK_CANNOT_CONTAIN_BOND_NAME)
                : ValidationResult.VALID;
    }

    protected ValidationResult storagePoolExists() {
        return getStoragePool() == null
                ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST)
                : ValidationResult.VALID;
    }

    @Override
    public List<PermissionSubject> getPermissionCheckSubjects() {
        Network network = getNetwork();
        Guid networkId = network == null ? null : network.getId();

        return Collections.singletonList(new PermissionSubject(networkId,
                VdcObjectType.Network,
                getActionType().getActionGroup()));
    }

    protected List<Network> getNetworks() {
        if (networks == null) {
            networks = getNetworkDAO().getAllForDataCenter(getNetwork().getDataCenterId());
        }
        return networks;
    }

    protected ValidationResult networkExists(Network network) {
        return network == null
                ? new ValidationResult(VdcBllMessages.NETWORK_NOT_EXISTS)
                : ValidationResult.VALID;
    }

    private ValidationResult networkNotUsed(List<? extends Nameable> entities, VdcBllMessages entitiesReplacement) {
        if (entities.isEmpty()) {
            return ValidationResult.VALID;
        }

        Collection<String> replacements = ReplacementUtils.replaceWithNameable("ENTITIES_USING_NETWORK", entities);
        replacements.add(entitiesReplacement.name());
        return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWORK_IN_USE, replacements);
    }

    protected ValidationResult networkNotUsedByVms(final Network network) {
        return networkNotUsed(getVmDAO().getAllForNetwork(network.getId()), VdcBllMessages.VAR__ENTITIES__VMS);
    }

    protected List<NetworkCluster> getClusterAttachments() {
        if (clusterAttachments == null) {
            clusterAttachments = getNetworkClusterDAO().getAllForNetwork(getNetwork().getId());
        }

        return clusterAttachments;
    }

    protected ValidationResult networkNotUsedByHosts(final Network network) {
        return networkNotUsed(getVdsDAO().getAllForNetwork(network.getId()), VdcBllMessages.VAR__ENTITIES__HOSTS);
    }

    protected ValidationResult networkNotUsedByTemplates(final Network network) {
        return networkNotUsed(getVmTemplateDAO().getAllForNetwork(network.getId()),
                VdcBllMessages.VAR__ENTITIES__VM_TEMPLATES);
    }
}

{'fraction_non_alphanumeric': 0.09689156054733845, 'fraction_numerical': 0.00015819030293443012, 'mean_word_length': 3.3405423961551666, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1121678', 'n_tokens_mistral': 3558, 'n_tokens_neox': 3422, 'n_words': 498}