Skip to content

Commit

Permalink
return the response back either as a return value on success or in th…
Browse files Browse the repository at this point in the history
…e exception on a non-200 status code
  • Loading branch information
jmazzitelli committed Apr 21, 2015
1 parent 264af96 commit e401b69
Show file tree
Hide file tree
Showing 2 changed files with 130 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;

Expand Down Expand Up @@ -54,9 +55,10 @@ public static enum Type {
*
* @param host
* @param port if null or -1, no port will be specified in the URL
* @throws MalformedURLException if one of the parameters consists of invalid URL syntax
* @throws RestClientException if the endpoint cannot be used to refer to queues or topics
* or if one of the parameters consists of invalid URL syntax
*/
public RestClient(String host, Integer port) throws MalformedURLException {
public RestClient(String host, Integer port) throws RestClientException {
this("http", host, port);
}

Expand All @@ -66,10 +68,19 @@ public RestClient(String host, Integer port) throws MalformedURLException {
* @param protocol http or https
* @param host
* @param port if null or -1, no port will be specified in the URL
* @throws MalformedURLException if one of the parameters consists of invalid URL syntax
* @throws RestClientException if the endpoint cannot be used to refer to queues or topics
* or if one of the parameters consists of invalid URL syntax
*/
public RestClient(String protocol, String host, Integer port) throws MalformedURLException {
this(new URL(protocol, host, ((port != null) ? port.intValue() : -1), DEFAULT_URL_PATH));
public RestClient(String protocol, String host, Integer port) throws RestClientException {
this(buildDefaultURL(protocol, host, port));
}

private static URL buildDefaultURL(String protocol, String host, Integer port) throws RestClientException {
try {
return new URL(protocol, host, ((port != null) ? port.intValue() : -1), DEFAULT_URL_PATH);
} catch (MalformedURLException e) {
throw new RestClientException(e);
}
}

/**
Expand All @@ -79,10 +90,9 @@ public RestClient(String protocol, String host, Integer port) throws MalformedUR
* If the given URL does not end with a "/", one will be added to it.
*
* @param endpoint the REST server endpoint, not including the queue/topic name
* @throws MalformedURLException if failed to append ending slash to the endpoint URL if one was required
* or if the endpoint cannot be used to refer to queues or topics
* @throws RestClientException if the endpoint cannot be used to refer to queues or topics
*/
public RestClient(URL endpoint) throws MalformedURLException {
public RestClient(URL endpoint) throws RestClientException {
// make sure the endpoint ends with a "/" since we later will append the queue/topic name to it
if (endpoint.toString().endsWith("/")){
this.endpoint = endpoint;
Expand Down Expand Up @@ -113,10 +123,12 @@ public URL getEndpoint() {
* @param topicName name of the topic
* @param jsonPayload the actual message (as a JSON string) to put on the bus
* @param headers any headers to send with the message (can be null or empty)
* @throws Exception
* @return the response
* @throws RestClientException if the response was not a 200 status code
*/
public void postTopicMessage(String topicName, String jsonPayload, Map<String, String> headers) throws Exception {
postMessage(Type.TOPIC, topicName, jsonPayload, headers);
public HttpResponse postTopicMessage(String topicName, String jsonPayload, Map<String, String> headers)
throws RestClientException {
return postMessage(Type.TOPIC, topicName, jsonPayload, headers);
}

/**
Expand All @@ -125,22 +137,34 @@ public void postTopicMessage(String topicName, String jsonPayload, Map<String, S
* @param queueName name of the queue
* @param jsonPayload the actual message (as a JSON string) to put on the bus
* @param headers any headers to send with the message (can be null or empty)
* @throws Exception
* @return the response
* @throws RestClientException if the response was not a 200 status code
*/
public void postQueueMessage(String queueName, String jsonPayload, Map<String, String> headers) throws Exception {
postMessage(Type.QUEUE, queueName, jsonPayload, headers);
public HttpResponse postQueueMessage(String queueName, String jsonPayload, Map<String, String> headers)
throws RestClientException {
return postMessage(Type.QUEUE, queueName, jsonPayload, headers);
}

protected void postMessage(Type type, String name, String jsonPayload, Map<String, String> headers)
throws Exception {
protected HttpResponse postMessage(Type type, String name, String jsonPayload, Map<String, String> headers)
throws RestClientException {
URL messageUrl = getEndpointForType(type, name);
sendPost(messageUrl.toURI(), jsonPayload, headers);
URI uri;
try {
uri = messageUrl.toURI();
} catch (URISyntaxException e) {
throw new RestClientException(e);
}
HttpResponse response = sendPost(uri, jsonPayload, headers);
return response;
}

protected void sendPost(URI uri, String jsonPayload, Map<String, String> headers) throws Exception {
protected HttpResponse sendPost(URI uri, String jsonPayload, Map<String, String> headers)
throws RestClientException {
LOG.tracef("Posting message to bus. uri=[%s], json=[%s], headers[%s]", uri, jsonPayload, headers);

HttpPost request = null;
HttpResponse httpResponse = null;

try {
request = new HttpPost(uri);
if (headers != null) {
Expand All @@ -149,39 +173,46 @@ protected void sendPost(URI uri, String jsonPayload, Map<String, String> headers
}
}
request.setEntity(new StringEntity(jsonPayload, ContentType.APPLICATION_JSON));
HttpResponse httpResponse = httpclient.execute(request);
httpResponse = httpclient.execute(request);
StatusLine statusLine = httpResponse.getStatusLine();

if (statusLine.getStatusCode() != 200) {
throw new Exception("HTTP post request failed. status-code=[" + statusLine.getStatusCode()
+ "], reason=["
+ statusLine.getReasonPhrase() + "], url=[" + request.getURI() + "]");
}

return httpResponse;
} catch (Exception e) {
LOG.debugf("Failed to post message to bus via URI [%s]. Cause: [%s]", uri.toString(), e.toString());
throw e;
String errStr = String.format("Failed to post message to bus via URI [%s]", uri.toString());
LOG.debugf("%s. Cause=[%s]", errStr, e.toString());
throw new RestClientException(httpResponse, errStr, e);
} finally {
if (request != null) {
request.releaseConnection();
}
}
}

protected URL getEndpointForType(Type type, String name) throws MalformedURLException {
protected URL getEndpointForType(Type type, String name) throws RestClientException {
switch (type) {
case QUEUE:
return appendToURL(endpoint, name + "?type=queue");
case TOPIC:
return appendToURL(endpoint, name + "?type=topic");
default: {
throw new RuntimeException("Invalid type - please report this bug");
throw new RuntimeException("Invalid type [" + type + "] - please report this bug");
}
}
}

protected URL appendToURL(URL url, String appendage) throws MalformedURLException {
protected URL appendToURL(URL url, String appendage) throws RestClientException {
String oldUrlString = url.toString();
String newUrlString = oldUrlString + appendage;
return new URL(newUrlString);
try {
return new URL(newUrlString);
} catch (MalformedURLException e) {
throw new RestClientException(String.format("URL [%s] cannot be appended with [%s]", url, appendage), e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.bus.restclient;

import org.apache.http.HttpResponse;

/**
* Thrown when the {@link RestClient} hits an error condition.
*/
public class RestClientException extends Exception {
private static final long serialVersionUID = 1L;

private final HttpResponse httpResponse;

/**
* If the exception occurred after a response was received, and that response is available
* this will be that response.
*
* @return the response that can help determine the error that occurred
*/
public HttpResponse getHttpResponse() {
return httpResponse;
}

public RestClientException() {
this((HttpResponse) null);
}

public RestClientException(String message, Throwable cause) {
this((HttpResponse) null, message, cause);
}

public RestClientException(String message) {
this((HttpResponse) null, message);
}

public RestClientException(Throwable cause) {
this((HttpResponse) null, cause);
}

public RestClientException(HttpResponse httpResponse) {
super();
this.httpResponse = httpResponse;
}

public RestClientException(HttpResponse httpResponse, String message, Throwable cause) {
super(message, cause);
this.httpResponse = httpResponse;
}

public RestClientException(HttpResponse httpResponse, String message) {
super(message);
this.httpResponse = httpResponse;
}

public RestClientException(HttpResponse httpResponse, Throwable cause) {
super(cause);
this.httpResponse = httpResponse;
}
}

0 comments on commit e401b69

Please sign in to comment.