1
18
19 package io.undertow.util;
20
21 import java.util.Collections;
22 import java.util.IdentityHashMap;
23 import java.util.List;
24 import java.util.Map;
25
26 import io.undertow.UndertowMessages;
27
28
33 public abstract class AbstractAttachable implements Attachable {
34
35 private Map<AttachmentKey<?>, Object> attachments;
36
37
40 @Override
41 public <T> T getAttachment(final AttachmentKey<T> key) {
42 if (key == null || attachments == null) {
43 return null;
44 }
45 return (T) attachments.get(key);
46 }
47
48
51 @Override
52 public <T> List<T> getAttachmentList(AttachmentKey<? extends List<T>> key) {
53 if (key == null || attachments == null) {
54 return Collections.emptyList();
55 }
56 List<T> list = (List<T>) attachments.get(key);
57 if (list == null) {
58 return Collections.emptyList();
59 }
60 return list;
61 }
62
63
66 @Override
67 public <T> T putAttachment(final AttachmentKey<T> key, final T value) {
68 if (key == null) {
69 throw UndertowMessages.MESSAGES.argumentCannotBeNull("key");
70 }
71 if(attachments == null) {
72 attachments = createAttachmentMap();
73 }
74 return (T) attachments.put(key, value);
75 }
76
77 protected Map<AttachmentKey<?>, Object> createAttachmentMap() {
78 return new IdentityHashMap<>(5);
79 }
80
81
84 @Override
85 public <T> T removeAttachment(final AttachmentKey<T> key) {
86 if (key == null || attachments == null) {
87 return null;
88 }
89 return (T) attachments.remove(key);
90 }
91
92
95 @Override
96 public <T> void addToAttachmentList(final AttachmentKey<AttachmentList<T>> key, final T value) {
97 if (key != null) {
98 if(attachments == null) {
99 attachments = createAttachmentMap();
100 }
101 final Map<AttachmentKey<?>, Object> attachments = this.attachments;
102 final AttachmentList<T> list = (AttachmentList<T>) attachments.get(key);
103 if (list == null) {
104 final AttachmentList<T> newList = new AttachmentList<>(((ListAttachmentKey<T>) key).getValueClass());
105 attachments.put(key, newList);
106 newList.add(value);
107 } else {
108 list.add(value);
109 }
110 }
111 }
112
113 }
114