[OLINGO-659] API review for ODataRequest/Response

This commit is contained in:
Michael Bolz 2015-08-14 09:51:12 +02:00
parent 4caeb8c00d
commit df5a4ff0de
13 changed files with 142 additions and 43 deletions

View File

@ -60,6 +60,30 @@ public class ODataRequest {
this.method = method; this.method = method;
} }
/**
* <p>Set a header to the response.</p>
* <p>The header name will be handled as case-insensitive key.</p>
* <p>If a header already exists then the header will be replaced by this new value.</p>
* @param name case-insensitive header name
* @param value value for the given header name
* @see <a href="http://ietf.org/rfc/rfc7230.txt">RFC 7230, section 3.2.2</a>
*/
public void setHeader(final String name, final String value) {
headers.setHeader(name, value);
}
/**
* <p>Adds a header to the request.</p>
* <p>The header name will be handled as case-insensitive key.</p>
* <p>If a header already exists then the list of values will just be extended.</p>
* @param name case-insensitive header name
* @param value value for the given header name
* @see <a href="http://ietf.org/rfc/rfc7230.txt">RFC 7230, section 3.2.2</a>
*/
public void addHeader(final String name, final String value) {
headers.addHeader(name, value);
}
/** /**
* <p>Adds a header to the request.</p> * <p>Adds a header to the request.</p>
* <p>The header name will be handled as case-insensitive key.</p> * <p>The header name will be handled as case-insensitive key.</p>
@ -73,20 +97,20 @@ public class ODataRequest {
} }
/** /**
* Gets header value for a given name. * Get header values for a given name.
* @param name the header name as a case-insensitive key * @param name the header name as a case-insensitive key
* @return the header value(s) or null if not found * @return the header value(s) or null if not found
*/ */
public List<String> getHeaders(final String name) { public List<String> getHeaders(final String name) {
HttpHeader h = headers.getHeader(name); HttpHeader h = headers.getHeader(name);
if(h == null) { if(h == null) {
return null;//Collections.emptyList(); return null;
} }
return new ArrayList<String>(h.getValues()); return new ArrayList<String>(h.getValues());
} }
/** /**
* Gets first header value for a given name. * Get first header value for a given name.
* @param name the header name as a case-insensitive key * @param name the header name as a case-insensitive key
* @return the first header value or null if not found * @return the first header value or null if not found
*/ */

View File

@ -19,9 +19,11 @@
package org.apache.olingo.server.api; package org.apache.olingo.server.api;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.olingo.commons.api.http.HttpHeader; import org.apache.olingo.commons.api.http.HttpHeader;
@ -54,27 +56,81 @@ public class ODataResponse {
} }
/** /**
* Sets a header. * <p>Set a header to the response.</p>
* @param name the name * <p>The header name will be handled as case-insensitive key.</p>
* @param value the value * <p>If a header already exists then the header will be replaced by this new value.</p>
* @param name case-insensitive header name
* @param value value for the given header name
* @see <a href="http://ietf.org/rfc/rfc7230.txt">RFC 7230, section 3.2.2</a>
*/ */
public void setHeader(final String name, final String value) { public void setHeader(final String name, final String value) {
headers.setHeader(name, value); headers.setHeader(name, value);
} }
/** /**
* Gets all headers. * <p>Adds a header to the response.</p>
* <p>The header name will be handled as case-insensitive key.</p>
* <p>If a header already exists then the list of values will just be extended.</p>
* @param name case-insensitive header name
* @param value value for the given header name
* @see <a href="http://ietf.org/rfc/rfc7230.txt">RFC 7230, section 3.2.2</a>
*/
public void addHeader(final String name, final String value) {
headers.setHeader(name, value);
}
/**
* <p>Adds a header to the response.</p>
* <p>The header name will be handled as case-insensitive key.</p>
* <p>If a header already exists then the list of values will just be extended.</p>
* @param name case-insensitive header name
* @param values list of values for the given header name
* @see <a href="http://ietf.org/rfc/rfc7230.txt">RFC 7230, section 3.2.2</a>
*/
public void addHeader(final String name, final List<String> values) {
headers.addHeader(name, values);
}
/**
* Get all headers with the according values.
*
* @return an unmodifiable Map of header names/values * @return an unmodifiable Map of header names/values
*/ */
public Map<String, String> getHeaders() { public Map<String, List<String>> getAllHeaders() {
Map<String, String> result = new HashMap<String, String>(); Map<String, List<String>> result = new HashMap<String, List<String>>();
Collection<HttpHeader> allHeaders = headers.getHeaders(); Collection<HttpHeader> allHeaders = headers.getHeaders();
for (HttpHeader header : allHeaders) { for (HttpHeader header : allHeaders) {
result.put(header.getName(), header.getValues().iterator().next()); result.put(header.getName(), new ArrayList<String>(header.getValues()));
} }
return Collections.unmodifiableMap(result); return Collections.unmodifiableMap(result);
} }
/**
* Gets header value for a given name.
* @param name the header name as a case-insensitive key
* @return the header value(s) or null if not found
*/
public List<String> getHeaders(final String name) {
HttpHeader h = headers.getHeader(name);
if(h == null) {
return null;
}
return new ArrayList<String>(h.getValues());
}
/**
* Gets first header value for a given name.
* If header name is not known <code>null</code> is returned.
*
* @param name the header name as a case-insensitive key
* @return the first header value or null if not found
*/
public String getHeader(final String name) {
final List<String> values = getHeaders(name);
return values == null ? null : values.get(0);
}
/** /**
* Sets the content (body). * Sets the content (body).
* @param content the content as {@link InputStream} * @param content the content as {@link InputStream}

View File

@ -55,7 +55,7 @@ public abstract class ServiceResponse {
if (!this.closed) { if (!this.closed) {
if (this.strictApplyPreferences) { if (this.strictApplyPreferences) {
if (!preferences.isEmpty()) { if (!preferences.isEmpty()) {
assert(this.response.getHeaders().get("Preference-Applied") != null); assert(this.response.getAllHeaders().get("Preference-Applied") != null);
} }
} }
this.closed = true; this.closed = true;
@ -97,7 +97,7 @@ public abstract class ServiceResponse {
public void writeHeader(String key, String value) { public void writeHeader(String key, String value) {
if ("Preference-Applied".equals(key)) { if ("Preference-Applied".equals(key)) {
String previous = this.response.getHeaders().get(key); String previous = this.response.getHeader(key);
if (previous != null) { if (previous != null) {
value = previous+";"+value; value = previous+";"+value;
} }

View File

@ -117,7 +117,9 @@ public class ODataHandler {
private void processInternal(final ODataRequest request, final ODataResponse response) private void processInternal(final ODataRequest request, final ODataResponse response)
throws ODataApplicationException, ODataLibraryException { throws ODataApplicationException, ODataLibraryException {
validateODataVersion(request, response); response.setHeader(HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString());
validateODataVersion(request);
int measurementUriParser = debugger.startRuntimeMeasurement("UriParser", "parseUri"); int measurementUriParser = debugger.startRuntimeMeasurement("UriParser", "parseUri");
uriInfo = new Parser().parseUri(request.getRawODataPath(), request.getRawQueryPath(), null, uriInfo = new Parser().parseUri(request.getRawODataPath(), request.getRawQueryPath(), null,
@ -157,11 +159,9 @@ public class ODataHandler {
debugger.stopRuntimeMeasurement(measurementHandle); debugger.stopRuntimeMeasurement(measurementHandle);
} }
private void validateODataVersion(final ODataRequest request, final ODataResponse response) private void validateODataVersion(final ODataRequest request)
throws ODataHandlerException { throws ODataHandlerException {
final String maxVersion = request.getHeader(HttpHeader.ODATA_MAX_VERSION); final String maxVersion = request.getHeader(HttpHeader.ODATA_MAX_VERSION);
response.setHeader(HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString());
if (maxVersion != null) { if (maxVersion != null) {
if (ODataServiceVersion.isBiggerThan(ODataServiceVersion.V40.toString(), maxVersion)) { if (ODataServiceVersion.isBiggerThan(ODataServiceVersion.V40.toString(), maxVersion)) {
throw new ODataHandlerException("ODataVersion not supported: " + maxVersion, throw new ODataHandlerException("ODataVersion not supported: " + maxVersion,

View File

@ -147,8 +147,10 @@ public class ODataHttpHandlerImpl implements ODataHttpHandler {
static void convertToHttp(final HttpServletResponse response, final ODataResponse odResponse) { static void convertToHttp(final HttpServletResponse response, final ODataResponse odResponse) {
response.setStatus(odResponse.getStatusCode()); response.setStatus(odResponse.getStatusCode());
for (Entry<String, String> entry : odResponse.getHeaders().entrySet()) { for (Entry<String, List<String>> entry : odResponse.getAllHeaders().entrySet()) {
response.setHeader(entry.getKey(), entry.getValue()); for (String headerValue : entry.getValue()) {
response.addHeader(entry.getKey(), headerValue);
}
} }
InputStream input = odResponse.getContent(); InputStream input = odResponse.getContent();

View File

@ -78,7 +78,7 @@ public class BatchReferenceRewriter {
if (request.getMethod() == HttpMethod.POST) { if (request.getMethod() == HttpMethod.POST) {
// Create entity // Create entity
// The URI of the new resource will be generated by the server and published in the location header // The URI of the new resource will be generated by the server and published in the location header
final String locationHeader = response.getHeaders().get(HttpHeader.LOCATION); final String locationHeader = response.getHeader(HttpHeader.LOCATION);
resourceUri = locationHeader == null ? null : parseODataPath(locationHeader, request.getRawBaseUri()); resourceUri = locationHeader == null ? null : parseODataPath(locationHeader, request.getRawBaseUri());
} else { } else {
// Update, Upsert (PUT, PATCH, Delete) // Update, Upsert (PUT, PATCH, Delete)

View File

@ -52,7 +52,7 @@ public class DebugTabBody implements DebugTab {
this.response = response; this.response = response;
this.serviceRoot = serviceRoot == null ? "/" : serviceRoot; this.serviceRoot = serviceRoot == null ? "/" : serviceRoot;
if (response != null) { if (response != null) {
final String contentType = response.getHeaders().get(HttpHeader.CONTENT_TYPE); final String contentType = response.getHeader(HttpHeader.CONTENT_TYPE);
// TODO: Differentiate better // TODO: Differentiate better
if (contentType != null) { if (contentType != null) {
responseContent = ResponseContent.JSON; responseContent = ResponseContent.JSON;
@ -125,7 +125,7 @@ public class DebugTabBody implements DebugTab {
break; break;
case IMAGE: case IMAGE:
// Make header query case insensitive // Make header query case insensitive
writer.append("<img src=\"data:").append(response.getHeaders().get(HttpHeader.CONTENT_TYPE)).append(";base64,") writer.append("<img src=\"data:").append(response.getHeader(HttpHeader.CONTENT_TYPE)).append(";base64,")
.append(body) .append(body)
.append("\" />\n"); .append("\" />\n");
break; break;

View File

@ -21,6 +21,8 @@ package org.apache.olingo.server.core.debug;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.olingo.commons.api.http.HttpStatusCode; import org.apache.olingo.commons.api.http.HttpStatusCode;
@ -36,13 +38,13 @@ public class DebugTabResponse implements DebugTab {
private final ODataResponse response; private final ODataResponse response;
private final String serviceRoot; private final String serviceRoot;
private final HttpStatusCode status; private final HttpStatusCode status;
private final Map<String, String> headers; private final Map<String, List<String>> headers;
public DebugTabResponse(final ODataResponse applicationResponse, final String serviceRoot) { public DebugTabResponse(final ODataResponse applicationResponse, final String serviceRoot) {
this.response = applicationResponse; this.response = applicationResponse;
if (response != null) { if (response != null) {
status = HttpStatusCode.fromStatusCode(response.getStatusCode()); status = HttpStatusCode.fromStatusCode(response.getStatusCode());
headers = response.getHeaders(); headers = response.getAllHeaders();
} else { } else {
status = HttpStatusCode.INTERNAL_SERVER_ERROR; status = HttpStatusCode.INTERNAL_SERVER_ERROR;
headers = Collections.emptyMap(); headers = Collections.emptyMap();
@ -69,7 +71,7 @@ public class DebugTabResponse implements DebugTab {
if (headers != null && !headers.isEmpty()) { if (headers != null && !headers.isEmpty()) {
gen.writeFieldName("headers"); gen.writeFieldName("headers");
DebugResponseHelperImpl.appendJsonTable(gen, headers); DebugResponseHelperImpl.appendJsonTable(gen, map(headers));
} }
gen.writeFieldName("body"); gen.writeFieldName("body");
@ -82,13 +84,25 @@ public class DebugTabResponse implements DebugTab {
gen.writeEndObject(); gen.writeEndObject();
} }
private Map<String, String> map(Map<String, List<String>> headers) {
Map<String, String> result = new HashMap<String, String>();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if(entry.getValue().size() == 1) {
result.put(entry.getKey(), entry.getValue().get(0));
} else {
result.put(entry.getKey(), entry.getValue().toString());
}
}
return result;
}
@Override @Override
public void appendHtml(final Writer writer) throws IOException { public void appendHtml(final Writer writer) throws IOException {
writer.append("<h2>Status Code</h2>\n") writer.append("<h2>Status Code</h2>\n")
.append("<p>").append(Integer.toString(status.getStatusCode())).append(' ') .append("<p>").append(Integer.toString(status.getStatusCode())).append(' ')
.append(status.getInfo()).append("</p>\n") .append(status.getInfo()).append("</p>\n")
.append("<h2>Response Headers</h2>\n"); .append("<h2>Response Headers</h2>\n");
DebugResponseHelperImpl.appendHtmlTable(writer, headers); DebugResponseHelperImpl.appendHtmlTable(writer, map(headers));
writer.append("<h2>Response Body</h2>\n"); writer.append("<h2>Response Body</h2>\n");
if (response != null && response.getContent() != null) { if (response != null && response.getContent() != null) {
new DebugTabBody(response, serviceRoot).appendHtml(writer); new DebugTabBody(response, serviceRoot).appendHtml(writer);

View File

@ -31,6 +31,7 @@ import java.nio.ByteBuffer;
import java.nio.channels.Channels; import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel; import java.nio.channels.WritableByteChannel;
import java.util.List;
import java.util.Map; import java.util.Map;
public class AsyncResponseSerializer { public class AsyncResponseSerializer {
@ -59,17 +60,19 @@ public class AsyncResponseSerializer {
private void appendResponseHeader(final ODataResponse response, private void appendResponseHeader(final ODataResponse response,
final ByteArrayOutputStream buffer) throws IOException { final ByteArrayOutputStream buffer) throws IOException {
final Map<String, String> header = response.getHeaders(); final Map<String, List<String>> header = response.getAllHeaders();
for (final Map.Entry<String, String> entry: header.entrySet()) { for (final Map.Entry<String, List<String>> entry: header.entrySet()) {
appendHeader(entry.getKey(), entry.getValue(), buffer); appendHeader(entry.getKey(), entry.getValue(), buffer);
} }
} }
private void appendHeader(final String name, final String value, final ByteArrayOutputStream buffer) private void appendHeader(final String name, final List<String> values, final ByteArrayOutputStream buffer)
throws IOException { throws IOException {
for (String value : values) {
append(name + COLON + SP + value + CRLF, buffer); append(name + COLON + SP + value + CRLF, buffer);
} }
}
private void appendStatusLine(final ODataResponse response, final ByteArrayOutputStream buffer) private void appendStatusLine(final ODataResponse response, final ByteArrayOutputStream buffer)
throws IOException { throws IOException {

View File

@ -135,12 +135,12 @@ public class BatchResponseSerializer {
private void appendResponseHeader(final ODataResponse response, final int contentLength, private void appendResponseHeader(final ODataResponse response, final int contentLength,
final BodyBuilder builder) { final BodyBuilder builder) {
final Map<String, String> header = response.getHeaders(); final Map<String, List<String>> header = response.getAllHeaders();
for (final Map.Entry<String, String> entry : header.entrySet()) { for (final Map.Entry<String, List<String>> entry : header.entrySet()) {
// Requests do never has a content id header // Requests do never has a content id header
if (!entry.getKey().equalsIgnoreCase(HttpHeader.CONTENT_ID)) { if (!entry.getKey().equalsIgnoreCase(HttpHeader.CONTENT_ID)) {
appendHeader(entry.getKey(), entry.getValue(), builder); appendHeader(entry.getKey(), entry.getValue().get(0), builder);
} }
} }
@ -153,8 +153,8 @@ public class BatchResponseSerializer {
appendHeader(BatchParserCommon.CONTENT_TRANSFER_ENCODING, BatchParserCommon.BINARY_ENCODING, builder); appendHeader(BatchParserCommon.CONTENT_TRANSFER_ENCODING, BatchParserCommon.BINARY_ENCODING, builder);
if (isChangeSet) { if (isChangeSet) {
if (response.getHeaders().get(HttpHeader.CONTENT_ID) != null) { if (response.getAllHeaders().get(HttpHeader.CONTENT_ID) != null) {
appendHeader(HttpHeader.CONTENT_ID, response.getHeaders().get(HttpHeader.CONTENT_ID), builder); appendHeader(HttpHeader.CONTENT_ID, response.getHeader(HttpHeader.CONTENT_ID), builder);
} else { } else {
throw new BatchSerializerException("Missing content id", MessageKeys.MISSING_CONTENT_ID); throw new BatchSerializerException("Missing content id", MessageKeys.MISSING_CONTENT_ID);
} }

View File

@ -193,8 +193,8 @@ public class AsyncProcessor<T extends Processor> {
private static ODataResponse createODataResponse(ODataResponse response) { private static ODataResponse createODataResponse(ODataResponse response) {
ODataResponse created = new ODataResponse(); ODataResponse created = new ODataResponse();
for (Map.Entry<String, String> header : response.getHeaders().entrySet()) { for (Map.Entry<String, List<String>> header : response.getAllHeaders().entrySet()) {
created.setHeader(header.getKey(), header.getValue()); created.addHeader(header.getKey(), header.getValue());
} }
return created; return created;
} }

View File

@ -106,7 +106,7 @@ public class ODataHandlerTest {
final ODataResponse response = dispatch(HttpMethod.GET, "/", null); final ODataResponse response = dispatch(HttpMethod.GET, "/", null);
assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode()); assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());
String ct = response.getHeaders().get(HttpHeader.CONTENT_TYPE); String ct = response.getHeader(HttpHeader.CONTENT_TYPE);
assertThat(ct, containsString("application/json")); assertThat(ct, containsString("application/json"));
assertThat(ct, containsString("odata.metadata=minimal")); assertThat(ct, containsString("odata.metadata=minimal"));
@ -121,7 +121,7 @@ public class ODataHandlerTest {
public void serviceDocumentRedirect() throws Exception { public void serviceDocumentRedirect() throws Exception {
final ODataResponse response = dispatch(HttpMethod.GET, "", null); final ODataResponse response = dispatch(HttpMethod.GET, "", null);
assertEquals(HttpStatusCode.TEMPORARY_REDIRECT.getStatusCode(), response.getStatusCode()); assertEquals(HttpStatusCode.TEMPORARY_REDIRECT.getStatusCode(), response.getStatusCode());
assertEquals(BASE_URI + "/", response.getHeaders().get(HttpHeader.LOCATION)); assertEquals(BASE_URI + "/", response.getHeader(HttpHeader.LOCATION));
} }
@Test @Test
@ -143,7 +143,7 @@ public class ODataHandlerTest {
public void metadataDefault() throws Exception { public void metadataDefault() throws Exception {
final ODataResponse response = dispatch(HttpMethod.GET, "$metadata", null); final ODataResponse response = dispatch(HttpMethod.GET, "$metadata", null);
assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode()); assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());
assertEquals(HttpContentType.APPLICATION_XML, response.getHeaders().get(HttpHeader.CONTENT_TYPE)); assertEquals(HttpContentType.APPLICATION_XML, response.getHeader(HttpHeader.CONTENT_TYPE));
assertNotNull(response.getContent()); assertNotNull(response.getContent());
assertThat(IOUtils.toString(response.getContent()), assertThat(IOUtils.toString(response.getContent()),
@ -153,14 +153,14 @@ public class ODataHandlerTest {
@Test @Test
public void maxVersionNone() { public void maxVersionNone() {
final ODataResponse response = dispatch(HttpMethod.GET, "$metadata", null); final ODataResponse response = dispatch(HttpMethod.GET, "$metadata", null);
assertEquals(ODataServiceVersion.V40.toString(), response.getHeaders().get(HttpHeader.ODATA_VERSION)); assertEquals(ODataServiceVersion.V40.toString(), response.getHeader(HttpHeader.ODATA_VERSION));
} }
@Test @Test
public void maxVersionSupported() { public void maxVersionSupported() {
final ODataResponse response = dispatch(HttpMethod.GET, "$metadata", null, final ODataResponse response = dispatch(HttpMethod.GET, "$metadata", null,
HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V40.toString(), null); HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V40.toString(), null);
assertEquals(ODataServiceVersion.V40.toString(), response.getHeaders().get(HttpHeader.ODATA_VERSION)); assertEquals(ODataServiceVersion.V40.toString(), response.getHeader(HttpHeader.ODATA_VERSION));
} }
@Test @Test
@ -168,7 +168,7 @@ public class ODataHandlerTest {
final ODataResponse response = dispatch(HttpMethod.GET, "$metadata", null, final ODataResponse response = dispatch(HttpMethod.GET, "$metadata", null,
HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V30.toString(), null); HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V30.toString(), null);
assertEquals(ODataServiceVersion.V40.toString(), response.getHeaders().get(HttpHeader.ODATA_VERSION)); assertEquals(ODataServiceVersion.V40.toString(), response.getHeader(HttpHeader.ODATA_VERSION));
assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), response.getStatusCode()); assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), response.getStatusCode());
} }