View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.testing.framework;
29  
30  import java.net.URI;
31  import java.util.HashMap;
32  import java.util.Map;
33  import java.util.Map.Entry;
34  
35  import org.apache.hc.core5.http.ClassicHttpResponse;
36  import org.apache.hc.core5.http.ContentType;
37  import org.apache.hc.core5.http.Header;
38  import org.apache.hc.core5.http.HttpEntity;
39  import org.apache.hc.core5.http.HttpException;
40  import org.apache.hc.core5.http.HttpHost;
41  import org.apache.hc.core5.http.ProtocolVersion;
42  import org.apache.hc.core5.http.io.SocketConfig;
43  import org.apache.hc.core5.http.io.entity.EntityUtils;
44  import org.apache.hc.core5.http.io.entity.StringEntity;
45  import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
46  import org.apache.hc.core5.http.protocol.HttpCoreContext;
47  import org.apache.hc.core5.testing.classic.ClassicTestClient;
48  import org.apache.hc.core5.util.Timeout;
49  
50  public class ClassicTestClientAdapter extends ClientPOJOAdapter {
51  
52      /**
53       * {@inheritDoc}
54       */
55      @Override
56      public Map<String, Object> execute(final String defaultURI, final Map<String, Object> request) throws Exception {
57          // check the request for missing items.
58          if (defaultURI == null) {
59              throw new HttpException("defaultURL cannot be null");
60          }
61          if (request == null) {
62              throw new HttpException("request cannot be null");
63          }
64          if (! request.containsKey(PATH)) {
65              throw new HttpException("Request path should be set.");
66          }
67          if (! request.containsKey(METHOD)) {
68              throw new HttpException("Request method should be set.");
69          }
70  
71          final Timeout timeout;
72          if (request.containsKey(TIMEOUT)) {
73              timeout = Timeout.ofMilliseconds((long) request.get(TIMEOUT));
74          } else {
75              timeout = null;
76          }
77          final ClassicTestClientic/ClassicTestClient.html#ClassicTestClient">ClassicTestClient client = new ClassicTestClient(SocketConfig.custom()
78                  .setSoTimeout(timeout)
79                  .build());
80  
81          // Append the path to the defaultURI.
82          String tempDefaultURI = defaultURI;
83          if (! defaultURI.endsWith("/")) {
84              tempDefaultURI += "/";
85          }
86          final URI startingURI = new URI(tempDefaultURI + request.get(PATH));
87          final URI uri;
88  
89          // append each parameter in the query to the uri.
90          @SuppressWarnings("unchecked")
91          final Map<String, String> queryMap = (Map<String, String>) request.get(QUERY);
92          if (queryMap != null) {
93              final String existingQuery = startingURI.getRawQuery();
94              final StringBuilder newQuery = new StringBuilder(existingQuery == null ? "" : existingQuery);
95  
96              // append each parm to the query
97              for (final Entry<String, String> parm : queryMap.entrySet()) {
98                  newQuery.append("&").append(parm.getKey()).append("=").append(parm.getValue());
99              }
100             // create a uri with the new query.
101             uri = new URI(
102                     startingURI.getRawSchemeSpecificPart(),
103                     startingURI.getRawUserInfo(),
104                     startingURI.getHost(),
105                     startingURI.getPort(),
106                     startingURI.getRawPath(),
107                     newQuery.toString(),
108                     startingURI.getRawFragment());
109         } else {
110             uri = startingURI;
111         }
112 
113         final BasicClassicHttpRequestcHttpRequest.html#BasicClassicHttpRequest">BasicClassicHttpRequest httpRequest = new BasicClassicHttpRequest(request.get(METHOD).toString(), uri);
114 
115         if (request.containsKey(PROTOCOL_VERSION)) {
116             httpRequest.setVersion((ProtocolVersion) request.get(PROTOCOL_VERSION));
117         }
118 
119         // call addHeader for each header in headers.
120         @SuppressWarnings("unchecked")
121         final Map<String, String> headersMap = (Map<String, String>) request.get(HEADERS);
122         if (headersMap != null) {
123             for (final Entry<String, String> header : headersMap.entrySet()) {
124                 httpRequest.addHeader(header.getKey(), header.getValue());
125             }
126         }
127 
128         // call setEntity if a body is specified.
129         final String requestBody = (String) request.get(BODY);
130         if (requestBody != null) {
131             final String requestContentType = (String) request.get(CONTENT_TYPE);
132             final StringEntity entity = requestContentType != null ?
133                                           new StringEntity(requestBody, ContentType.parse(requestContentType)) :
134                                           new StringEntity(requestBody);
135             httpRequest.setEntity(entity);
136         }
137 
138         client.start(null);
139 
140         // Now start the request.
141         final HttpHosttp/HttpHost.html#HttpHost">HttpHost host = new HttpHost(uri.getHost(), uri.getPort());
142         final HttpCoreContext context = HttpCoreContext.create();
143         try (final ClassicHttpResponse response = client.execute(host, httpRequest, context)) {
144             // Prepare the response.  It will contain status, body, headers, and contentType.
145             final HttpEntity entity = response.getEntity();
146             final String body = entity == null ? null : EntityUtils.toString(entity);
147             final String contentType = entity == null ? null : entity.getContentType();
148 
149             // prepare the returned information
150             final Map<String, Object> ret = new HashMap<>();
151             ret.put(STATUS, response.getCode());
152 
153             // convert the headers to a Map
154             final Map<String, Object> headerMap = new HashMap<>();
155             for (final Header header : response.getHeaders()) {
156                 headerMap.put(header.getName(), header.getValue());
157             }
158             ret.put(HEADERS, headerMap);
159             ret.put(BODY, body);
160             ret.put(CONTENT_TYPE, contentType);
161 
162             return ret ;
163         }
164     }
165 
166     /**
167      * {@inheritDoc}
168      */
169     @Override
170     public String getClientName() {
171         return "ClassicTestClient";
172     }
173 }