Java源码示例:org.apache.olingo.odata2.api.processor.ODataResponse

示例1
@Test
public void selectAge() throws Exception {
  ExpandSelectTreeNode selectTree = getSelectExpandTree("Age", null);

  EntityProviderWriteProperties properties =
      EntityProviderWriteProperties.serviceRoot(BASE_URI).expandSelectTree(selectTree).build();
  AtomEntityProvider provider = createAtomEntityProvider();
  ODataResponse response =
      provider.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"),
          employeeData, properties);

  String xmlString = verifyResponse(response);

  verifyNavigationProperties(xmlString, F, F, F);
  assertXpathExists("/a:entry/m:properties", xmlString);
  verifyKeyProperties(xmlString, F, F, F, F);
  verifySingleProperties(xmlString, F, T, F, F);
  verifyComplexProperties(xmlString, F);
}
 
示例2
@Test
public void serializeWithValueEncoding() throws IOException, XpathException, SAXException, XMLStreamException,
 FactoryConfigurationError, ODataException {
 photoData.addProperty("Type", "< Ö >");
 photoData.setWriteProperties(DEFAULT_PROPERTIES);
 
 AtomSerializerDeserializer ser = createAtomEntityProvider();
 ODataResponse response =
 ser.writeEntry(MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"), photoData);
 String xmlString = verifyResponse(response);
 
 assertXpathExists("/a:entry", xmlString);
 assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString);
 assertXpathExists("/a:entry/a:id", xmlString);
 assertXpathEvaluatesTo(BASE_URI.toASCIIString() + "Container2.Photos(Id=1,Type='%3C%20%C3%96%20%3E')",
 "/a:entry/a:id/text()", xmlString);
 assertXpathEvaluatesTo("Container2.Photos(Id=1,Type='%3C%20%C3%96%20%3E')", "/a:entry/a:link/@href", xmlString);
 }
 
示例3
@Override
public ODataResponse writeFunctionImport(final EdmFunctionImport functionImport, final Object data,
    final EntityProviderWriteProperties properties) throws EntityProviderException {
  try {
    if(functionImport.getReturnType() !=null){
      if (functionImport.getReturnType().getType().getKind() == EdmTypeKind.ENTITY) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) data;
        return writeEntry(functionImport.getEntitySet(), map, properties);
      }

      final EntityPropertyInfo info = EntityInfoAggregator.create(functionImport);
      if (functionImport.getReturnType().getMultiplicity() == EdmMultiplicity.MANY) {
        return writeCollection(info, (List<?>) data);
      } else {
        return writeSingleTypedElement(info, data);
      }
    }else{
      return ODataResponse.newBuilder().status(HttpStatusCodes.ACCEPTED).build();
    }
  } catch (final EdmException e) {
    throw new EntityProviderProducerException(e.getMessageReference(), e);
  }
}
 
示例4
@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);
}
 
示例5
@Test
public void noReturnTypeAction() throws Exception {
  final EdmFunctionImport functionImport =
      MockFacade.getMockEdm().getDefaultEntityContainer().getFunctionImport("AddEmployee");
  final String uri = "http://host:80/service/";
  final EntityProviderWriteProperties properties =
      EntityProviderWriteProperties.serviceRoot(URI.create(uri)).build();
  Map<String, Object> employeeData = new HashMap<String, Object>();
  employeeData.put("EmployeeId", "1");
  employeeData.put("getImageType", "image/jpeg");
  final ODataResponse response =
      new JsonEntityProvider().writeFunctionImport(functionImport, employeeData, properties);
  assertNotNull(response);
  assertNull(response.getEntity());
  assertNull(response.getContentHeader());
  assertEquals(HttpStatusCodes.ACCEPTED, response.getStatus());
 
}
 
示例6
@Test
public void serializeWithCustomSrcAttributeOnEmployee() throws Exception {
  AtomSerializerDeserializer ser = createAtomEntityProvider();
  Entity localEmployeeData = new Entity();
  for (Entry<String, Object> data : employeeData.getProperties().entrySet()) {
    localEmployeeData.addProperty(data.getKey(), data.getValue());
  }
  String mediaResourceSourceKey = "~src";
  localEmployeeData.addProperty(mediaResourceSourceKey, "http://localhost:8080/images/image1");
  EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  EdmMapping mapping = employeesSet.getEntityType().getMapping();
  when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey);
  localEmployeeData.setWriteProperties(DEFAULT_PROPERTIES);
  ODataResponse response = ser.writeEntry(employeesSet, localEmployeeData);
  String xmlString = verifyResponse(response);

  assertXpathExists(
      "/a:entry/a:link[@href=\"Employees('1')/$value\" and" +
          " @rel=\"edit-media\" and @type=\"application/octet-stream\"]", xmlString);
  assertXpathExists("/a:entry/a:content[@type=\"application/octet-stream\"]", xmlString);
  assertXpathExists("/a:entry/a:content[@src=\"http://localhost:8080/images/image1\"]", xmlString);
}
 
示例7
@Test
public void expandBuildingAndSelectIdFromRoom() throws Exception {
  EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  List<String> expandedNavigationProperties = new ArrayList<String>();
  expandedNavigationProperties.add("nr_Building");

  List<String> selectedProperties = new ArrayList<String>();
  selectedProperties.add("Id");

  ExpandSelectTreeNode expandSelectTree =
      ExpandSelectTreeNode.entitySet(roomsSet).selectedProperties(selectedProperties).expandedLinks(
          expandedNavigationProperties).build();

  Map<String, ODataCallback> callbacks = new HashMap<String, ODataCallback>();
  callbacks.put("nr_Building", new LocalCallback());
  EntityProviderWriteProperties properties =
      EntityProviderWriteProperties.fromProperties(DEFAULT_PROPERTIES).callbacks(callbacks).expandSelectTree(
          expandSelectTree).build();
  ODataResponse entry = EntityProvider.writeEntry("application/xml", roomsSet, roomData, properties);

  String xml = StringHelper.inputStreamToString((InputStream) entry.getEntity());
  assertXpathExists("/a:entry/a:content/m:properties/d:Id", xml);
  assertXpathNotExists("/a:entry/a:content/m:properties/d:Name", xml);
  assertXpathExists("/a:entry/a:link[@type]/m:inline", xml);
}
 
示例8
@Override
public ODataResponse readEntity(GetEntityUriInfo uriInfo, String contentType) throws ODataException {
  HashMap<String, Object> data = new HashMap<String, Object>();

  if ("Employees".equals(uriInfo.getTargetEntitySet().getName())) {
    if ("2".equals(uriInfo.getKeyPredicates().get(0).getLiteral())) {
      data.put("EmployeeId", "1");
      data.put("TeamId", "420");
    }

    ODataContext context = getContext();
    EntityProviderWriteProperties writeProperties =
        EntityProviderWriteProperties.serviceRoot(context.getPathInfo().getServiceRoot()).build();

    return EntityProvider.writeEntry(contentType, uriInfo.getTargetEntitySet(), data, writeProperties);
  } else {
    throw new ODataApplicationException("Wrong testcall", Locale.getDefault(), HttpStatusCodes.NOT_IMPLEMENTED);
  }
}
 
示例9
@Test
public void entityWithEmptyInlineEntry() throws Exception {

  Entity roomData = new Entity();
  roomData.addProperty("Id", "1");
  roomData.addProperty("Name", "Neu Schwanstein");
  roomData.addProperty("Seats", new Integer(20));
  Entity buildingData = new Entity();
  roomData.addNavigation("nr_Building", buildingData);
  EntitySerializerProperties properties =
      EntitySerializerProperties.serviceRoot(BASE_URI)
          .includeMetadata(true).build();
  roomData.setWriteProperties(properties);
  buildingData.setWriteProperties(properties);
  AtomSerializerDeserializer provider = createAtomEntityProvider();
  ODataResponse response =
      provider.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), roomData);

  String xmlString = verifyResponse(response);
  assertXpathNotExists("/a:entry/m:properties", xmlString);
  assertXpathExists("/a:entry/a:link", xmlString);
  assertXpathExists("/a:entry/a:content/m:properties/d:Id", xmlString);
  assertXpathExists("/a:entry/a:content/m:properties/d:Name", xmlString);
  assertXpathExists("/a:entry/a:content/m:properties/d:Seats", xmlString);
}
 
示例10
protected void handleRedirect(final HttpServletRequest req, final HttpServletResponse resp,
                              ODataServiceFactory serviceFactory) throws IOException {
  String method = req.getMethod();
  if (ODataHttpMethod.GET.name().equals(method) ||
      ODataHttpMethod.POST.name().equals(method) ||
      ODataHttpMethod.PUT.name().equals(method) ||
      ODataHttpMethod.DELETE.name().equals(method) ||
      ODataHttpMethod.PATCH.name().equals(method) ||
      ODataHttpMethod.MERGE.name().equals(method) ||
      HTTP_METHOD_HEAD.equals(method) ||
      HTTP_METHOD_OPTIONS.equals(method)) {
    ODataResponse odataResponse = ODataResponse.status(HttpStatusCodes.TEMPORARY_REDIRECT)
        .header(HttpHeaders.LOCATION, createLocation(req))
        .build();
    createResponse(resp, odataResponse);
  } else {
    createNotImplementedResponse(req, ODataHttpException.COMMON, resp, serviceFactory);
  }

}
 
示例11
private HttpResponse testGetRequest(final String uriExtension, final String acceptHeader,
    final HttpStatusCodes expectedStatus, final String expectedContentType)
    throws ClientProtocolException, IOException, ODataException {
  // prepare
  ODataResponse expectedResponse = ODataResponse.contentHeader(expectedContentType).entity("Test passed.").build();
  when(processor.readMetadata(any(GetMetadataUriInfo.class), any(String.class))).thenReturn(expectedResponse);
  when(processor.readEntity(any(GetEntityUriInfo.class), any(String.class))).thenReturn(expectedResponse);
  when(processor.readEntitySet(any(GetEntitySetUriInfo.class), any(String.class))).thenReturn(expectedResponse);

  HttpGet getRequest = new HttpGet(URI.create(getEndpoint().toString() + uriExtension));
  getRequest.setHeader(HttpHeaders.ACCEPT, acceptHeader);

  // execute
  HttpResponse response = getHttpClient().execute(getRequest);

  // validate
  assertEquals(expectedStatus.getStatusCode(), response.getStatusLine().getStatusCode());
  Header[] contentTypeHeaders = response.getHeaders("Content-Type");
  assertEquals("Found more then one content type header in response.", 1, contentTypeHeaders.length);
  assertEquals("Received content type does not match expected.", expectedContentType, contentTypeHeaders[0]
      .getValue());
  assertEquals("Received status code does not match expected.", expectedStatus.getStatusCode(), response
      .getStatusLine().getStatusCode());
  //
  return response;
}
 
示例12
@Test
public void serializeWithoutFacetsValidation() throws Exception {
  Edm edm = MockFacade.getMockEdm();
  EdmTyped roomNameProperty = edm.getEntityType("RefScenario", "Room").getProperty("Name");
  EdmFacets facets = mock(EdmFacets.class);
  when(facets.getMaxLength()).thenReturn(3);
  when(((EdmProperty) roomNameProperty).getFacets()).thenReturn(facets);

  String name = "1234567";
  roomData.put("Name", name);
  AtomEntityProvider ser = createAtomEntityProvider();
  EntityProviderWriteProperties properties = EntityProviderWriteProperties
      .fromProperties(DEFAULT_PROPERTIES).validatingFacets(false).build();
  ODataResponse response =
      ser.writeEntry(edm.getDefaultEntityContainer().getEntitySet("Rooms"), roomData, properties);
  assertNotNull(response);


  assertNotNull(response.getEntity());
  String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity());

  assertXpathEvaluatesTo(name, "/a:entry/a:content/m:properties/d:Name/text()", xmlString);
}
 
示例13
@Test
public void serializeETagEncoding() throws IOException, XpathException, SAXException, XMLStreamException,
    FactoryConfigurationError, ODataException {
  Edm edm = MockFacade.getMockEdm();
  EdmTyped roomIdProperty = edm.getEntityType("RefScenario", "Room").getProperty("Id");
  EdmFacets facets = mock(EdmFacets.class);
  when(facets.getConcurrencyMode()).thenReturn(EdmConcurrencyMode.Fixed);
  when(facets.getMaxLength()).thenReturn(3);
  when(((EdmProperty) roomIdProperty).getFacets()).thenReturn(facets);

  roomData.put("Id", "<\">");
  AtomEntityProvider ser = createAtomEntityProvider();
  ODataResponse response =
      ser.writeEntry(edm.getDefaultEntityContainer().getEntitySet("Rooms"), roomData, DEFAULT_PROPERTIES);

  assertNotNull(response);
  assertNotNull(response.getEntity());
  assertNull("EntityProvider should not set content header", response.getContentHeader());
  assertEquals("W/\"<\">.3\"", response.getETag());

  String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity());

  assertXpathExists("/a:entry", xmlString);
  assertXpathExists("/a:entry/@m:etag", xmlString);
  assertXpathEvaluatesTo("W/\"<\">.3\"", "/a:entry/@m:etag", xmlString);
}
 
示例14
@Test
public void feedWithGlobalEntityProperties() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams");
  EntityCollection teamsData = new EntityCollection();
  Entity team1Data = new Entity();
  team1Data.addProperty("Id", "1");
  team1Data.addProperty("isScrumTeam", true);
  Entity team2Data = new Entity();
  team2Data.addProperty("Id", "2");
  team2Data.addProperty("isScrumTeam", false);
  teamsData.addEntity(team1Data);
  teamsData.addEntity(team2Data);
  teamsData.setCollectionProperties(EntityCollectionSerializerProperties.serviceRoot(BASE_URI).build());
  teamsData.setGlobalEntityProperties(EntitySerializerProperties.serviceRoot(BASE_URI).
      includeMetadata(true).build());
  
  final ODataResponse response = new AtomSerializerDeserializer().writeFeed(entitySet, teamsData);
  final String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertNotNull(xmlString);
  assertXpathExists("/a:feed", xmlString);
  assertXpathExists("/a:feed/a:entry/a:id", xmlString);
  assertXpathExists("/a:feed/a:entry/a:content/m:properties", xmlString);
  assertXpathExists("/a:feed/a:entry/a:content/m:properties/d:Id", xmlString);
  assertXpathExists("/a:feed/a:entry/a:content/m:properties/d:isScrumTeam", xmlString);
}
 
示例15
@Test
public void unbalancedPropertyFeedWithSelect() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Companys");
  List<Map<String, Object>> originalData = createData(true);
  List<String> selectedPropertyNames = new ArrayList<String>();
  selectedPropertyNames.add("Id");
  selectedPropertyNames.add("Location");
  ExpandSelectTreeNode select =
      ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).build();
  
  final ODataResponse response = new JsonEntityProvider().writeFeed(entitySet, originalData,
      EntityProviderWriteProperties.serviceRoot(URI.create(BASE_URI)).expandSelectTree(select).
      isDataBasedPropertySerialization(true).build());

  EntityProviderReadProperties readProperties = EntityProviderReadProperties.init().mergeSemantic(false).build();
  JsonEntityConsumer consumer = new JsonEntityConsumer();
  ODataFeed feed = consumer.readFeed(entitySet, (InputStream) response.getEntity(), readProperties);

  compareList(originalData, feed.getEntries());
}
 
示例16
private ODataResponse setContentIdHeader(ODataRequest request, final ODataResponse response, 
    final String mimeHeaderContentId, final String requestHeaderContentId) {
  ODataResponse modifiedResponse;
  if (requestHeaderContentId != null && mimeHeaderContentId != null) {
    String baseUri = getBaseUri(request);
    fillContentIdMap(response, requestHeaderContentId, baseUri);
    fillContentIdMap(response, mimeHeaderContentId, baseUri);
    modifiedResponse =
        ODataResponse.fromResponse(response).header(BatchHelper.REQUEST_HEADER_CONTENT_ID, requestHeaderContentId)
            .header(BatchHelper.MIME_HEADER_CONTENT_ID, mimeHeaderContentId).build();
  } else if (requestHeaderContentId != null) {
    modifiedResponse =
        ODataResponse.fromResponse(response).header(BatchHelper.REQUEST_HEADER_CONTENT_ID, requestHeaderContentId)
            .build();
  } else if (mimeHeaderContentId != null) {
    modifiedResponse =
        ODataResponse.fromResponse(response).header(BatchHelper.MIME_HEADER_CONTENT_ID, mimeHeaderContentId).build();
  } else {
    return response;
  }
  return modifiedResponse;
}
 
示例17
@Test
public void singleComplexType() throws Exception {
  final EdmFunctionImport functionImport =
      MockFacade.getMockEdm().getDefaultEntityContainer().getFunctionImport("MostCommonLocation");

  final ODataResponse response =
      createAtomEntityProvider()
          .writeFunctionImport(functionImport, employeeData.get("Location"), DEFAULT_PROPERTIES);
  assertNotNull(response);
  assertNotNull(response.getEntity());
  assertNull("EntitypProvider must not set content header", response.getContentHeader());

  final String xml = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertNotNull(xml);

  assertXpathExists("/d:MostCommonLocation", xml);
  assertXpathEvaluatesTo("RefScenario.c_Location", "/d:MostCommonLocation/@m:type", xml);
  assertXpathEvaluatesTo("Duckburg", "/d:MostCommonLocation/d:City/d:CityName/text()", xml);
}
 
示例18
@Test
public void testissueWithHeaderHavingUmlautChars() throws BatchException, IOException {
  List<BatchResponsePart> parts = new ArrayList<BatchResponsePart>();
  String headerValue = "<notification xmlns:ns=\"http://namespace\">"
      + "<code>TEST_MSG/004</code><message>Team ID 'XXX_E'äöü Ö is not in the defined range."
      + "</message><target>Team_Identifier</target><severity>error</severity><details><detail>"
      + "<code>TEST_MSG/010</code><message>"
      + "This is a message text of a business exception raised by the provider.</message><target>"
      + "</target><severity>warning</severity></detail></details></notification>";
  ODataResponse response = ODataResponse.entity("Walter Winter")
      .status(HttpStatusCodes.OK)
      .header("message", headerValue)
      .contentHeader("application/xml")
      .build();
  List<ODataResponse> responses = new ArrayList<ODataResponse>(1);
  responses.add(response);
  parts.add(BatchResponsePart.responses(responses).changeSet(false).build());

  BatchResponseWriter writer = new BatchResponseWriter();
  ODataResponse batchResponse = writer.writeResponse(parts);

  assertNotNull(batchResponse.getEntity());
  assertTrue(batchResponse.getEntity().toString().
      contains("Team ID 'XXX_E'äöü Ö is not in the defined range."));
}
 
示例19
@Test
public void addEmptyEntityToNavigation() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  Entity employeeData = new Entity();
  employeeData.addProperty("EmployeeId", "1");
  Entity managerLink = new Entity();
  employeeData.addNavigation("ne_Manager", managerLink); 

  EntitySerializerProperties properties =
      EntitySerializerProperties.fromProperties(DEFAULT_PROPERTIES).build();
  employeeData.setWriteProperties(properties);
  final ODataResponse response = new JsonSerializerDeserializer().writeEntry(entitySet, employeeData);
  @SuppressWarnings("unchecked")
  Map<String, Object> employee =
      (Map<String, Object>) new Gson().fromJson(new InputStreamReader((InputStream) response.getEntity()), Map.class);
  assertNull(employee.get("__metadata"));
  assertNull(employee.get("ne_Team"));
  assertNull(employee.get("ne_Room"));

  assertEquals("1", employee.get("EmployeeId"));
  assertNotNull(employee.get("ne_Manager"));
}
 
示例20
@Test
public void serializeLinksAndInlineCount() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  Map<String, Object> employee1 = new HashMap<String, Object>();
  employee1.put("EmployeeId", "1");
  Map<String, Object> employee2 = new HashMap<String, Object>();
  employee2.put("EmployeeId", "2");
  ArrayList<Map<String, Object>> employeesData = new ArrayList<Map<String, Object>>();
  employeesData.add(employee1);
  employeesData.add(employee2);

  final ODataResponse response = new JsonEntityProvider().writeLinks(entitySet, employeesData,
      EntityProviderWriteProperties.serviceRoot(URI.create(BASE_URI))
          .inlineCountType(InlineCount.ALLPAGES).inlineCount(42).build());
  assertNotNull(response);
  assertNotNull(response.getEntity());
  assertNull("EntitypProvider must not set content header", response.getContentHeader());

  final String json = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertNotNull(json);
  assertEquals("{\"d\":{\"__count\":\"42\",\"results\":["
      + "{\"uri\":\"" + BASE_URI + "Employees('1')\"},"
      + "{\"uri\":\"" + BASE_URI + "Employees('2')\"}]}}",
      json);
}
 
示例21
@Override
public ODataResponse executeFunctionImportValue(final GetFunctionImportUriInfo uriInfo, final String contentType)
    throws ODataException {
  final EdmFunctionImport functionImport = uriInfo.getFunctionImport();
  final EdmSimpleType type = (EdmSimpleType) functionImport.getReturnType().getType();

  final Object data = dataSource.readData(
      functionImport,
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      null);

  if (data == null) {
    throw new ODataNotFoundException(ODataHttpException.COMMON);
  }

  ODataResponse response;
  if (type == EdmSimpleTypeKind.Binary.getEdmSimpleTypeInstance()) {
    response = EntityProvider.writeBinary(((BinaryData) data).getMimeType(), ((BinaryData) data).getData());
  } else {
    final String value = type.valueToString(data, EdmLiteralKind.DEFAULT, null);
    response = EntityProvider.writeText(value == null ? "" : value);
  }
  return ODataResponse.fromResponse(response).build();
}
 
示例22
@Test
public void testTwoChangeSetResponse() throws BatchException, IOException {
  List<BatchResponsePart> parts = new ArrayList<BatchResponsePart>();
  ODataResponse changeSetResponse = ODataResponse.status(HttpStatusCodes.NO_CONTENT).build();
  ODataResponse changeSetResponseTwo = ODataResponse.status(HttpStatusCodes.NO_CONTENT).build();
  List<ODataResponse> responses = new ArrayList<ODataResponse>(1);
  responses.add(changeSetResponse);
  responses.add(changeSetResponseTwo);
  parts.add(BatchResponsePart.responses(responses).changeSet(true).build());

  BatchResponseWriter writer = new BatchResponseWriter();
  ODataResponse batchResponse = writer.writeResponse(parts);

  assertEquals(202, batchResponse.getStatus().getStatusCode());
  assertNotNull(batchResponse.getEntity());
  String body = (String) batchResponse.getEntity();
  assertTrue(body.contains("--batch"));
  assertTrue(body.contains("--changeset"));
  assertTrue(body.indexOf("--changeset") != body.lastIndexOf("--changeset"));
  assertFalse(body.contains("HTTP/1.1 200 OK" + "\r\n"));
  assertTrue(body.contains("Content-Type: application/http" + "\r\n"));
  assertTrue(body.contains("Content-Transfer-Encoding: binary" + "\r\n"));
  assertTrue(body.contains("HTTP/1.1 204 No Content" + "\r\n"));
  assertTrue(body.contains("Content-Type: multipart/mixed; boundary=changeset"));

  String contentHeader = batchResponse.getContentHeader();
  BatchParser parser = new BatchParser(contentHeader, true);
  StringHelper.Stream content = StringHelper.toStream(body);
  List<BatchSingleResponse> result = parser.parseBatchResponse(content.asStream());
  assertEquals(2, result.size());
  assertEquals("Failing content:\n" + content.asString(), 19, content.linesCount());
}
 
示例23
@Test
public void body() throws Exception {
  final ODataContext context = mockContext(ODataHttpMethod.GET);
  ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, "\"test\"", HttpContentType.APPLICATION_JSON);

  ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
      ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
  String entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertEquals(EXPECTED.replace("}},\"server",
      "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.APPLICATION_JSON + "\"},"
          + "\"body\":\"test\"},\"server"),
      entity);

  wrappedResponse = mockResponse(HttpStatusCodes.OK, "test", HttpContentType.TEXT_PLAIN);
  response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
      ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
  entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertEquals(EXPECTED.replace("}},\"server",
      "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.TEXT_PLAIN + "\"},"
          + "\"body\":\"test\"},\"server"),
      entity);

  wrappedResponse = mockResponse(HttpStatusCodes.OK, null, "image/png");
  when(wrappedResponse.getEntity()).thenReturn(new ByteArrayInputStream("test".getBytes()));
  response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
      ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
  entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertEquals(EXPECTED.replace("}},\"server",
      "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"image/png\"},"
          + "\"body\":\"dGVzdA==\"},\"server"),
      entity);

  when(wrappedResponse.getEntity()).thenReturn(new ByteArrayInputStream("test".getBytes()));
  response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
      ODataDebugResponseWrapper.ODATA_DEBUG_HTML).wrapResponse();
  entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertTrue(entity.contains("<img src=\"data:image/png;base64,dGVzdA==\" />"));
}
 
示例24
private String verifyResponse(final ODataResponse response) throws IOException {
  assertNotNull(response);
  assertNotNull(response.getEntity());
  assertNull("EntityProvider should not set content header", response.getContentHeader());
  String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity());
  return xmlString;
}
 
示例25
@Test
public void serializeImage() throws Exception {
  final EdmProperty property =
      (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario2", "Photo").getProperty("Image");
  ODataResponse response = createAtomEntityProvider().writeProperty(property, photoData.get("Image"));
  assertNotNull(response);
  assertNotNull(response.getEntity());
  assertNull("EntityProvider should not set content header", response.getContentHeader());

  final String xml = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertNotNull(xml);
  assertXpathExists("/d:Image", xml);
  assertXpathExists("/d:Image/@m:MimeType", xml);
  assertXpathEvaluatesTo("image/png", "/d:Image/@m:MimeType", xml);
}
 
示例26
@Test
public void readManagers() throws Exception {
  final UriInfo uriResult = mockUriResult("Managers");

  ODataResponse response =
      processor.readEntitySet(uriResult, ContentType.APPLICATION_ATOM_XML_FEED.toContentTypeString());
  assertNotNull(response);
  assertTrue(readContent(response).contains("Manager"));
}
 
示例27
@Test
public void testRefScenario() throws Exception {
  EdmProvider testProvider = new EdmTestProvider();
  ODataResponse response = EntityProvider.writeMetadata(testProvider.getSchemas(), null);

  String stream = StringHelper.inputStreamToString((InputStream) response.getEntity());
  XmlMetadataDeserializer parser = new XmlMetadataDeserializer();
  EdmDataServices result = parser.readMetadata(createStreamReader(stream), true);
 
  assertNotNull(result);
}
 
示例28
@Override
public ODataResponse existsEntity(final GetEntityCountUriInfo uriInfo, final String contentType)
    throws ODataException {
  final Object data = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      uriInfo.getNavigationSegments());

  return ODataResponse.fromResponse(EntityProvider.writeText(
      appliesFilter(uriInfo.getTargetEntitySet(), data, uriInfo.getFilter()) ? "1" : "0"))
      .build();
}
 
示例29
public ODataResponse getEntityMedia(GetMediaResourceUriInfo uri_info,
      ODataSingleProcessor processor) throws ODataException
{
   KeyPredicate startKP = uri_info.getKeyPredicates().get(0);
   T t = Navigator.<T>navigate(uri_info.getStartEntitySet(), startKP,
         uri_info.getNavigationSegments(), null);
   ODataResponse resp = t.getEntityMedia(processor);
   if (resp == null)
   {
      throw new ExpectedException("No stream for entity " + getEntityName());
   }
   return resp;
}
 
示例30
@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);
}