4d151165f18a67979fb075ffdea7b1521674bbec
[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 / IpPrefixBuilder.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 IpPrefixBuilder {
16     private static final Pattern IPV4_PATTERN = 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])/(([0-9])|([1-2][0-9])|(3[0-2]))");
17     private static final Pattern IPV6_PATTERN1 = 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])))(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))");
18     private static final Pattern IPV6_PATTERN2 = Pattern.compile("(([^:]+:){6}(([^:]+:[^:]+)|(.*\\..*)))|((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)(/.+)");
19
20     private IpPrefixBuilder() {
21
22     }
23
24     public static IpPrefix getDefaultInstance(final String defaultValue) {
25         final Matcher ipv4Matcher = IPV4_PATTERN.matcher(defaultValue);
26
27         if (ipv4Matcher.matches()) {
28             if (IPV6_PATTERN1.matcher(defaultValue).matches() && IPV6_PATTERN2.matcher(defaultValue).matches()) {
29                 throw new IllegalArgumentException(
30                         String.format("Cannot create IpPrefix from \"%s\", matches both %s and %s",
31                                 defaultValue, Ipv4Address.class.getSimpleName(), Ipv6Address.class.getSimpleName()));
32
33             }
34             return new IpPrefix(new Ipv4Prefix(defaultValue));
35         } else if (IPV6_PATTERN1.matcher(defaultValue).matches() && IPV6_PATTERN2.matcher(defaultValue).matches()) {
36             return new IpPrefix(new Ipv6Prefix(defaultValue));
37         } else {
38             throw new IllegalArgumentException("Cannot create IpPrefix from " + defaultValue);
39         }
40     }
41
42 }