26bfa2d981ddc67d45915ec03f49a34a31a4fc29
[mdsal.git] / model / ietf / ietf-inet-types / src / main / java / org / opendaylight / yang / gen / v1 / urn / ietf / params / xml / ns / yang / ietf / inet / types / rev100924 / IpAddressBuilder.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924;
9
10 import java.util.regex.Matcher;
11 import java.util.regex.Pattern;
12
13 /**
14  **/
15 public final class IpAddressBuilder {
16     private static final Pattern IPV4_PATTERN =
17             Pattern.compile("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?");
18     private static final Pattern IPV6_PATTERN1 =
19             Pattern.compile("((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))(%[\\p{N}\\p{L}]+)?");
20     private static final Pattern IPV6_PATTERN2 =
21             Pattern.compile("(([^:]+:){6}(([^:]+:[^:]+)|(.*\\..*)))|((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)(%.+)?");
22
23     private IpAddressBuilder() {
24
25     }
26
27     public static IpAddress getDefaultInstance(final String defaultValue) {
28         final Matcher ipv4Matcher = IPV4_PATTERN.matcher(defaultValue);
29
30         if (ipv4Matcher.matches()) {
31             if (IPV6_PATTERN1.matcher(defaultValue).matches() && IPV6_PATTERN2.matcher(defaultValue).matches()) {
32                 throw new IllegalArgumentException(
33                         String.format("Cannot create IpAddress from \"%s\", matches both %s and %s",
34                                 defaultValue, Ipv4Address.class.getSimpleName(), Ipv6Address.class.getSimpleName()));
35
36             }
37             return new IpAddress(new Ipv4Address(defaultValue));
38         } else if (IPV6_PATTERN1.matcher(defaultValue).matches() && IPV6_PATTERN2.matcher(defaultValue).matches()) {
39             return new IpAddress(new Ipv6Address(defaultValue));
40         } else {
41             throw new IllegalArgumentException("Cannot create IpAddress from " + defaultValue);
42         }
43     }
44
45 }