id
int64 22
34.9k
| comment_id
int64 0
328
| comment
stringlengths 2
2.55k
| code
stringlengths 31
107k
| classification
stringclasses 6
values | isFinished
bool 1
class | code_context_2
stringlengths 21
27.3k
| code_context_10
stringlengths 29
27.3k
| code_context_20
stringlengths 29
27.3k
|
---|---|---|---|---|---|---|---|---|
25,388 | 15 | // For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | }
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) { | if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) { | throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else { |
25,388 | 16 | //for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | } else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0); | }
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool | URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
} |
25,388 | 17 | // Fail network creation if specified vlan is dedicated to a different account | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId(); | if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) { | + zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
} |
25,388 | 18 | // Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId()); | //the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
} | if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
} |
25,388 | 19 | // don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | }
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId); | final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns); | final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) { |
25,388 | 20 | // If networkDomain is not specified, take it from the global configuration | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | }
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId), | }
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else { | if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId); |
25,388 | 21 | // TBD: NetworkOfferingId and zoneId. Send uuids instead. | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | DESIGN | true | if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
} | }
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
} | }
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\""); |
25,388 | 22 | // 1) Get networkDomain from the corresponding account/domain/zone | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | } else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId); | final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else { | // don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x |
25,388 | 23 | // 2) If null, generate networkDomain using domain suffix from the global config variables | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId); | throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
} | }
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))); |
25,388 | 24 | // validate network domain | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | }
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain " | if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges | Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled"); |
25,388 | 25 | // In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | DESIGN | true | }
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest | } else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
} | // 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant"); |
25,388 | 26 | // No cidr can be specified in Basic zone | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | }
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic); | && (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain; | + "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId); |
25,388 | 27 | // Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4 | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) { | throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override | }
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr); |
25,388 | 28 | //Logical router's UUID provided as VLAN_ID | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else { | if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) { | userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) { |
25,388 | 29 | //Set transient field | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk); | userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan); | userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal + |
25,388 | 30 | // For shared network | @DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId,
boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk,
final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr,
final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
final DataCenterVO zone = _dcDao.findById(zoneId);
// this method supports only guest network creation
if (ntwkOff.getTrafficType() != TrafficType.Guest) {
s_logger.warn("Only guest networks can be created using this method");
return null;
}
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
//check resource limits
if (updateResourceCount) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
}
// Validate network offering
if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
// see NetworkOfferingVO
final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
throw ex;
}
// Validate physical network
if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
// see PhysicalNetworkVO.java
final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
throw ex;
}
boolean ipv6 = false;
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
ipv6 = true;
}
// Validate zone
if (zone.getNetworkType() == NetworkType.Basic) {
// In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
if (aclType == null || aclType != ACLType.Domain) {
throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
}
// Only one guest network is supported in Basic zone
final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
if (!guestNetworks.isEmpty()) {
throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
}
// if zone is basic, only Shared network offerings w/o source nat service are allowed
if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled "
+ Service.SourceNat.getName() + " service are allowed");
}
if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
}
if (subdomainAccess == null) {
subdomainAccess = true;
} else if (!subdomainAccess) {
throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
} else {
if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
}
}
} else if (zone.getNetworkType() == NetworkType.Advanced) {
if (zone.isSecurityGroupEnabled()) {
if (isolatedPvlan != null) {
throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
}
// Only Account specific Isolated network with sourceNat service disabled are allowed in security group
// enabled zone
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
}
if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
}
}
//don't allow eip/elb networks in Advance zone
if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
}
}
if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
}
//TODO(VXLAN): Support VNI specified
// VlanId can be specified only when network offering supports it
final boolean vlanSpecified = vlanId != null;
if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
if (vlanSpecified) {
throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
} else {
throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
}
}
if (vlanSpecified) {
URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
// Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
//don't allow to specify vlan tag used by physical network for dynamic vlan allocation
if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) &&
_dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone "
+ zone.getName());
}
if (! UuidUtils.validateUUID(vlanId)){
// For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
} else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
} else {
final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
//for the network that is created as part of private gateway,
//the vnet is not coming from the data center vnet table, so the list can be empty
if (!dcVnets.isEmpty()) {
final DataCenterVnetVO dcVnet = dcVnets.get(0);
// Fail network creation if specified vlan is dedicated to a different account
if (dcVnet.getAccountGuestVlanMapId() != null) {
final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
if (map.getAccountId() != owner.getAccountId()) {
throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
}
// Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
} else {
final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
if (maps != null && !maps.isEmpty()) {
final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner "
+ owner.getAccountName());
}
}
}
}
}
} else {
// don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or
// shared network with same Vlan ID in the zone
if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) {
throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
}
}
}
}
// If networkDomain is not specified, take it from the global configuration
if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId),
Service.Dns);
final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
if (networkDomain != null) {
// TBD: NetworkOfferingId and zoneId. Send uuids instead.
throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
}
} else {
if (networkDomain == null) {
// 1) Get networkDomain from the corresponding account/domain/zone
if (aclType == ACLType.Domain) {
networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
} else if (aclType == ACLType.Account) {
networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
}
// 2) If null, generate networkDomain using domain suffix from the global config variables
if (networkDomain == null) {
networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
}
} else {
// validate network domain
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain "
+ "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
+ "and the hyphen ('-'); can't start or end with \"-\"");
}
}
}
}
// In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
// limitation, remove after we introduce support for multiple ip ranges
// with different Cidrs for the same Shared network
final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced
&& ntwkOff.getTrafficType() == TrafficType.Guest
&& (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated
&& !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
if (cidr == null && ip6Cidr == null && cidrRequired) {
if (ntwkOff.getGuestType() == GuestType.Shared) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared);
} else {
throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
}
}
checkL2OfferingServices(ntwkOff);
// No cidr can be specified in Basic zone
if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
}
// Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
if (!NetUtils.validateGuestCidr(cidr)) {
throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
}
}
final String networkDomainFinal = networkDomain;
final String vlanIdFinal = vlanId;
final Boolean subdomainAccessFinal = subdomainAccess;
final Network network = Transaction.execute(new TransactionCallback<Network>() {
@Override
public Network doInTransaction(final TransactionStatus status) {
Long physicalNetworkId = null;
if (pNtwk != null) {
physicalNetworkId = pNtwk.getId();
}
final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
final NetworkVO userNetwork = new NetworkVO();
userNetwork.setNetworkDomain(networkDomainFinal);
if (cidr != null && gateway != null) {
userNetwork.setCidr(cidr);
userNetwork.setGateway(gateway);
}
if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
userNetwork.setIp6Cidr(ip6Cidr);
userNetwork.setIp6Gateway(ip6Gateway);
}
if (externalId != null) {
userNetwork.setExternalId(externalId);
}
if (StringUtils.isNotBlank(routerIp)) {
userNetwork.setRouterIp(routerIp);
}
if (StringUtils.isNotBlank(routerIpv6)) {
userNetwork.setRouterIpv6(routerIpv6);
}
if (vlanIdFinal != null) {
if (isolatedPvlan == null) {
URI uri = null;
if (UuidUtils.validateUUID(vlanIdFinal)){
//Logical router's UUID provided as VLAN_ID
userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field
} else {
uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
}
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
} else {
userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
}
} else {
if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
}
URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal +
" and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType +
" already exists or overlaps with other network pvlans in zone " + zoneId);
}
userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} | NONSATD | true | network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
} | } else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId()); | userNetwork.setBroadcastUri(uri);
userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
userNetwork.setPvlanType(isolatedPvlanType);
}
}
final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId,
isDisplayNetworkEnabled);
Network network = null;
if (networks == null || networks.isEmpty()) {
throw new CloudRuntimeException("Fail to create a network");
} else {
if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
Network defaultGuestNetwork = networks.get(0);
for (final Network nw : networks) {
if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
defaultGuestNetwork = nw;
}
}
network = defaultGuestNetwork;
} else {
// For shared network
network = networks.get(0);
}
}
if (updateResourceCount) {
_resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
}
return network;
}
});
CallContext.current().setEventDetails("Network Id: " + network.getId());
CallContext.current().putContextParameter(Network.class, network.getUuid());
return network;
} |
813 | 0 | // TODO(calvin): Make this supported again. | @Override
public boolean asyncCheckpoint(long fileId) throws AlluxioTException {
return false;
} | DESIGN | true | @Override
public boolean asyncCheckpoint(long fileId) throws AlluxioTException {
return false;
} | @Override
public boolean asyncCheckpoint(long fileId) throws AlluxioTException {
return false;
} | @Override
public boolean asyncCheckpoint(long fileId) throws AlluxioTException {
return false;
} |
9,010 | 0 | /**
* Main method to invoke this demo on how to send a message to an Azure Event Hub.
*
* @param args Unused arguments to the program.
*/ | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} | NONSATD | true | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} |
9,010 | 1 | // The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties. | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} | NONSATD | true | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder() | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
} |
9,010 | 2 | // Create an event to send. | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} | NONSATD | true | .connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString()); | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} |
9,010 | 3 | // Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance. | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} | NONSATD | true | // Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."), | // 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> { | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} |
9,010 | 4 | // Disposing of our producer and client. | public static void main(String[] args) {
// The connection string value can be obtained by:
// 1. Going to your Event Hubs namespace in Azure Portal.
// 2. Creating an Event Hub instance.
// 3. Creating a "Shared access policy" for your Event Hub instance.
// 4. Copying the connection string from the policy's properties.
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} | NONSATD | true | }
}, () -> {
// Disposing of our producer and client.
producer.close();
}); | producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} | EventHubProducerAsyncClient producer = new EventHubClientBuilder()
.connectionString(connectionString)
.buildAsyncProducer();
// Create an event to send.
EventData data = new EventData("Hello world!".getBytes(UTF_8));
// Send that event. This call returns a Mono<Void>, which we subscribe to. It completes successfully when the
// event has been delivered to the Event Hub. It completes with an error if an exception occurred while sending
// the event.
// SendOptions are not specified, so events sent are load balanced between all available partitions in the
// Event Hub instance.
producer.send(data).subscribe(
(ignored) -> System.out.println("Event sent."),
error -> {
System.err.println("There was an error sending the event: " + error.toString());
if (error instanceof AmqpException) {
AmqpException amqpException = (AmqpException) error;
System.err.println(String.format("Is send operation retriable? %s. Error condition: %s",
amqpException.isTransient(), amqpException.getErrorCondition()));
}
}, () -> {
// Disposing of our producer and client.
producer.close();
});
} |
17,204 | 0 | // Ignore
// TODO: add an error message instead for counter key | public void getDagInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
Map<String, Object> dagInfo = new HashMap<String, Object>();
dagInfo.put("id", dag.getID().toString());
dagInfo.put("progress", Float.toString(dag.getCompletedTaskProgress()));
dagInfo.put("status", dag.getState().toString());
try {
if (counterNames != null && !counterNames.isEmpty()) {
TezCounters counters = dag.getCachedCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
dagInfo.put("counters", counterMap);
}
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
renderJSON(ImmutableMap.of(
"dag", dagInfo
));
} | IMPLEMENTATION | true | }
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
renderJSON(ImmutableMap.of( | dagInfo.put("status", dag.getState().toString());
try {
if (counterNames != null && !counterNames.isEmpty()) {
TezCounters counters = dag.getCachedCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
dagInfo.put("counters", counterMap);
}
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
renderJSON(ImmutableMap.of(
"dag", dagInfo
));
} | return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
Map<String, Object> dagInfo = new HashMap<String, Object>();
dagInfo.put("id", dag.getID().toString());
dagInfo.put("progress", Float.toString(dag.getCompletedTaskProgress()));
dagInfo.put("status", dag.getState().toString());
try {
if (counterNames != null && !counterNames.isEmpty()) {
TezCounters counters = dag.getCachedCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
dagInfo.put("counters", counterMap);
}
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
renderJSON(ImmutableMap.of(
"dag", dagInfo
));
} |
17,205 | 0 | // Ignore
// TODO: add an error message instead for counter key | private Map<String, Object> getVertexInfoMap(Vertex vertex,
Map<String, Set<String>> counterNames) {
Map<String, Object> vertexInfo = new HashMap<String, Object>();
vertexInfo.put("id", vertex.getVertexId().toString());
vertexInfo.put("status", vertex.getState().toString());
vertexInfo.put("progress", Float.toString(vertex.getCompletedTaskProgress()));
vertexInfo.put("initTime", Long.toString(vertex.getInitTime()));
vertexInfo.put("startTime", Long.toString(vertex.getStartTime()));
vertexInfo.put("finishTime", Long.toString(vertex.getFinishTime()));
vertexInfo.put("firstTaskStartTime", Long.toString(vertex.getFirstTaskStartTime()));
vertexInfo.put("lastTaskFinishTime", Long.toString(vertex.getLastTaskFinishTime()));
ProgressBuilder vertexProgress = vertex.getVertexProgress();
vertexInfo.put("totalTasks", Integer.toString(vertexProgress.getTotalTaskCount()));
vertexInfo.put("runningTasks", Integer.toString(vertexProgress.getRunningTaskCount()));
vertexInfo.put("succeededTasks", Integer.toString(vertexProgress.getSucceededTaskCount()));
vertexInfo.put("failedTaskAttempts",
Integer.toString(vertexProgress.getFailedTaskAttemptCount()));
vertexInfo.put("killedTaskAttempts",
Integer.toString(vertexProgress.getKilledTaskAttemptCount()));
try {
if (counterNames != null && !counterNames.isEmpty()) {
TezCounters counters = vertex.getCachedCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
vertexInfo.put("counters", counterMap);
}
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
return vertexInfo;
} | IMPLEMENTATION | true | }
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
return vertexInfo; | Integer.toString(vertexProgress.getKilledTaskAttemptCount()));
try {
if (counterNames != null && !counterNames.isEmpty()) {
TezCounters counters = vertex.getCachedCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
vertexInfo.put("counters", counterMap);
}
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
return vertexInfo;
} | vertexInfo.put("finishTime", Long.toString(vertex.getFinishTime()));
vertexInfo.put("firstTaskStartTime", Long.toString(vertex.getFirstTaskStartTime()));
vertexInfo.put("lastTaskFinishTime", Long.toString(vertex.getLastTaskFinishTime()));
ProgressBuilder vertexProgress = vertex.getVertexProgress();
vertexInfo.put("totalTasks", Integer.toString(vertexProgress.getTotalTaskCount()));
vertexInfo.put("runningTasks", Integer.toString(vertexProgress.getRunningTaskCount()));
vertexInfo.put("succeededTasks", Integer.toString(vertexProgress.getSucceededTaskCount()));
vertexInfo.put("failedTaskAttempts",
Integer.toString(vertexProgress.getFailedTaskAttemptCount()));
vertexInfo.put("killedTaskAttempts",
Integer.toString(vertexProgress.getKilledTaskAttemptCount()));
try {
if (counterNames != null && !counterNames.isEmpty()) {
TezCounters counters = vertex.getCachedCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
vertexInfo.put("counters", counterMap);
}
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
return vertexInfo;
} |
822 | 0 | //TODO(bazel-team): support \x escapes | private BasePrinter escapeCharacter(char c) {
if (c == '"') {
return backslashChar(c);
}
switch (c) {
case '\\':
return backslashChar('\\');
case '\r':
return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} | IMPLEMENTATION | true | default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
} | case '\\':
return backslashChar('\\');
case '\r':
return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} | private BasePrinter escapeCharacter(char c) {
if (c == '"') {
return backslashChar(c);
}
switch (c) {
case '\\':
return backslashChar('\\');
case '\r':
return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} |
822 | 1 | // no need to support UTF-8 | private BasePrinter escapeCharacter(char c) {
if (c == '"') {
return backslashChar(c);
}
switch (c) {
case '\\':
return backslashChar('\\');
case '\r':
return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} | NONSATD | true | return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} | return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} | private BasePrinter escapeCharacter(char c) {
if (c == '"') {
return backslashChar(c);
}
switch (c) {
case '\\':
return backslashChar('\\');
case '\r':
return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} |
822 | 2 | // endswitch | private BasePrinter escapeCharacter(char c) {
if (c == '"') {
return backslashChar(c);
}
switch (c) {
case '\\':
return backslashChar('\\');
case '\r':
return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} | NONSATD | true | }
return this.append(c); // no need to support UTF-8
} // endswitch
} | case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} | private BasePrinter escapeCharacter(char c) {
if (c == '"') {
return backslashChar(c);
}
switch (c) {
case '\\':
return backslashChar('\\');
case '\r':
return backslashChar('r');
case '\n':
return backslashChar('n');
case '\t':
return backslashChar('t');
default:
if (c < 32) {
//TODO(bazel-team): support \x escapes
return this.append(String.format("\\x%02x", (int) c));
}
return this.append(c); // no need to support UTF-8
} // endswitch
} |
17,206 | 0 | /**
* Renders the response JSON for tasksInfo API
* The JSON will have an array of task objects under the key tasks.
*/ | public void getTasksInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit);
if(tasks == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>();
for(Task t : tasks) {
Map<String, Object> taskInfo = new HashMap<String, Object>();
taskInfo.put("id", t.getTaskId().toString());
taskInfo.put("progress", Float.toString(t.getProgress()));
taskInfo.put("status", t.getState().toString());
try {
TezCounters counters = t.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
taskInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
tasksInfo.add(taskInfo);
}
renderJSON(ImmutableMap.of(
"tasks", tasksInfo
));
} | NONSATD | true | public void getTasksInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit);
if(tasks == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>();
for(Task t : tasks) {
Map<String, Object> taskInfo = new HashMap<String, Object>();
taskInfo.put("id", t.getTaskId().toString());
taskInfo.put("progress", Float.toString(t.getProgress()));
taskInfo.put("status", t.getState().toString());
try {
TezCounters counters = t.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
taskInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
tasksInfo.add(taskInfo);
}
renderJSON(ImmutableMap.of(
"tasks", tasksInfo
));
} | public void getTasksInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit);
if(tasks == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>();
for(Task t : tasks) {
Map<String, Object> taskInfo = new HashMap<String, Object>();
taskInfo.put("id", t.getTaskId().toString());
taskInfo.put("progress", Float.toString(t.getProgress()));
taskInfo.put("status", t.getState().toString());
try {
TezCounters counters = t.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
taskInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
tasksInfo.add(taskInfo);
}
renderJSON(ImmutableMap.of(
"tasks", tasksInfo
));
} | public void getTasksInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit);
if(tasks == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>();
for(Task t : tasks) {
Map<String, Object> taskInfo = new HashMap<String, Object>();
taskInfo.put("id", t.getTaskId().toString());
taskInfo.put("progress", Float.toString(t.getProgress()));
taskInfo.put("status", t.getState().toString());
try {
TezCounters counters = t.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
taskInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
tasksInfo.add(taskInfo);
}
renderJSON(ImmutableMap.of(
"tasks", tasksInfo
));
} |
17,206 | 1 | //Ignore | public void getTasksInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit);
if(tasks == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>();
for(Task t : tasks) {
Map<String, Object> taskInfo = new HashMap<String, Object>();
taskInfo.put("id", t.getTaskId().toString());
taskInfo.put("progress", Float.toString(t.getProgress()));
taskInfo.put("status", t.getState().toString());
try {
TezCounters counters = t.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
taskInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
tasksInfo.add(taskInfo);
}
renderJSON(ImmutableMap.of(
"tasks", tasksInfo
));
} | NONSATD | true | limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit); | return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit);
if(tasks == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>();
for(Task t : tasks) {
Map<String, Object> taskInfo = new HashMap<String, Object>();
taskInfo.put("id", t.getTaskId().toString()); | public void getTasksInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit);
if(tasks == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>();
for(Task t : tasks) {
Map<String, Object> taskInfo = new HashMap<String, Object>();
taskInfo.put("id", t.getTaskId().toString());
taskInfo.put("progress", Float.toString(t.getProgress()));
taskInfo.put("status", t.getState().toString());
try {
TezCounters counters = t.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
taskInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore |
17,206 | 2 | // Ignore
// TODO: add an error message instead for counter key | public void getTasksInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit);
if(tasks == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>();
for(Task t : tasks) {
Map<String, Object> taskInfo = new HashMap<String, Object>();
taskInfo.put("id", t.getTaskId().toString());
taskInfo.put("progress", Float.toString(t.getProgress()));
taskInfo.put("status", t.getState().toString());
try {
TezCounters counters = t.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
taskInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
tasksInfo.add(taskInfo);
}
renderJSON(ImmutableMap.of(
"tasks", tasksInfo
));
} | IMPLEMENTATION | true | }
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
tasksInfo.add(taskInfo); | taskInfo.put("id", t.getTaskId().toString());
taskInfo.put("progress", Float.toString(t.getProgress()));
taskInfo.put("status", t.getState().toString());
try {
TezCounters counters = t.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
taskInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
tasksInfo.add(taskInfo);
}
renderJSON(ImmutableMap.of(
"tasks", tasksInfo
));
} | //Ignore
}
List<Task> tasks = getRequestedTasks(dag, limit);
if(tasks == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>();
for(Task t : tasks) {
Map<String, Object> taskInfo = new HashMap<String, Object>();
taskInfo.put("id", t.getTaskId().toString());
taskInfo.put("progress", Float.toString(t.getProgress()));
taskInfo.put("status", t.getState().toString());
try {
TezCounters counters = t.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
taskInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
tasksInfo.add(taskInfo);
}
renderJSON(ImmutableMap.of(
"tasks", tasksInfo
));
} |
17,208 | 0 | // TODO AstUtils.getClassFilesForSource(f.toString()); - attempt to get only relevant classpaths for a given source file?
// TODO Naively we can multi-thread here (i.e. per file) but simple testing indicated that this slowed us down. | protected void runOperations(String directoryPath, UseCase useCase) throws IOException {
log.info(System.lineSeparator() +
"================================================" + System.lineSeparator() +
" ____ ____________________ ____" + System.lineSeparator() +
" / \\ / __|__ __| _ \\ / \\" + System.lineSeparator() +
" / /\\ \\ \\ \\ | | | |/ / / /\\ \\" + System.lineSeparator() +
" / /__\\ \\__\\ \\ | | | |\\ \\ / /__\\ \\" + System.lineSeparator() +
" /__/ \\__\\____/ |__| |__| \\__\\__/ \\__\\" + System.lineSeparator() +
"================================================");
log.info("Starting Astra run for directory: " + directoryPath);
AtomicLong currentFileIndex = new AtomicLong();
AtomicLong currentPercentage = new AtomicLong();
log.info("Counting files (this may take a few seconds)");
Instant startTime = Instant.now();
List<Path> javaFilesInDirectory;
try (Stream<Path> walk = Files.walk(Paths.get(directoryPath))) {
javaFilesInDirectory = walk
.filter(f -> f.toFile().isFile())
.filter(f -> f.getFileName().toString().endsWith("java"))
.collect(Collectors.toList());
}
log.info(javaFilesInDirectory.size() + " .java files in directory to review");
log.info("Applying prefilters to files in directory");
Predicate<String> prefilteringPredicate = useCase.getPrefilteringPredicate();
List<Path> filteredJavaFiles = javaFilesInDirectory.stream()
.filter(f -> prefilteringPredicate.test(f.toString()))
.collect(Collectors.toList());
log.info(filteredJavaFiles.size() + " files remain after prefiltering");
final Set<? extends ASTOperation> operations = useCase.getOperations();
final String[] sources = useCase.getSources();
final String[] classPath = useCase.getClassPath();
for (Path f : filteredJavaFiles) {
// TODO AstUtils.getClassFilesForSource(f.toString()); - attempt to get only relevant classpaths for a given source file?
// TODO Naively we can multi-thread here (i.e. per file) but simple testing indicated that this slowed us down.
applyOperationsAndSave(new File(f.toString()), operations, sources, classPath);
long newPercentage = currentFileIndex.incrementAndGet() * 100 / filteredJavaFiles.size();
if (newPercentage != currentPercentage.get()) {
currentPercentage.set(newPercentage);
logProgress(currentFileIndex.get(), currentPercentage.get(), startTime, filteredJavaFiles.size());
}
}
log.info(getPrintableDuration(Duration.between(startTime, Instant.now())));
} | DESIGN | true | final String[] classPath = useCase.getClassPath();
for (Path f : filteredJavaFiles) {
// TODO AstUtils.getClassFilesForSource(f.toString()); - attempt to get only relevant classpaths for a given source file?
// TODO Naively we can multi-thread here (i.e. per file) but simple testing indicated that this slowed us down.
applyOperationsAndSave(new File(f.toString()), operations, sources, classPath);
long newPercentage = currentFileIndex.incrementAndGet() * 100 / filteredJavaFiles.size(); | log.info("Applying prefilters to files in directory");
Predicate<String> prefilteringPredicate = useCase.getPrefilteringPredicate();
List<Path> filteredJavaFiles = javaFilesInDirectory.stream()
.filter(f -> prefilteringPredicate.test(f.toString()))
.collect(Collectors.toList());
log.info(filteredJavaFiles.size() + " files remain after prefiltering");
final Set<? extends ASTOperation> operations = useCase.getOperations();
final String[] sources = useCase.getSources();
final String[] classPath = useCase.getClassPath();
for (Path f : filteredJavaFiles) {
// TODO AstUtils.getClassFilesForSource(f.toString()); - attempt to get only relevant classpaths for a given source file?
// TODO Naively we can multi-thread here (i.e. per file) but simple testing indicated that this slowed us down.
applyOperationsAndSave(new File(f.toString()), operations, sources, classPath);
long newPercentage = currentFileIndex.incrementAndGet() * 100 / filteredJavaFiles.size();
if (newPercentage != currentPercentage.get()) {
currentPercentage.set(newPercentage);
logProgress(currentFileIndex.get(), currentPercentage.get(), startTime, filteredJavaFiles.size());
}
}
log.info(getPrintableDuration(Duration.between(startTime, Instant.now())));
} | log.info("Counting files (this may take a few seconds)");
Instant startTime = Instant.now();
List<Path> javaFilesInDirectory;
try (Stream<Path> walk = Files.walk(Paths.get(directoryPath))) {
javaFilesInDirectory = walk
.filter(f -> f.toFile().isFile())
.filter(f -> f.getFileName().toString().endsWith("java"))
.collect(Collectors.toList());
}
log.info(javaFilesInDirectory.size() + " .java files in directory to review");
log.info("Applying prefilters to files in directory");
Predicate<String> prefilteringPredicate = useCase.getPrefilteringPredicate();
List<Path> filteredJavaFiles = javaFilesInDirectory.stream()
.filter(f -> prefilteringPredicate.test(f.toString()))
.collect(Collectors.toList());
log.info(filteredJavaFiles.size() + " files remain after prefiltering");
final Set<? extends ASTOperation> operations = useCase.getOperations();
final String[] sources = useCase.getSources();
final String[] classPath = useCase.getClassPath();
for (Path f : filteredJavaFiles) {
// TODO AstUtils.getClassFilesForSource(f.toString()); - attempt to get only relevant classpaths for a given source file?
// TODO Naively we can multi-thread here (i.e. per file) but simple testing indicated that this slowed us down.
applyOperationsAndSave(new File(f.toString()), operations, sources, classPath);
long newPercentage = currentFileIndex.incrementAndGet() * 100 / filteredJavaFiles.size();
if (newPercentage != currentPercentage.get()) {
currentPercentage.set(newPercentage);
logProgress(currentFileIndex.get(), currentPercentage.get(), startTime, filteredJavaFiles.size());
}
}
log.info(getPrintableDuration(Duration.between(startTime, Instant.now())));
} |
17,207 | 0 | /**
* Renders the response JSON for attemptsInfo API
* The JSON will have an array of attempt objects under the key attempts.
*/ | public void getAttemptsInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit);
if(attempts == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>();
for(TaskAttempt a : attempts) {
Map<String, Object> attemptInfo = new HashMap<String, Object>();
attemptInfo.put("id", a.getID().toString());
attemptInfo.put("progress", Float.toString(a.getProgress()));
attemptInfo.put("status", a.getState().toString());
try {
TezCounters counters = a.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
attemptInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
attemptsInfo.add(attemptInfo);
}
renderJSON(ImmutableMap.of("attempts", attemptsInfo));
} | NONSATD | true | public void getAttemptsInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit);
if(attempts == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>();
for(TaskAttempt a : attempts) {
Map<String, Object> attemptInfo = new HashMap<String, Object>();
attemptInfo.put("id", a.getID().toString());
attemptInfo.put("progress", Float.toString(a.getProgress()));
attemptInfo.put("status", a.getState().toString());
try {
TezCounters counters = a.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
attemptInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
attemptsInfo.add(attemptInfo);
}
renderJSON(ImmutableMap.of("attempts", attemptsInfo));
} | public void getAttemptsInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit);
if(attempts == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>();
for(TaskAttempt a : attempts) {
Map<String, Object> attemptInfo = new HashMap<String, Object>();
attemptInfo.put("id", a.getID().toString());
attemptInfo.put("progress", Float.toString(a.getProgress()));
attemptInfo.put("status", a.getState().toString());
try {
TezCounters counters = a.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
attemptInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
attemptsInfo.add(attemptInfo);
}
renderJSON(ImmutableMap.of("attempts", attemptsInfo));
} | public void getAttemptsInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit);
if(attempts == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>();
for(TaskAttempt a : attempts) {
Map<String, Object> attemptInfo = new HashMap<String, Object>();
attemptInfo.put("id", a.getID().toString());
attemptInfo.put("progress", Float.toString(a.getProgress()));
attemptInfo.put("status", a.getState().toString());
try {
TezCounters counters = a.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
attemptInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
attemptsInfo.add(attemptInfo);
}
renderJSON(ImmutableMap.of("attempts", attemptsInfo));
} |
17,207 | 1 | //Ignore | public void getAttemptsInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit);
if(attempts == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>();
for(TaskAttempt a : attempts) {
Map<String, Object> attemptInfo = new HashMap<String, Object>();
attemptInfo.put("id", a.getID().toString());
attemptInfo.put("progress", Float.toString(a.getProgress()));
attemptInfo.put("status", a.getState().toString());
try {
TezCounters counters = a.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
attemptInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
attemptsInfo.add(attemptInfo);
}
renderJSON(ImmutableMap.of("attempts", attemptsInfo));
} | NONSATD | true | limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit); | return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit);
if(attempts == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>();
for(TaskAttempt a : attempts) {
Map<String, Object> attemptInfo = new HashMap<String, Object>();
attemptInfo.put("id", a.getID().toString()); | public void getAttemptsInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit);
if(attempts == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>();
for(TaskAttempt a : attempts) {
Map<String, Object> attemptInfo = new HashMap<String, Object>();
attemptInfo.put("id", a.getID().toString());
attemptInfo.put("progress", Float.toString(a.getProgress()));
attemptInfo.put("status", a.getState().toString());
try {
TezCounters counters = a.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
attemptInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore |
17,207 | 2 | // Ignore
// TODO: add an error message instead for counter key | public void getAttemptsInfo() {
if (!setupResponse()) {
return;
}
DAG dag = checkAndGetDAGFromRequest();
if (dag == null) {
return;
}
int limit = MAX_QUERIED;
try {
limit = getQueryParamInt(WebUIService.LIMIT);
} catch (NumberFormatException e) {
//Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit);
if(attempts == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>();
for(TaskAttempt a : attempts) {
Map<String, Object> attemptInfo = new HashMap<String, Object>();
attemptInfo.put("id", a.getID().toString());
attemptInfo.put("progress", Float.toString(a.getProgress()));
attemptInfo.put("status", a.getState().toString());
try {
TezCounters counters = a.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
attemptInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
attemptsInfo.add(attemptInfo);
}
renderJSON(ImmutableMap.of("attempts", attemptsInfo));
} | IMPLEMENTATION | true | }
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
attemptsInfo.add(attemptInfo); | attemptInfo.put("id", a.getID().toString());
attemptInfo.put("progress", Float.toString(a.getProgress()));
attemptInfo.put("status", a.getState().toString());
try {
TezCounters counters = a.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
attemptInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
attemptsInfo.add(attemptInfo);
}
renderJSON(ImmutableMap.of("attempts", attemptsInfo));
} | //Ignore
}
List<TaskAttempt> attempts = getRequestedAttempts(dag, limit);
if(attempts == null) {
return;
}
Map<String, Set<String>> counterNames = getCounterListFromRequest();
ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>();
for(TaskAttempt a : attempts) {
Map<String, Object> attemptInfo = new HashMap<String, Object>();
attemptInfo.put("id", a.getID().toString());
attemptInfo.put("progress", Float.toString(a.getProgress()));
attemptInfo.put("status", a.getState().toString());
try {
TezCounters counters = a.getCounters();
Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
if (counterMap != null && !counterMap.isEmpty()) {
attemptInfo.put("counters", counterMap);
}
} catch (LimitExceededException e) {
// Ignore
// TODO: add an error message instead for counter key
}
attemptsInfo.add(attemptInfo);
}
renderJSON(ImmutableMap.of("attempts", attemptsInfo));
} |
824 | 0 | /**
* Resolve the specific DID in untrusted mode, internal use only.
*
* @param did the DID object to be resolve
* @param force ignore the local cache and resolve from the ID chain if true;
* try to use cache first if false.
* @return the DIDDocument object
* @throws DIDResolveException if an error occurred when resolving DID
*/
// TODO: to be remove in the future | public DIDDocument resolveUntrustedDid(DID did, boolean force)
throws DIDResolveException {
log.debug("Resolving untrusted DID {}...", did.toString());
if (resolveHandle != null) {
DIDDocument doc = resolveHandle.resolve(did);
if (doc != null)
return doc;
}
DIDBiography bio = resolveDidBiography(did, false, force);
DIDTransaction tx = null;
switch (bio.getStatus()) {
case VALID:
tx = bio.getTransaction(0);
break;
case DEACTIVATED:
if (bio.size() != 2)
throw new DIDResolveException("Invalid DID biography, wrong transaction count.");
tx = bio.getTransaction(0);
if (tx.getRequest().getOperation() != IDChainRequest.Operation.DEACTIVATE)
throw new DIDResolveException("Invalid DID biography, wrong status.");
DIDDocument doc = bio.getTransaction(1).getRequest().getDocument();
if (doc == null)
throw new DIDResolveException("Invalid DID biography, invalid trancations.");
tx = bio.getTransaction(1);
break;
case NOT_FOUND:
return null;
}
if (tx.getRequest().getOperation() != IDChainRequest.Operation.CREATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.UPDATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER)
throw new DIDResolveException("Invalid ID transaction, unknown operation.");
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
DIDDocument doc = tx.getRequest().getDocument().clone();
DIDMetadata metadata = doc.getMetadata();
metadata.setTransactionId(tx.getTransactionId());
metadata.setSignature(doc.getProof().getSignature());
metadata.setPublishTime(tx.getTimestamp());
if (bio.getStatus() == DIDBiography.Status.DEACTIVATED)
metadata.setDeactivated(true);
return doc;
} | DESIGN | true | public DIDDocument resolveUntrustedDid(DID did, boolean force)
throws DIDResolveException {
log.debug("Resolving untrusted DID {}...", did.toString());
if (resolveHandle != null) {
DIDDocument doc = resolveHandle.resolve(did);
if (doc != null)
return doc;
}
DIDBiography bio = resolveDidBiography(did, false, force);
DIDTransaction tx = null;
switch (bio.getStatus()) {
case VALID:
tx = bio.getTransaction(0);
break;
case DEACTIVATED:
if (bio.size() != 2)
throw new DIDResolveException("Invalid DID biography, wrong transaction count.");
tx = bio.getTransaction(0);
if (tx.getRequest().getOperation() != IDChainRequest.Operation.DEACTIVATE)
throw new DIDResolveException("Invalid DID biography, wrong status.");
DIDDocument doc = bio.getTransaction(1).getRequest().getDocument();
if (doc == null)
throw new DIDResolveException("Invalid DID biography, invalid trancations.");
tx = bio.getTransaction(1);
break;
case NOT_FOUND:
return null;
}
if (tx.getRequest().getOperation() != IDChainRequest.Operation.CREATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.UPDATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER)
throw new DIDResolveException("Invalid ID transaction, unknown operation.");
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
DIDDocument doc = tx.getRequest().getDocument().clone();
DIDMetadata metadata = doc.getMetadata();
metadata.setTransactionId(tx.getTransactionId());
metadata.setSignature(doc.getProof().getSignature());
metadata.setPublishTime(tx.getTimestamp());
if (bio.getStatus() == DIDBiography.Status.DEACTIVATED)
metadata.setDeactivated(true);
return doc;
} | public DIDDocument resolveUntrustedDid(DID did, boolean force)
throws DIDResolveException {
log.debug("Resolving untrusted DID {}...", did.toString());
if (resolveHandle != null) {
DIDDocument doc = resolveHandle.resolve(did);
if (doc != null)
return doc;
}
DIDBiography bio = resolveDidBiography(did, false, force);
DIDTransaction tx = null;
switch (bio.getStatus()) {
case VALID:
tx = bio.getTransaction(0);
break;
case DEACTIVATED:
if (bio.size() != 2)
throw new DIDResolveException("Invalid DID biography, wrong transaction count.");
tx = bio.getTransaction(0);
if (tx.getRequest().getOperation() != IDChainRequest.Operation.DEACTIVATE)
throw new DIDResolveException("Invalid DID biography, wrong status.");
DIDDocument doc = bio.getTransaction(1).getRequest().getDocument();
if (doc == null)
throw new DIDResolveException("Invalid DID biography, invalid trancations.");
tx = bio.getTransaction(1);
break;
case NOT_FOUND:
return null;
}
if (tx.getRequest().getOperation() != IDChainRequest.Operation.CREATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.UPDATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER)
throw new DIDResolveException("Invalid ID transaction, unknown operation.");
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
DIDDocument doc = tx.getRequest().getDocument().clone();
DIDMetadata metadata = doc.getMetadata();
metadata.setTransactionId(tx.getTransactionId());
metadata.setSignature(doc.getProof().getSignature());
metadata.setPublishTime(tx.getTimestamp());
if (bio.getStatus() == DIDBiography.Status.DEACTIVATED)
metadata.setDeactivated(true);
return doc;
} | public DIDDocument resolveUntrustedDid(DID did, boolean force)
throws DIDResolveException {
log.debug("Resolving untrusted DID {}...", did.toString());
if (resolveHandle != null) {
DIDDocument doc = resolveHandle.resolve(did);
if (doc != null)
return doc;
}
DIDBiography bio = resolveDidBiography(did, false, force);
DIDTransaction tx = null;
switch (bio.getStatus()) {
case VALID:
tx = bio.getTransaction(0);
break;
case DEACTIVATED:
if (bio.size() != 2)
throw new DIDResolveException("Invalid DID biography, wrong transaction count.");
tx = bio.getTransaction(0);
if (tx.getRequest().getOperation() != IDChainRequest.Operation.DEACTIVATE)
throw new DIDResolveException("Invalid DID biography, wrong status.");
DIDDocument doc = bio.getTransaction(1).getRequest().getDocument();
if (doc == null)
throw new DIDResolveException("Invalid DID biography, invalid trancations.");
tx = bio.getTransaction(1);
break;
case NOT_FOUND:
return null;
}
if (tx.getRequest().getOperation() != IDChainRequest.Operation.CREATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.UPDATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER)
throw new DIDResolveException("Invalid ID transaction, unknown operation.");
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
DIDDocument doc = tx.getRequest().getDocument().clone();
DIDMetadata metadata = doc.getMetadata();
metadata.setTransactionId(tx.getTransactionId());
metadata.setSignature(doc.getProof().getSignature());
metadata.setPublishTime(tx.getTimestamp());
if (bio.getStatus() == DIDBiography.Status.DEACTIVATED)
metadata.setDeactivated(true);
return doc;
} |
824 | 1 | // NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache. | public DIDDocument resolveUntrustedDid(DID did, boolean force)
throws DIDResolveException {
log.debug("Resolving untrusted DID {}...", did.toString());
if (resolveHandle != null) {
DIDDocument doc = resolveHandle.resolve(did);
if (doc != null)
return doc;
}
DIDBiography bio = resolveDidBiography(did, false, force);
DIDTransaction tx = null;
switch (bio.getStatus()) {
case VALID:
tx = bio.getTransaction(0);
break;
case DEACTIVATED:
if (bio.size() != 2)
throw new DIDResolveException("Invalid DID biography, wrong transaction count.");
tx = bio.getTransaction(0);
if (tx.getRequest().getOperation() != IDChainRequest.Operation.DEACTIVATE)
throw new DIDResolveException("Invalid DID biography, wrong status.");
DIDDocument doc = bio.getTransaction(1).getRequest().getDocument();
if (doc == null)
throw new DIDResolveException("Invalid DID biography, invalid trancations.");
tx = bio.getTransaction(1);
break;
case NOT_FOUND:
return null;
}
if (tx.getRequest().getOperation() != IDChainRequest.Operation.CREATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.UPDATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER)
throw new DIDResolveException("Invalid ID transaction, unknown operation.");
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
DIDDocument doc = tx.getRequest().getDocument().clone();
DIDMetadata metadata = doc.getMetadata();
metadata.setTransactionId(tx.getTransactionId());
metadata.setSignature(doc.getProof().getSignature());
metadata.setPublishTime(tx.getTimestamp());
if (bio.getStatus() == DIDBiography.Status.DEACTIVATED)
metadata.setDeactivated(true);
return doc;
} | NONSATD | true | tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER)
throw new DIDResolveException("Invalid ID transaction, unknown operation.");
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
DIDDocument doc = tx.getRequest().getDocument().clone();
DIDMetadata metadata = doc.getMetadata(); | throw new DIDResolveException("Invalid DID biography, invalid trancations.");
tx = bio.getTransaction(1);
break;
case NOT_FOUND:
return null;
}
if (tx.getRequest().getOperation() != IDChainRequest.Operation.CREATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.UPDATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER)
throw new DIDResolveException("Invalid ID transaction, unknown operation.");
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
DIDDocument doc = tx.getRequest().getDocument().clone();
DIDMetadata metadata = doc.getMetadata();
metadata.setTransactionId(tx.getTransactionId());
metadata.setSignature(doc.getProof().getSignature());
metadata.setPublishTime(tx.getTimestamp());
if (bio.getStatus() == DIDBiography.Status.DEACTIVATED)
metadata.setDeactivated(true);
return doc;
} | tx = bio.getTransaction(0);
break;
case DEACTIVATED:
if (bio.size() != 2)
throw new DIDResolveException("Invalid DID biography, wrong transaction count.");
tx = bio.getTransaction(0);
if (tx.getRequest().getOperation() != IDChainRequest.Operation.DEACTIVATE)
throw new DIDResolveException("Invalid DID biography, wrong status.");
DIDDocument doc = bio.getTransaction(1).getRequest().getDocument();
if (doc == null)
throw new DIDResolveException("Invalid DID biography, invalid trancations.");
tx = bio.getTransaction(1);
break;
case NOT_FOUND:
return null;
}
if (tx.getRequest().getOperation() != IDChainRequest.Operation.CREATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.UPDATE &&
tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER)
throw new DIDResolveException("Invalid ID transaction, unknown operation.");
// NOTICE: Make a copy from DIDBackend cache.
// Avoid share same DIDDocument instance between DIDBackend
// cache and DIDStore cache.
DIDDocument doc = tx.getRequest().getDocument().clone();
DIDMetadata metadata = doc.getMetadata();
metadata.setTransactionId(tx.getTransactionId());
metadata.setSignature(doc.getProof().getSignature());
metadata.setPublishTime(tx.getTimestamp());
if (bio.getStatus() == DIDBiography.Status.DEACTIVATED)
metadata.setDeactivated(true);
return doc;
} |
825 | 0 | /**
* Private helper that marshals the information from each instance into something that
* Turbine can understand. Override this method for your own implementation for
* parsing Eureka info.
* @param serviceInstance
* @return Instance
*/ | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} | NONSATD | true | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} |
825 | 1 | //TODO: where to get? | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} | DESIGN | true | String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status); | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort())); | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} |
825 | 2 | // TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/ | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} | IMPLEMENTATION | true | if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort())); | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null; | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} |
825 | 3 | // add ports | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} | NONSATD | true | instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure(); | String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
} | private Instance marshall(ServiceInstance serviceInstance) {
String hostname = serviceInstance.getHost();
String cluster = getClusterName(serviceInstance);
Boolean status = Boolean.TRUE; //TODO: where to get?
if (hostname != null && cluster != null && status != null) {
Instance instance = new Instance(hostname, cluster, status);
// TODO: reimplement when metadata is in commons
// add metadata
/*Map<String, String> metadata = instanceInfo.getMetadata();
if (metadata != null) {
instance.getAttributes().putAll(metadata);
}*/
// add ports
instance.getAttributes().put("port", String.valueOf(serviceInstance.getPort()));
boolean securePortEnabled = serviceInstance.isSecure();
if (securePortEnabled) {
instance.getAttributes().put("securePort", String.valueOf(serviceInstance.getPort()));
}
return instance;
}
else {
return null;
}
} |
25,403 | 0 | /**
* Serializes a DOM document to String.
*
* Public for other transformation plugins
* TODO refactor out to own class
*
* @param document The document to serialize.
* @param output The Output to print errors to.
*
* @return The serialized document as string.
*/ | public static String domToString(Document document) {
Source source = new DOMSource(document);
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys. INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
StringWriter sw=new StringWriter();
StreamResult resultStream = new StreamResult(sw);
transformer.transform(source, resultStream);
return sw.toString();
} catch (TransformerException e) {
return e.toString();
}
} | DESIGN | true | public static String domToString(Document document) {
Source source = new DOMSource(document);
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys. INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
StringWriter sw=new StringWriter();
StreamResult resultStream = new StreamResult(sw);
transformer.transform(source, resultStream);
return sw.toString();
} catch (TransformerException e) {
return e.toString();
}
} | public static String domToString(Document document) {
Source source = new DOMSource(document);
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys. INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
StringWriter sw=new StringWriter();
StreamResult resultStream = new StreamResult(sw);
transformer.transform(source, resultStream);
return sw.toString();
} catch (TransformerException e) {
return e.toString();
}
} | public static String domToString(Document document) {
Source source = new DOMSource(document);
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys. INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
StringWriter sw=new StringWriter();
StreamResult resultStream = new StreamResult(sw);
transformer.transform(source, resultStream);
return sw.toString();
} catch (TransformerException e) {
return e.toString();
}
} |
25,405 | 0 | // TODO: Some auto handling here? | public static FragmentHostManager get(View view) {
try {
return Dependency.get(FragmentService.class).getFragmentHostManager(view);
} catch (ClassCastException e) {
// TODO: Some auto handling here?
throw e;
}
} | IMPLEMENTATION | true | return Dependency.get(FragmentService.class).getFragmentHostManager(view);
} catch (ClassCastException e) {
// TODO: Some auto handling here?
throw e;
} | public static FragmentHostManager get(View view) {
try {
return Dependency.get(FragmentService.class).getFragmentHostManager(view);
} catch (ClassCastException e) {
// TODO: Some auto handling here?
throw e;
}
} | public static FragmentHostManager get(View view) {
try {
return Dependency.get(FragmentService.class).getFragmentHostManager(view);
} catch (ClassCastException e) {
// TODO: Some auto handling here?
throw e;
}
} |
831 | 0 | //TODO: change filename param to INT | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} | NONSATD | true | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} |
831 | 1 | //TODO: USE BELOW WHEN INFO IS CHANGED | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} | DESIGN | true | Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId)); | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption); | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} |
831 | 2 | // return new Pair<>(image, caption); | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} | NONSATD | true | Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){ | //TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} |
831 | 3 | //This shouldn't ever happen | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} | NONSATD | true | catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null; | System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} | private Pair<ImageView, String> loadImageWithCaption(int fileId, String caption, Map <String,
Integer> weaponMap, Integer id) {
try {
//TODO: USE BELOW WHEN INFO IS CHANGED
System.out.println(fileId);
var image = new ImageView(myLogic.getImage(fileId));
System.out.println("**********");
System.out.println(image);
weaponMap.put(image.toString(), id);
image.setFitWidth(100);
image.setFitHeight(100);
Pair pair = new Pair<>(image, caption);
return pair;
// return new Pair<>(image, caption);
}
catch(Exception e){
System.out.println(e);
//This shouldn't ever happen
}
return null;
} |
832 | 0 | // TODO: eventually use caching here | public Raster getRaster(int xOffset, int yOffset, int w, int h) {
ColorModel cm = getColorModel();
if (raster == null) createRaster();
// TODO: eventually use caching here
WritableRaster childRaster = cm.createCompatibleWritableRaster(w, h);
Rectangle2D childRect = new Rectangle2D.Double(xOffset, yOffset, w, h);
if (!childRect.intersects(deviceBounds)) {
// usually doesn't happen ...
return childRaster;
}
Rectangle2D destRect = new Rectangle2D.Double();
Rectangle2D.intersect(childRect, deviceBounds, destRect);
int dx = (int)(destRect.getX()-deviceBounds.getX());
int dy = (int)(destRect.getY()-deviceBounds.getY());
int dw = (int)destRect.getWidth();
int dh = (int)destRect.getHeight();
Object data = raster.getDataElements(dx, dy, dw, dh, null);
dx = (int)(destRect.getX()-childRect.getX());
dy = (int)(destRect.getY()-childRect.getY());
childRaster.setDataElements(dx, dy, dw, dh, data);
return childRaster;
} | DESIGN | true | ColorModel cm = getColorModel();
if (raster == null) createRaster();
// TODO: eventually use caching here
WritableRaster childRaster = cm.createCompatibleWritableRaster(w, h);
Rectangle2D childRect = new Rectangle2D.Double(xOffset, yOffset, w, h); | public Raster getRaster(int xOffset, int yOffset, int w, int h) {
ColorModel cm = getColorModel();
if (raster == null) createRaster();
// TODO: eventually use caching here
WritableRaster childRaster = cm.createCompatibleWritableRaster(w, h);
Rectangle2D childRect = new Rectangle2D.Double(xOffset, yOffset, w, h);
if (!childRect.intersects(deviceBounds)) {
// usually doesn't happen ...
return childRaster;
}
Rectangle2D destRect = new Rectangle2D.Double();
Rectangle2D.intersect(childRect, deviceBounds, destRect);
int dx = (int)(destRect.getX()-deviceBounds.getX());
int dy = (int)(destRect.getY()-deviceBounds.getY()); | public Raster getRaster(int xOffset, int yOffset, int w, int h) {
ColorModel cm = getColorModel();
if (raster == null) createRaster();
// TODO: eventually use caching here
WritableRaster childRaster = cm.createCompatibleWritableRaster(w, h);
Rectangle2D childRect = new Rectangle2D.Double(xOffset, yOffset, w, h);
if (!childRect.intersects(deviceBounds)) {
// usually doesn't happen ...
return childRaster;
}
Rectangle2D destRect = new Rectangle2D.Double();
Rectangle2D.intersect(childRect, deviceBounds, destRect);
int dx = (int)(destRect.getX()-deviceBounds.getX());
int dy = (int)(destRect.getY()-deviceBounds.getY());
int dw = (int)destRect.getWidth();
int dh = (int)destRect.getHeight();
Object data = raster.getDataElements(dx, dy, dw, dh, null);
dx = (int)(destRect.getX()-childRect.getX());
dy = (int)(destRect.getY()-childRect.getY());
childRaster.setDataElements(dx, dy, dw, dh, data);
return childRaster;
} |
832 | 1 | // usually doesn't happen ... | public Raster getRaster(int xOffset, int yOffset, int w, int h) {
ColorModel cm = getColorModel();
if (raster == null) createRaster();
// TODO: eventually use caching here
WritableRaster childRaster = cm.createCompatibleWritableRaster(w, h);
Rectangle2D childRect = new Rectangle2D.Double(xOffset, yOffset, w, h);
if (!childRect.intersects(deviceBounds)) {
// usually doesn't happen ...
return childRaster;
}
Rectangle2D destRect = new Rectangle2D.Double();
Rectangle2D.intersect(childRect, deviceBounds, destRect);
int dx = (int)(destRect.getX()-deviceBounds.getX());
int dy = (int)(destRect.getY()-deviceBounds.getY());
int dw = (int)destRect.getWidth();
int dh = (int)destRect.getHeight();
Object data = raster.getDataElements(dx, dy, dw, dh, null);
dx = (int)(destRect.getX()-childRect.getX());
dy = (int)(destRect.getY()-childRect.getY());
childRaster.setDataElements(dx, dy, dw, dh, data);
return childRaster;
} | NONSATD | true | Rectangle2D childRect = new Rectangle2D.Double(xOffset, yOffset, w, h);
if (!childRect.intersects(deviceBounds)) {
// usually doesn't happen ...
return childRaster;
} | public Raster getRaster(int xOffset, int yOffset, int w, int h) {
ColorModel cm = getColorModel();
if (raster == null) createRaster();
// TODO: eventually use caching here
WritableRaster childRaster = cm.createCompatibleWritableRaster(w, h);
Rectangle2D childRect = new Rectangle2D.Double(xOffset, yOffset, w, h);
if (!childRect.intersects(deviceBounds)) {
// usually doesn't happen ...
return childRaster;
}
Rectangle2D destRect = new Rectangle2D.Double();
Rectangle2D.intersect(childRect, deviceBounds, destRect);
int dx = (int)(destRect.getX()-deviceBounds.getX());
int dy = (int)(destRect.getY()-deviceBounds.getY());
int dw = (int)destRect.getWidth();
int dh = (int)destRect.getHeight();
Object data = raster.getDataElements(dx, dy, dw, dh, null);
dx = (int)(destRect.getX()-childRect.getX()); | public Raster getRaster(int xOffset, int yOffset, int w, int h) {
ColorModel cm = getColorModel();
if (raster == null) createRaster();
// TODO: eventually use caching here
WritableRaster childRaster = cm.createCompatibleWritableRaster(w, h);
Rectangle2D childRect = new Rectangle2D.Double(xOffset, yOffset, w, h);
if (!childRect.intersects(deviceBounds)) {
// usually doesn't happen ...
return childRaster;
}
Rectangle2D destRect = new Rectangle2D.Double();
Rectangle2D.intersect(childRect, deviceBounds, destRect);
int dx = (int)(destRect.getX()-deviceBounds.getX());
int dy = (int)(destRect.getY()-deviceBounds.getY());
int dw = (int)destRect.getWidth();
int dh = (int)destRect.getHeight();
Object data = raster.getDataElements(dx, dy, dw, dh, null);
dx = (int)(destRect.getX()-childRect.getX());
dy = (int)(destRect.getY()-childRect.getY());
childRaster.setDataElements(dx, dy, dw, dh, data);
return childRaster;
} |
25,437 | 0 | // TODO(peis): Fix this, we should not assert here. | @Override
public void channelRead0(final ChannelHandlerContext ctx, final RPCMessage msg)
throws IOException {
switch (msg.getType()) {
case RPC_BLOCK_READ_REQUEST:
assert msg instanceof RPCBlockReadRequest;
mBlockHandler.handleBlockReadRequest(ctx, (RPCBlockReadRequest) msg);
break;
case RPC_BLOCK_WRITE_REQUEST:
assert msg instanceof RPCBlockWriteRequest;
mBlockHandler.handleBlockWriteRequest(ctx, (RPCBlockWriteRequest) msg);
break;
case RPC_FILE_READ_REQUEST:
assert msg instanceof RPCFileReadRequest;
mUnderFileSystemHandler.handleFileReadRequest(ctx, (RPCFileReadRequest) msg);
break;
case RPC_FILE_WRITE_REQUEST:
assert msg instanceof RPCFileWriteRequest;
mUnderFileSystemHandler.handleFileWriteRequest(ctx, (RPCFileWriteRequest) msg);
break;
case RPC_ERROR_RESPONSE:
// TODO(peis): Fix this, we should not assert here.
assert msg instanceof RPCErrorResponse;
LOG.error("Received an error response from the client: " + msg.toString());
break;
default:
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.UNKNOWN_MESSAGE_ERROR);
ctx.writeAndFlush(resp);
// TODO(peis): Fix this. We should not throw an exception here.
throw new IllegalArgumentException(
"No handler implementation for rpc msg type: " + msg.getType());
}
} | DESIGN | true | break;
case RPC_ERROR_RESPONSE:
// TODO(peis): Fix this, we should not assert here.
assert msg instanceof RPCErrorResponse;
LOG.error("Received an error response from the client: " + msg.toString()); | break;
case RPC_FILE_READ_REQUEST:
assert msg instanceof RPCFileReadRequest;
mUnderFileSystemHandler.handleFileReadRequest(ctx, (RPCFileReadRequest) msg);
break;
case RPC_FILE_WRITE_REQUEST:
assert msg instanceof RPCFileWriteRequest;
mUnderFileSystemHandler.handleFileWriteRequest(ctx, (RPCFileWriteRequest) msg);
break;
case RPC_ERROR_RESPONSE:
// TODO(peis): Fix this, we should not assert here.
assert msg instanceof RPCErrorResponse;
LOG.error("Received an error response from the client: " + msg.toString());
break;
default:
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.UNKNOWN_MESSAGE_ERROR);
ctx.writeAndFlush(resp);
// TODO(peis): Fix this. We should not throw an exception here.
throw new IllegalArgumentException(
"No handler implementation for rpc msg type: " + msg.getType());
} | public void channelRead0(final ChannelHandlerContext ctx, final RPCMessage msg)
throws IOException {
switch (msg.getType()) {
case RPC_BLOCK_READ_REQUEST:
assert msg instanceof RPCBlockReadRequest;
mBlockHandler.handleBlockReadRequest(ctx, (RPCBlockReadRequest) msg);
break;
case RPC_BLOCK_WRITE_REQUEST:
assert msg instanceof RPCBlockWriteRequest;
mBlockHandler.handleBlockWriteRequest(ctx, (RPCBlockWriteRequest) msg);
break;
case RPC_FILE_READ_REQUEST:
assert msg instanceof RPCFileReadRequest;
mUnderFileSystemHandler.handleFileReadRequest(ctx, (RPCFileReadRequest) msg);
break;
case RPC_FILE_WRITE_REQUEST:
assert msg instanceof RPCFileWriteRequest;
mUnderFileSystemHandler.handleFileWriteRequest(ctx, (RPCFileWriteRequest) msg);
break;
case RPC_ERROR_RESPONSE:
// TODO(peis): Fix this, we should not assert here.
assert msg instanceof RPCErrorResponse;
LOG.error("Received an error response from the client: " + msg.toString());
break;
default:
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.UNKNOWN_MESSAGE_ERROR);
ctx.writeAndFlush(resp);
// TODO(peis): Fix this. We should not throw an exception here.
throw new IllegalArgumentException(
"No handler implementation for rpc msg type: " + msg.getType());
}
} |
25,437 | 1 | // TODO(peis): Fix this. We should not throw an exception here. | @Override
public void channelRead0(final ChannelHandlerContext ctx, final RPCMessage msg)
throws IOException {
switch (msg.getType()) {
case RPC_BLOCK_READ_REQUEST:
assert msg instanceof RPCBlockReadRequest;
mBlockHandler.handleBlockReadRequest(ctx, (RPCBlockReadRequest) msg);
break;
case RPC_BLOCK_WRITE_REQUEST:
assert msg instanceof RPCBlockWriteRequest;
mBlockHandler.handleBlockWriteRequest(ctx, (RPCBlockWriteRequest) msg);
break;
case RPC_FILE_READ_REQUEST:
assert msg instanceof RPCFileReadRequest;
mUnderFileSystemHandler.handleFileReadRequest(ctx, (RPCFileReadRequest) msg);
break;
case RPC_FILE_WRITE_REQUEST:
assert msg instanceof RPCFileWriteRequest;
mUnderFileSystemHandler.handleFileWriteRequest(ctx, (RPCFileWriteRequest) msg);
break;
case RPC_ERROR_RESPONSE:
// TODO(peis): Fix this, we should not assert here.
assert msg instanceof RPCErrorResponse;
LOG.error("Received an error response from the client: " + msg.toString());
break;
default:
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.UNKNOWN_MESSAGE_ERROR);
ctx.writeAndFlush(resp);
// TODO(peis): Fix this. We should not throw an exception here.
throw new IllegalArgumentException(
"No handler implementation for rpc msg type: " + msg.getType());
}
} | DEFECT | true | RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.UNKNOWN_MESSAGE_ERROR);
ctx.writeAndFlush(resp);
// TODO(peis): Fix this. We should not throw an exception here.
throw new IllegalArgumentException(
"No handler implementation for rpc msg type: " + msg.getType()); | mUnderFileSystemHandler.handleFileWriteRequest(ctx, (RPCFileWriteRequest) msg);
break;
case RPC_ERROR_RESPONSE:
// TODO(peis): Fix this, we should not assert here.
assert msg instanceof RPCErrorResponse;
LOG.error("Received an error response from the client: " + msg.toString());
break;
default:
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.UNKNOWN_MESSAGE_ERROR);
ctx.writeAndFlush(resp);
// TODO(peis): Fix this. We should not throw an exception here.
throw new IllegalArgumentException(
"No handler implementation for rpc msg type: " + msg.getType());
}
} | case RPC_BLOCK_WRITE_REQUEST:
assert msg instanceof RPCBlockWriteRequest;
mBlockHandler.handleBlockWriteRequest(ctx, (RPCBlockWriteRequest) msg);
break;
case RPC_FILE_READ_REQUEST:
assert msg instanceof RPCFileReadRequest;
mUnderFileSystemHandler.handleFileReadRequest(ctx, (RPCFileReadRequest) msg);
break;
case RPC_FILE_WRITE_REQUEST:
assert msg instanceof RPCFileWriteRequest;
mUnderFileSystemHandler.handleFileWriteRequest(ctx, (RPCFileWriteRequest) msg);
break;
case RPC_ERROR_RESPONSE:
// TODO(peis): Fix this, we should not assert here.
assert msg instanceof RPCErrorResponse;
LOG.error("Received an error response from the client: " + msg.toString());
break;
default:
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.UNKNOWN_MESSAGE_ERROR);
ctx.writeAndFlush(resp);
// TODO(peis): Fix this. We should not throw an exception here.
throw new IllegalArgumentException(
"No handler implementation for rpc msg type: " + msg.getType());
}
} |
25,438 | 0 | // TODO(peis): This doesn't have to be decode error, it can also be any network errors such as
// connection reset. Fix this ALLUXIO-2235. | @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception thrown while processing request", cause);
// TODO(peis): This doesn't have to be decode error, it can also be any network errors such as
// connection reset. Fix this ALLUXIO-2235.
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.DECODE_ERROR);
ChannelFuture channelFuture = ctx.writeAndFlush(resp);
// Close the channel because it is likely a network error.
channelFuture.addListener(ChannelFutureListener.CLOSE);
} | DEFECT | true | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception thrown while processing request", cause);
// TODO(peis): This doesn't have to be decode error, it can also be any network errors such as
// connection reset. Fix this ALLUXIO-2235.
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.DECODE_ERROR);
ChannelFuture channelFuture = ctx.writeAndFlush(resp); | @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception thrown while processing request", cause);
// TODO(peis): This doesn't have to be decode error, it can also be any network errors such as
// connection reset. Fix this ALLUXIO-2235.
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.DECODE_ERROR);
ChannelFuture channelFuture = ctx.writeAndFlush(resp);
// Close the channel because it is likely a network error.
channelFuture.addListener(ChannelFutureListener.CLOSE);
} | @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception thrown while processing request", cause);
// TODO(peis): This doesn't have to be decode error, it can also be any network errors such as
// connection reset. Fix this ALLUXIO-2235.
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.DECODE_ERROR);
ChannelFuture channelFuture = ctx.writeAndFlush(resp);
// Close the channel because it is likely a network error.
channelFuture.addListener(ChannelFutureListener.CLOSE);
} |
25,438 | 1 | // Close the channel because it is likely a network error. | @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception thrown while processing request", cause);
// TODO(peis): This doesn't have to be decode error, it can also be any network errors such as
// connection reset. Fix this ALLUXIO-2235.
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.DECODE_ERROR);
ChannelFuture channelFuture = ctx.writeAndFlush(resp);
// Close the channel because it is likely a network error.
channelFuture.addListener(ChannelFutureListener.CLOSE);
} | NONSATD | true | RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.DECODE_ERROR);
ChannelFuture channelFuture = ctx.writeAndFlush(resp);
// Close the channel because it is likely a network error.
channelFuture.addListener(ChannelFutureListener.CLOSE);
} | @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception thrown while processing request", cause);
// TODO(peis): This doesn't have to be decode error, it can also be any network errors such as
// connection reset. Fix this ALLUXIO-2235.
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.DECODE_ERROR);
ChannelFuture channelFuture = ctx.writeAndFlush(resp);
// Close the channel because it is likely a network error.
channelFuture.addListener(ChannelFutureListener.CLOSE);
} | @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception thrown while processing request", cause);
// TODO(peis): This doesn't have to be decode error, it can also be any network errors such as
// connection reset. Fix this ALLUXIO-2235.
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.DECODE_ERROR);
ChannelFuture channelFuture = ctx.writeAndFlush(resp);
// Close the channel because it is likely a network error.
channelFuture.addListener(ChannelFutureListener.CLOSE);
} |
17,246 | 0 | // Create filesystem for the given user and given path
// TODO: DX-16001 - make async configurable for Hive. | private boolean checkAccessPermission() throws IOException {
final JobConf jobConf = new JobConf(hiveConf);
Preconditions.checkArgument(updateKey.getCachedEntitiesCount() > 0, "hive partition update key should contain at least one path");
for (FileSystemCachedEntity cachedEntity : updateKey.getCachedEntitiesList()) {
final Path cachedEntityPath;
if (cachedEntity.getPath() == null || cachedEntity.getPath().isEmpty()) {
cachedEntityPath = new Path(updateKey.getPartitionRootDir());
} else {
cachedEntityPath = new Path(updateKey.getPartitionRootDir(), cachedEntity.getPath());
}
// Create filesystem for the given user and given path
// TODO: DX-16001 - make async configurable for Hive.
final HadoopFileSystemWrapper userFS = HiveImpersonationUtil.createFileSystem(user, jobConf, cachedEntityPath);
try {
if (cachedEntity.getIsDir()) {
//DX-7850 : remove once solution for maprfs is found
if (userFS.isMapRfs()) {
userFS.access(cachedEntityPath, FsAction.READ);
} else {
userFS.access(cachedEntityPath, FsAction.READ_EXECUTE);
}
} else {
userFS.access(cachedEntityPath, FsAction.READ);
}
} catch (AccessControlException ace) {
return false;
}
}
return true;
} | IMPLEMENTATION | true | cachedEntityPath = new Path(updateKey.getPartitionRootDir(), cachedEntity.getPath());
}
// Create filesystem for the given user and given path
// TODO: DX-16001 - make async configurable for Hive.
final HadoopFileSystemWrapper userFS = HiveImpersonationUtil.createFileSystem(user, jobConf, cachedEntityPath);
try { | private boolean checkAccessPermission() throws IOException {
final JobConf jobConf = new JobConf(hiveConf);
Preconditions.checkArgument(updateKey.getCachedEntitiesCount() > 0, "hive partition update key should contain at least one path");
for (FileSystemCachedEntity cachedEntity : updateKey.getCachedEntitiesList()) {
final Path cachedEntityPath;
if (cachedEntity.getPath() == null || cachedEntity.getPath().isEmpty()) {
cachedEntityPath = new Path(updateKey.getPartitionRootDir());
} else {
cachedEntityPath = new Path(updateKey.getPartitionRootDir(), cachedEntity.getPath());
}
// Create filesystem for the given user and given path
// TODO: DX-16001 - make async configurable for Hive.
final HadoopFileSystemWrapper userFS = HiveImpersonationUtil.createFileSystem(user, jobConf, cachedEntityPath);
try {
if (cachedEntity.getIsDir()) {
//DX-7850 : remove once solution for maprfs is found
if (userFS.isMapRfs()) {
userFS.access(cachedEntityPath, FsAction.READ);
} else {
userFS.access(cachedEntityPath, FsAction.READ_EXECUTE);
}
} else { | private boolean checkAccessPermission() throws IOException {
final JobConf jobConf = new JobConf(hiveConf);
Preconditions.checkArgument(updateKey.getCachedEntitiesCount() > 0, "hive partition update key should contain at least one path");
for (FileSystemCachedEntity cachedEntity : updateKey.getCachedEntitiesList()) {
final Path cachedEntityPath;
if (cachedEntity.getPath() == null || cachedEntity.getPath().isEmpty()) {
cachedEntityPath = new Path(updateKey.getPartitionRootDir());
} else {
cachedEntityPath = new Path(updateKey.getPartitionRootDir(), cachedEntity.getPath());
}
// Create filesystem for the given user and given path
// TODO: DX-16001 - make async configurable for Hive.
final HadoopFileSystemWrapper userFS = HiveImpersonationUtil.createFileSystem(user, jobConf, cachedEntityPath);
try {
if (cachedEntity.getIsDir()) {
//DX-7850 : remove once solution for maprfs is found
if (userFS.isMapRfs()) {
userFS.access(cachedEntityPath, FsAction.READ);
} else {
userFS.access(cachedEntityPath, FsAction.READ_EXECUTE);
}
} else {
userFS.access(cachedEntityPath, FsAction.READ);
}
} catch (AccessControlException ace) {
return false;
}
}
return true;
} |
17,246 | 1 | //DX-7850 : remove once solution for maprfs is found | private boolean checkAccessPermission() throws IOException {
final JobConf jobConf = new JobConf(hiveConf);
Preconditions.checkArgument(updateKey.getCachedEntitiesCount() > 0, "hive partition update key should contain at least one path");
for (FileSystemCachedEntity cachedEntity : updateKey.getCachedEntitiesList()) {
final Path cachedEntityPath;
if (cachedEntity.getPath() == null || cachedEntity.getPath().isEmpty()) {
cachedEntityPath = new Path(updateKey.getPartitionRootDir());
} else {
cachedEntityPath = new Path(updateKey.getPartitionRootDir(), cachedEntity.getPath());
}
// Create filesystem for the given user and given path
// TODO: DX-16001 - make async configurable for Hive.
final HadoopFileSystemWrapper userFS = HiveImpersonationUtil.createFileSystem(user, jobConf, cachedEntityPath);
try {
if (cachedEntity.getIsDir()) {
//DX-7850 : remove once solution for maprfs is found
if (userFS.isMapRfs()) {
userFS.access(cachedEntityPath, FsAction.READ);
} else {
userFS.access(cachedEntityPath, FsAction.READ_EXECUTE);
}
} else {
userFS.access(cachedEntityPath, FsAction.READ);
}
} catch (AccessControlException ace) {
return false;
}
}
return true;
} | DESIGN | true | try {
if (cachedEntity.getIsDir()) {
//DX-7850 : remove once solution for maprfs is found
if (userFS.isMapRfs()) {
userFS.access(cachedEntityPath, FsAction.READ); | if (cachedEntity.getPath() == null || cachedEntity.getPath().isEmpty()) {
cachedEntityPath = new Path(updateKey.getPartitionRootDir());
} else {
cachedEntityPath = new Path(updateKey.getPartitionRootDir(), cachedEntity.getPath());
}
// Create filesystem for the given user and given path
// TODO: DX-16001 - make async configurable for Hive.
final HadoopFileSystemWrapper userFS = HiveImpersonationUtil.createFileSystem(user, jobConf, cachedEntityPath);
try {
if (cachedEntity.getIsDir()) {
//DX-7850 : remove once solution for maprfs is found
if (userFS.isMapRfs()) {
userFS.access(cachedEntityPath, FsAction.READ);
} else {
userFS.access(cachedEntityPath, FsAction.READ_EXECUTE);
}
} else {
userFS.access(cachedEntityPath, FsAction.READ);
}
} catch (AccessControlException ace) {
return false; | private boolean checkAccessPermission() throws IOException {
final JobConf jobConf = new JobConf(hiveConf);
Preconditions.checkArgument(updateKey.getCachedEntitiesCount() > 0, "hive partition update key should contain at least one path");
for (FileSystemCachedEntity cachedEntity : updateKey.getCachedEntitiesList()) {
final Path cachedEntityPath;
if (cachedEntity.getPath() == null || cachedEntity.getPath().isEmpty()) {
cachedEntityPath = new Path(updateKey.getPartitionRootDir());
} else {
cachedEntityPath = new Path(updateKey.getPartitionRootDir(), cachedEntity.getPath());
}
// Create filesystem for the given user and given path
// TODO: DX-16001 - make async configurable for Hive.
final HadoopFileSystemWrapper userFS = HiveImpersonationUtil.createFileSystem(user, jobConf, cachedEntityPath);
try {
if (cachedEntity.getIsDir()) {
//DX-7850 : remove once solution for maprfs is found
if (userFS.isMapRfs()) {
userFS.access(cachedEntityPath, FsAction.READ);
} else {
userFS.access(cachedEntityPath, FsAction.READ_EXECUTE);
}
} else {
userFS.access(cachedEntityPath, FsAction.READ);
}
} catch (AccessControlException ace) {
return false;
}
}
return true;
} |
17,260 | 0 | /**
* Get the line number corresponding to the specified vertical position.
* If you ask for a position above 0, you get 0; if you ask for a position
* below the bottom of the text, you get the last line.
*/
// FIXME: It may be faster to do a linear search for layouts without many lines. | public int getLineForVertical(int vertical) {
int high = getLineCount(), low = -1, guess;
while (high - low > 1) {
guess = (high + low) / 2;
if (getLineTop(guess) > vertical)
high = guess;
else
low = guess;
}
if (low < 0)
return 0;
else
return low;
} | DESIGN | true | public int getLineForVertical(int vertical) {
int high = getLineCount(), low = -1, guess;
while (high - low > 1) {
guess = (high + low) / 2;
if (getLineTop(guess) > vertical)
high = guess;
else
low = guess;
}
if (low < 0)
return 0;
else
return low;
} | public int getLineForVertical(int vertical) {
int high = getLineCount(), low = -1, guess;
while (high - low > 1) {
guess = (high + low) / 2;
if (getLineTop(guess) > vertical)
high = guess;
else
low = guess;
}
if (low < 0)
return 0;
else
return low;
} | public int getLineForVertical(int vertical) {
int high = getLineCount(), low = -1, guess;
while (high - low > 1) {
guess = (high + low) / 2;
if (getLineTop(guess) > vertical)
high = guess;
else
low = guess;
}
if (low < 0)
return 0;
else
return low;
} |
17,264 | 0 | // ignored | public static NavigableMap<String, Object> readAttrs(Buffer buffer, int version) {
NavigableMap<String, Object> attrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int flags = buffer.getInt();
if (version >= SftpConstants.SFTP_V4) {
int type = buffer.getUByte();
switch (type) {
case SftpConstants.SSH_FILEXFER_TYPE_REGULAR:
attrs.put("isRegular", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY:
attrs.put("isDirectory", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SYMLINK:
attrs.put("isSymbolicLink", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
attrs.put("permissions", permissionsToAttributes(buffer.getInt()));
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
} else if (version >= SftpConstants.SFTP_V4) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACCESSTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_CREATETIME) != 0) {
attrs.put("creationTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MODIFYTIME) != 0) {
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
if ((version >= SftpConstants.SFTP_V6) && (flags & SftpConstants.SSH_FILEXFER_ATTR_CTIME) != 0) {
attrs.put("ctime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} | NONSATD | true | attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
} | break;
case SftpConstants.SSH_FILEXFER_TYPE_SYMLINK:
attrs.put("isSymbolicLink", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
} | NavigableMap<String, Object> attrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int flags = buffer.getInt();
if (version >= SftpConstants.SFTP_V4) {
int type = buffer.getUByte();
switch (type) {
case SftpConstants.SSH_FILEXFER_TYPE_REGULAR:
attrs.put("isRegular", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY:
attrs.put("isDirectory", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SYMLINK:
attrs.put("isSymbolicLink", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
} |
17,264 | 1 | // TODO handle allocation size | public static NavigableMap<String, Object> readAttrs(Buffer buffer, int version) {
NavigableMap<String, Object> attrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int flags = buffer.getInt();
if (version >= SftpConstants.SFTP_V4) {
int type = buffer.getUByte();
switch (type) {
case SftpConstants.SSH_FILEXFER_TYPE_REGULAR:
attrs.put("isRegular", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY:
attrs.put("isDirectory", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SYMLINK:
attrs.put("isSymbolicLink", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
attrs.put("permissions", permissionsToAttributes(buffer.getInt()));
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
} else if (version >= SftpConstants.SFTP_V4) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACCESSTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_CREATETIME) != 0) {
attrs.put("creationTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MODIFYTIME) != 0) {
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
if ((version >= SftpConstants.SFTP_V6) && (flags & SftpConstants.SSH_FILEXFER_ATTR_CTIME) != 0) {
attrs.put("ctime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} | IMPLEMENTATION | true | if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) { | attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
attrs.put("permissions", permissionsToAttributes(buffer.getInt()));
}
if (version == SftpConstants.SFTP_V3) { | case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
attrs.put("permissions", permissionsToAttributes(buffer.getInt()));
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
} else if (version >= SftpConstants.SFTP_V4) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACCESSTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_CREATETIME) != 0) {
attrs.put("creationTime", readTime(buffer, version, flags)); |
17,264 | 2 | // TODO: handle attrib bits | public static NavigableMap<String, Object> readAttrs(Buffer buffer, int version) {
NavigableMap<String, Object> attrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int flags = buffer.getInt();
if (version >= SftpConstants.SFTP_V4) {
int type = buffer.getUByte();
switch (type) {
case SftpConstants.SSH_FILEXFER_TYPE_REGULAR:
attrs.put("isRegular", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY:
attrs.put("isDirectory", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SYMLINK:
attrs.put("isSymbolicLink", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
attrs.put("permissions", permissionsToAttributes(buffer.getInt()));
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
} else if (version >= SftpConstants.SFTP_V4) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACCESSTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_CREATETIME) != 0) {
attrs.put("creationTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MODIFYTIME) != 0) {
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
if ((version >= SftpConstants.SFTP_V6) && (flags & SftpConstants.SSH_FILEXFER_ATTR_CTIME) != 0) {
attrs.put("ctime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} | IMPLEMENTATION | true | valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) { | attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
} | if ((flags & SftpConstants.SSH_FILEXFER_ATTR_CREATETIME) != 0) {
attrs.put("creationTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MODIFYTIME) != 0) {
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
if ((version >= SftpConstants.SFTP_V6) && (flags & SftpConstants.SSH_FILEXFER_ATTR_CTIME) != 0) {
attrs.put("ctime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
} |
17,264 | 3 | // TODO: handle text | public static NavigableMap<String, Object> readAttrs(Buffer buffer, int version) {
NavigableMap<String, Object> attrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int flags = buffer.getInt();
if (version >= SftpConstants.SFTP_V4) {
int type = buffer.getUByte();
switch (type) {
case SftpConstants.SSH_FILEXFER_TYPE_REGULAR:
attrs.put("isRegular", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY:
attrs.put("isDirectory", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SYMLINK:
attrs.put("isSymbolicLink", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
attrs.put("permissions", permissionsToAttributes(buffer.getInt()));
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
} else if (version >= SftpConstants.SFTP_V4) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACCESSTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_CREATETIME) != 0) {
attrs.put("creationTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MODIFYTIME) != 0) {
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
if ((version >= SftpConstants.SFTP_V6) && (flags & SftpConstants.SSH_FILEXFER_ATTR_CTIME) != 0) {
attrs.put("ctime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} | IMPLEMENTATION | true | if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) { | @SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) { | }
if ((version >= SftpConstants.SFTP_V6) && (flags & SftpConstants.SSH_FILEXFER_ATTR_CTIME) != 0) {
attrs.put("ctime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} |
17,264 | 4 | // TODO: handle mime-type | public static NavigableMap<String, Object> readAttrs(Buffer buffer, int version) {
NavigableMap<String, Object> attrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int flags = buffer.getInt();
if (version >= SftpConstants.SFTP_V4) {
int type = buffer.getUByte();
switch (type) {
case SftpConstants.SSH_FILEXFER_TYPE_REGULAR:
attrs.put("isRegular", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY:
attrs.put("isDirectory", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SYMLINK:
attrs.put("isSymbolicLink", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
attrs.put("permissions", permissionsToAttributes(buffer.getInt()));
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
} else if (version >= SftpConstants.SFTP_V4) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACCESSTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_CREATETIME) != 0) {
attrs.put("creationTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MODIFYTIME) != 0) {
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
if ((version >= SftpConstants.SFTP_V6) && (flags & SftpConstants.SSH_FILEXFER_ATTR_CTIME) != 0) {
attrs.put("ctime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} | IMPLEMENTATION | true | if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) { | }
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
} | if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} |
17,264 | 5 | // TODO: handle link-count | public static NavigableMap<String, Object> readAttrs(Buffer buffer, int version) {
NavigableMap<String, Object> attrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int flags = buffer.getInt();
if (version >= SftpConstants.SFTP_V4) {
int type = buffer.getUByte();
switch (type) {
case SftpConstants.SSH_FILEXFER_TYPE_REGULAR:
attrs.put("isRegular", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY:
attrs.put("isDirectory", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SYMLINK:
attrs.put("isSymbolicLink", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
attrs.put("permissions", permissionsToAttributes(buffer.getInt()));
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
} else if (version >= SftpConstants.SFTP_V4) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACCESSTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_CREATETIME) != 0) {
attrs.put("creationTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MODIFYTIME) != 0) {
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
if ((version >= SftpConstants.SFTP_V6) && (flags & SftpConstants.SSH_FILEXFER_ATTR_CTIME) != 0) {
attrs.put("ctime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} | IMPLEMENTATION | true | if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) { | if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
} | @SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} |
17,264 | 6 | // TODO: handle untranslated-name | public static NavigableMap<String, Object> readAttrs(Buffer buffer, int version) {
NavigableMap<String, Object> attrs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
int flags = buffer.getInt();
if (version >= SftpConstants.SFTP_V4) {
int type = buffer.getUByte();
switch (type) {
case SftpConstants.SSH_FILEXFER_TYPE_REGULAR:
attrs.put("isRegular", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY:
attrs.put("isDirectory", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SYMLINK:
attrs.put("isSymbolicLink", Boolean.TRUE);
break;
case SftpConstants.SSH_FILEXFER_TYPE_SOCKET:
case SftpConstants.SSH_FILEXFER_TYPE_CHAR_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_BLOCK_DEVICE:
case SftpConstants.SSH_FILEXFER_TYPE_FIFO:
attrs.put("isOther", Boolean.TRUE);
break;
default: // ignored
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_SIZE) != 0) {
attrs.put("size", buffer.getLong());
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UIDGID) != 0) {
attrs.put("uid", buffer.getInt());
attrs.put("gid", buffer.getInt());
}
} else {
if ((version >= SftpConstants.SFTP_V6) && ((flags & SftpConstants.SSH_FILEXFER_ATTR_ALLOCATION_SIZE) != 0)) {
@SuppressWarnings("unused")
long allocSize = buffer.getLong(); // TODO handle allocation size
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_OWNERGROUP) != 0) {
attrs.put("owner", new DefaultGroupPrincipal(buffer.getString()));
attrs.put("group", new DefaultGroupPrincipal(buffer.getString()));
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
attrs.put("permissions", permissionsToAttributes(buffer.getInt()));
}
if (version == SftpConstants.SFTP_V3) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
} else if (version >= SftpConstants.SFTP_V4) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACCESSTIME) != 0) {
attrs.put("lastAccessTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_CREATETIME) != 0) {
attrs.put("creationTime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MODIFYTIME) != 0) {
attrs.put("lastModifiedTime", readTime(buffer, version, flags));
}
if ((version >= SftpConstants.SFTP_V6) && (flags & SftpConstants.SSH_FILEXFER_ATTR_CTIME) != 0) {
attrs.put("ctime", readTime(buffer, version, flags));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_ACL) != 0) {
attrs.put("acl", readACLs(buffer, version));
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_BITS) != 0) {
@SuppressWarnings("unused")
int bits = buffer.getInt();
@SuppressWarnings("unused")
int valid = 0xffffffff;
if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} | IMPLEMENTATION | true | if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
} | if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} | if (version >= SftpConstants.SFTP_V6) {
valid = buffer.getInt();
}
// TODO: handle attrib bits
}
if (version >= SftpConstants.SFTP_V6) {
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_TEXT_HINT) != 0) {
@SuppressWarnings("unused")
boolean text = buffer.getBoolean(); // TODO: handle text
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_MIME_TYPE) != 0) {
@SuppressWarnings("unused")
String mimeType = buffer.getString(); // TODO: handle mime-type
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_LINK_COUNT) != 0) {
@SuppressWarnings("unused")
int nlink = buffer.getInt(); // TODO: handle link-count
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_UNTRANSLATED_NAME) != 0) {
@SuppressWarnings("unused")
String untranslated = buffer.getString(); // TODO: handle untranslated-name
}
}
}
if ((flags & SftpConstants.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
attrs.put("extended", readExtensions(buffer));
}
return attrs;
} |
17,267 | 0 | // xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains() | public void split (FeatureSelection fs)
{
if (ilist == null)
throw new IllegalStateException ("Frozen. Cannot split.");
InstanceList ilist0 = new InstanceList (ilist.getPipe());
InstanceList ilist1 = new InstanceList (ilist.getPipe());
for (int i = 0; i < ilist.size(); i++) {
Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
}
}
logger.info("child0="+ilist0.size()+" child1="+ilist1.size());
child0 = new Node (ilist0, this, fs);
child1 = new Node (ilist1, this, fs);
} | TEST | true | Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i)); | public void split (FeatureSelection fs)
{
if (ilist == null)
throw new IllegalStateException ("Frozen. Cannot split.");
InstanceList ilist0 = new InstanceList (ilist.getPipe());
InstanceList ilist1 = new InstanceList (ilist.getPipe());
for (int i = 0; i < ilist.size(); i++) {
Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
}
}
logger.info("child0="+ilist0.size()+" child1="+ilist1.size());
child0 = new Node (ilist0, this, fs); | public void split (FeatureSelection fs)
{
if (ilist == null)
throw new IllegalStateException ("Frozen. Cannot split.");
InstanceList ilist0 = new InstanceList (ilist.getPipe());
InstanceList ilist1 = new InstanceList (ilist.getPipe());
for (int i = 0; i < ilist.size(); i++) {
Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
}
}
logger.info("child0="+ilist0.size()+" child1="+ilist1.size());
child0 = new Node (ilist0, this, fs);
child1 = new Node (ilist1, this, fs);
} |
17,267 | 1 | //System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i)); | public void split (FeatureSelection fs)
{
if (ilist == null)
throw new IllegalStateException ("Frozen. Cannot split.");
InstanceList ilist0 = new InstanceList (ilist.getPipe());
InstanceList ilist1 = new InstanceList (ilist.getPipe());
for (int i = 0; i < ilist.size(); i++) {
Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
}
}
logger.info("child0="+ilist0.size()+" child1="+ilist1.size());
child0 = new Node (ilist0, this, fs);
child1 = new Node (ilist1, this, fs);
} | NONSATD | true | // Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else { | if (ilist == null)
throw new IllegalStateException ("Frozen. Cannot split.");
InstanceList ilist0 = new InstanceList (ilist.getPipe());
InstanceList ilist1 = new InstanceList (ilist.getPipe());
for (int i = 0; i < ilist.size(); i++) {
Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
}
}
logger.info("child0="+ilist0.size()+" child1="+ilist1.size());
child0 = new Node (ilist0, this, fs);
child1 = new Node (ilist1, this, fs);
} | public void split (FeatureSelection fs)
{
if (ilist == null)
throw new IllegalStateException ("Frozen. Cannot split.");
InstanceList ilist0 = new InstanceList (ilist.getPipe());
InstanceList ilist1 = new InstanceList (ilist.getPipe());
for (int i = 0; i < ilist.size(); i++) {
Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
}
}
logger.info("child0="+ilist0.size()+" child1="+ilist1.size());
child0 = new Node (ilist0, this, fs);
child1 = new Node (ilist1, this, fs);
} |
17,267 | 2 | //System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i)); | public void split (FeatureSelection fs)
{
if (ilist == null)
throw new IllegalStateException ("Frozen. Cannot split.");
InstanceList ilist0 = new InstanceList (ilist.getPipe());
InstanceList ilist1 = new InstanceList (ilist.getPipe());
for (int i = 0; i < ilist.size(); i++) {
Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
}
}
logger.info("child0="+ilist0.size()+" child1="+ilist1.size());
child0 = new Node (ilist0, this, fs);
child1 = new Node (ilist1, this, fs);
} | NONSATD | true | ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
} | InstanceList ilist1 = new InstanceList (ilist.getPipe());
for (int i = 0; i < ilist.size(); i++) {
Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
}
}
logger.info("child0="+ilist0.size()+" child1="+ilist1.size());
child0 = new Node (ilist0, this, fs);
child1 = new Node (ilist1, this, fs);
} | public void split (FeatureSelection fs)
{
if (ilist == null)
throw new IllegalStateException ("Frozen. Cannot split.");
InstanceList ilist0 = new InstanceList (ilist.getPipe());
InstanceList ilist1 = new InstanceList (ilist.getPipe());
for (int i = 0; i < ilist.size(); i++) {
Instance instance = ilist.getInstance(i);
FeatureVector fv = (FeatureVector) instance.getData ();
// xxx What test should this be? What to do with negative values?
// Whatever is decided here should also go in InfoGain.calcInfoGains()
if (fv.value (featureIndex) != 0) {
//System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist1.add (instance, ilist.getInstanceWeight(i));
} else {
//System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i));
ilist0.add (instance, ilist.getInstanceWeight(i));
}
}
logger.info("child0="+ilist0.size()+" child1="+ilist1.size());
child0 = new Node (ilist0, this, fs);
child1 = new Node (ilist1, this, fs);
} |
25,463 | 0 | /**
* <p>Constructs the textual content of the given node and
* recursively the textual content of its sub element nodes.
* Appends the result to the given StringBuilder.</p>
*
* @param node XML node
* @param sb StringBuilder that will contain the textual content of the node
*/ | public static void getText(Node node, StringBuilder sb) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' '); // BUG: this is a hack
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
getText(child, sb);
}
}
} | NONSATD | true | public static void getText(Node node, StringBuilder sb) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' '); // BUG: this is a hack
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
getText(child, sb);
}
}
} | public static void getText(Node node, StringBuilder sb) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' '); // BUG: this is a hack
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
getText(child, sb);
}
}
} | public static void getText(Node node, StringBuilder sb) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' '); // BUG: this is a hack
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
getText(child, sb);
}
}
} |
25,463 | 1 | // BUG: this is a hack | public static void getText(Node node, StringBuilder sb) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' '); // BUG: this is a hack
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
getText(child, sb);
}
}
} | DEFECT | true | Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' '); // BUG: this is a hack
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) { | public static void getText(Node node, StringBuilder sb) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' '); // BUG: this is a hack
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
getText(child, sb);
}
}
} | public static void getText(Node node, StringBuilder sb) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(' '); // BUG: this is a hack
sb.append(child.getNodeValue().trim());
} else if (child.getNodeType() == Node.ELEMENT_NODE) {
getText(child, sb);
}
}
} |
17,282 | 0 | // | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} | NONSATD | true | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,// | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader); | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} |
17,282 | 1 | // | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} | NONSATD | true | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,// | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader); | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} |
17,282 | 2 | // | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} | NONSATD | true | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,// | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader); | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} |
17,282 | 3 | // | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} | NONSATD | true | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,// | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader); | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} |
17,282 | 4 | // server replied bare NTLM => we didn't preemptively sent Type1Msg | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} | NONSATD | true | NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} |
17,282 | 5 | // FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched) | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} | DEFECT | true | // server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false); | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
} | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} |
17,282 | 6 | // FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched) | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} | DEFECT | true | // server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false); | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
} | private void ntlmProxyChallenge(String authenticateHeader,//
Request request,//
HttpHeaders requestHeaders,//
Realm proxyRealm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.getInProxyAuth().set(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
} |
17,289 | 0 | //Do not use getClass() here... a typical weld issue... | @PostConstruct
public void setup(){
//Do not use getClass() here... a typical weld issue...
endpointUrl=appConfiguration.getBaseEndpoint() + ServiceProviderConfigWS.class.getAnnotation(Path.class).value();
} | DEFECT | true | @PostConstruct
public void setup(){
//Do not use getClass() here... a typical weld issue...
endpointUrl=appConfiguration.getBaseEndpoint() + ServiceProviderConfigWS.class.getAnnotation(Path.class).value();
} | @PostConstruct
public void setup(){
//Do not use getClass() here... a typical weld issue...
endpointUrl=appConfiguration.getBaseEndpoint() + ServiceProviderConfigWS.class.getAnnotation(Path.class).value();
} | @PostConstruct
public void setup(){
//Do not use getClass() here... a typical weld issue...
endpointUrl=appConfiguration.getBaseEndpoint() + ServiceProviderConfigWS.class.getAnnotation(Path.class).value();
} |
25,484 | 0 | /** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1434">[CALCITE-1434]
* AggregateFunctionImpl doesnt work if the class implements a generic
* interface</a>. */ | @Test public void testUserDefinedAggregateFunctionImplementsInterface() {
final String empDept = JdbcTest.EmpDeptTableFactory.class.getName();
final String mySum3 = Smalls.MySum3.class.getName();
final String model = "{\n"
+ " version: '1.0',\n"
+ " schemas: [\n"
+ " {\n"
+ " name: 'adhoc',\n"
+ " tables: [\n"
+ " {\n"
+ " name: 'EMPLOYEES',\n"
+ " type: 'custom',\n"
+ " factory: '" + empDept + "',\n"
+ " operand: {'foo': true, 'bar': 345}\n"
+ " }\n"
+ " ],\n"
+ " functions: [\n"
+ " {\n"
+ " name: 'MY_SUM3',\n"
+ " className: '" + mySum3 + "'\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ "}";
final CalciteAssert.AssertThat with = CalciteAssert.model(model)
.withDefaultSchema("adhoc");
with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n")
.returns("P=50\n");
with.withDefaultSchema(null)
.query("select \"adhoc\".my_sum3(\"deptno\") as p\n"
+ "from \"adhoc\".EMPLOYEES\n")
.returns("P=50\n");
with.query("select my_sum3(\"empid\"), \"deptno\" as p from EMPLOYEES\n")
.throws_("Expression 'deptno' is not being grouped");
with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n")
.returns("P=50\n");
with.query("select my_sum3(\"name\") as p from EMPLOYEES\n")
.throws_("No match found for function signature MY_SUM3(<CHARACTER>)");
with.query("select my_sum3(\"deptno\", 1) as p from EMPLOYEES\n")
.throws_("No match found for function signature "
+ "MY_SUM3(<NUMERIC>, <NUMERIC>)");
with.query("select my_sum3() as p from EMPLOYEES\n")
.throws_("No match found for function signature MY_SUM3()");
with.query("select \"deptno\", my_sum3(\"deptno\") as p from EMPLOYEES\n"
+ "group by \"deptno\"")
.returnsUnordered("deptno=20; P=20",
"deptno=10; P=30");
} | TEST | true | @Test public void testUserDefinedAggregateFunctionImplementsInterface() {
final String empDept = JdbcTest.EmpDeptTableFactory.class.getName();
final String mySum3 = Smalls.MySum3.class.getName();
final String model = "{\n"
+ " version: '1.0',\n"
+ " schemas: [\n"
+ " {\n"
+ " name: 'adhoc',\n"
+ " tables: [\n"
+ " {\n"
+ " name: 'EMPLOYEES',\n"
+ " type: 'custom',\n"
+ " factory: '" + empDept + "',\n"
+ " operand: {'foo': true, 'bar': 345}\n"
+ " }\n"
+ " ],\n"
+ " functions: [\n"
+ " {\n"
+ " name: 'MY_SUM3',\n"
+ " className: '" + mySum3 + "'\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ "}";
final CalciteAssert.AssertThat with = CalciteAssert.model(model)
.withDefaultSchema("adhoc");
with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n")
.returns("P=50\n");
with.withDefaultSchema(null)
.query("select \"adhoc\".my_sum3(\"deptno\") as p\n"
+ "from \"adhoc\".EMPLOYEES\n")
.returns("P=50\n");
with.query("select my_sum3(\"empid\"), \"deptno\" as p from EMPLOYEES\n")
.throws_("Expression 'deptno' is not being grouped");
with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n")
.returns("P=50\n");
with.query("select my_sum3(\"name\") as p from EMPLOYEES\n")
.throws_("No match found for function signature MY_SUM3(<CHARACTER>)");
with.query("select my_sum3(\"deptno\", 1) as p from EMPLOYEES\n")
.throws_("No match found for function signature "
+ "MY_SUM3(<NUMERIC>, <NUMERIC>)");
with.query("select my_sum3() as p from EMPLOYEES\n")
.throws_("No match found for function signature MY_SUM3()");
with.query("select \"deptno\", my_sum3(\"deptno\") as p from EMPLOYEES\n"
+ "group by \"deptno\"")
.returnsUnordered("deptno=20; P=20",
"deptno=10; P=30");
} | @Test public void testUserDefinedAggregateFunctionImplementsInterface() {
final String empDept = JdbcTest.EmpDeptTableFactory.class.getName();
final String mySum3 = Smalls.MySum3.class.getName();
final String model = "{\n"
+ " version: '1.0',\n"
+ " schemas: [\n"
+ " {\n"
+ " name: 'adhoc',\n"
+ " tables: [\n"
+ " {\n"
+ " name: 'EMPLOYEES',\n"
+ " type: 'custom',\n"
+ " factory: '" + empDept + "',\n"
+ " operand: {'foo': true, 'bar': 345}\n"
+ " }\n"
+ " ],\n"
+ " functions: [\n"
+ " {\n"
+ " name: 'MY_SUM3',\n"
+ " className: '" + mySum3 + "'\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ "}";
final CalciteAssert.AssertThat with = CalciteAssert.model(model)
.withDefaultSchema("adhoc");
with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n")
.returns("P=50\n");
with.withDefaultSchema(null)
.query("select \"adhoc\".my_sum3(\"deptno\") as p\n"
+ "from \"adhoc\".EMPLOYEES\n")
.returns("P=50\n");
with.query("select my_sum3(\"empid\"), \"deptno\" as p from EMPLOYEES\n")
.throws_("Expression 'deptno' is not being grouped");
with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n")
.returns("P=50\n");
with.query("select my_sum3(\"name\") as p from EMPLOYEES\n")
.throws_("No match found for function signature MY_SUM3(<CHARACTER>)");
with.query("select my_sum3(\"deptno\", 1) as p from EMPLOYEES\n")
.throws_("No match found for function signature "
+ "MY_SUM3(<NUMERIC>, <NUMERIC>)");
with.query("select my_sum3() as p from EMPLOYEES\n")
.throws_("No match found for function signature MY_SUM3()");
with.query("select \"deptno\", my_sum3(\"deptno\") as p from EMPLOYEES\n"
+ "group by \"deptno\"")
.returnsUnordered("deptno=20; P=20",
"deptno=10; P=30");
} | @Test public void testUserDefinedAggregateFunctionImplementsInterface() {
final String empDept = JdbcTest.EmpDeptTableFactory.class.getName();
final String mySum3 = Smalls.MySum3.class.getName();
final String model = "{\n"
+ " version: '1.0',\n"
+ " schemas: [\n"
+ " {\n"
+ " name: 'adhoc',\n"
+ " tables: [\n"
+ " {\n"
+ " name: 'EMPLOYEES',\n"
+ " type: 'custom',\n"
+ " factory: '" + empDept + "',\n"
+ " operand: {'foo': true, 'bar': 345}\n"
+ " }\n"
+ " ],\n"
+ " functions: [\n"
+ " {\n"
+ " name: 'MY_SUM3',\n"
+ " className: '" + mySum3 + "'\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ "}";
final CalciteAssert.AssertThat with = CalciteAssert.model(model)
.withDefaultSchema("adhoc");
with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n")
.returns("P=50\n");
with.withDefaultSchema(null)
.query("select \"adhoc\".my_sum3(\"deptno\") as p\n"
+ "from \"adhoc\".EMPLOYEES\n")
.returns("P=50\n");
with.query("select my_sum3(\"empid\"), \"deptno\" as p from EMPLOYEES\n")
.throws_("Expression 'deptno' is not being grouped");
with.query("select my_sum3(\"deptno\") as p from EMPLOYEES\n")
.returns("P=50\n");
with.query("select my_sum3(\"name\") as p from EMPLOYEES\n")
.throws_("No match found for function signature MY_SUM3(<CHARACTER>)");
with.query("select my_sum3(\"deptno\", 1) as p from EMPLOYEES\n")
.throws_("No match found for function signature "
+ "MY_SUM3(<NUMERIC>, <NUMERIC>)");
with.query("select my_sum3() as p from EMPLOYEES\n")
.throws_("No match found for function signature MY_SUM3()");
with.query("select \"deptno\", my_sum3(\"deptno\") as p from EMPLOYEES\n"
+ "group by \"deptno\"")
.returnsUnordered("deptno=20; P=20",
"deptno=10; P=30");
} |
25,500 | 0 | // PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available | @Override
public void generateNormalAppearance()
{
PDAnnotationInk ink = (PDAnnotationInk) getAnnotation();
PDColor color = ink.getColor();
if (color == null || color.getComponents().length == 0)
{
return;
}
// PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle());
if (Float.compare(ab.width, 0) == 0)
{
return;
}
// Adjust rectangle even if not empty
// file from PDF.js issue 13447
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
PDRectangle rect = ink.getRectangle();
rect.setLowerLeftX(Math.min(minX - ab.width * 2, rect.getLowerLeftX()));
rect.setLowerLeftY(Math.min(minY - ab.width * 2, rect.getLowerLeftY()));
rect.setUpperRightX(Math.max(maxX + ab.width * 2, rect.getUpperRightX()));
rect.setUpperRightY(Math.max(maxY + ab.width * 2, rect.getUpperRightY()));
ink.setRectangle(rect);
try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream())
{
setOpacity(cs, ink.getConstantOpacity());
cs.setStrokingColor(color);
if (ab.dashArray != null)
{
cs.setLineDashPattern(ab.dashArray, 0);
}
cs.setLineWidth(ab.width);
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
// "When drawn, the points shall be connected by straight lines or curves
// in an implementation-dependent way" - we do lines.
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
if (i == 0)
{
cs.moveTo(x, y);
}
else
{
cs.lineTo(x, y);
}
}
cs.stroke();
}
}
catch (IOException ex)
{
LOG.error(ex);
}
} | NONSATD | true | return;
}
// PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle());
if (Float.compare(ab.width, 0) == 0) | @Override
public void generateNormalAppearance()
{
PDAnnotationInk ink = (PDAnnotationInk) getAnnotation();
PDColor color = ink.getColor();
if (color == null || color.getComponents().length == 0)
{
return;
}
// PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle());
if (Float.compare(ab.width, 0) == 0)
{
return;
}
// Adjust rectangle even if not empty
// file from PDF.js issue 13447
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE; | @Override
public void generateNormalAppearance()
{
PDAnnotationInk ink = (PDAnnotationInk) getAnnotation();
PDColor color = ink.getColor();
if (color == null || color.getComponents().length == 0)
{
return;
}
// PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle());
if (Float.compare(ab.width, 0) == 0)
{
return;
}
// Adjust rectangle even if not empty
// file from PDF.js issue 13447
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
minX = Math.min(minX, x); |
25,500 | 1 | // Adjust rectangle even if not empty
// file from PDF.js issue 13447
//TODO in a class structure this should be overridable | @Override
public void generateNormalAppearance()
{
PDAnnotationInk ink = (PDAnnotationInk) getAnnotation();
PDColor color = ink.getColor();
if (color == null || color.getComponents().length == 0)
{
return;
}
// PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle());
if (Float.compare(ab.width, 0) == 0)
{
return;
}
// Adjust rectangle even if not empty
// file from PDF.js issue 13447
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
PDRectangle rect = ink.getRectangle();
rect.setLowerLeftX(Math.min(minX - ab.width * 2, rect.getLowerLeftX()));
rect.setLowerLeftY(Math.min(minY - ab.width * 2, rect.getLowerLeftY()));
rect.setUpperRightX(Math.max(maxX + ab.width * 2, rect.getUpperRightX()));
rect.setUpperRightY(Math.max(maxY + ab.width * 2, rect.getUpperRightY()));
ink.setRectangle(rect);
try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream())
{
setOpacity(cs, ink.getConstantOpacity());
cs.setStrokingColor(color);
if (ab.dashArray != null)
{
cs.setLineDashPattern(ab.dashArray, 0);
}
cs.setLineWidth(ab.width);
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
// "When drawn, the points shall be connected by straight lines or curves
// in an implementation-dependent way" - we do lines.
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
if (i == 0)
{
cs.moveTo(x, y);
}
else
{
cs.lineTo(x, y);
}
}
cs.stroke();
}
}
catch (IOException ex)
{
LOG.error(ex);
}
} | DESIGN | true | return;
}
// Adjust rectangle even if not empty
// file from PDF.js issue 13447
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE; | if (color == null || color.getComponents().length == 0)
{
return;
}
// PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle());
if (Float.compare(ab.width, 0) == 0)
{
return;
}
// Adjust rectangle even if not empty
// file from PDF.js issue 13447
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2]; | @Override
public void generateNormalAppearance()
{
PDAnnotationInk ink = (PDAnnotationInk) getAnnotation();
PDColor color = ink.getColor();
if (color == null || color.getComponents().length == 0)
{
return;
}
// PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle());
if (Float.compare(ab.width, 0) == 0)
{
return;
}
// Adjust rectangle even if not empty
// file from PDF.js issue 13447
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
PDRectangle rect = ink.getRectangle();
rect.setLowerLeftX(Math.min(minX - ab.width * 2, rect.getLowerLeftX()));
rect.setLowerLeftY(Math.min(minY - ab.width * 2, rect.getLowerLeftY())); |
25,500 | 2 | // "When drawn, the points shall be connected by straight lines or curves
// in an implementation-dependent way" - we do lines. | @Override
public void generateNormalAppearance()
{
PDAnnotationInk ink = (PDAnnotationInk) getAnnotation();
PDColor color = ink.getColor();
if (color == null || color.getComponents().length == 0)
{
return;
}
// PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(ink, ink.getBorderStyle());
if (Float.compare(ab.width, 0) == 0)
{
return;
}
// Adjust rectangle even if not empty
// file from PDF.js issue 13447
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
PDRectangle rect = ink.getRectangle();
rect.setLowerLeftX(Math.min(minX - ab.width * 2, rect.getLowerLeftX()));
rect.setLowerLeftY(Math.min(minY - ab.width * 2, rect.getLowerLeftY()));
rect.setUpperRightX(Math.max(maxX + ab.width * 2, rect.getUpperRightX()));
rect.setUpperRightY(Math.max(maxY + ab.width * 2, rect.getUpperRightY()));
ink.setRectangle(rect);
try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream())
{
setOpacity(cs, ink.getConstantOpacity());
cs.setStrokingColor(color);
if (ab.dashArray != null)
{
cs.setLineDashPattern(ab.dashArray, 0);
}
cs.setLineWidth(ab.width);
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
// "When drawn, the points shall be connected by straight lines or curves
// in an implementation-dependent way" - we do lines.
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
if (i == 0)
{
cs.moveTo(x, y);
}
else
{
cs.lineTo(x, y);
}
}
cs.stroke();
}
}
catch (IOException ex)
{
LOG.error(ex);
}
} | NONSATD | true | {
int nPoints = pathArray.length / 2;
// "When drawn, the points shall be connected by straight lines or curves
// in an implementation-dependent way" - we do lines.
for (int i = 0; i < nPoints; ++i)
{ | setOpacity(cs, ink.getConstantOpacity());
cs.setStrokingColor(color);
if (ab.dashArray != null)
{
cs.setLineDashPattern(ab.dashArray, 0);
}
cs.setLineWidth(ab.width);
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
// "When drawn, the points shall be connected by straight lines or curves
// in an implementation-dependent way" - we do lines.
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
if (i == 0)
{
cs.moveTo(x, y);
}
else
{ | }
}
PDRectangle rect = ink.getRectangle();
rect.setLowerLeftX(Math.min(minX - ab.width * 2, rect.getLowerLeftX()));
rect.setLowerLeftY(Math.min(minY - ab.width * 2, rect.getLowerLeftY()));
rect.setUpperRightX(Math.max(maxX + ab.width * 2, rect.getUpperRightX()));
rect.setUpperRightY(Math.max(maxY + ab.width * 2, rect.getUpperRightY()));
ink.setRectangle(rect);
try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream())
{
setOpacity(cs, ink.getConstantOpacity());
cs.setStrokingColor(color);
if (ab.dashArray != null)
{
cs.setLineDashPattern(ab.dashArray, 0);
}
cs.setLineWidth(ab.width);
for (float[] pathArray : ink.getInkList())
{
int nPoints = pathArray.length / 2;
// "When drawn, the points shall be connected by straight lines or curves
// in an implementation-dependent way" - we do lines.
for (int i = 0; i < nPoints; ++i)
{
float x = pathArray[i * 2];
float y = pathArray[i * 2 + 1];
if (i == 0)
{
cs.moveTo(x, y);
}
else
{
cs.lineTo(x, y);
}
}
cs.stroke();
}
}
catch (IOException ex)
{
LOG.error(ex);
} |
17,318 | 0 | // Store chnages in manifest | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | NONSATD | true | void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) { | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages(); |
17,318 | 1 | // store localized info | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | NONSATD | true | // Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store(); | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) { |
17,318 | 2 | // XXX else ignore for now but we could save into some default location | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | DESIGN | true | if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) { | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages |
17,318 | 3 | // Store project.xml changes
// store module dependencies | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | NONSATD | true | } // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) { | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
} | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true; |
17,318 | 4 | // NOI18N | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | NONSATD | true | if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave); | // store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) { | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel); |
17,318 | 5 | // store friends packages | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | NONSATD | true | boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages | try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>(); | if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
} |
17,318 | 6 | // store public packages | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | NONSATD | true | if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
} | } catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath(); | } // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left |
17,318 | 7 | // store class-path-extensions + its src & javadoc | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | NONSATD | true | refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel); | Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt(); | if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) { |
17,318 | 8 | // delete removed JARs, remove any remaining exported packages and src&javadoc refs left | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | NONSATD | true | }
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values()); | String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete(); | } else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
} |
17,318 | 9 | // XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// } | @Override
void storeProperties() throws IOException {
super.storeProperties();
// Store chnages in manifest
storeManifestChanges();
// store localized info
if (bundleInfo != null && bundleInfo.isModified()) {
bundleInfo.store();
} // XXX else ignore for now but we could save into some default location
ProjectXMLManager pxm = getProjectXMLManager();
// Store project.xml changes
// store module dependencies
DependencyListModel dependencyModel = getDependenciesListModel();
if (dependencyModel.isChanged()) {
Set<ModuleDependency> depsToSave = new TreeSet<ModuleDependency>(dependencyModel.getDependencies());
logNetBeansAPIUsage("DEPENDENCIES", dependencyModel.getDependencies()); // NOI18N
try {
pxm.replaceDependencies(depsToSave);
} catch (CyclicDependencyException ex) {
throw new IOException(ex);
}
}
Set<String> friends = getFriendListModel().getFriends();
Set<String> publicPkgs = getPublicPackagesModel().getSelectedPackages();
boolean refreshModuleList = false;
if (getPublicPackagesModel().isChanged() || getFriendListModel().isChanged()) {
if (friends.size() > 0) { // store friends packages
pxm.replaceFriends(friends, publicPkgs);
} else { // store public packages
pxm.replacePublicPackages(publicPkgs);
}
refreshModuleList = true;
}
// store class-path-extensions + its src & javadoc
if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) {
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), true);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(ModuleList.findNetBeansOrg(getProjectDirectoryFile()));
}
}
} | DEFECT | true | Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper()); | newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) { | if (cps != null && wrappedJarsListModel != null && wrappedJarsChanged) {
final List<Item> cpExtList = ClassPathUiSupport.getList(wrappedJarsListModel);
Map<String, String> newCpExt = new HashMap<String, String>();
for (Item item : cpExtList) {
String binPath = item.getFilePath();
if (binPath != null) {
FileObject fo = FileUtil.toFileObject(PropertyUtils.resolveFile(getProjectDirectoryFile(), binPath));
if(fo != null)
{
String runtimePath = ApisupportAntUtils.CPEXT_RUNTIME_RELATIVE_PATH + fo.getNameExt();
newCpExt.put(runtimePath, binPath);
}
}
}
// delete removed JARs, remove any remaining exported packages and src&javadoc refs left
Iterator<Item> it = getCPExtIterator();
HashSet<String> jarsSet = new HashSet<String>(newCpExt.values());
while (it.hasNext()) {
Item item = it.next();
if (!jarsSet.contains(item.getFilePath())) {
// XXX deleting here doesn't work on Windows:
// File f = PropertyUtils.resolveFile(getProjectDirectoryFile(), item.getFilePath());
// FileObject toDel = FileUtil.toFileObject(f);
// if (toDel != null) {
// toDel.delete();
// }
assert item.getReference() != null : "getCPExtIterator() initializes references to wrapped JARs";
item.removeSourceAndJavadoc(getUpdateHelper());
getRefHelper().destroyReference(item.getReference());
}
}
cps.encodeToStrings(cpExtList, CPEXT);
pxm.replaceClassPathExtensions(newCpExt);
wrappedJarsChanged = false;
}
if (isStandalone()) {
ModuleProperties.storePlatform(getHelper(), getActivePlatform());
if (javaPlatformChanged) {
ModuleProperties.storeJavaPlatform(getHelper(), getEvaluator(), getActiveJavaPlatform(), false);
}
if (refreshModuleList) {
ModuleList.refreshModuleListForRoot(getProjectDirectoryFile());
}
} else if (isSuiteComponent() && refreshModuleList) {
ModuleList.refreshModuleListForRoot(getSuiteDirectory());
} else if (isNetBeansOrg()) { |
17,336 | 0 | // ToDo: Need to rewrite. | @Test(expected = TaskExecutionException.class)
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_throwWhenAnotherTaskIsBeingExecuted()
throws Exception {
thread.execute(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
thread.interrupt();
}
});
thread.execute(mock(ITask.class));
} | IMPLEMENTATION | true | @Test(expected = TaskExecutionException.class)
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_throwWhenAnotherTaskIsBeingExecuted()
throws Exception { | @Test(expected = TaskExecutionException.class)
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_throwWhenAnotherTaskIsBeingExecuted()
throws Exception {
thread.execute(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
thread.interrupt();
}
});
thread.execute(mock(ITask.class)); | @Test(expected = TaskExecutionException.class)
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_throwWhenAnotherTaskIsBeingExecuted()
throws Exception {
thread.execute(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
thread.interrupt();
}
});
thread.execute(mock(ITask.class));
} |
17,337 | 0 | // ToDo: Need to rewrite. | @Test(expected = TaskExecutionException.class)
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_throwWhenThreadIsNotAlive()
throws Exception {
ITask taskMock = mock(ITask.class);
thread.interrupt();
thread.execute(taskMock);
fail();
} | IMPLEMENTATION | true | @Test(expected = TaskExecutionException.class)
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_throwWhenThreadIsNotAlive()
throws Exception { | @Test(expected = TaskExecutionException.class)
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_throwWhenThreadIsNotAlive()
throws Exception {
ITask taskMock = mock(ITask.class);
thread.interrupt();
thread.execute(taskMock);
fail();
} | @Test(expected = TaskExecutionException.class)
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_throwWhenThreadIsNotAlive()
throws Exception {
ITask taskMock = mock(ITask.class);
thread.interrupt();
thread.execute(taskMock);
fail();
} |
17,338 | 0 | // ToDo: Need to rewrite. | @Test
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_ignoreExceptionsFromTask()
throws Exception {
ITask taskMock1 = mock(ITask.class), taskMock2 = mock(ITask.class);
doThrow(new TaskExecutionException("Whoops!")).when(taskMock1).execute();
thread.execute(taskMock1);
verify(taskMock1, timeout(100)).execute();
Thread.sleep(200);
thread.execute(taskMock2);
verify(taskMock2, timeout(100)).execute(); } | IMPLEMENTATION | true | @Test
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_ignoreExceptionsFromTask()
throws Exception { | @Test
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_ignoreExceptionsFromTask()
throws Exception {
ITask taskMock1 = mock(ITask.class), taskMock2 = mock(ITask.class);
doThrow(new TaskExecutionException("Whoops!")).when(taskMock1).execute();
thread.execute(taskMock1);
verify(taskMock1, timeout(100)).execute();
Thread.sleep(200);
thread.execute(taskMock2);
verify(taskMock2, timeout(100)).execute(); } | @Test
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_ignoreExceptionsFromTask()
throws Exception {
ITask taskMock1 = mock(ITask.class), taskMock2 = mock(ITask.class);
doThrow(new TaskExecutionException("Whoops!")).when(taskMock1).execute();
thread.execute(taskMock1);
verify(taskMock1, timeout(100)).execute();
Thread.sleep(200);
thread.execute(taskMock2);
verify(taskMock2, timeout(100)).execute(); } |
25,541 | 0 | // TODO: Unify with searchSubtitles() | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null;
File videoRaw = null;
if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker
DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri);
DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri);
video = SubtitleUtils.findDocInScope(fileScope, fileMedia);
}
} else if (isTvBox) {
videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart());
video = DocumentFile.fromFile(videoRaw);
}
if (video != null) {
DocumentFile next;
if (!isTvBox) {
next = SubtitleUtils.findNext(video);
} else {
File parentRaw = videoRaw.getParentFile();
DocumentFile dir = DocumentFile.fromFile(parentRaw);
next = SubtitleUtils.findNext(video, dir);
}
if (next != null) {
return next.getUri();
}
}
}
return null;
} | IMPLEMENTATION | true | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null; | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null;
File videoRaw = null;
if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null;
File videoRaw = null;
if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker
DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri);
DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri);
video = SubtitleUtils.findDocInScope(fileScope, fileMedia);
}
} else if (isTvBox) {
videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart());
video = DocumentFile.fromFile(videoRaw);
}
if (video != null) {
DocumentFile next; |
25,541 | 1 | // Fast search based on path in uri | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null;
File videoRaw = null;
if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker
DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri);
DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri);
video = SubtitleUtils.findDocInScope(fileScope, fileMedia);
}
} else if (isTvBox) {
videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart());
video = DocumentFile.fromFile(videoRaw);
}
if (video != null) {
DocumentFile next;
if (!isTvBox) {
next = SubtitleUtils.findNext(video);
} else {
File parentRaw = videoRaw.getParentFile();
DocumentFile dir = DocumentFile.fromFile(parentRaw);
next = SubtitleUtils.findNext(video, dir);
}
if (next != null) {
return next.getUri();
}
}
}
return null;
} | NONSATD | true | if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else { | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null;
File videoRaw = null;
if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker
DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri);
DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri);
video = SubtitleUtils.findDocInScope(fileScope, fileMedia);
}
} else if (isTvBox) {
videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart()); | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null;
File videoRaw = null;
if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker
DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri);
DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri);
video = SubtitleUtils.findDocInScope(fileScope, fileMedia);
}
} else if (isTvBox) {
videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart());
video = DocumentFile.fromFile(videoRaw);
}
if (video != null) {
DocumentFile next;
if (!isTvBox) {
next = SubtitleUtils.findNext(video);
} else {
File parentRaw = videoRaw.getParentFile();
DocumentFile dir = DocumentFile.fromFile(parentRaw);
next = SubtitleUtils.findNext(video, dir); |
25,541 | 2 | // Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null;
File videoRaw = null;
if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker
DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri);
DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri);
video = SubtitleUtils.findDocInScope(fileScope, fileMedia);
}
} else if (isTvBox) {
videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart());
video = DocumentFile.fromFile(videoRaw);
}
if (video != null) {
DocumentFile next;
if (!isTvBox) {
next = SubtitleUtils.findNext(video);
} else {
File parentRaw = videoRaw.getParentFile();
DocumentFile dir = DocumentFile.fromFile(parentRaw);
next = SubtitleUtils.findNext(video, dir);
}
if (next != null) {
return next.getUri();
}
}
}
return null;
} | NONSATD | true | video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker
DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri);
DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri); | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null;
File videoRaw = null;
if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker
DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri);
DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri);
video = SubtitleUtils.findDocInScope(fileScope, fileMedia);
}
} else if (isTvBox) {
videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart());
video = DocumentFile.fromFile(videoRaw);
}
if (video != null) {
DocumentFile next; | Uri findNext() {
// TODO: Unify with searchSubtitles()
if (mPrefs.scopeUri != null || isTvBox) {
DocumentFile video = null;
File videoRaw = null;
if (!isTvBox && mPrefs.scopeUri != null) {
if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) {
// Fast search based on path in uri
video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri);
} else {
// Slow search based on matching metadata, no path in uri
// Provider "com.android.providers.media.documents" when using "Videos" tab in file picker
DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri);
DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri);
video = SubtitleUtils.findDocInScope(fileScope, fileMedia);
}
} else if (isTvBox) {
videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart());
video = DocumentFile.fromFile(videoRaw);
}
if (video != null) {
DocumentFile next;
if (!isTvBox) {
next = SubtitleUtils.findNext(video);
} else {
File parentRaw = videoRaw.getParentFile();
DocumentFile dir = DocumentFile.fromFile(parentRaw);
next = SubtitleUtils.findNext(video, dir);
}
if (next != null) {
return next.getUri();
} |
17,350 | 0 | /**
* Bug 4933099: There is some funny-business to deal with when this
* method is called with a Window instead of a Frame. See 4836744
* for more information on this. One side-effect of our workaround
* for the problem is that the owning Frame of a Window may end
* up getting resized during the fullscreen process. When we
* return from fullscreen mode, we should resize the Frame to
* its original size (just like the Window is being resized
* to its original size in GraphicsDevice).
*/ | @Override
protected void removeFSWindowListener(Window w) {
realFSWindow.removeWindowListener(fsWindowListener);
fsWindowListener = null;
/**
* Bug 4933099: There is some funny-business to deal with when this
* method is called with a Window instead of a Frame. See 4836744
* for more information on this. One side-effect of our workaround
* for the problem is that the owning Frame of a Window may end
* up getting resized during the fullscreen process. When we
* return from fullscreen mode, we should resize the Frame to
* its original size (just like the Window is being resized
* to its original size in GraphicsDevice).
*/
final WWindowPeer wpeer = AWTAccessor.getComponentAccessor()
.getPeer(realFSWindow);
if (wpeer != null) {
if (ownerOrigBounds != null) {
// if the window went into fs mode before it was realized it
// could have (0,0) dimensions
if (ownerOrigBounds.width == 0) ownerOrigBounds.width = 1;
if (ownerOrigBounds.height == 0) ownerOrigBounds.height = 1;
wpeer.reshape(ownerOrigBounds.x, ownerOrigBounds.y,
ownerOrigBounds.width, ownerOrigBounds.height);
if (!ownerWasVisible) {
wpeer.setVisible(false);
}
ownerOrigBounds = null;
}
if (!fsWindowWasAlwaysOnTop) {
wpeer.setAlwaysOnTop(false);
}
}
realFSWindow = null;
} | DEFECT | true | realFSWindow.removeWindowListener(fsWindowListener);
fsWindowListener = null;
/**
* Bug 4933099: There is some funny-business to deal with when this
* method is called with a Window instead of a Frame. See 4836744
* for more information on this. One side-effect of our workaround
* for the problem is that the owning Frame of a Window may end
* up getting resized during the fullscreen process. When we
* return from fullscreen mode, we should resize the Frame to
* its original size (just like the Window is being resized
* to its original size in GraphicsDevice).
*/
final WWindowPeer wpeer = AWTAccessor.getComponentAccessor()
.getPeer(realFSWindow); | @Override
protected void removeFSWindowListener(Window w) {
realFSWindow.removeWindowListener(fsWindowListener);
fsWindowListener = null;
/**
* Bug 4933099: There is some funny-business to deal with when this
* method is called with a Window instead of a Frame. See 4836744
* for more information on this. One side-effect of our workaround
* for the problem is that the owning Frame of a Window may end
* up getting resized during the fullscreen process. When we
* return from fullscreen mode, we should resize the Frame to
* its original size (just like the Window is being resized
* to its original size in GraphicsDevice).
*/
final WWindowPeer wpeer = AWTAccessor.getComponentAccessor()
.getPeer(realFSWindow);
if (wpeer != null) {
if (ownerOrigBounds != null) {
// if the window went into fs mode before it was realized it
// could have (0,0) dimensions
if (ownerOrigBounds.width == 0) ownerOrigBounds.width = 1;
if (ownerOrigBounds.height == 0) ownerOrigBounds.height = 1;
wpeer.reshape(ownerOrigBounds.x, ownerOrigBounds.y,
ownerOrigBounds.width, ownerOrigBounds.height); | @Override
protected void removeFSWindowListener(Window w) {
realFSWindow.removeWindowListener(fsWindowListener);
fsWindowListener = null;
/**
* Bug 4933099: There is some funny-business to deal with when this
* method is called with a Window instead of a Frame. See 4836744
* for more information on this. One side-effect of our workaround
* for the problem is that the owning Frame of a Window may end
* up getting resized during the fullscreen process. When we
* return from fullscreen mode, we should resize the Frame to
* its original size (just like the Window is being resized
* to its original size in GraphicsDevice).
*/
final WWindowPeer wpeer = AWTAccessor.getComponentAccessor()
.getPeer(realFSWindow);
if (wpeer != null) {
if (ownerOrigBounds != null) {
// if the window went into fs mode before it was realized it
// could have (0,0) dimensions
if (ownerOrigBounds.width == 0) ownerOrigBounds.width = 1;
if (ownerOrigBounds.height == 0) ownerOrigBounds.height = 1;
wpeer.reshape(ownerOrigBounds.x, ownerOrigBounds.y,
ownerOrigBounds.width, ownerOrigBounds.height);
if (!ownerWasVisible) {
wpeer.setVisible(false);
}
ownerOrigBounds = null;
}
if (!fsWindowWasAlwaysOnTop) {
wpeer.setAlwaysOnTop(false);
}
}
realFSWindow = null; |
17,350 | 1 | // if the window went into fs mode before it was realized it
// could have (0,0) dimensions | @Override
protected void removeFSWindowListener(Window w) {
realFSWindow.removeWindowListener(fsWindowListener);
fsWindowListener = null;
/**
* Bug 4933099: There is some funny-business to deal with when this
* method is called with a Window instead of a Frame. See 4836744
* for more information on this. One side-effect of our workaround
* for the problem is that the owning Frame of a Window may end
* up getting resized during the fullscreen process. When we
* return from fullscreen mode, we should resize the Frame to
* its original size (just like the Window is being resized
* to its original size in GraphicsDevice).
*/
final WWindowPeer wpeer = AWTAccessor.getComponentAccessor()
.getPeer(realFSWindow);
if (wpeer != null) {
if (ownerOrigBounds != null) {
// if the window went into fs mode before it was realized it
// could have (0,0) dimensions
if (ownerOrigBounds.width == 0) ownerOrigBounds.width = 1;
if (ownerOrigBounds.height == 0) ownerOrigBounds.height = 1;
wpeer.reshape(ownerOrigBounds.x, ownerOrigBounds.y,
ownerOrigBounds.width, ownerOrigBounds.height);
if (!ownerWasVisible) {
wpeer.setVisible(false);
}
ownerOrigBounds = null;
}
if (!fsWindowWasAlwaysOnTop) {
wpeer.setAlwaysOnTop(false);
}
}
realFSWindow = null;
} | NONSATD | true | if (wpeer != null) {
if (ownerOrigBounds != null) {
// if the window went into fs mode before it was realized it
// could have (0,0) dimensions
if (ownerOrigBounds.width == 0) ownerOrigBounds.width = 1;
if (ownerOrigBounds.height == 0) ownerOrigBounds.height = 1; | * for the problem is that the owning Frame of a Window may end
* up getting resized during the fullscreen process. When we
* return from fullscreen mode, we should resize the Frame to
* its original size (just like the Window is being resized
* to its original size in GraphicsDevice).
*/
final WWindowPeer wpeer = AWTAccessor.getComponentAccessor()
.getPeer(realFSWindow);
if (wpeer != null) {
if (ownerOrigBounds != null) {
// if the window went into fs mode before it was realized it
// could have (0,0) dimensions
if (ownerOrigBounds.width == 0) ownerOrigBounds.width = 1;
if (ownerOrigBounds.height == 0) ownerOrigBounds.height = 1;
wpeer.reshape(ownerOrigBounds.x, ownerOrigBounds.y,
ownerOrigBounds.width, ownerOrigBounds.height);
if (!ownerWasVisible) {
wpeer.setVisible(false);
}
ownerOrigBounds = null;
}
if (!fsWindowWasAlwaysOnTop) { | @Override
protected void removeFSWindowListener(Window w) {
realFSWindow.removeWindowListener(fsWindowListener);
fsWindowListener = null;
/**
* Bug 4933099: There is some funny-business to deal with when this
* method is called with a Window instead of a Frame. See 4836744
* for more information on this. One side-effect of our workaround
* for the problem is that the owning Frame of a Window may end
* up getting resized during the fullscreen process. When we
* return from fullscreen mode, we should resize the Frame to
* its original size (just like the Window is being resized
* to its original size in GraphicsDevice).
*/
final WWindowPeer wpeer = AWTAccessor.getComponentAccessor()
.getPeer(realFSWindow);
if (wpeer != null) {
if (ownerOrigBounds != null) {
// if the window went into fs mode before it was realized it
// could have (0,0) dimensions
if (ownerOrigBounds.width == 0) ownerOrigBounds.width = 1;
if (ownerOrigBounds.height == 0) ownerOrigBounds.height = 1;
wpeer.reshape(ownerOrigBounds.x, ownerOrigBounds.y,
ownerOrigBounds.width, ownerOrigBounds.height);
if (!ownerWasVisible) {
wpeer.setVisible(false);
}
ownerOrigBounds = null;
}
if (!fsWindowWasAlwaysOnTop) {
wpeer.setAlwaysOnTop(false);
}
}
realFSWindow = null;
} |
974 | 0 | // TODO May be possible to do finer-grained locks. | private void trackWatchForAttempt(WatchedPathInfo watchedPathInfo, WatchKey watchKey) {
assert watchedPathInfo.pathIdentifier != null;
// TODO May be possible to do finer-grained locks.
synchronized (watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.get(watchedPathInfo.pathIdentifier);
if (list == null) {
list = new LinkedList<>();
watchesPerAttempt.put(watchedPathInfo.pathIdentifier, list);
}
list.add(watchKey);
}
} | DESIGN | true | private void trackWatchForAttempt(WatchedPathInfo watchedPathInfo, WatchKey watchKey) {
assert watchedPathInfo.pathIdentifier != null;
// TODO May be possible to do finer-grained locks.
synchronized (watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.get(watchedPathInfo.pathIdentifier); | private void trackWatchForAttempt(WatchedPathInfo watchedPathInfo, WatchKey watchKey) {
assert watchedPathInfo.pathIdentifier != null;
// TODO May be possible to do finer-grained locks.
synchronized (watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.get(watchedPathInfo.pathIdentifier);
if (list == null) {
list = new LinkedList<>();
watchesPerAttempt.put(watchedPathInfo.pathIdentifier, list);
}
list.add(watchKey);
}
} | private void trackWatchForAttempt(WatchedPathInfo watchedPathInfo, WatchKey watchKey) {
assert watchedPathInfo.pathIdentifier != null;
// TODO May be possible to do finer-grained locks.
synchronized (watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.get(watchedPathInfo.pathIdentifier);
if (list == null) {
list = new LinkedList<>();
watchesPerAttempt.put(watchedPathInfo.pathIdentifier, list);
}
list.add(watchKey);
}
} |
975 | 0 | // TODO May be possible to do finer-grained locks. | private void cancelWatchesForAttempt(AttemptPathIdentifier pathIdentifier) {
// TODO May be possible to do finer-grained locks.
synchronized(watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.remove(pathIdentifier);
if (list != null) {
for (WatchKey watchKey : list) {
watchKey.cancel();
}
}
}
} | DESIGN | true | private void cancelWatchesForAttempt(AttemptPathIdentifier pathIdentifier) {
// TODO May be possible to do finer-grained locks.
synchronized(watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.remove(pathIdentifier); | private void cancelWatchesForAttempt(AttemptPathIdentifier pathIdentifier) {
// TODO May be possible to do finer-grained locks.
synchronized(watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.remove(pathIdentifier);
if (list != null) {
for (WatchKey watchKey : list) {
watchKey.cancel();
}
}
}
} | private void cancelWatchesForAttempt(AttemptPathIdentifier pathIdentifier) {
// TODO May be possible to do finer-grained locks.
synchronized(watchesPerAttempt) {
List<WatchKey> list = watchesPerAttempt.remove(pathIdentifier);
if (list != null) {
for (WatchKey watchKey : list) {
watchKey.cancel();
}
}
}
} |
987 | 0 | // Strip out non-deterministic conjuncts | private OuterJoinPushDownResult processLimitedOuterJoin(RowExpression inheritedPredicate, RowExpression outerEffectivePredicate, RowExpression innerEffectivePredicate, RowExpression joinPredicate, Collection<VariableReferenceExpression> outerVariables)
{
checkArgument(Iterables.all(VariablesExtractor.extractUnique(outerEffectivePredicate), in(outerVariables)), "outerEffectivePredicate must only contain variables from outerVariables");
checkArgument(Iterables.all(VariablesExtractor.extractUnique(innerEffectivePredicate), not(in(outerVariables))), "innerEffectivePredicate must not contain variables from outerVariables");
ImmutableList.Builder<RowExpression> outerPushdownConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> innerPushdownConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> postJoinConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> joinConjuncts = ImmutableList.builder();
// Strip out non-deterministic conjuncts
postJoinConjuncts.addAll(filter(extractConjuncts(inheritedPredicate), not(determinismEvaluator::isDeterministic)));
inheritedPredicate = logicalRowExpressions.filterDeterministicConjuncts(inheritedPredicate);
outerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(outerEffectivePredicate);
innerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(innerEffectivePredicate);
joinConjuncts.addAll(filter(extractConjuncts(joinPredicate), not(determinismEvaluator::isDeterministic)));
joinPredicate = logicalRowExpressions.filterDeterministicConjuncts(joinPredicate);
// Generate equality inferences
EqualityInference inheritedInference = createEqualityInference(inheritedPredicate);
EqualityInference outerInference = createEqualityInference(inheritedPredicate, outerEffectivePredicate);
EqualityInference.EqualityPartition equalityPartition = inheritedInference.generateEqualitiesPartitionedBy(in(outerVariables));
RowExpression outerOnlyInheritedEqualities = logicalRowExpressions.combineConjuncts(equalityPartition.getScopeEqualities());
EqualityInference potentialNullSymbolInference = createEqualityInference(outerOnlyInheritedEqualities, outerEffectivePredicate, innerEffectivePredicate, joinPredicate);
// See if we can push inherited predicates down
for (RowExpression conjunct : nonInferableConjuncts(inheritedPredicate)) {
RowExpression outerRewritten = outerInference.rewriteExpression(conjunct, in(outerVariables));
if (outerRewritten != null) {
outerPushdownConjuncts.add(outerRewritten);
// A conjunct can only be pushed down into an inner side if it can be rewritten in terms of the outer side
RowExpression innerRewritten = potentialNullSymbolInference.rewriteExpression(outerRewritten, not(in(outerVariables)));
if (innerRewritten != null) {
innerPushdownConjuncts.add(innerRewritten);
}
}
else {
postJoinConjuncts.add(conjunct);
}
}
// Add the equalities from the inferences back in
outerPushdownConjuncts.addAll(equalityPartition.getScopeEqualities());
postJoinConjuncts.addAll(equalityPartition.getScopeComplementEqualities());
postJoinConjuncts.addAll(equalityPartition.getScopeStraddlingEqualities());
// See if we can push down any outer effective predicates to the inner side
for (RowExpression conjunct : nonInferableConjuncts(outerEffectivePredicate)) {
RowExpression rewritten = potentialNullSymbolInference.rewriteExpression(conjunct, not(in(outerVariables)));
if (rewritten != null) {
innerPushdownConjuncts.add(rewritten);
}
}
// See if we can push down join predicates to the inner side
for (RowExpression conjunct : nonInferableConjuncts(joinPredicate)) {
RowExpression innerRewritten = potentialNullSymbolInference.rewriteExpression(conjunct, not(in(outerVariables)));
if (innerRewritten != null) {
innerPushdownConjuncts.add(innerRewritten);
}
else {
joinConjuncts.add(conjunct);
}
}
// Push outer and join equalities into the inner side. For example:
// SELECT * FROM nation LEFT OUTER JOIN region ON nation.regionkey = region.regionkey and nation.name = region.name WHERE nation.name = 'blah'
EqualityInference potentialNullSymbolInferenceWithoutInnerInferred = createEqualityInference(outerOnlyInheritedEqualities, outerEffectivePredicate, joinPredicate);
innerPushdownConjuncts.addAll(potentialNullSymbolInferenceWithoutInnerInferred.generateEqualitiesPartitionedBy(not(in(outerVariables))).getScopeEqualities());
// TODO: we can further improve simplifying the equalities by considering other relationships from the outer side
EqualityInference.EqualityPartition joinEqualityPartition = createEqualityInference(joinPredicate).generateEqualitiesPartitionedBy(not(in(outerVariables)));
innerPushdownConjuncts.addAll(joinEqualityPartition.getScopeEqualities());
joinConjuncts.addAll(joinEqualityPartition.getScopeComplementEqualities())
.addAll(joinEqualityPartition.getScopeStraddlingEqualities());
return new OuterJoinPushDownResult(logicalRowExpressions.combineConjuncts(outerPushdownConjuncts.build()),
logicalRowExpressions.combineConjuncts(innerPushdownConjuncts.build()),
logicalRowExpressions.combineConjuncts(joinConjuncts.build()),
logicalRowExpressions.combineConjuncts(postJoinConjuncts.build()));
} | NONSATD | true | ImmutableList.Builder<RowExpression> postJoinConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> joinConjuncts = ImmutableList.builder();
// Strip out non-deterministic conjuncts
postJoinConjuncts.addAll(filter(extractConjuncts(inheritedPredicate), not(determinismEvaluator::isDeterministic)));
inheritedPredicate = logicalRowExpressions.filterDeterministicConjuncts(inheritedPredicate); | private OuterJoinPushDownResult processLimitedOuterJoin(RowExpression inheritedPredicate, RowExpression outerEffectivePredicate, RowExpression innerEffectivePredicate, RowExpression joinPredicate, Collection<VariableReferenceExpression> outerVariables)
{
checkArgument(Iterables.all(VariablesExtractor.extractUnique(outerEffectivePredicate), in(outerVariables)), "outerEffectivePredicate must only contain variables from outerVariables");
checkArgument(Iterables.all(VariablesExtractor.extractUnique(innerEffectivePredicate), not(in(outerVariables))), "innerEffectivePredicate must not contain variables from outerVariables");
ImmutableList.Builder<RowExpression> outerPushdownConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> innerPushdownConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> postJoinConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> joinConjuncts = ImmutableList.builder();
// Strip out non-deterministic conjuncts
postJoinConjuncts.addAll(filter(extractConjuncts(inheritedPredicate), not(determinismEvaluator::isDeterministic)));
inheritedPredicate = logicalRowExpressions.filterDeterministicConjuncts(inheritedPredicate);
outerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(outerEffectivePredicate);
innerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(innerEffectivePredicate);
joinConjuncts.addAll(filter(extractConjuncts(joinPredicate), not(determinismEvaluator::isDeterministic)));
joinPredicate = logicalRowExpressions.filterDeterministicConjuncts(joinPredicate);
// Generate equality inferences
EqualityInference inheritedInference = createEqualityInference(inheritedPredicate);
EqualityInference outerInference = createEqualityInference(inheritedPredicate, outerEffectivePredicate);
EqualityInference.EqualityPartition equalityPartition = inheritedInference.generateEqualitiesPartitionedBy(in(outerVariables)); | private OuterJoinPushDownResult processLimitedOuterJoin(RowExpression inheritedPredicate, RowExpression outerEffectivePredicate, RowExpression innerEffectivePredicate, RowExpression joinPredicate, Collection<VariableReferenceExpression> outerVariables)
{
checkArgument(Iterables.all(VariablesExtractor.extractUnique(outerEffectivePredicate), in(outerVariables)), "outerEffectivePredicate must only contain variables from outerVariables");
checkArgument(Iterables.all(VariablesExtractor.extractUnique(innerEffectivePredicate), not(in(outerVariables))), "innerEffectivePredicate must not contain variables from outerVariables");
ImmutableList.Builder<RowExpression> outerPushdownConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> innerPushdownConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> postJoinConjuncts = ImmutableList.builder();
ImmutableList.Builder<RowExpression> joinConjuncts = ImmutableList.builder();
// Strip out non-deterministic conjuncts
postJoinConjuncts.addAll(filter(extractConjuncts(inheritedPredicate), not(determinismEvaluator::isDeterministic)));
inheritedPredicate = logicalRowExpressions.filterDeterministicConjuncts(inheritedPredicate);
outerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(outerEffectivePredicate);
innerEffectivePredicate = logicalRowExpressions.filterDeterministicConjuncts(innerEffectivePredicate);
joinConjuncts.addAll(filter(extractConjuncts(joinPredicate), not(determinismEvaluator::isDeterministic)));
joinPredicate = logicalRowExpressions.filterDeterministicConjuncts(joinPredicate);
// Generate equality inferences
EqualityInference inheritedInference = createEqualityInference(inheritedPredicate);
EqualityInference outerInference = createEqualityInference(inheritedPredicate, outerEffectivePredicate);
EqualityInference.EqualityPartition equalityPartition = inheritedInference.generateEqualitiesPartitionedBy(in(outerVariables));
RowExpression outerOnlyInheritedEqualities = logicalRowExpressions.combineConjuncts(equalityPartition.getScopeEqualities());
EqualityInference potentialNullSymbolInference = createEqualityInference(outerOnlyInheritedEqualities, outerEffectivePredicate, innerEffectivePredicate, joinPredicate);
// See if we can push inherited predicates down
for (RowExpression conjunct : nonInferableConjuncts(inheritedPredicate)) {
RowExpression outerRewritten = outerInference.rewriteExpression(conjunct, in(outerVariables));
if (outerRewritten != null) {
outerPushdownConjuncts.add(outerRewritten);
// A conjunct can only be pushed down into an inner side if it can be rewritten in terms of the outer side
RowExpression innerRewritten = potentialNullSymbolInference.rewriteExpression(outerRewritten, not(in(outerVariables)));
if (innerRewritten != null) { |