summaryrefslogtreecommitdiffstats
path: root/ecomp-sdk/epsdk-music/src/main/java/org/onap/portalapp/music/conf/MusicSession.java
blob: dfaf5dc773dfbe85bc4ada412a7c7d9bb483e83b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/*
 * ============LICENSE_START==========================================
 * ONAP Portal SDK
 * ===================================================================
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ============LICENSE_END============================================
 *
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */
/*
 * Copyright 2014-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.portalapp.music.conf;

import java.io.Serializable;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.onap.music.eelf.logging.EELFLoggerDelegate;
import org.onap.music.exceptions.MusicLockingException;
import org.onap.music.exceptions.MusicServiceException;
import org.onap.portalapp.music.service.MusicService;
import org.onap.portalapp.music.util.MusicProperties;
import org.onap.portalapp.music.util.MusicUtil;
import org.springframework.session.MapSession;
import org.springframework.session.Session;

/**
 * <p>
 * A {@link Session} implementation that is backed by a {@link java.util.Map}. The
 * defaults for the properties are:
 * </p>
 * <ul>
 * <li>id - a secure random generated id</li>
 * <li>creationTime - the moment the {@link MapSession} was instantiated</li>
 * <li>lastAccessedTime - the moment the {@link MapSession} was instantiated</li>
 * <li>maxInactiveInterval - 30 minutes</li>
 * </ul>
 *
 * <p>
 * This implementation has no synchronization, so it is best to use the copy constructor
 * when working on multiple threads.
 * </p>
 *
 * @author SRIDHAR REDDY M
 * @since 1.0
 */
public final class MusicSession implements Session, Serializable  {
	/**
	 * Default {@link #setMaxInactiveInterval(Duration)} (30 minutes).
	 */
	public static final int DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS = MusicProperties.getProperty(MusicProperties.SESSION_MAX_INACTIVE_INTERVAL_SECONDS)==null ? 1800 :Integer.valueOf(MusicProperties.getProperty(MusicProperties.SESSION_MAX_INACTIVE_INTERVAL_SECONDS)) ;
	private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicSession.class);

	private String id;
	private String originalId;
	private Map<String, Object> sessionAttrs = new HashMap<>();
	private Instant creationTime = Instant.now();
	private Instant lastAccessedTime = this.creationTime;
	private Map<String,Integer> cachingMap = new HashMap<>();
	private boolean musicCache = MusicUtil.isCached();
	/**
	 * Defaults to 30 minutes.
	 */
	private Duration maxInactiveInterval = Duration.ofSeconds(DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);

	/**
	 * Creates a new instance with a secure randomly generated identifier.
	 */
	public MusicSession() {
		this(generateId());
	}


	/**
	 * Creates a new instance with the specified id. This is preferred to the default
	 * constructor when the id is known to prevent unnecessary consumption on entropy
	 * which can be slow.
	 *
	 * @param id the identifier to use
	 */
	public MusicSession(String id) {
		this.id = id;
		this.originalId = id;
	}

	/**
	 * Creates a new instance from the provided {@link Session}.
	 *
	 * @param session the {@link Session} to initialize this {@link Session} with. Cannot
	 * be null.
	 */
	public MusicSession(Session session) {
		if (session == null) {
			throw new IllegalArgumentException("session cannot be null");
		}
		this.id = session.getId();
		this.originalId = this.id;
		this.sessionAttrs = new HashMap<>(
				session.getAttributeNames().size());
		for (String attrName : session.getAttributeNames()) {
			Object attrValue = session.getAttribute(attrName);
			if (attrValue != null) {
				this.sessionAttrs.put(attrName, attrValue);
			}
		}
		this.creationTime = session.getCreationTime();
		this.lastAccessedTime = session.getLastAccessedTime();
		this.maxInactiveInterval = session.getMaxInactiveInterval();
	}

	@Override
	public void setLastAccessedTime(Instant lastAccessedTime) {
		logger.debug(EELFLoggerDelegate.debugLogger, "setLastAccessedTime: start");
		try{
			MusicService.setAttribute(MusicProperties.LAST_ACCESS_TIME, this.lastAccessedTime, this.id);
		}catch(Exception e){
			logger.error(EELFLoggerDelegate.errorLogger, "setLastAccessedTime failed with id " + this.id, e);
		}
		this.lastAccessedTime = lastAccessedTime;
	}

	@Override
	public Instant getCreationTime() {
		Instant creationTime = null;
		logger.debug(EELFLoggerDelegate.debugLogger, "getCreationTime: start");
		if(musicCache)
			creationTime = this.creationTime;
		else{
			try {
				String creationTimeStr = MusicService.getAttribute( MusicProperties.CREATION_TIME, this.id);
				if(creationTimeStr!=null)
					creationTime = Instant.parse(creationTimeStr); 
				else
					creationTime = Instant.now();
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger, "getCreationTime failed with id " + this.id, e);
			}
		}
		return creationTime;
	}

	@Override
	public String getId() {
		return this.id;
	}

	String getOriginalId() {
		return this.originalId;
	}

	void setOriginalId(String originalId) {
		this.originalId = originalId;
	}

	@Override
	public String changeSessionId() {
		String changedId = generateId();
		setId(changedId);
		return changedId;
	}

	@Override
	public Instant getLastAccessedTime() {
		Instant lastAccessedTime = null;
		logger.debug(EELFLoggerDelegate.debugLogger, "getLastAccessedTime: start");
		if(musicCache)
			lastAccessedTime = this.lastAccessedTime;
		else{
			try {
				String lastAccessedTimeStr = MusicService.getAttribute( MusicProperties.LAST_ACCESS_TIME, this.id);
				if(lastAccessedTimeStr!=null)
					lastAccessedTime = Instant.parse(lastAccessedTimeStr); 
				else
					lastAccessedTime = this.creationTime;
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger, "getLastAccessedTime failed with id "+this.id, e);
			}
		}
		return lastAccessedTime;
	}

	@Override
	public void setMaxInactiveInterval(Duration interval) {
		logger.debug(EELFLoggerDelegate.debugLogger, "setMaxInactiveInterval: start");
		this.maxInactiveInterval = interval;
		try{
			MusicService.setAttribute(MusicProperties.MAX_INACTIVE_INTERVAL, this.maxInactiveInterval, this.id);
		}catch(Exception e){
			logger.error(EELFLoggerDelegate.errorLogger, "setMaxInactiveInterval failed with id " + this.id, e);
		}
	}

	@Override
	public Duration getMaxInactiveInterval() {
		logger.debug(EELFLoggerDelegate.debugLogger, "getMaxInactiveInterval: start");
		Duration maxInactiveInterval = null;
		if(musicCache)
			maxInactiveInterval = this.maxInactiveInterval;
		else{	
			try {
				String maxInactiveIntervalStr = MusicService.getAttribute( MusicProperties.MAX_INACTIVE_INTERVAL, this.id);
				if(maxInactiveIntervalStr!=null)
					maxInactiveInterval = Duration.parse(maxInactiveIntervalStr);
				else
					maxInactiveInterval = Duration.ofSeconds(DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger, "getMaxInactiveInterval failed with id " + this.id, e);
			}
		}
		return maxInactiveInterval==null? Duration.ofSeconds(DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS):maxInactiveInterval;
	}

	@Override
	public boolean isExpired() {
		return isExpired(Instant.now());
	}

	boolean isExpired(Instant now) {
		logger.debug(EELFLoggerDelegate.debugLogger, "isExpired: start");
		boolean isExpired = false;
		Duration maxInactiveInterval = null;
		Instant lastAccessedTime = null;
		try {
			if(musicCache){
				maxInactiveInterval = this.maxInactiveInterval;
				lastAccessedTime = this.lastAccessedTime;
			}else{
				maxInactiveInterval = getMaxInactiveInterval();
				lastAccessedTime = getLastAccessedTime();
			}
			if (maxInactiveInterval.isNegative()) {
				return false;
			}
			isExpired = now.minus(maxInactiveInterval).compareTo(lastAccessedTime) >= 0;
			if(isExpired){
				MusicService.removeSession(this.id);
			}
		} catch (MusicLockingException e) {
			logger.error(EELFLoggerDelegate.errorLogger, "isExpired locking failed with id:" + id, e);
		} catch (MusicServiceException e) {
			logger.error(EELFLoggerDelegate.errorLogger, "isExpired failed with id:" + id, e);
		}
		return isExpired;
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T getAttribute(String attributeName) {
		if(musicCache){
			return (T) this.sessionAttrs.get(attributeName);
		}else{
			try {
				return MusicService.getAttribute( attributeName, this.id);
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger, " getAttribute failed with id:" + this.id + " attribute name "+ attributeName , e);
				return null;
			}	
		}

	}

	@Override
	public Set<String> getAttributeNames() {
		return this.sessionAttrs.keySet();
	}

	@Override
	public void setAttribute(String attributeName, Object attributeValue) {
		if (attributeValue == null) {
			removeAttribute(attributeName);
		}else {
			this.sessionAttrs.put(attributeName, attributeValue);
			try{
				MusicService.setAttribute(attributeName , attributeValue, this.id);
			}catch(Exception e){
				logger.error(EELFLoggerDelegate.errorLogger, " setAttribute failed id:" + this.id + " attribute name "+ attributeName , e);
			}
		}
	}

	@Override
	public void removeAttribute(String attributeName) {
		this.sessionAttrs.remove(attributeName);
		try{
			MusicService.removeAttribute(attributeName, this.id);
		}catch(MusicLockingException e){
			logger.error(EELFLoggerDelegate.errorLogger, " removeAttribute locking failed id:" + this.id + " attribute name "+ attributeName , e);
		}catch(MusicServiceException e){
			logger.error(EELFLoggerDelegate.errorLogger, " removeAttribute failed id:" + this.id + " attribute name "+ attributeName , e);
		}
		
	}

	/**
	 * Sets the time that this {@link Session} was created. The default is when the
	 * {@link Session} was instantiated.
	 * @param creationTime the time that this {@link Session} was created.
	 */
	public void setCreationTime(Instant creationTime) {
		//MusicService musicService = new MusicService();
		this.creationTime = creationTime;
		try{
			MusicService.setAttribute(MusicProperties.CREATION_TIME, creationTime, this.id);
		}catch(Exception e){
			logger.error(EELFLoggerDelegate.errorLogger, " setCreationTime failed id:" + this.id + " creationTime  "+ creationTime , e);
		}

	}

	/**
	 * Sets the identifier for this {@link Session}. The id should be a secure random
	 * generated value to prevent malicious users from guessing this value. The default is
	 * a secure random generated identifier.
	 *
	 * @param id the identifier for this session.
	 */
	public void setId(String id) {
		this.id = id;
	}

	@Override
	public boolean equals(Object obj) {
		return obj instanceof Session && this.id.equals(((Session) obj).getId());
	}

	@Override
	public int hashCode() {
		return this.id.hashCode();
	}

	private static String generateId() {
		return UUID.randomUUID().toString();
	}

	private static final long serialVersionUID = 7160779239673823561L;
}