Brian O'Connor | 7cbbbb7 | 2016-04-09 02:13:23 -0700 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2015-present Open Networking Foundation |
Brian O'Connor | 7cbbbb7 | 2016-04-09 02:13:23 -0700 | [diff] [blame] | 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
lishuai | 6c56f5e | 2015-11-17 16:38:19 +0800 | [diff] [blame] | 16 | package org.onosproject.vtn.util; |
| 17 | |
| 18 | import static org.onlab.util.Tools.toHex; |
| 19 | |
| 20 | import java.net.URI; |
| 21 | import java.net.URISyntaxException; |
| 22 | import java.util.Calendar; |
| 23 | |
| 24 | import org.onosproject.core.IdGenerator; |
| 25 | import org.onosproject.net.DeviceId; |
| 26 | |
| 27 | public final class DataPathIdGenerator implements IdGenerator { |
| 28 | private static final String SCHEME = "of"; |
| 29 | private String ipAddress; |
| 30 | private String timeStamp; |
| 31 | |
| 32 | private DataPathIdGenerator(Builder builder) { |
| 33 | this.ipAddress = builder.ipAddress; |
| 34 | Calendar cal = Calendar.getInstance(); |
| 35 | this.timeStamp = String.valueOf(cal.get(Calendar.SECOND)) |
| 36 | + String.valueOf(cal.get(Calendar.MILLISECOND)); |
| 37 | } |
| 38 | |
| 39 | @Override |
| 40 | public long getNewId() { |
| 41 | String dpid = ipAddress.replace(".", "") + timeStamp; |
| 42 | return Long.parseLong(dpid); |
| 43 | } |
| 44 | |
| 45 | public String getDpId() { |
| 46 | return toHex(getNewId()); |
| 47 | } |
| 48 | |
| 49 | public DeviceId getDeviceId() { |
| 50 | try { |
| 51 | URI uri = new URI(SCHEME, toHex(getNewId()), null); |
| 52 | return DeviceId.deviceId(uri); |
| 53 | } catch (URISyntaxException e) { |
| 54 | return null; |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Returns a new builder. |
| 60 | * |
| 61 | * @return new builder |
| 62 | */ |
| 63 | public static Builder builder() { |
| 64 | return new Builder(); |
| 65 | } |
| 66 | |
| 67 | public static final class Builder { |
| 68 | private String ipAddress; |
| 69 | |
| 70 | public Builder addIpAddress(String ipAddress) { |
| 71 | this.ipAddress = ipAddress; |
| 72 | return this; |
| 73 | } |
| 74 | |
| 75 | public DataPathIdGenerator build() { |
| 76 | return new DataPathIdGenerator(this); |
| 77 | } |
| 78 | } |
| 79 | } |