List of usage examples for org.apache.commons.net.util SubnetUtils SubnetUtils
public SubnetUtils(String cidrNotation)
From source file:com.qwazr.server.configuration.ServerConfiguration.java
/** * Manage that kind of pattern:/*from ww w .jav a 2s . c om*/ * 192.168.0.0/16,172.168.0.0/16 * 192.168.0.0/16 * 10.3.12.12 * * @param addressPattern a mask or an ip address * @param collect a collection filled with the matching addresses * @throws SocketException */ private static void findMatchingAddress(final String addressPattern, final Collection<String> collect) throws SocketException { final String[] patterns = StringUtils.split(addressPattern, ",; "); if (patterns == null) return; for (String pattern : patterns) { if (pattern == null) continue; pattern = pattern.trim(); if (!pattern.contains("/")) { collect.add(pattern); continue; } final SubnetUtils.SubnetInfo subnet = pattern.contains("/") ? new SubnetUtils(pattern).getInfo() : null; final Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces(); while (enumInterfaces != null && enumInterfaces.hasMoreElements()) { final NetworkInterface ifc = enumInterfaces.nextElement(); if (!ifc.isUp()) continue; final Enumeration<InetAddress> enumAddresses = ifc.getInetAddresses(); while (enumAddresses != null && enumAddresses.hasMoreElements()) { final InetAddress inetAddress = enumAddresses.nextElement(); if (!(inetAddress instanceof Inet4Address)) continue; final String address = inetAddress.getHostAddress(); if (subnet != null && subnet.isInRange(address) || address.equals(pattern)) collect.add(address); } } } }
From source file:com.dianping.cat.system.page.router.config.RouterConfigManager.java
private void refreshNetInfo() { Map<String, List<SubnetInfo>> subNetInfos = new HashMap<String, List<SubnetInfo>>(); for (Entry<String, NetworkPolicy> netPolicy : m_routerConfig.getNetworkPolicies().entrySet()) { ArrayList<SubnetInfo> infos = new ArrayList<SubnetInfo>(); if (!DEFAULT.equals(netPolicy.getKey())) { for (Entry<String, Network> network : netPolicy.getValue().getNetworks().entrySet()) { try { SubnetUtils subnetUtils = new SubnetUtils(network.getValue().getId()); SubnetInfo netInfo = subnetUtils.getInfo(); infos.add(netInfo);// www . ja v a2s.c o m } catch (Exception e) { Cat.logError(e); } } subNetInfos.put(netPolicy.getKey(), infos); } } m_subNetInfos = subNetInfos; m_ipToGroupInfo = new HashMap<String, String>(); }
From source file:core.Task.java
/** * ----------------------//from w w w .j a v a2 s . c o m * Executing discovery * ---------------------- */ private void runDiscovery() { HashMap<String, HashMap<String, String>> networks; List<String> exclusions; /* * Get networks */ ApiRequest networksRequest = new ApiRequest(this.coordinates).setRequestMethod(ApiRequestMethods.GET) .setApiMethod("v1/core/get-networks"); ApiResponse networksResponse = ApiCaller.request(networksRequest); if (!networksResponse.success) { /* * Log record * Can't get node list */ this.logBadResponse("ERROR", "TASK GET NODES", "Task " + this.coordinates.get("taskName") + " can't get discovery network list.", networksResponse); return; } String networksJson = networksResponse.response; Type networksType = new TypeToken<HashMap<String, HashMap<String, String>>>() { }.getType(); try { networks = gson.fromJson(networksJson, networksType); } catch (JsonSyntaxException e) { this.logException("ERROR", "TASK GET NODES", "Task " + this.coordinates.get("taskName") + " can't parse discovery network list from json.", e); return; } /* * Get exclusions IP's */ ApiRequest exclusionsRequest = new ApiRequest(this.coordinates).setRequestMethod(ApiRequestMethods.GET) .setApiMethod("v1/core/get-exclusions"); ApiResponse exclusionsResponse = ApiCaller.request(exclusionsRequest); if (!exclusionsResponse.success) { /* * Log record * Can't get node list */ this.logBadResponse("ERROR", "TASK GET NODES", "Task " + this.coordinates.get("taskName") + " can't get exclusions ip list.", exclusionsResponse); return; } String exclusionsJson = exclusionsResponse.response; Type exclusionsType = new TypeToken<ArrayList<String>>() { }.getType(); try { exclusions = gson.fromJson(exclusionsJson, exclusionsType); } catch (JsonSyntaxException e) { this.logException("ERROR", "TASK GET NODES", "Task " + this.coordinates.get("taskName") + " can't parse exclusions ip list from json.", e); return; } /* * Thread executor init */ ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadCount); // number of threads /* * Futures for workers results return */ List<Future<Boolean>> results = new ArrayList<>(); // Adding discovery workers to executor // noinspection Java8MapForEach networks.entrySet().forEach(node -> { Boolean dataValid = true; String[] allIps = {}; List<String> allExclusions = new ArrayList<>(); String snmpRead = node.getValue().get("snmp_read"); String version = node.getValue().get("snmp_version"); String port = node.getValue().get("port_snmp"); String networkId = node.getValue().get("id"); Integer snmpVer = 1; Integer snmpPort = 161; if (snmpRead == null || snmpRead.length() == 0) { dataValid = false; String unknownTaskMessage = "Task " + this.coordinates.get("taskName") + ". Network " + node.getKey() + ": empty SNMP read community."; this.logMessage("ERROR", "TASK EXECUTE", unknownTaskMessage); } if (version == null || version.length() == 0) { dataValid = false; String unknownTaskMessage = "Task " + this.coordinates.get("taskName") + ". Network " + node.getKey() + ": empty SNMP version."; this.logMessage("ERROR", "TASK EXECUTE", unknownTaskMessage); } if (port == null || port.length() == 0) { dataValid = false; String unknownTaskMessage = "Task " + this.coordinates.get("taskName") + ". Network " + node.getKey() + ": empty SNMP port."; this.logMessage("ERROR", "TASK EXECUTE", unknownTaskMessage); } if (dataValid) { /* * Set SNMP version */ try { snmpVer = Integer.parseInt(version); } catch (NumberFormatException e) { dataValid = false; String parseVersionMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't parse SNMP version of network"; this.logException("ERROR", "TASK EXECUTE", parseVersionMessage, e); } /* * Set SNMP port */ try { snmpPort = Integer.parseInt(port); } catch (NumberFormatException e) { dataValid = false; String parsePortMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't parse SNMP port to integer."; this.logException("WARNING", "TASK EXECUTE", parsePortMessage, e); } } /* * Calculating all IPs of current subnet */ if (dataValid) { try { SubnetUtils subnet = new SubnetUtils(node.getKey()); /* * If exclusions ip is in subnet range, add it to exclusuins list */ for (String exclusionIp : exclusions) { try { if (subnet.getInfo().isInRange(exclusionIp)) { allExclusions.add(exclusionIp); } } catch (IllegalArgumentException e) { dataValid = false; String validateExclusionsMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": wrong exclusion ip " + exclusionIp; this.logException("WARNING", "TASK EXECUTE", validateExclusionsMessage, e); } } allIps = subnet.getInfo().getAllAddresses(); } catch (Exception e) { dataValid = false; String extractIpsMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't extract IPs from subnet."; this.logException("WARNING", "TASK EXECUTE", extractIpsMessage, e); } } if (dataValid) { for (String ip : allIps) { if (!allExclusions.contains(ip)) { Map<String, String> currentCoord = new HashMap<>(); currentCoord.putAll(this.coordinates); currentCoord.put("nodeIp", ip); results.add(executor.submit(new WorkerDiscovery(currentCoord, this.settings, networkId, snmpVer, snmpRead, snmpPort))); } } } }); for (Future<Boolean> result : results) { Boolean currentResult; try { currentResult = result.get(); if (currentResult) { this.success++; } else { this.failed++; } } catch (Exception e) { this.logException("ERROR", "TASK GET WORKER RESPONSE", "Task " + this.coordinates.get("taskName") + " was interrupted while waiting for discovery worker result.", e); return; } } executor.shutdown(); /* * Task finish log */ String finalMessage = "Task " + this.coordinates.get("taskName") + " has been finished. " + " Success: " + this.success + ". Failed or offline: " + this.failed + "."; this.logMessage("INFO", "TASK FINISH", finalMessage); }
From source file:com.buaa.cfs.nfs3.NfsExports.java
/** * Loading a matcher from a string. The default access privilege is read-only. The string contains 1 or 2 parts, * separated by whitespace characters, where the first part specifies the client hosts, and the second part (if * existent) specifies the access privilege of the client hosts. I.e., * <p>//from w w w .j a v a2 s . c om * "client-hosts [access-privilege]" */ private static Match getMatch(String line) { String[] parts = line.split("\\s+"); final String host; AccessPrivilege privilege = AccessPrivilege.READ_ONLY; switch (parts.length) { case 1: host = StringUtils.toLowerCase(parts[0]).trim(); break; case 2: host = StringUtils.toLowerCase(parts[0]).trim(); String option = parts[1].trim(); if ("rw".equalsIgnoreCase(option)) { privilege = AccessPrivilege.READ_WRITE; } break; default: throw new IllegalArgumentException("Incorrectly formatted line '" + line + "'"); } if (host.equals("*")) { if (LOG.isDebugEnabled()) { LOG.debug("Using match all for '" + host + "' and " + privilege); } return new AnonymousMatch(privilege); } else if (CIDR_FORMAT_SHORT.matcher(host).matches()) { if (LOG.isDebugEnabled()) { LOG.debug("Using CIDR match for '" + host + "' and " + privilege); } return new CIDRMatch(privilege, new SubnetUtils(host).getInfo()); } else if (CIDR_FORMAT_LONG.matcher(host).matches()) { if (LOG.isDebugEnabled()) { LOG.debug("Using CIDR match for '" + host + "' and " + privilege); } String[] pair = host.split("/"); return new CIDRMatch(privilege, new SubnetUtils(pair[0], pair[1]).getInfo()); } else if (host.contains("*") || host.contains("?") || host.contains("[") || host.contains("]") || host.contains("(") || host.contains(")")) { if (LOG.isDebugEnabled()) { LOG.debug("Using Regex match for '" + host + "' and " + privilege); } return new RegexMatch(privilege, host); } else if (HOSTNAME_FORMAT.matcher(host).matches()) { if (LOG.isDebugEnabled()) { LOG.debug("Using exact match for '" + host + "' and " + privilege); } return new ExactMatch(privilege, host); } else { throw new IllegalArgumentException("Invalid hostname provided '" + host + "'"); } }
From source file:eu.smartenit.sdn.floodlight090.dtm.DTM.java
/** * Updates reference vector. Does nothing if provided with null value. * * @param referenceVector reference vector *///w w w .ja v a2 s . c om public synchronized void setReferenceVector(RVector referenceVector) throws IllegalArgumentException { logger.debug("setReferenceVector(RVector) begin"); if (configData == null) { throw new IllegalArgumentException("DTM has not been configured yet (ConfigData is null)"); } if (referenceVector == null) { logger.debug("Not updating Reference vector"); logger.debug("setReferenceVector(RVector) end"); return; } validateReferenceVector(referenceVector); this.referenceVector = referenceVector; for (VectorValue vectorValue : referenceVector.getVectorValues()) { rVectorMap.put(vectorValue.getTunnelEndPrefix(), vectorValue.getValue()); } for (VectorValue vectorValue : referenceVector.getVectorValues()) { String subnet = vectorValue.getTunnelEndPrefix().getPrefix() + "/" + Integer.toString(vectorValue.getTunnelEndPrefix().getPrefixLength()); SubnetUtils utils = new SubnetUtils(subnet); for (ConfigDataEntry configDataEntry : configData.getEntries()) { for (TunnelInfo tunnelInfo : configDataEntry.getTunnels()) { if (utils.getInfo() .isInRange(tunnelInfo.getTunnelID().getRemoteTunnelEndAddress().getPrefix())) { daRouterRVectorMap.put((short) tunnelInfo.getDaRouterOfPortNumber(), vectorValue.getValue()); } } } } calculateRInvMap(referenceVector); logger.debug("Reference vector set to " + referenceVector); logger.debug("setReferenceVector(RVector) end"); }
From source file:com.terremark.impl.AbstractAPIImpl.java
/** * Validates the query arguments against the metadata. {@link java.lang.IllegalArgumentException} is thrown if the * arguments does not match the metadata information. * * @param filterArguments Query arguments. Can be null. * @param metadata Metadata for the query arguments. *//*from w w w. java 2 s.c o m*/ @SuppressWarnings({ "unused", "PMD.AvoidInstantiatingObjectsInLoops", "PMD.AvoidDuplicateLiterals" }) protected static void validateQueryArguments(final Map<String, String> filterArguments, final Map<String, QueryArgument> metadata) { if (filterArguments == null) { return; } for (Map.Entry<String, String> entry : filterArguments.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (key == null) { throw new IllegalArgumentException("Invalid filter argument key"); } if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("Invalid filter argument value for " + key); } final QueryArgument argInfo = metadata.get(key); if (argInfo == null) { throw new IllegalArgumentException("Invalid filter argument: " + key); } switch (argInfo.getType()) { case INTEGER: int i; try { i = Integer.parseInt(value); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value + ". Must be a valid integer", ex); } if (argInfo.getMinValue() != Integer.MAX_VALUE && argInfo.getMaxValue() != Integer.MIN_VALUE && (i < argInfo.getMinValue() || i > argInfo.getMaxValue())) { throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value + ". It should be between " + argInfo.getMinValue() + " and " + argInfo.getMaxValue()); } break; case LIST: boolean found = false; for (String str : argInfo.getArgs()) { if (value.equalsIgnoreCase(str)) { found = true; break; } } if (!found) { throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value + ". It should be one of: " + Arrays.asList(argInfo.getArgs())); } break; case ISO8601_DATE: final SimpleDateFormat sdf = new SimpleDateFormat(TerremarkConstants.ISO_8601_DATE_FORMAT, Locale.getDefault()); try { sdf.parse(value); } catch (ParseException ex) { throw new IllegalArgumentException( "Invalid filter argument value for '" + key + "': " + value + ". Must be a valid date/time in ISO 8601 format: yyyy-MM-dd'T'HH:mm:'00Z'", ex); } break; case HOSTNAME: try { InetAddress.getByName(value); } catch (UnknownHostException ex) { throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value + ". Must be a valid hostname/IP address", ex); } break; case IP_ADDRESS: if (!InetAddressUtils.isIPv4Address(value)) { throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value + ". Must be a valid IPv4 address"); } break; case SUBNET: new SubnetUtils(value); break; case URI: try { new URI(value); } catch (URISyntaxException ex) { throw new IllegalArgumentException("Invalid filter argument value for '" + key + "': " + value + ". Must be a valid relative URI", ex); } break; default: break; } } }
From source file:com.vmware.photon.controller.housekeeper.xenon.SubnetIPLeaseSyncServiceTest.java
private void createDhcpSubnet(TestEnvironment env) throws Throwable { String cidr = "192.168.0.0/16"; SubnetUtils subnetUtils = new SubnetUtils(cidr); SubnetUtils.SubnetInfo subnetInfo = subnetUtils.getInfo(); DhcpSubnetService.State subnetState = new DhcpSubnetService.State(); subnetState.subnetId = SUBNET_ID;//from www . ja v a2 s .c o m subnetState.version = 1L; subnetState.lowIp = IpHelper.ipStringToLong(subnetInfo.getLowAddress()); subnetState.highIp = IpHelper.ipStringToLong(subnetInfo.getHighAddress()); subnetState.lowIpDynamic = subnetState.lowIp + 1; subnetState.highIpDynamic = subnetState.highIp - 1; subnetState.cidr = cidr; URI hostUri = env.getHosts()[0].getUri(); subnetState.dhcpAgentEndpoint = hostUri.getScheme() + "://" + hostUri.getHost() + ":" + hostUri.getPort(); env.sendPostAndWaitForReplication(DhcpSubnetService.FACTORY_LINK, subnetState); }
From source file:eu.smartenit.sdn.floodlight090.dtm.DTM.java
/** * Updates compensation vector.//from www. j ava 2 s . c om * * @param compensationVector compensation vector */ public synchronized void setCompensationVector(CVector compensationVector) { logger.debug("setCompensationVector(CVector) begin"); if (configData == null) { throw new IllegalArgumentException("DTM has not been configured yet (ConfigData is null)"); } validateCompensationVector(compensationVector); this.compensationVector = compensationVector; logger.debug("Compensation vector set to " + compensationVector); int i = 1; for (VectorValue vectorValue : compensationVector.getVectorValues()) { String subnet = vectorValue.getTunnelEndPrefix().getPrefix() + "/" + Integer.toString(vectorValue.getTunnelEndPrefix().getPrefixLength()); SubnetUtils utils = new SubnetUtils(subnet); for (ConfigDataEntry configDataEntry : configData.getEntries()) { dcNumberCompensateMap.put(i, Boolean.TRUE); //TODO for (TunnelInfo tunnelInfo : configDataEntry.getTunnels()) { if (utils.getInfo() .isInRange(tunnelInfo.getTunnelID().getRemoteTunnelEndAddress().getPrefix())) { daRouterCVectorMap.put((short) tunnelInfo.getDaRouterOfPortNumber(), vectorValue.getValue()); if (configData.getOperationModeSDN() == OperationModeSDN.proactiveWithReferenceVector || configData .getOperationModeSDN() == OperationModeSDN.reactiveWithReferenceVector) { transmittedBytesStartMap.put((short) tunnelInfo.getDaRouterOfPortNumber(), transmittedBytesMap.get((short) tunnelInfo.getDaRouterOfPortNumber())); if (vectorValue.getValue() > 0) { daRouterCompenstatingToTunnelMap.put((short) tunnelInfo.getDaRouterOfPortNumber(), (short) 1); } if (vectorValue.getValue() < 0) { daRouterCompenstatingToTunnelMap.put((short) tunnelInfo.getDaRouterOfPortNumber(), (short) -1); } if (vectorValue.getValue() == 0) { daRouterCompenstatingToTunnelMap.put((short) tunnelInfo.getDaRouterOfPortNumber(), (short) 0); } } } } i++; } } for (VectorValue vectorValue : compensationVector.getVectorValues()) { cVectorMap.put(vectorValue.getTunnelEndPrefix(), vectorValue.getValue()); if (vectorValue.getValue() > 0) { compensatingMap.put((short) compensationVector.getSourceAsNumber(), true); compensatingToTunnelMap.put((short) compensationVector.getSourceAsNumber(), vectorValue.getTunnelEndPrefix()); } } if (configData.getOperationModeSDN() == OperationModeSDN.proactiveWithReferenceVector || configData.getOperationModeSDN() == OperationModeSDN.proactiveWithoutReferenceVector) { sendStaticFlowRule(getProactiveOutOfPortNumber()); } logger.debug("setCompensationVector(CVector) end"); }
From source file:com.cloud.network.bigswitch.BigSwitchBcfUtils.java
public List<AclData> listACLbyNetwork(Network network) { List<AclData> aclList = new ArrayList<AclData>(); List<FirewallRuleVO> fwRules; fwRules = _fwRulesDao.listByNetworkAndPurposeAndNotRevoked(network.getId(), Purpose.Firewall); List<FirewallRulesCidrsVO> fwCidrList = null; SubnetUtils utils;/*w w w. j a v a 2s .co m*/ for (FirewallRuleVO rule : fwRules) { AclData acl = new AclData(); acl.setId(rule.getUuid()); acl.setPriority((int) rule.getId()); // CloudStack Firewall interface does not have priority acl.setIpProto(rule.getProtocol()); String cidr = null; Integer port = rule.getSourcePortStart(); fwCidrList = _fwCidrsDao.listByFirewallRuleId(rule.getId()); if (fwCidrList != null) { if (fwCidrList.size() > 1 || !rule.getSourcePortEnd().equals(port)) { continue; } else { cidr = fwCidrList.get(0).getCidr(); } } if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) { cidr = ""; } else { utils = new SubnetUtils(cidr); if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) { continue; } } acl.setSource(acl.new AclNetwork(cidr, port)); acl.setAction("permit"); aclList.add(acl); } List<NetworkACLItemVO> aclItems; List<NetworkACLItemCidrsVO> aclCidrList; if (network.getNetworkACLId() != null) { aclItems = _aclItemDao.listByACL(network.getNetworkACLId()); for (NetworkACLItem item : aclItems) { AclData acl = new AclData(); acl.setId(item.getUuid()); acl.setPriority(item.getNumber()); acl.setIpProto(item.getProtocol()); String cidr = null; // currently BCF supports single cidr policy Integer port = item.getSourcePortStart(); // currently BCF supports single port policy aclCidrList = _aclItemCidrsDao.listByNetworkACLItemId(item.getId()); if (aclCidrList != null) { if (aclCidrList.size() > 1 || !item.getSourcePortEnd().equals(port)) { continue; } else { cidr = aclCidrList.get(0).getCidr(); } } if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) { cidr = ""; } else { utils = new SubnetUtils(cidr); if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) { continue; } } acl.setSource(acl.new AclNetwork(cidr, port)); acl.setAction(item.getAction().name()); aclList.add(acl); } } return aclList; }
From source file:com.vmware.photon.controller.api.backend.workflows.RemoveFloatingIpFromVmWorkflowServiceTest.java
private static DhcpSubnetService.State createDhcpRootSubnetServiceInCloudStore(TestEnvironment testEnvironment) throws Throwable { String cidr = "192.168.1.0/24"; SubnetUtils subnetUtils = new SubnetUtils(cidr); SubnetUtils.SubnetInfo subnetInfo = subnetUtils.getInfo(); DhcpSubnetService.State state = new DhcpSubnetService.State(); state.cidr = cidr;//from w w w . j av a 2s. com state.lowIp = IpHelper.ipStringToLong(subnetInfo.getLowAddress()); state.highIp = IpHelper.ipStringToLong(subnetInfo.getHighAddress()); state.documentSelfLink = DhcpSubnetService.FLOATING_IP_SUBNET_SINGLETON_LINK; state.isFloatingIpSubnet = true; Operation result = testEnvironment.sendPostAndWait(DhcpSubnetService.FACTORY_LINK, state); return result.getBody(DhcpSubnetService.State.class); }