Java Code Examples for org.apache.olingo.commons.api.data.Entity#getETag()

The following examples show how to use org.apache.olingo.commons.api.data.Entity#getETag() . 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: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void updateMediaEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType requestFormat, final ContentType responseFormat)
    throws ODataApplicationException, ODataLibraryException {
  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo);
  final EdmEntityType edmEntityType = edmEntitySet.getEntityType();

  Entity entity = readEntity(uriInfo);
  odata.createETagHelper().checkChangePreconditions(entity.getMediaETag(),
      request.getHeaders(HttpHeader.IF_MATCH),
      request.getHeaders(HttpHeader.IF_NONE_MATCH));
  checkRequestFormat(requestFormat);
  dataProvider.setMedia(entity, odata.createFixedFormatDeserializer().binary(request.getBody()),
      requestFormat.toContentTypeString());

  final Return returnPreference = odata.createPreferences(request.getHeaders(HttpHeader.PREFER)).getReturn();
  if (returnPreference == null || returnPreference == Return.REPRESENTATION) {
    response.setContent(serializeEntity(request, entity, edmEntitySet, edmEntityType, responseFormat)
        .getContent());
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
  } else {
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
  }
  if (returnPreference != null) {
    response.setHeader(HttpHeader.PREFERENCE_APPLIED,
        PreferencesApplied.with().returnRepresentation(returnPreference).build().toValueString());
  }
  if (entity.getETag() != null) {
    response.setHeader(HttpHeader.ETAG, entity.getETag());
  }
}
 
Example 2
Source File: TechnicalPrimitiveComplexProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void deleteProperty(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
    final boolean isValue) throws ODataLibraryException, ODataApplicationException {
  final UriInfoResource resource = uriInfo.asUriInfoResource();
  validatePath(resource);
  getEdmEntitySet(uriInfo); // including checks

  Entity entity = readEntity(uriInfo);
  odata.createETagHelper().checkChangePreconditions(entity.getETag(),
      request.getHeaders(HttpHeader.IF_MATCH),
      request.getHeaders(HttpHeader.IF_NONE_MATCH));

  final List<UriResource> resourceParts = resource.getUriResourceParts();
  final int trailing = isValue ? 1 : 0;
  final List<String> path = getPropertyPath(resourceParts, trailing);

  Property property = getPropertyData(entity, path);

  final EdmProperty edmProperty = ((UriResourceProperty) resourceParts.get(resourceParts.size() - trailing - 1))
      .getProperty();

  if (edmProperty.isNullable()) {
    property.setValue(property.getValueType(), edmProperty.isCollection() ? Collections.emptyList() : null);
    dataProvider.updateETag(entity);
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    if (entity.getETag() != null) {
      response.setHeader(HttpHeader.ETAG, entity.getETag());
    }
  } else {
    throw new ODataApplicationException("Not nullable.", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
  }
}
 
Example 3
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public void updateETag(Entity entity) {
  if (entity.getETag() != null) {
    entity.setETag("W/\"" + UUID.randomUUID() + "\"");
  }
}
 
Example 4
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public void updateEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType requestFormat, final ContentType responseFormat)
    throws ODataApplicationException, ODataLibraryException {
  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo);
  final EdmEntityType edmEntityType = edmEntitySet.getEntityType();

  Entity entity;
  try {
    entity = readEntity(uriInfo);
  } catch (ODataApplicationException e) {
    if (e.getStatusCode() == HttpStatusCode.NOT_FOUND.getStatusCode()) {
      // Perform upsert
      createEntity(request, response, uriInfo, requestFormat, responseFormat);
      return;
    } else {
      throw e;
    }
  }

  odata.createETagHelper().checkChangePreconditions(entity.getETag(),
      request.getHeaders(HttpHeader.IF_MATCH),
      request.getHeaders(HttpHeader.IF_NONE_MATCH));
  final ODataDeserializer deserializer = odata.createDeserializer(requestFormat, serviceMetadata);
  final Entity changedEntity = deserializer.entity(request.getBody(), edmEntitySet.getEntityType()).getEntity();

  new RequestValidator(dataProvider,
      true, // Update
      request.getMethod() == HttpMethod.PATCH,
      request.getRawBaseUri()).validate(edmEntitySet, changedEntity);

  dataProvider.update(request.getRawBaseUri(), edmEntitySet, entity, changedEntity,
      request.getMethod() == HttpMethod.PATCH, false);

  final Return returnPreference = odata.createPreferences(request.getHeaders(HttpHeader.PREFER)).getReturn();
  if (returnPreference == null || returnPreference == Return.REPRESENTATION) {
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    response.setContent(serializeEntity(request, entity, edmEntitySet, edmEntityType, responseFormat)
        .getContent());
    response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
  } else {
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
  }
  if (returnPreference != null) {
    response.setHeader(HttpHeader.PREFERENCE_APPLIED,
        PreferencesApplied.with().returnRepresentation(returnPreference).build().toValueString());
  }
  if (entity.getETag() != null) {
    response.setHeader(HttpHeader.ETAG, entity.getETag());
  }
}
 
Example 5
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void readEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType requestedFormat, final boolean isReference)
    throws ODataApplicationException, ODataLibraryException {
  //
  if (odata.createPreferences(request.getHeaders(HttpHeader.PREFER)).hasRespondAsync()) {
    TechnicalAsyncService asyncService = TechnicalAsyncService.getInstance();
    TechnicalEntityProcessor processor = new TechnicalEntityProcessor(dataProvider, serviceMetadata);
    processor.init(odata, serviceMetadata);
    AsyncProcessor<EntityProcessor> asyncProcessor = asyncService.register(processor, EntityProcessor.class);
    asyncProcessor.prepareFor().readEntity(request, response, uriInfo, requestedFormat);
    String location = asyncProcessor.processAsync();
    TechnicalAsyncService.acceptedResponse(response, location);
    //
    return;
  }
  //

  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo);
  
  //for Singleton/$ref edmEntityset will be null throw error
  validateSingletonRef(isReference,edmEntitySet);
 
  EdmEntityType edmEntityType = null;
  edmEntityType = getEdmTypeForContNavProperty(uriInfo);
  final boolean iscontNav = checkIfContNavigation(uriInfo);
  if (edmEntityType == null) {
    edmEntityType = getEdmType(uriInfo, edmEntitySet);
  }

  final Entity entity = readEntity(uriInfo);

  if (odata.createETagHelper().checkReadPreconditions(entity.getETag(),
      request.getHeaders(HttpHeader.IF_MATCH),
      request.getHeaders(HttpHeader.IF_NONE_MATCH))) {
    response.setStatusCode(HttpStatusCode.NOT_MODIFIED.getStatusCode());
    response.setHeader(HttpHeader.ETAG, entity.getETag());
    return;
  }

  final ExpandOption expand = uriInfo.getExpandOption();
  final SelectOption select = uriInfo.getSelectOption();

  final ExpandSystemQueryOptionHandler expandHandler = new ExpandSystemQueryOptionHandler();
  final Entity entitySerialization = expandHandler.transformEntityGraphToTree(entity, edmEntitySet, expand, null);
  expandHandler.applyExpandQueryOptions(entitySerialization, edmEntitySet, expand, uriInfo,
      serviceMetadata.getEdm());

  final SerializerResult serializerResult = isReference ?
      serializeReference(entity, edmEntitySet, requestedFormat) :
      serializeEntity(request, entitySerialization, edmEntitySet, edmEntityType, 
          requestedFormat, expand, select, iscontNav);

  if (entity.getETag() != null) {
    response.setHeader(HttpHeader.ETAG, entity.getETag());
  }
  response.setContent(serializerResult.getContent());
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, requestedFormat.toContentTypeString());
}
 
Example 6
Source File: TechnicalPrimitiveComplexProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void readProperty(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
    final ContentType contentType, final RepresentationType representationType)
        throws ODataApplicationException, ODataLibraryException {
  final UriInfoResource resource = uriInfo.asUriInfoResource();
  validateOptions(resource);
  validatePath(resource);
  final EdmEntitySet edmEntitySet = getEdmEntitySet(resource);

  final List<UriResource> resourceParts = resource.getUriResourceParts();
  final int trailing =
      representationType == RepresentationType.COUNT || representationType == RepresentationType.VALUE ? 1 : 0;
  final List<String> path = getPropertyPath(resourceParts, trailing);

  final Entity entity = readEntity(uriInfo);

  if (entity != null && entity.getETag() != null) {
    if (odata.createETagHelper().checkReadPreconditions(entity.getETag(),
        request.getHeaders(HttpHeader.IF_MATCH),
        request.getHeaders(HttpHeader.IF_NONE_MATCH))) {
      response.setStatusCode(HttpStatusCode.NOT_MODIFIED.getStatusCode());
      response.setHeader(HttpHeader.ETAG, entity.getETag());
      return;
    }
  }

  final Property property = entity == null ?
      getPropertyData(
          dataProvider.readFunctionPrimitiveComplex(((UriResourceFunction) resourceParts.get(0)).getFunction(),
          ((UriResourceFunction) resourceParts.get(0)).getParameters(), resource), path) :
      getData(entity, path, resourceParts, resource);

  // TODO: implement filter on collection properties (on a shallow copy of the values)
  // FilterHandler.applyFilterSystemQuery(uriInfo.getFilterOption(), property, uriInfo, serviceMetadata.getEdm());

  if (property == null && representationType != RepresentationType.COUNT) {
    if (representationType == RepresentationType.VALUE) {
      response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    } else {
      throw new ODataApplicationException("Nothing found.", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
    }
  } else {
    if (property.getValue() == null && representationType != RepresentationType.COUNT) {
      response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    } else {
      response.setStatusCode(HttpStatusCode.OK.getStatusCode());
      if (representationType == RepresentationType.COUNT) {
        response.setContent(odata.createFixedFormatSerializer().count(
            property.asCollection().size()));
      } else {
        final EdmProperty edmProperty = path.isEmpty() ? null :
            ((UriResourceProperty) resourceParts.get(resourceParts.size() - trailing - 1)).getProperty();
        EdmType type = null;
        if (resourceParts.get(resourceParts.size() - trailing - 1) 
           instanceof UriResourceComplexProperty &&
            ((UriResourceComplexProperty)resourceParts.get(resourceParts.size() - trailing - 1)).
            getComplexTypeFilter() != null) {
          type = ((UriResourceComplexProperty)resourceParts.get(resourceParts.size() - trailing - 1)).
              getComplexTypeFilter();
        }else if(resourceParts.get(resourceParts.size() - trailing - 1) 
           instanceof UriResourceFunction &&
            ((UriResourceFunction)resourceParts.get(resourceParts.size() - trailing - 1)).
            getFunction() != null){ 
          type = ((UriResourceFunction)resourceParts.get(resourceParts.size() - trailing - 1)).
              getType();
        }else {
          type = edmProperty == null ?
              ((UriResourceFunction) resourceParts.get(0)).getType() :
              edmProperty.getType();
        }
        final EdmReturnType returnType = resourceParts.get(0) instanceof UriResourceFunction ?
            ((UriResourceFunction) resourceParts.get(0)).getFunction().getReturnType() : 
              resourceParts.get(1) instanceof UriResourceFunction ? 
                  ((UriResourceFunction) resourceParts.get(1)).getFunction().getReturnType():null ;

        if (representationType == RepresentationType.VALUE) {
          response.setContent(serializePrimitiveValue(property, edmProperty, (EdmPrimitiveType) type, returnType));
        }else if(representationType == RepresentationType.PRIMITIVE && type.getFullQualifiedName()
            .getFullQualifiedNameAsString().equals(EDMSTREAM)){
          response.setContent(odata.createFixedFormatSerializer().binary(dataProvider.readStreamProperty(property)));
          response.setStatusCode(HttpStatusCode.OK.getStatusCode());
          response.setHeader(HttpHeader.CONTENT_TYPE, ((Link)property.getValue()).getType());
          if (entity.getMediaETag() != null) {
            response.setHeader(HttpHeader.ETAG, entity.getMediaETag());
          }
        }else {
          final ExpandOption expand = uriInfo.getExpandOption();
          final SelectOption select = uriInfo.getSelectOption();
          final SerializerResult result = serializeProperty(entity, edmEntitySet, path, property, edmProperty,
              type, returnType, representationType, contentType, expand, select);
          response.setContent(result.getContent());
        }
      }
      response.setHeader(HttpHeader.CONTENT_TYPE, contentType.toContentTypeString());
    }
    if (entity != null && entity.getETag() != null) {
      response.setHeader(HttpHeader.ETAG, entity.getETag());
    }
  }
}
 
Example 7
Source File: TechnicalPrimitiveComplexProcessor.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void updateProperty(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
    final ContentType requestFormat, final ContentType responseFormat, final RepresentationType representationType)
    throws ODataApplicationException, ODataLibraryException {
  final UriInfoResource resource = uriInfo.asUriInfoResource();
  validatePath(resource);
  final EdmEntitySet edmEntitySet = getEdmEntitySet(resource);

  Entity entity = readEntity(uriInfo);
  odata.createETagHelper().checkChangePreconditions(entity.getETag(),
      request.getHeaders(HttpHeader.IF_MATCH),
      request.getHeaders(HttpHeader.IF_NONE_MATCH));

  final List<UriResource> resourceParts = resource.getUriResourceParts();
  final int trailing = representationType == RepresentationType.VALUE ? 1 : 0;
  final List<String> path = getPropertyPath(resourceParts, trailing);
  final EdmProperty edmProperty = ((UriResourceProperty) resourceParts.get(resourceParts.size() - trailing - 1))
      .getProperty();

  Property property = getPropertyData(entity, path);

  if (representationType == RepresentationType.VALUE || 
  		edmProperty.getType().getFullQualifiedName()
  		.getFullQualifiedNameAsString().equalsIgnoreCase(EDMSTREAM)) {
    final FixedFormatDeserializer deserializer = odata.createFixedFormatDeserializer();
    final Object value = edmProperty.getType() == odata.createPrimitiveTypeInstance(EdmPrimitiveTypeKind.Binary) 
  		  || edmProperty.getType() == odata.createPrimitiveTypeInstance(EdmPrimitiveTypeKind.Stream) ?
        deserializer.binary(request.getBody()) :
        deserializer.primitiveValue(request.getBody(), edmProperty);
    dataProvider.updatePropertyValue(property, value);
  } else {
    final Property changedProperty = odata.createDeserializer(requestFormat)
        .property(request.getBody(), edmProperty).getProperty();
    if (changedProperty.isNull() && !edmProperty.isNullable()) {
      throw new ODataApplicationException("Not nullable.", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
    }
    dataProvider.updateProperty(edmProperty, property, changedProperty, request.getMethod() == HttpMethod.PATCH);
  }

  dataProvider.updateETag(entity);

  final Return returnPreference = odata.createPreferences(request.getHeaders(HttpHeader.PREFER)).getReturn();
  if (returnPreference == null || returnPreference == Return.REPRESENTATION) {
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    if (representationType == RepresentationType.VALUE || 
      		edmProperty.getType().getFullQualifiedName()
        		.getFullQualifiedNameAsString().equalsIgnoreCase(EDMSTREAM)) {
      response.setContent(
          serializePrimitiveValue(property, edmProperty, (EdmPrimitiveType) edmProperty.getType(), null));
    } else {
      final SerializerResult result = serializeProperty(entity, edmEntitySet, path, property, edmProperty,
          edmProperty.getType(), null, representationType, responseFormat, null, null);
      response.setContent(result.getContent());
    }
    if (edmProperty.getType().getFullQualifiedName()
      		.getFullQualifiedNameAsString().equalsIgnoreCase(EDMSTREAM)) {
    	  response.setHeader(HttpHeader.CONTENT_TYPE, requestFormat.toContentTypeString());
      } else {
    	  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
      }
  } else {
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
  }
  if (returnPreference != null) {
    response.setHeader(HttpHeader.PREFERENCE_APPLIED,
        PreferencesApplied.with().returnRepresentation(returnPreference).build().toValueString());
  }
  if (entity.getETag() != null) {
    response.setHeader(HttpHeader.ETAG, entity.getETag());
  }
}
 
Example 8
Source File: ODataJsonSerializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
protected void writeEntity(final ServiceMetadata metadata, final EdmEntityType entityType, final Entity entity,
    final ContextURL contextURL, final ExpandOption expand, Integer toDepth, 
    final SelectOption select, final boolean onlyReference, Set<String> ancestors, 
    String name, final JsonGenerator json)
    throws IOException, SerializerException, DecoderException {
  boolean cycle = false;
  if (expand != null) {
    if (ancestors == null) {
      ancestors = new HashSet<>();
    }
    cycle = !ancestors.add(getEntityId(entity, entityType, name));
  }
  try {
    json.writeStartObject();
    if (!isODataMetadataNone) {
      // top-level entity
      if (contextURL != null) {
        writeContextURL(contextURL, json);
        writeMetadataETag(metadata, json);
      }
      if (entity.getETag() != null) {
        json.writeStringField(constants.getEtag(), entity.getETag());
      }
      if (entityType.hasStream()) {
        if (entity.getMediaETag() != null) {
          json.writeStringField(constants.getMediaEtag(), entity.getMediaETag());
        }
        if (entity.getMediaContentType() != null) {
          json.writeStringField(constants.getMediaContentType(), entity.getMediaContentType());
        }
        if (entity.getMediaContentSource() != null) {
          json.writeStringField(constants.getMediaReadLink(), entity.getMediaContentSource().toString());
        }
        if (entity.getMediaEditLinks() != null && !entity.getMediaEditLinks().isEmpty()) {
          json.writeStringField(constants.getMediaEditLink(), entity.getMediaEditLinks().get(0).getHref());
        }
      }
    }
    if (cycle || onlyReference) {
      json.writeStringField(constants.getId(), getEntityId(entity, entityType, name));
    } else {
      final EdmEntityType resolvedType = resolveEntityType(metadata, entityType, entity.getType());
      if ((!isODataMetadataNone && !resolvedType.equals(entityType)) || isODataMetadataFull) {
        json.writeStringField(constants.getType(), "#" + entity.getType());
      }
      if ((!isODataMetadataNone && !areKeyPredicateNamesSelected(select, resolvedType)) || isODataMetadataFull) {
        json.writeStringField(constants.getId(), getEntityId(entity, resolvedType, name));
      }
      
      if (isODataMetadataFull) {
        if (entity.getSelfLink() != null) {
          json.writeStringField(constants.getReadLink(), entity.getSelfLink().getHref());
        }
        if (entity.getEditLink() != null) {
          json.writeStringField(constants.getEditLink(), entity.getEditLink().getHref());
        }
      }
      
      writeProperties(metadata, resolvedType, entity.getProperties(), select, json, entity, expand);
      writeNavigationProperties(metadata, resolvedType, entity, expand, toDepth, ancestors, name, json);
      writeOperations(entity.getOperations(), json);      
    }
    json.writeEndObject();
  } finally {
    if (expand != null && !cycle && ancestors != null) {
      ancestors.remove(getEntityId(entity, entityType, name));
    }
  }
}
 
Example 9
Source File: ODataXmlSerializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
protected void writeEntity(final ServiceMetadata metadata, final EdmEntityType entityType,
    final Entity entity, final ContextURL contextURL, final ExpandOption expand, final Integer toDepth,
    final SelectOption select, final String xml10InvalidCharReplacement,
    final XMLStreamWriter writer, final boolean top, final boolean writeOnlyRef,String name,  Set<String> ancestors)
    throws XMLStreamException, SerializerException {
  boolean cycle = false;
  if (expand != null) {
    if (ancestors == null) {
      ancestors = new HashSet<String>();
    }
    cycle = !ancestors.add(getEntityId(entity, entityType, name));
  }

  if (cycle || writeOnlyRef) {
    writeReference(entity, contextURL, writer, top);
    return;
  }
  try {
    writer.writeStartElement(ATOM, Constants.ATOM_ELEM_ENTRY, NS_ATOM);
    if (top) {
      writer.writeNamespace(ATOM, NS_ATOM);
      writer.writeNamespace(METADATA, NS_METADATA);
      writer.writeNamespace(DATA, NS_DATA);

      if (contextURL != null) { // top-level entity
        writer.writeAttribute(METADATA, NS_METADATA, Constants.CONTEXT,
            ContextURLBuilder.create(contextURL).toASCIIString());
        writeMetadataETag(metadata, writer);
      }
    }
    if (entity.getETag() != null) {
      writer.writeAttribute(METADATA, NS_METADATA, Constants.ATOM_ATTR_ETAG, entity.getETag());
    }

    if (entity.getId() != null) {
      writer.writeStartElement(NS_ATOM, Constants.ATOM_ELEM_ID);
      writer.writeCharacters(entity.getId().toASCIIString());
      writer.writeEndElement();
    }

    writerAuthorInfo(entity.getTitle(), writer);

    if (entity.getId() != null) {
      writer.writeStartElement(NS_ATOM, Constants.ATOM_ELEM_LINK);
      writer.writeAttribute(Constants.ATTR_REL, Constants.EDIT_LINK_REL);
      writer.writeAttribute(Constants.ATTR_HREF, entity.getId().toASCIIString());
      writer.writeEndElement();
    }

    if (entityType.hasStream()) {
      writer.writeStartElement(NS_ATOM, Constants.ATOM_ELEM_CONTENT);
      writer.writeAttribute(Constants.ATTR_TYPE, entity.getMediaContentType());
      if (entity.getMediaContentSource() != null) {
        writer.writeAttribute(Constants.ATOM_ATTR_SRC, entity.getMediaContentSource().toString());
      } else {
        String id = entity.getId().toASCIIString();
        writer.writeAttribute(Constants.ATOM_ATTR_SRC,
            id + (id.endsWith("/") ? "" : "/") + "$value");
      }
      writer.writeEndElement();
    }

    // write media links
    for (Link link : entity.getMediaEditLinks()) {
      writeLink(writer, link);
    }

    EdmEntityType resolvedType = resolveEntityType(metadata, entityType, entity.getType());
    writeNavigationProperties(metadata, resolvedType, entity, expand,
      toDepth, xml10InvalidCharReplacement, ancestors, name, writer);

    writer.writeStartElement(ATOM, Constants.ATOM_ELEM_CATEGORY, NS_ATOM);
    writer.writeAttribute(Constants.ATOM_ATTR_SCHEME, Constants.NS_SCHEME);
    writer.writeAttribute(Constants.ATOM_ATTR_TERM,
        "#" + resolvedType.getFullQualifiedName().getFullQualifiedNameAsString());
    writer.writeEndElement();

    // In the case media, content is sibiling
    if (!entityType.hasStream()) {
      writer.writeStartElement(NS_ATOM, Constants.ATOM_ELEM_CONTENT);
      writer.writeAttribute(Constants.ATTR_TYPE, "application/xml");
    }

    writer.writeStartElement(METADATA, Constants.PROPERTIES, NS_METADATA);
    writeProperties(metadata, resolvedType, entity.getProperties(), select, 
        xml10InvalidCharReplacement, writer, entity, expand);
    writer.writeEndElement(); // properties

    if (!entityType.hasStream()) { // content
      writer.writeEndElement();
    }
    
    writeOperations(entity.getOperations(), writer);
    
    writer.writeEndElement(); // entry
  } finally {
    if (!cycle && ancestors != null) {
      ancestors.remove(getEntityId(entity, entityType, name));
    }
  }
}
 
Example 10
Source File: JsonEntitySerializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
protected void doContainerSerialize(final ResWrap<Entity> container, final JsonGenerator jgen)
    throws IOException, EdmPrimitiveTypeException {

  final Entity entity = container.getPayload();

  jgen.writeStartObject();

  if (serverMode && !isODataMetadataNone) {
    if (container.getContextURL() != null) {
      jgen.writeStringField(Constants.JSON_CONTEXT, container.getContextURL().toASCIIString());
    }
    if (container.getMetadataETag() != null) {
      jgen.writeStringField(Constants.JSON_METADATA_ETAG, container.getMetadataETag());
    }

    if (entity.getETag() != null) {
      jgen.writeStringField(Constants.JSON_ETAG, entity.getETag());
    }
  }

  if (entity.getType() != null && isODataMetadataFull) {
    jgen.writeStringField(Constants.JSON_TYPE,
        new EdmTypeInfo.Builder().setTypeExpression(entity.getType()).build().external());
  }

  if (entity.getId() != null && isODataMetadataFull) {
    jgen.writeStringField(Constants.JSON_ID, entity.getId().toASCIIString());
  }

  for (Annotation annotation : entity.getAnnotations()) {
    valuable(jgen, annotation, "@" + annotation.getTerm());
  }

  for (Property property : entity.getProperties()) {
    valuable(jgen, property, property.getName());
  }

  if (serverMode && entity.getEditLink() != null && 
      entity.getEditLink().getHref() != null && isODataMetadataFull) {
    jgen.writeStringField(Constants.JSON_EDIT_LINK, entity.getEditLink().getHref());

    if (entity.isMediaEntity() && isODataMetadataFull) {
      jgen.writeStringField(Constants.JSON_MEDIA_READ_LINK,
          entity.getEditLink().getHref() + "/$value");
    }
  }

  if (!isODataMetadataNone) {
    links(entity, jgen);
  }

  if (isODataMetadataFull) {
    for (Link link : entity.getMediaEditLinks()) {
      if (link.getTitle() == null) {
        jgen.writeStringField(Constants.JSON_MEDIA_EDIT_LINK, link.getHref());
      }

      if (link.getInlineEntity() != null) {
        jgen.writeObjectField(link.getTitle(), link.getInlineEntity());
      }
      if (link.getInlineEntitySet() != null) {
        jgen.writeArrayFieldStart(link.getTitle());
        for (Entity subEntry : link.getInlineEntitySet().getEntities()) {
          jgen.writeObject(subEntry);
        }
        jgen.writeEndArray();
      }
    }
  }

  if (serverMode && isODataMetadataFull) {
    for (Operation operation : entity.getOperations()) {
      final String anchor = operation.getMetadataAnchor();
      final int index = anchor.lastIndexOf('#');
      jgen.writeObjectFieldStart('#' + anchor.substring(index < 0 ? 0 : (index + 1)));
      jgen.writeStringField(Constants.ATTR_TITLE, operation.getTitle());
      jgen.writeStringField(Constants.ATTR_TARGET, operation.getTarget().toASCIIString());
      jgen.writeEndObject();
    }
  }

  jgen.writeEndObject();
}