2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
6 * ======================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ========================LICENSE_END===================================
21 package org.onap.ccsdk.oran.a1policymanagementservice.repository;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.TypeAdapter;
26 import com.google.gson.stream.JsonReader;
27 import com.google.gson.stream.JsonWriter;
29 import java.io.IOException;
30 import java.time.Duration;
31 import java.time.Instant;
36 public class Service {
38 static class InstantAdapter extends TypeAdapter<Instant> {
40 public Instant read(JsonReader reader) throws IOException {
42 return Instant.now(); // Pretend that the last ping was now (after a restart)
46 public void write(JsonWriter writer, Instant value) throws IOException {
47 writer.value(value.toString());
51 static class DurationAdapter extends TypeAdapter<Duration> {
53 public Duration read(JsonReader reader) throws IOException {
54 long value = reader.nextLong();
55 return Duration.ofNanos(value);
59 public void write(JsonWriter writer, Duration value) throws IOException {
60 writer.value(value.toNanos());
64 public static Gson createGson() {
65 return new GsonBuilder() //
66 .registerTypeAdapter(Instant.class, new Service.InstantAdapter()) //
67 .registerTypeAdapter(Duration.class, new Service.DurationAdapter()) //
72 private final String name;
75 private final Duration keepAliveInterval;
77 private Instant lastPing;
81 private String callbackUrl;
83 public Service(String name, Duration keepAliveInterval, String callbackUrl) {
85 this.keepAliveInterval = keepAliveInterval;
86 this.callbackUrl = callbackUrl;
90 public synchronized void keepAlive() {
91 this.lastPing = Instant.now();
94 public synchronized boolean isExpired() {
95 return this.keepAliveInterval.getSeconds() > 0 && timeSinceLastPing().compareTo(this.keepAliveInterval) > 0;
98 public synchronized Duration timeSinceLastPing() {
99 return Duration.between(this.lastPing, Instant.now());