Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * #%L
   * Wildfly Camel :: Testsuite :: Common
   * %%
   * Copyright (C) 2013 - 2014 RedHat
   * %%
   * 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.
  * #L%
  */
 
 package org.wildfly.camel.test.common;
 
 import java.net.URL;
 import java.util.Map;
 import java.util.Set;

Author(s):
Carlo de Wolf
 
 public class HttpRequest {
 
     private HttpRequest(){
     }
 
     public static HttpRequestBuilder get(String url) {
         return new HttpRequestBuilder(url"GET");
     }
 
     public static HttpRequestBuilder post(String url) {
         return new HttpRequestBuilder(url"POST");
     }
 
     public static HttpRequestBuilder put(String url) {
         return new HttpRequestBuilder(url"PUT");
     }
 
     public static HttpRequestBuilder delete(String url) {
         return new HttpRequestBuilder(url"DELETE");
     }
 
     public static final class HttpRequestBuilder {
         private String requestUrl;
         private String method;
         private String content;
         private long timeout = 10;
         private boolean throwExceptionOnFailure = true;
         private Map<StringStringheaders = new HashMap<>();
         private TimeUnit timeUnit = .;
 
         HttpRequestBuilder(String urlString method) {
             this. = url;
             this. = method;
         }
 
         public HttpRequestBuilder content(String value) {
             this. = value;
             return this;
         }
 
         public HttpRequestBuilder header(String nameString value) {
             this..put(namevalue);
             return this;
         }
 
         public HttpRequestBuilder throwExceptionOnFailure(boolean value) {
             this. = value;
             return this;
         }
 
         public HttpRequestBuilder timeout(long value) {
             this. = value;
             return this;
         }
 
         public HttpRequestBuilder timeout(long valueTimeUnit unit) {
            this. = value;
            this. = unit;
            return this;
        }
        public HttpResponse getResponse() throws TimeoutExceptionIOException {
            Callable<HttpResponsetask = new Callable<HttpResponse>() {
                @Override
                public HttpResponse call() throws Exception {
                    URL url = new URL();
                    final HttpURLConnection conn = (HttpURLConnectionurl.openConnection();
                    conn.setDoInput(true);
                    conn.setRequestMethod();
                    Set<StringheaderNames = .keySet();
                    for(String headerName : headerNames) {
                        conn.setRequestProperty(headerName.get(headerName));
                    }
                    if(.equals("POST") || .equals("PUT")) {
                        conn.setDoOutput(true);
                    }
                    if( != null && !.isEmpty()) {
                        OutputStream outputStream = conn.getOutputStream();
                        outputStream.write(.getBytes("UTF-8"));
                        outputStream.flush();
                        outputStream.close();
                    }
                    return processResponse(conn);
                }
            };
            return executeRequest(task);
        }
        private HttpResponse executeRequest(final Callable<HttpResponsetaskfinal long timeoutfinal TimeUnit unitthrows TimeoutExceptionIOException {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            try {
                Throwable lastCause = null;
                long endTime = System.currentTimeMillis() + unit.toMillis(timeout);
                while (System.currentTimeMillis() < endTime) {
                    Future<HttpResponseresult = executor.submit(task);
                    try {
                        return result.get(timeoutunit);
                    } catch (InterruptedException ex) {
                        throw new IllegalStateException(ex);
                    } catch (ExecutionException ex) {
                        lastCause = ex.getCause();
                        // HttpURLConnection throws FileNotFoundException on 404 so handle this
                        if (lastCause instanceof FileNotFoundException) {
                            HttpResponse httpResult = new HttpResponse();
                            httpResult.setStatusCode(.);
                            return httpResult;
                        } else {
                            continue;
                        }
                    }
                }
                TimeoutException toex = new TimeoutException();
                if (lastCause != null) {
                    toex.initCause(lastCause);
                }
                throw toex;
            } finally {
                executor.shutdownNow();
            }
        }
        private String read(final InputStream inthrows IOException {
            final ByteArrayOutputStream out = new ByteArrayOutputStream();
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            return out.toString();
        }
        private HttpResponse processResponse(HttpURLConnection connthrows IOException {
            int responseCode = conn.getResponseCode();
            if ( && responseCode != .) {
                final InputStream err = conn.getErrorStream();
                try {
                    throw new IOException(read(err));
                } finally {
                    err.close();
                }
            }
            final InputStream in = conn.getInputStream();
            try {
                HttpResponse result = new HttpResponse();
                result.setStatusCode(responseCode);
                result.setBody(read(in));
                return result;
            } finally {
                in.close();
            }
        }
    }
New to GrepCode? Check out our FAQ X