1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.esigate.http;
17
18 import java.util.LinkedList;
19 import java.util.Queue;
20
21 import org.apache.http.HttpHost;
22 import org.apache.http.HttpRequest;
23 import org.apache.http.client.protocol.HttpClientContext;
24 import org.apache.http.protocol.HttpContext;
25 import org.apache.http.protocol.HttpCoreContext;
26
27 public class OutgoingRequestContext extends HttpClientContext {
28 private static final String PROXY = "PROXY";
29 private static final String OUTGOING_REQUEST = "OUTGOING_REQUEST";
30 private static final String PHYSICAL_HOST = "PHYSICAL_HOST";
31
32 public static OutgoingRequestContext adapt(final HttpContext context) {
33 if (context instanceof OutgoingRequestContext) {
34 return (OutgoingRequestContext) context;
35 } else {
36 return new OutgoingRequestContext(context);
37 }
38 }
39
40 private OutgoingRequestContext(final HttpContext context) {
41 super(context);
42 }
43
44 OutgoingRequestContext() {
45 super();
46 }
47
48 public boolean isProxy() {
49 Boolean proxy = getAttribute(PROXY, Boolean.class);
50 return proxy != null && proxy;
51 }
52
53 void setProxy(boolean proxy) {
54 setAttribute(PROXY, proxy);
55 }
56
57 public OutgoingRequest getOutgoingRequest() {
58 return getAttribute(OUTGOING_REQUEST, OutgoingRequest.class);
59 }
60
61 void setOutgoingRequest(OutgoingRequest outgoingRequest) {
62 setAttribute(OUTGOING_REQUEST, outgoingRequest);
63 }
64
65
66
67
68
69 HttpHost getPhysicalHost() {
70 return getAttribute(PHYSICAL_HOST, HttpHost.class);
71 }
72
73
74
75
76
77
78 void setPhysicalHost(HttpHost httpHost) {
79 setAttribute(PHYSICAL_HOST, httpHost);
80 }
81
82
83
84
85
86
87
88
89
90
91
92 public void setAttribute(String id, Object obj, boolean save) {
93 if (save) {
94 String historyAttribute = id + "history";
95 Queue<Object> history = (Queue<Object>) getAttribute(historyAttribute);
96 if (history == null) {
97 history = new LinkedList<>();
98 setAttribute(historyAttribute, history);
99 }
100 if (this.getAttribute(id) != null) {
101 history.add(getAttribute(id));
102 }
103 }
104 setAttribute(id, obj);
105 }
106
107
108
109
110
111
112
113
114
115
116 public Object removeAttribute(String id, boolean restore) {
117 Object value = removeAttribute(id);
118 if (restore) {
119 String historyAttribute = id + "history";
120 Queue<Object> history = (Queue<Object>) getAttribute(historyAttribute);
121 if (history != null && !history.isEmpty()) {
122 Object previous = history.remove();
123 setAttribute(id, previous);
124 }
125 }
126 return value;
127 }
128
129
130
131
132 public HttpRequest getSentRequest() {
133 return (HttpRequest) getAttribute(HttpCoreContext.HTTP_REQUEST);
134 }
135 }