org.apache.olingo.odata2.api.processor.ODataErrorContext Java Examples

The following examples show how to use org.apache.olingo.odata2.api.processor.ODataErrorContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleODataErrorCallback.java    From cloud-sfsf-benefits-ext with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse handleError(final ODataErrorContext context) throws ODataApplicationException {
	Throwable rootCause = context.getException();
	LOGGER.error("Error in the OData. Reason: " + rootCause.getMessage(), rootCause); //$NON-NLS-1$

	Throwable innerCause = rootCause.getCause();
	if (rootCause instanceof ODataJPAException && innerCause != null && innerCause instanceof AppODataException) {
		context.setMessage(innerCause.getMessage());
		Throwable childInnerCause = innerCause.getCause();
		context.setInnerError(childInnerCause != null ? childInnerCause.getMessage() : ""); //$NON-NLS-1$
	} else {
		context.setMessage(HttpStatusCodes.INTERNAL_SERVER_ERROR.getInfo());
		context.setInnerError(rootCause.getMessage());
	}

	context.setHttpStatus(HttpStatusCodes.INTERNAL_SERVER_ERROR);
	return EntityProvider.writeErrorDocument(context);
}
 
Example #2
Source File: ProviderFacadeImplTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void readErrorDocumentXml() throws EntityProviderException {
  ProviderFacadeImpl providerFacade = new ProviderFacadeImpl();
  String errorDoc =
      "<?xml version='1.0' encoding='UTF-8'?>\n" +
          "<error xmlns=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\">\n" +
          "\t<code>ErrorCode</code>\n" +
          "\t<message xml:lang=\"en-US\">Message</message>\n" +
          "</error>";
  ODataErrorContext errorContext = providerFacade.readErrorDocument(StringHelper.encapsulate(errorDoc),
      ContentType.APPLICATION_XML.toContentTypeString());
  //
  assertEquals("Wrong content type", "application/xml", errorContext.getContentType());
  assertEquals("Wrong message", "Message", errorContext.getMessage());
  assertEquals("Wrong error code", "ErrorCode", errorContext.getErrorCode());
  assertEquals("Wrong locale for lang", Locale.US, errorContext.getLocale());
}
 
Example #3
Source File: JsonErrorProducerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private void testSerializeJSON(final String errorCode, final String message, final Locale locale) throws Exception {
  ODataErrorContext ctx = new ODataErrorContext();
  ctx.setContentType(HttpContentType.APPLICATION_JSON);
  ctx.setErrorCode(errorCode);
  ctx.setHttpStatus(HttpStatusCodes.INTERNAL_SERVER_ERROR);
  ctx.setLocale(locale);
  ctx.setMessage(message);

  ODataResponse response = new ProviderFacadeImpl().writeErrorDocument(ctx);
  assertNull("EntitypProvider must not set content header", response.getContentHeader());
  assertEquals(ODataServiceVersion.V10, response.getHeader(ODataHttpHeaders.DATASERVICEVERSION));
  final String jsonErrorMessage = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertEquals("{\"error\":{\"code\":"
      + (errorCode == null ? "null" : "\"" + errorCode + "\"")
      + ","
      + "\"message\":{\"lang\":"
      + (locale == null ? "null" : ("\"" + locale.getLanguage()
          + (locale.getCountry().isEmpty() ? "" : ("-" + locale.getCountry())) + "\""))
      + ",\"value\":" + (message == null ? "null" : "\"" + message + "\"") + "}}}",
      jsonErrorMessage);
}
 
Example #4
Source File: JsonErrorDocumentDeserializer.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param reader
 * @return ODataErrorContext
 * @throws IOException
 * @throws EntityProviderException
 */
private ODataErrorContext parseJson(final JsonReader reader) throws IOException, EntityProviderException {
  ODataErrorContext errorContext;

  if (reader.hasNext()) {
    reader.beginObject();
    String currentName = reader.nextName();
    if (FormatJson.ERROR.equals(currentName)) {
      errorContext = parseError(reader);
    } else {
      throw new EntityProviderException(EntityProviderException.INVALID_STATE.addContent(
          "Invalid object with name '" + currentName + FOUND));
    }
  } else {
    throw new EntityProviderException(EntityProviderException.INVALID_STATE.addContent(
        "No content to parse found."));
  }

  errorContext.setContentType(ContentType.APPLICATION_JSON.toContentTypeString());
  return errorContext;
}
 
Example #5
Source File: XmlErrorDocumentDeserializer.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private void handleInnerError(final XMLStreamReader reader, final ODataErrorContext errorContext)
    throws XMLStreamException {

  StringBuilder sb = new StringBuilder();
  while (notFinished(reader, FormatXml.M_INNER_ERROR)) {
    if (reader.hasName() && !FormatXml.M_INNER_ERROR.equals(reader.getLocalName())) {
      sb.append("<");
      if (reader.isEndElement()) {
        sb.append("/");
      }
      sb.append(reader.getLocalName()).append(">");
    } else if (reader.isCharacters()) {
      sb.append(reader.getText());
    }
    reader.next();
  }

  errorContext.setInnerError(sb.toString());
}
 
Example #6
Source File: JsonErrorDocumentConsumer.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private ODataErrorContext parseJson(final JsonReader reader) throws IOException, EntityProviderException {
  ODataErrorContext errorContext;

  if (reader.hasNext()) {
    reader.beginObject();
    String currentName = reader.nextName();
    if (FormatJson.ERROR.equals(currentName)) {
      errorContext = parseError(reader);
    } else {
      throw new EntityProviderException(EntityProviderException.INVALID_STATE.addContent(
          "Invalid object with name '" + currentName + "' found."));
    }
  } else {
    throw new EntityProviderException(EntityProviderException.INVALID_STATE.addContent(
        "No content to parse found."));
  }

  errorContext.setContentType(ContentType.APPLICATION_JSON.toContentTypeString());
  return errorContext;
}
 
Example #7
Source File: XmlErrorDocumentConsumer.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private void handleInnerError(final XMLStreamReader reader, final ODataErrorContext errorContext)
    throws XMLStreamException {

  StringBuilder sb = new StringBuilder();
  while (notFinished(reader, FormatXml.M_INNER_ERROR)) {
    if (reader.hasName() && !FormatXml.M_INNER_ERROR.equals(reader.getLocalName())) {
      sb.append("<");
      if (reader.isEndElement()) {
        sb.append("/");
      }
      sb.append(reader.getLocalName()).append(">");
    } else if (reader.isCharacters()) {
      sb.append(reader.getText());
    }
    reader.next();
  }

  errorContext.setInnerError(sb.toString());
}
 
Example #8
Source File: JSON_XMLErrorConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void readErrorDocumentXml() throws EntityProviderException {
  ODataClient providerFacade = ODataClient.newInstance();
  String errorDoc =
      "<?xml version='1.0' encoding='UTF-8'?>\n" +
          "<error xmlns=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\">\n" +
          "\t<code>ErrorCode</code>\n" +
          "\t<message xml:lang=\"en-US\">Message</message>\n" +
          "</error>";
  ODataErrorContext errorContext = providerFacade.createDeserializer(XML).
      readErrorDocument(StringHelper.encapsulate(errorDoc));
  //
  assertEquals("Wrong content type", "application/xml", errorContext.getContentType());
  assertEquals("Wrong message", "Message", errorContext.getMessage());
  assertEquals("Wrong error code", "ErrorCode", errorContext.getErrorCode());
  assertEquals("Wrong locale for lang", Locale.US, errorContext.getLocale());
}
 
Example #9
Source File: XmlErrorDocumentTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void innerErrorComplex() throws Exception {
  InputStream in = StringHelper.encapsulate(XML_ERROR_DOCUMENT_INNER_ERROR_COMPLEX);
  ODataErrorContext error = xedc.readError(in);

  assertEquals("Wrong content type", "application/xml", error.getContentType());
  assertEquals("Wrong message", "Message", error.getMessage());
  assertEquals("Wrong error code", "ErrorCode", error.getErrorCode());
  assertEquals("Wrong inner error", "<moreInner>More Inner Error</moreInner>", error.getInnerError());
}
 
Example #10
Source File: XmlErrorDocumentTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void innerErrorComplexTwo() throws Exception {
  String innerErrorText = "<firstTag>tagText</firstTag><secondTag>secondText</secondTag>";
  String innerError = "<innererror>" + innerErrorText + "</innererror>";
  String errorDocument = XML_ERROR_DOCUMENT_INNER_ERROR_COMPLEX.replaceAll(
      "<innererror.*error>", innerError);
  InputStream in = StringHelper.encapsulate(errorDocument);
  ODataErrorContext error = xedc.readError(in);

  assertEquals("Wrong content type", "application/xml", error.getContentType());
  assertEquals("Wrong message", "Message", error.getMessage());
  assertEquals("Wrong error code", "ErrorCode", error.getErrorCode());
  assertEquals("Wrong inner error", innerErrorText, error.getInnerError());
}
 
Example #11
Source File: XmlErrorDocumentTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void innerErrorComplexMoreCharacters() throws Exception {
  String innerErrorText = "\n\t<firstTag>tagText</firstTag>\n<secondTag>secondText</secondTag>\n";
  String innerError = "<innererror>" + innerErrorText + "</innererror>";
  String errorDocument = XML_ERROR_DOCUMENT_INNER_ERROR_COMPLEX.replaceAll(
      "<innererror.*error>", innerError);
  InputStream in = StringHelper.encapsulate(errorDocument);
  ODataErrorContext error = xedc.readError(in);

  assertEquals("Wrong content type", "application/xml", error.getContentType());
  assertEquals("Wrong message", "Message", error.getMessage());
  assertEquals("Wrong error code", "ErrorCode", error.getErrorCode());
  assertEquals("Wrong inner error", innerErrorText, error.getInnerError());
}
 
Example #12
Source File: XmlErrorDocumentTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void innerError() throws Exception {
  InputStream in = StringHelper.encapsulate(XML_ERROR_DOCUMENT_INNER_ERROR);
  ODataErrorContext error = xedc.readError(in);

  assertEquals("Wrong content type", "application/xml", error.getContentType());
  assertEquals("Wrong message", "Message", error.getMessage());
  assertEquals("Wrong error code", "ErrorCode", error.getErrorCode());
  assertEquals("Wrong inner error", "Some InnerError", error.getInnerError());
}
 
Example #13
Source File: JSON_XMLErrorConsumerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void readErrorDocumentJson() throws EntityProviderException {
  ODataClient providerFacade = ODataClient.newInstance();
  String errorDoc = "{\"error\":{\"code\":\"ErrorCode\",\"message\":{\"lang\":\"en-US\",\"value\":\"Message\"}}}";
  ODataErrorContext errorContext = providerFacade.createDeserializer(JSON).
      readErrorDocument(StringHelper.encapsulate(errorDoc));
  //
  assertEquals("Wrong content type", "application/json", errorContext.getContentType());
  assertEquals("Wrong message", "Message", errorContext.getMessage());
  assertEquals("Wrong error code", "ErrorCode", errorContext.getErrorCode());
  assertEquals("Wrong locale for lang", Locale.US, errorContext.getLocale());
}
 
Example #14
Source File: NullServiceTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void nullServiceMustResultInODataResponse() throws Exception {
  disableLogging();
  final HttpResponse response = executeGetRequest("$metadata");
  assertEquals(HttpStatusCodes.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusLine().getStatusCode());

  
  ODataErrorContext error = EntityProvider.readErrorDocument(response.getEntity().getContent(), "application/xml");
  assertEquals("Service unavailable.", error.getMessage());
}
 
Example #15
Source File: JsonErrorDocumentDeserializerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void innerError() throws Exception {
  InputStream in = StringHelper.encapsulate(JSON_ERROR_DOCUMENT_INNER_ERROR);
  ODataErrorContext error = jedc.readError(in);

  assertEquals("Wrong content type", "application/json", error.getContentType());
  assertEquals("Wrong message", "Message", error.getMessage());
  assertEquals("Wrong error code", "ErrorCode", error.getErrorCode());
  assertEquals("Wrong inner error", "Some InnerError", error.getInnerError());
}
 
Example #16
Source File: AnnotationSampleServiceFactory.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public ODataResponse handleError(final ODataErrorContext context) throws ODataApplicationException {
  if (context.getHttpStatus() == HttpStatusCodes.INTERNAL_SERVER_ERROR) {
    LOG.error("Internal Server Error", context.getException());
  }

  return EntityProvider.writeErrorDocument(context);
}
 
Example #17
Source File: XmlErrorDocumentTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void localeNull() throws Exception {
  InputStream in = StringHelper.encapsulate(XML_ERROR_DOCUMENT_NULL_LOCALE);
  ODataErrorContext error = xedc.readError(in);

  assertEquals("Wrong content type", "application/xml", error.getContentType());
  assertEquals("Wrong message", "Message", error.getMessage());
  assertEquals("Wrong error code", "ErrorCode", error.getErrorCode());
  assertNull("Expected NULL for locale", error.getLocale());
}
 
Example #18
Source File: XmlErrorDocumentConsumerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void innerErrorComplexMoreCharacters() throws Exception {
  String innerErrorText = "\n\t<firstTag>tagText</firstTag>\n<secondTag>secondText</secondTag>\n";
  String innerError = "<innererror>" + innerErrorText + "</innererror>";
  String errorDocument = XML_ERROR_DOCUMENT_INNER_ERROR_COMPLEX.replaceAll(
      "<innererror.*error>", innerError);
  InputStream in = StringHelper.encapsulate(errorDocument);
  ODataErrorContext error = xedc.readError(in);

  assertEquals("Wrong content type", "application/xml", error.getContentType());
  assertEquals("Wrong message", "Message", error.getMessage());
  assertEquals("Wrong error code", "ErrorCode", error.getErrorCode());
  assertEquals("Wrong inner error", innerErrorText, error.getInnerError());
}
 
Example #19
Source File: JsonErrorDocumentDeserializerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void innerErrorComplex() throws Exception {
  InputStream in = StringHelper.encapsulate(JSON_ERROR_DOCUMENT_INNER_ERROR_COMPLEX);
  ODataErrorContext error = jedc.readError(in);

  assertEquals("Wrong content type", "application/json", error.getContentType());
  assertEquals("Wrong message", "Message", error.getMessage());
  assertEquals("Wrong error code", "ErrorCode", error.getErrorCode());
  assertEquals("Wrong inner error", "{\"moreInner\":\"More Inner Error\"}", error.getInnerError());
}
 
Example #20
Source File: JsonErrorDocumentDeserializer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param reader
 * @param errorContext
 * @throws IOException
 * @throws EntityProviderException
 */
private void parseMessage(final JsonReader reader, final ODataErrorContext errorContext)
    throws IOException, EntityProviderException {

  reader.beginObject();
  boolean valueFound = false;
  boolean langFound = false;
  String currentName;

  while (reader.hasNext()) {
    currentName = reader.nextName();
    if (FormatJson.LANG.equals(currentName)) {
      langFound = true;
      String langValue = getValue(reader);
      if (langValue != null) {
        errorContext.setLocale(getLocale(langValue));
      }
    } else if (FormatJson.VALUE.equals(currentName)) {
      valueFound = true;
      errorContext.setMessage(getValue(reader));
    } else {
      throw new EntityProviderException(EntityProviderException.INVALID_STATE.addContent("Invalid name '" +
          currentName + FOUND));
    }
  }

  if (!langFound) {
    throw new EntityProviderException(
        EntityProviderException.MISSING_PROPERTY.addContent("Mandatory 'lang' property not found.'"));
  }
  if (!valueFound) {
    throw new EntityProviderException(
        EntityProviderException.MISSING_PROPERTY.addContent("Mandatory 'value' property not found.'"));
  }
  reader.endObject();
}
 
Example #21
Source File: JsonErrorDocumentDeserializer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param reader
 * @param errorContext
 * @throws IOException
 */
private void parseInnerError(final JsonReader reader, final ODataErrorContext errorContext) throws IOException {
  JsonToken token = reader.peek();
  if (token == JsonToken.STRING) {
    // implementation for parse content as provided by JsonErrorDocumentProducer
    String innerError = reader.nextString();
    errorContext.setInnerError(innerError);
  } else if (token == JsonToken.BEGIN_OBJECT) {
    // implementation for OData v2 Section 2.2.8.1.2 JSON Error Response
    // (RFC4627 Section 2.2 -> https://www.ietf.org/rfc/rfc4627.txt))
    // currently partial provided
    errorContext.setInnerError(readJson(reader));
  }
}
 
Example #22
Source File: JsonErrorDocumentDeserializer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param reader
 * @return ODataErrorContext
 * @throws IOException
 * @throws EntityProviderException
 */
private ODataErrorContext parseError(final JsonReader reader) throws IOException, EntityProviderException {
  ODataErrorContext errorContext = new ODataErrorContext();
  String currentName;
  reader.beginObject();
  boolean messageFound = false;
  boolean codeFound = false;

  while (reader.hasNext()) {
    currentName = reader.nextName();
    if (FormatJson.CODE.equals(currentName)) {
      codeFound = true;
      errorContext.setErrorCode(getValue(reader));
    } else if (FormatJson.MESSAGE.equals(currentName)) {
      messageFound = true;
      parseMessage(reader, errorContext);
    } else if (FormatJson.INNER_ERROR.equals(currentName)) {
      parseInnerError(reader, errorContext);
    } else {
      throw new EntityProviderException(EntityProviderException.INVALID_STATE.addContent(
          "Invalid name '" + currentName + FOUND));
    }
  }

  if (!codeFound) {
    throw new EntityProviderException(
        EntityProviderException.MISSING_PROPERTY.addContent("Mandatory 'code' property not found.'"));
  }
  if (!messageFound) {
    throw new EntityProviderException(
        EntityProviderException.MISSING_PROPERTY.addContent("Mandatory 'message' property not found.'"));
  }

  reader.endObject();
  return errorContext;
}
 
Example #23
Source File: JsonErrorDocumentDeserializer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
/**
 * Deserialize / read OData error document in ODataErrorContext.
 * 
 * @param errorDocument OData error document in JSON format
 * @return created ODataErrorContext based on input stream content.
 * @throws EntityProviderException if an exception during read / deserialization occurs.
 */
public ODataErrorContext readError(final InputStream errorDocument) throws EntityProviderException {
  JsonReader reader = createJsonReader(errorDocument);
  try {
    return parseJson(reader);
  } catch (IOException e) {
    throw new EntityProviderException(
        EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getMessage()), e);
  }
}
 
Example #24
Source File: XmlErrorDocumentDeserializer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private void handleMessage(final XMLStreamReader reader, final ODataErrorContext errorContext)
    throws XMLStreamException {
  String lang = reader.getAttributeValue(Edm.NAMESPACE_XML_1998, FormatXml.XML_LANG);
  errorContext.setLocale(getLocale(lang));
  String message = reader.getElementText();
  errorContext.setMessage(message);
}
 
Example #25
Source File: XmlErrorDocumentDeserializer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private ODataErrorContext parserError(final XMLStreamReader reader)
    throws XMLStreamException, EntityProviderException {
  // read xml tag
  reader.require(XMLStreamConstants.START_DOCUMENT, null, null);
  reader.nextTag();

  // read error tag
  reader.require(XMLStreamConstants.START_ELEMENT, Edm.NAMESPACE_M_2007_08, FormatXml.M_ERROR);

  // read error data
  boolean codeFound = false;
  boolean messageFound = false;
  ODataErrorContext errorContext = new ODataErrorContext();
  while (notFinished(reader)) {
    reader.nextTag();
    if (reader.isStartElement()) {
      String name = reader.getLocalName();
      if (FormatXml.M_CODE.equals(name)) {
        codeFound = true;
        handleCode(reader, errorContext);
      } else if (FormatXml.M_MESSAGE.equals(name)) {
        messageFound = true;
        handleMessage(reader, errorContext);
      } else if (FormatXml.M_INNER_ERROR.equals(name)) {
        handleInnerError(reader, errorContext);
      } else {
        throw new EntityProviderException(
            EntityProviderException.INVALID_CONTENT.addContent(name, FormatXml.M_ERROR));
      }
    }
  }
  validate(codeFound, messageFound);

  errorContext.setContentType(ContentType.APPLICATION_XML.toContentTypeString());
  return errorContext;
}
 
Example #26
Source File: FitErrorCallback.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public ODataResponse handleError(final ODataErrorContext context) throws ODataApplicationException {
  if (context.getHttpStatus() == HttpStatusCodes.INTERNAL_SERVER_ERROR) {
    LOG.error("Internal Server Error", context.getException());
  }
  return EntityProvider.writeErrorDocument(context);
}
 
Example #27
Source File: ScenarioErrorCallback.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public ODataResponse handleError(final ODataErrorContext context) throws ODataApplicationException {
  if (context.getHttpStatus() == HttpStatusCodes.INTERNAL_SERVER_ERROR) {
    LOG.error("Internal Server Error", context.getException());
  }

  return EntityProvider.writeErrorDocument(context);
}
 
Example #28
Source File: ODataErrorHandlerCallbackImpl.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public ODataResponse handleError(final ODataErrorContext context) {
  ODataResponseBuilder responseBuilder =
      ODataResponse.entity("bla").status(HttpStatusCodes.BAD_REQUEST).contentHeader("text/html");

  if (context.getRequestUri() != null) {
    responseBuilder.header("RequestUri", context.getRequestUri().toASCIIString());
    PathInfo pathInfo = context.getPathInfo();
    if (pathInfo == null) {
      responseBuilder.header("PathInfo", "NULL");
    } else {
      responseBuilder.header("PathInfo", "TRUE");
      responseBuilder.header("PathInfo.oDataSegments", pathInfo.getODataSegments().toString());
      responseBuilder.header("PathInfo.precedingSegments", pathInfo.getPrecedingSegments().toString());
      responseBuilder.header("PathInfo.requestUri", pathInfo.getRequestUri().toString());
      responseBuilder.header("PathInfo.serviceRoot", pathInfo.getServiceRoot().toString());
    }
  }

  Map<String, List<String>> requestHeaders = context.getRequestHeaders();
  if (requestHeaders != null && requestHeaders.entrySet() != null) {
    Set<Entry<String, List<String>>> entries = requestHeaders.entrySet();
    for (Entry<String, List<String>> entry : entries) {
      responseBuilder.header(entry.getKey(), entry.getValue().toString());
    }
  }

  return responseBuilder.build();
}
 
Example #29
Source File: ServiceLogger.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Handle an error with adding the error message in the stream thanks to 
 * {@link EntityProvider#writeErrorDocument(ODataErrorContext)} method, but
 * when the response stream is not identified as binary stream (uri contains
 * $value), no ascii message is inserted into the stream.
 */
@Override
public ODataResponse handleError(ODataErrorContext ctx) throws ODataApplicationException
{
   // Compute the error message
   String message = ctx.getMessage();
   if (ctx.getException() != null)
   {
      message = ctx.getException().getClass().getSimpleName();
      if (ctx.getException().getMessage() != null)
      {
         message += " : " + ctx.getException().getMessage();
      }
      else if (ctx.getMessage() != null)
      {
         message += " : " + ctx.getMessage();
      }
   }

   // Suppress in-stream error messages
   // ExpectedException are never thrown while streaming the payload
   if (ctx.getRequestUri().toString().endsWith("$value")
         && (ctx.getException() == null || ctx.getException() instanceof ExpectedException))
   {
      return ODataResponse
            .header("cause-message", message)
            .status(HttpStatusCodes.INTERNAL_SERVER_ERROR)
            .build();
   }
   return ODataResponse
         .fromResponse(EntityProvider.writeErrorDocument(ctx))
         .header("cause-message", message)
         .build();
}
 
Example #30
Source File: ODataExceptionWrapperTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCallbackWithLocales1() throws Exception {
  UriInfo uriInfo = getMockedUriInfo();
  HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class);
  List<Locale> locales = new ArrayList<Locale>();
  locales.add(Locale.GERMANY);
  locales.add(Locale.FRANCE);
  when(httpHeaders.getAcceptableLanguages()).thenReturn(locales);
  
  ODataErrorCallback errorCallback = new ODataErrorCallback() {
    @Override
    public ODataResponse handleError(final ODataErrorContext context) throws ODataApplicationException {
      assertEquals("de", context.getLocale().getLanguage());
      assertEquals("DE", context.getLocale().getCountry());
      return ODataResponse.entity("bla").status(HttpStatusCodes.BAD_REQUEST).contentHeader("text/html").build();
    }
  };

  ODataExceptionWrapper exceptionWrapper = createWrapper1(uriInfo, httpHeaders, errorCallback);
  ODataResponse response = exceptionWrapper.wrapInExceptionResponse(
      new ODataApplicationException("Error",Locale.GERMANY));

  // verify
  assertNotNull(response);
  assertEquals(HttpStatusCodes.BAD_REQUEST.getStatusCode(), response.getStatus().getStatusCode());
  String errorMessage = (String) response.getEntity();
  assertEquals("bla", errorMessage);
  String contentTypeHeader = response.getContentHeader();
  assertEquals("text/html", contentTypeHeader);
}