List of usage examples for com.google.common.net InetAddresses forString
public static InetAddress forString(String ipString)
From source file:com.tresys.jalop.utils.jnltest.Config.Config.java
/** * Get IP address from the {@link JSONObject}. This expects there to be a * key with the name "address" in the {@link JSONObject} obj. * * @param obj//from ww w.j a v a 2s.c om * The context to look in. * @throws ConfigurationException * If 'address' is not found. */ void handleAddress(final JSONObject obj) throws ConfigurationException { final String addrString = itemAsString(ADDRESS, obj); this.address = InetAddresses.forString(addrString); }
From source file:com.eucalyptus.auth.euare.identity.region.RegionConfigurationManager.java
public boolean isValidForwardedForAddress(final String address) { boolean valid = false; try {/*from w w w . j ava 2 s .c om*/ valid = isValidAddress(InetAddresses.forString(address), RegionInfoToCidrSetTransform.FORWARDED_FOR); } catch (final IllegalArgumentException e) { // invalid } return valid; }
From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.IpConversionUtil.java
/** * Convert Ipv6Address object to a valid Canonical v6 address in byte format * * @param ipv6Address - v6 Address object * @return - byte array of size 16. Last byte contains netmask *///from w w w . ja va2s . co m public static byte[] canonicalBinaryV6Address(final Ipv6Address ipv6Address) { /* * Do not modify this routine to take direct strings input!!! * Key checks have been removed based on the assumption that * the input is validated via regexps in Ipv6Prefix() */ String[] address = (ipv6Address.getValue()).split("%"); int colonp; char ch; boolean saw_xdigit; /* Isn't it fun - the above variable names are the same in BSD and Sun sources */ int val; char[] src = address[0].toCharArray(); byte[] dst = new byte[INADDR6SZ]; int src_length = src.length; colonp = -1; int i = 0, j = 0; /* Leading :: requires some special handling. */ /* Isn't it fun - the above comment is again the same in BSD and Sun sources, * We will derive our code from BSD. Shakespear always sounds better * in original Clingon. So does Dilbert. */ if (src[i] == ':') { Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address"); } int curtok = i; saw_xdigit = false; val = 0; while (i < src_length) { ch = src[i++]; int chval = Character.digit(ch, 16); /* Business as usual - ipv6 address digit. * We can remove all checks from the original BSD code because * the regexp has already verified that we are not being fed * anything bigger than 0xffff between the separators. */ if (chval != -1) { val <<= 4; val |= chval; saw_xdigit = true; continue; } /* v6 separator */ if (ch == ':') { curtok = i; if (!saw_xdigit) { /* no need to check separator position validity - regexp does that */ colonp = j; continue; } /* removed overrun check - the regexp checks for valid data */ dst[j++] = (byte) ((val >>> 8) & 0xff); dst[j++] = (byte) (val & 0xff); saw_xdigit = false; val = 0; continue; } /* frankenstein - v4 attached to v6, mixed notation */ if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) { /* this has passed the regexp so it is fairly safe to parse it * straight away. As v4 addresses do not suffer from the same * defficiencies as the java v6 implementation we can invoke it * straight away and be done with it */ Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping"); InetAddress _inet_form = InetAddresses.forString(address[0].substring(curtok, src_length)); Preconditions.checkArgument(_inet_form instanceof Inet4Address); System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ); j += INADDR4SZ; saw_xdigit = false; break; } /* removed parser exit on invalid char - no need to do it, regexp checks it */ } if (saw_xdigit) { Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur"); dst[j++] = (byte) ((val >> 8) & 0xff); dst[j++] = (byte) (val & 0xff); } if (colonp != -1) { int n = j - colonp; Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur"); for (i = 1; i <= n; i++) { dst[INADDR6SZ - i] = dst[colonp + n - i]; dst[colonp + n - i] = 0; } j = INADDR6SZ; } Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur"); return dst; }
From source file:com.gemini.provision.network.openstack.NetworkProviderOpenStackImpl.java
@Override public List<GeminiNetwork> getNetworks(GeminiTenant tenant, GeminiEnvironment env) { //authenticate the session with the OpenStack installation OSClient os = OSFactory.builder().endpoint(env.getEndPoint()) .credentials(env.getAdminUserName(), env.getAdminPassword()).tenantName(tenant.getName()) .authenticate();//w w w. java 2 s . c o m if (os == null) { Logger.error("Failed to authenticate Tenant: {}", ToStringBuilder.reflectionToString(tenant, ToStringStyle.MULTI_LINE_STYLE)); return null; } //get all the subnets List<? extends Network> networks = os.networking().network().list(); List<GeminiNetwork> gemNetworks = new ArrayList(); //map the list of network gateways and their subnets to gemini equivalents networks.stream().forEach(osn -> { GeminiNetwork gn = null; try { //first see if this network belongs to an application gn = env.getApplications().stream().map(GeminiApplication::getNetworks).flatMap(List::stream) //invoke the getNetworks on each application and convert the result into one large stream .filter(n -> n.getCloudID().equals(osn.getId())) //filter on the OpenStack network object cloud id .findFirst().get(); gn.setCloudID(osn.getId()); //in the event the ID has not been updated } catch (NoSuchElementException | NullPointerException e) { //not part of an application, see if it is in the orphan list try { gn = env.getOrphanNetworks().stream().filter(n -> n.getCloudID().equals(osn.getId())) //filter on the OpenStack network object cloud id .findFirst().get(); } catch (NoSuchElementException | NullPointerException ex) { //not an error, just log the event. the network object will be created below Logger.debug("Network {} not mapped in Gemini models, creating one...", osn.getName()); } } GeminiNetwork newGn = null; if (gn == null) { newGn = new GeminiNetwork(); newGn.setName(osn.getName()); newGn.setCloudID(osn.getId()); if (osn.getNetworkType() != null) { newGn.setNetworkType(osn.getNetworkType().name()); } //we don't which application this network belongs to... so add it to orphan networks list env.addOrphanNetwork(newGn); gn = newGn; } //add the subnets to the new network. For some reason Network::getNeutronSubnets //always returned null. List all subnets and filter by the parent network id List<? extends Subnet> osSubnets = os.networking().subnet().list(); if (osSubnets != null && !osSubnets.isEmpty() && osSubnets.stream().anyMatch(osSubnet -> osSubnet.getNetworkId().equals(osn.getId()))) { GeminiNetwork tmpParent = newGn == null ? gn : newGn; osSubnets.stream().filter(osSubnet -> osSubnet.getNetworkId().equals(osn.getId())) .forEach(osSubnet -> { if (tmpParent.getSubnets().stream() .noneMatch(s -> s.getName().equals(osSubnet.getName()))) { //this subnet is not mapped on the Gemini side GeminiSubnet geminiSubnet = new GeminiSubnet(); geminiSubnet.setCloudID(osSubnet.getId()); geminiSubnet.setParent(tmpParent); geminiSubnet.setCidr(osSubnet.getCidr()); geminiSubnet.setName(osSubnet.getName()); geminiSubnet.setEnableDHCP(osSubnet.isDHCPEnabled()); geminiSubnet.setParent(tmpParent); geminiSubnet.setNetworkType( osSubnet.getIpVersion() == IPVersionType.V4 ? IPAddressType.IPv4 : IPAddressType.IPv6); // try { // geminiSubnet.setGateway(env.getGateways().stream().filter(g -> g.getName().equals(osSubnet.getGateway())).findAny().get()); // } catch (NoSuchElementException | NullPointerException ex) { // Logger.error("Subnet {} has a gateway that isn't mappeed to a an object in Gemini. Gateway {}", // geminiSubnet.getName(), osSubnet.getGateway()); // geminiSubnet.setGateway(null); // } osSubnet.getAllocationPools().stream().forEach(ap -> { GeminiSubnetAllocationPool geminiAp = new GeminiSubnetAllocationPool( InetAddresses.forString(ap.getStart()), InetAddresses.forString(ap.getEnd())); geminiAp.setParent(geminiSubnet); geminiSubnet.addAllocationPool(geminiAp); }); tmpParent.addSubnet(geminiSubnet); } }); } gemNetworks.add(gn); }); return gemNetworks; }
From source file:diskCacheV111.doors.NettyLineBasedDoor.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HAProxyMessage) { HAProxyMessage proxyMessage = (HAProxyMessage) msg; switch (proxyMessage.command()) { case LOCAL: ctx.close();/*from w w w . j a v a 2 s . c o m*/ return; case PROXY: String sourceAddress = proxyMessage.sourceAddress(); String destinationAddress = proxyMessage.destinationAddress(); InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress(); if (proxyMessage.proxiedProtocol() == HAProxyProxiedProtocol.TCP4 || proxyMessage.proxiedProtocol() == HAProxyProxiedProtocol.TCP6) { if (Objects.equals(destinationAddress, localAddress.getAddress().getHostAddress())) { /* Workaround for what looks like a bug in HAProxy - health checks should * generate a LOCAL command, but it appears they do actually use PROXY. */ ctx.close(); return; } else { this.proxyAddress = new InetSocketAddress(InetAddresses.forString(destinationAddress), proxyMessage.destinationPort()); this.remoteAddress = new InetSocketAddress(InetAddresses.forString(sourceAddress), proxyMessage.sourcePort()); } } break; } start(ctx); } else if (msg instanceof String) { if (interpreter == null) { throw new IOException("Unexpected input: " + msg); } commandExecutor.execute(new Command((String) msg)); } }
From source file:google.registry.xml.XmlTestUtils.java
/** * Deeply explore the object and normalize values so that things we consider equal compare so. * The return value consists of two parts: the updated key and the value. The value is * straightforward enough: it is the rendering of the subtree to be attached at the current point. * The key is more complicated, because of namespaces. When an XML element specifies namespaces * using xmlns attributes, those namespaces apply to the element as well as all of its * descendants. That means that, when prefixing the element name with the full namespace path, * as required to do proper comparison, the element name depends on its children. When looping * through a JSONObject map, we can't just recursively generate the value and store it using the * key. We may have to update the key as well, to get the namespaces correct. A returned key of * null indicates that we should use the existing key. A non-null key indicates that we should * replace the existing key.//from w w w . j ava2 s . co m * * @param elementName the name under which the current subtree was found, or null if the current * subtree's name is nonexistent or irrelevant * @param obj the current subtree * @param path the (non-namespaced) element path used for ignoredPaths purposes * @param ignoredPaths the set of paths whose values should be set to IGNORED * @param nsMap the inherited namespace identifier-to-URI map * @return the key under which the rendered subtree should be stored (or null), and the rendered * subtree */ private static Map.Entry<String, Object> normalize(@Nullable String elementName, Object obj, @Nullable String path, Set<String> ignoredPaths, Map<String, String> nsMap) throws Exception { if (obj instanceof JSONObject) { JSONObject jsonObject = (JSONObject) obj; Map<String, Object> map = new HashMap<>(); String[] names = JSONObject.getNames(jsonObject); if (names != null) { // Separate all elements and keys into namespace specifications, which we must process // first, and everything else. ImmutableList.Builder<String> namespacesBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<String> othersBuilder = new ImmutableList.Builder<>(); for (String key : names) { (key.startsWith("xmlns") ? namespacesBuilder : othersBuilder).add(key); } // First, handle all namespace specifications, updating our ns-to-URI map. Use a HashMap // rather than an ImmutableMap.Builder so that we can override existing map entries. HashMap<String, String> newNsMap = new HashMap<>(); newNsMap.putAll(nsMap); for (String key : namespacesBuilder.build()) { // Parse the attribute name, of the form xmlns:nsid, and extract the namespace identifier. // If there's no colon, we are setting the default namespace. List<String> components = Splitter.on(':').splitToList(key); String ns = (components.size() >= 2) ? components.get(1) : ""; newNsMap.put(ns, jsonObject.get(key).toString()); } nsMap = ImmutableMap.copyOf(newNsMap); // Now, handle the non-namespace items, recursively transforming the map and mapping all // namespaces to the full URI for proper comparison. for (String key : othersBuilder.build()) { String simpleKey = Iterables.getLast(Splitter.on(':').split(key)); String newPath = (path == null) ? simpleKey : (path + "." + simpleKey); String mappedKey; Object value; if (ignoredPaths.contains(newPath)) { mappedKey = null; // Set ignored fields to a value that will compare equal. value = "IGNORED"; } else { Map.Entry<String, Object> simpleEntry = normalize(key, jsonObject.get(key), newPath, ignoredPaths, nsMap); mappedKey = simpleEntry.getKey(); value = simpleEntry.getValue(); } if (mappedKey == null) { // Note that this does not follow the XML rules exactly. I read somewhere that attribute // names, unlike element names, never use the default namespace. But after // JSONification, we cannot distinguish between attributes and child elements, so we // apply the default namespace to everything. Hopefully that will not cause a problem. mappedKey = key.equals("content") ? key : mapName(key, nsMap, true); } map.put(mappedKey, value); } } // Map the namespace of the element name of the map we are normalizing. elementName = mapName(elementName, nsMap, true); // If a node has both text content and attributes, the text content will end up under a key // called "content". If that's the only thing left (which will only happen if there was an // "xmlns:*" key that we removed), treat the node as just text and recurse. if (map.size() == 1 && map.containsKey("content")) { return new AbstractMap.SimpleEntry<>(elementName, normalize(null, jsonObject.get("content"), path, ignoredPaths, nsMap).getValue()); } // The conversion to JSON converts <a/> into "" and the semantically equivalent <a></a> into // an empty map, so normalize that here. return new AbstractMap.SimpleEntry<>(elementName, map.isEmpty() ? "" : map); } if (obj instanceof JSONArray) { // Another problem resulting from JSONification: If the array contains elements whose names // are the same before URI expansion, but different after URI expansion, because they use // xmlns attribute that define the namespaces differently, we will screw up. Again, hopefully // that doesn't happen much. The reverse is also true: If the array contains names that are // different before URI expansion, but the same after, we may have a problem, because the // elements will wind up in different JSONArrays as a result of JSONification. We wave our // hands and just assume that the URI expansion of the first element holds for all others. Set<Object> set = new HashSet<>(); String mappedKey = null; for (int i = 0; i < ((JSONArray) obj).length(); ++i) { Map.Entry<String, Object> simpleEntry = normalize(null, ((JSONArray) obj).get(i), path, ignoredPaths, nsMap); if (i == 0) { mappedKey = simpleEntry.getKey(); } set.add(simpleEntry.getValue()); } return new AbstractMap.SimpleEntry<String, Object>(mappedKey, set); } if (obj instanceof Number) { return new AbstractMap.SimpleEntry<String, Object>(null, obj.toString()); } if (obj instanceof Boolean) { return new AbstractMap.SimpleEntry<String, Object>(null, ((Boolean) obj) ? "1" : "0"); } if (obj instanceof String) { // Turn stringified booleans into integers. Both are acceptable as xml boolean values, but // we use "true" and "false" whereas the samples use "1" and "0". if (obj.equals("true")) { return new AbstractMap.SimpleEntry<String, Object>(null, "1"); } if (obj.equals("false")) { return new AbstractMap.SimpleEntry<String, Object>(null, "0"); } String string = obj.toString(); // We use a slightly different datetime format (both legal) than the samples, so normalize // both into Datetime objects. try { return new AbstractMap.SimpleEntry<String, Object>(null, ISODateTimeFormat.dateTime().parseDateTime(string).toDateTime(UTC)); } catch (IllegalArgumentException e) { // It wasn't a DateTime. } try { return new AbstractMap.SimpleEntry<String, Object>(null, ISODateTimeFormat.dateTimeNoMillis().parseDateTime(string).toDateTime(UTC)); } catch (IllegalArgumentException e) { // It wasn't a DateTime. } try { if (!InternetDomainName.isValid(string)) { // It's not a domain name, but it is an InetAddress. Ergo, it's an ip address. return new AbstractMap.SimpleEntry<String, Object>(null, InetAddresses.forString(string)); } } catch (IllegalArgumentException e) { // Not an ip address. } return new AbstractMap.SimpleEntry<String, Object>(null, string); } return new AbstractMap.SimpleEntry<>(null, checkNotNull(obj)); }
From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.common.IpConversionUtil.java
private static byte[] canonicalBinaryV6AddressFromString(final String ipv6Address) { Iterable<String> splittedV6Address = Splitter.on("%").trimResults().omitEmptyStrings().split(ipv6Address); List<String> partsV6Address = Lists.newArrayList(splittedV6Address.iterator()); int colonp;/*from www . j a v a2 s . c om*/ char ch; boolean saw_xdigit; /* Isn't it fun - the above variable names are the same in BSD and Sun sources */ int val; char[] src = partsV6Address.get(0).toCharArray(); byte[] dst = new byte[INADDR6SZ]; int src_length = src.length; colonp = -1; int i = 0, j = 0; /* Leading :: requires some special handling. */ /* Isn't it fun - the above comment is again the same in BSD and Sun sources, * We will derive our code from BSD. Shakespear always sounds better * in original Clingon. So does Dilbert. */ if (src[i] == ':') { Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address"); } int curtok = i; saw_xdigit = false; val = 0; while (i < src_length) { ch = src[i++]; int chval = Character.digit(ch, 16); /* Business as usual - ipv6 address digit. * We can remove all checks from the original BSD code because * the regexp has already verified that we are not being fed * anything bigger than 0xffff between the separators. */ if (chval != -1) { val <<= 4; val |= chval; saw_xdigit = true; continue; } /* v6 separator */ if (ch == ':') { curtok = i; if (!saw_xdigit) { /* no need to check separator position validity - regexp does that */ colonp = j; continue; } /* removed overrun check - the regexp checks for valid data */ dst[j++] = (byte) ((val >>> 8) & 0xff); dst[j++] = (byte) (val & 0xff); saw_xdigit = false; val = 0; continue; } /* frankenstein - v4 attached to v6, mixed notation */ if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) { /* this has passed the regexp so it is fairly safe to parse it * straight away. As v4 addresses do not suffer from the same * defficiencies as the java v6 implementation we can invoke it * straight away and be done with it */ Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping"); InetAddress _inet_form = InetAddresses .forString(partsV6Address.get(0).substring(curtok, src_length)); Preconditions.checkArgument(_inet_form instanceof Inet4Address); System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ); j += INADDR4SZ; saw_xdigit = false; break; } /* removed parser exit on invalid char - no need to do it, regexp checks it */ } if (saw_xdigit) { Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur"); dst[j++] = (byte) ((val >> 8) & 0xff); dst[j++] = (byte) (val & 0xff); } if (colonp != -1) { int n = j - colonp; Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur"); for (i = 1; i <= n; i++) { dst[INADDR6SZ - i] = dst[colonp + n - i]; dst[colonp + n - i] = 0; } j = INADDR6SZ; } Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur"); return dst; }
From source file:com.intellij.util.net.HttpProxySettingsUi.java
private boolean isValid() { if (myUseHTTPProxyRb.isSelected()) { String host = getText(myProxyHostTextField); if (host == null) { return false; }// w w w . jav a2 s. c o m try { HostAndPort parsedHost = HostAndPort.fromString(host); if (parsedHost.hasPort()) { return false; } host = parsedHost.getHostText(); try { InetAddresses.forString(host); return true; } catch (IllegalArgumentException e) { // it is not an IPv4 or IPv6 literal } InternetDomainName.from(host); } catch (IllegalArgumentException e) { return false; } if (myProxyAuthCheckBox.isSelected()) { return !StringUtil.isEmptyOrSpaces(myProxyLoginTextField.getText()) && myProxyPasswordTextField.getPassword().length > 0; } } return true; }
From source file:org.opendaylight.netvirt.ipv6service.utils.Ipv6ServiceUtils.java
public Ipv6Address getIpv6LinkLocalAddressFromMac(MacAddress mac) { byte[] octets = bytesFromHexString(mac.getValue()); /* As per the RFC2373, steps involved to generate a LLA include 1. Convert the 48 bit MAC address to 64 bit value by inserting 0xFFFE between OUI and NIC Specific part. 2. Invert the Universal/Local flag in the OUI portion of the address. 3. Use the prefix "FE80::/10" along with the above 64 bit Interface identifier to generate the IPv6 LLA. */ StringBuffer interfaceID = new StringBuffer(); short u8byte = (short) (octets[0] & 0xff); u8byte ^= 1 << 1; interfaceID.append(Integer.toHexString(0xFF & u8byte)); interfaceID.append(StringUtils.leftPad(Integer.toHexString(0xFF & octets[1]), 2, "0")); interfaceID.append(":"); interfaceID.append(Integer.toHexString(0xFF & octets[2])); interfaceID.append("ff:fe"); interfaceID.append(StringUtils.leftPad(Integer.toHexString(0xFF & octets[3]), 2, "0")); interfaceID.append(":"); interfaceID.append(Integer.toHexString(0xFF & octets[4])); interfaceID.append(StringUtils.leftPad(Integer.toHexString(0xFF & octets[5]), 2, "0")); // Return the address in its fully expanded format. Ipv6Address ipv6LLA = new Ipv6Address( InetAddresses.forString("fe80:0:0:0:" + interfaceID.toString()).getHostAddress()); return ipv6LLA; }
From source file:org.opendaylight.vpnservice.itm.impl.ItmUtils.java
public static InetAddress getInetAddressFromIpAddress(IpAddress ip) { return InetAddresses.forString(ip.getIpv4Address().getValue()); }