org.apache.olingo.server.api.serializer.SerializerException Java Examples

The following examples show how to use org.apache.olingo.server.api.serializer.SerializerException. 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: JsonDeltaSerializerWithNavigationsTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test(expected = SerializerException.class)
public void negativeDeltaDeletedEntityTest2() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESDelta");
  Delta delta = new Delta();   
    
  List<DeletedEntity> deletedEntity = new ArrayList<DeletedEntity>();
  DeletedEntity delEntity1 = new DeletedEntity();
  delEntity1.setId(new URI("ESDelta(100)"));
 
  deletedEntity.add(delEntity1);
  delta.getDeletedEntities().addAll(deletedEntity);    
 
  ser.entityCollection(metadata, edmEntitySet.getEntityType(), delta ,
      EntityCollectionSerializerOptions.with()
      .contextURL(ContextURL.with().entitySet(edmEntitySet).build())
      .build()).getContent();
    
   }
 
Example #2
Source File: JsonDeltaSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected void closeCircleStreamBufferOutput(final OutputStream outputStream,
    final SerializerException cachedException)
    throws SerializerException {
  if (outputStream != null) {
    try {
      outputStream.close();
    } catch (IOException e) {
      if (cachedException != null) {
        throw cachedException;
      } else {
        throw new SerializerException(IO_EXCEPTION_TEXT, e,
            SerializerException.MessageKeys.IO_EXCEPTION);
      }
    }
  }
}
 
Example #3
Source File: ContextURLHelper.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a key predicate for the ContextURL.
 * @param keys the keys as a list of {@link UriParameter} instances
 * @return a String with the key predicate
 */
public static String buildKeyPredicate(final List<UriParameter> keys) throws SerializerException {
  if (keys == null || keys.isEmpty()) {
    return null;
  } else if (keys.size() == 1) {
    return Encoder.encode(keys.get(0).getText());
  } else {
    StringBuilder result = new StringBuilder();
    for (final UriParameter key : keys) {
      if (result.length() > 0) {
        result.append(',');
      }
      result.append(Encoder.encode(key.getName())).append('=').append(Encoder.encode(key.getText()));
    }
    return result.toString();
  }
}
 
Example #4
Source File: MetadataDocumentJsonSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void appendOperationReturnType(final JsonGenerator json, 
    final EdmOperation operation) throws SerializerException, IOException {
  EdmReturnType returnType = operation.getReturnType();
  if (returnType != null) {
    json.writeObjectFieldStart(RETURN_TYPE);
    String returnTypeFqnString;
    if (EdmTypeKind.PRIMITIVE.equals(returnType.getType().getKind())) {
      returnTypeFqnString = getFullQualifiedName(returnType.getType());
    } else {
      returnTypeFqnString = getAliasedFullQualifiedName(returnType.getType());
    }
    json.writeStringField(TYPE, returnTypeFqnString);
    if (returnType.isCollection()) {
      json.writeBooleanField(COLLECTION, returnType.isCollection());
    }
    
    appendReturnTypeFacets(json, returnType);
    json.writeEndObject();
  }
}
 
Example #5
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public Entity create(final EdmEntitySet edmEntitySet) throws DataProviderException {
  final EdmEntityType edmEntityType = edmEntitySet.getEntityType();
  EntityCollection entitySet = readAll(edmEntitySet);
  final List<Entity> entities = entitySet.getEntities();
  final Map<String, Object> newKey = findFreeComposedKey(entities, edmEntityType);
  Entity newEntity = new Entity();
  newEntity.setType(edmEntityType.getFullQualifiedName().getFullQualifiedNameAsString());
  for (final String keyName : edmEntityType.getKeyPredicateNames()) {
    newEntity.addProperty(DataCreator.createPrimitive(keyName, newKey.get(keyName)));
  }

  createProperties(edmEntityType, newEntity.getProperties());
  try {
    newEntity.setId(URI.create(odata.createUriHelper().buildCanonicalURL(edmEntitySet, newEntity)));
  } catch (final SerializerException e) {
    throw new DataProviderException("Unable to set entity ID!", HttpStatusCode.INTERNAL_SERVER_ERROR, e);
  }
  entities.add(newEntity);

  return newEntity;
}
 
Example #6
Source File: MetadataDocumentJsonSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void appendReference(JsonGenerator json) throws SerializerException, IOException {
  json.writeObjectFieldStart(REFERENCES);
  for (final EdmxReference reference : serviceMetadata.getReferences()) {
    json.writeObjectFieldStart(reference.getUri().toASCIIString());

    List<EdmxReferenceInclude> includes = reference.getIncludes();
    if (!includes.isEmpty()) {
      appendIncludes(json, includes);
    }

    List<EdmxReferenceIncludeAnnotation> includeAnnotations = reference.getIncludeAnnotations();
    if (!includeAnnotations.isEmpty()) {
      appendIncludeAnnotations(json, includeAnnotations);
    }
    json.writeEndObject();
  }
  json.writeEndObject();
}
 
Example #7
Source File: ODataJsonSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void writePrimitive(final EdmPrimitiveType type, final Property property,
    final Boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale,
    final Boolean isUnicode, final JsonGenerator json)
    throws EdmPrimitiveTypeException, IOException, SerializerException {
  if (property.isPrimitive()) {
    writePrimitiveValue(property.getName(), type, property.asPrimitive(),
        isNullable, maxLength, precision, scale, isUnicode, json);
  } else if (property.isGeospatial()) {
    writeGeoValue(property.getName(), type, property.asGeospatial(), isNullable, json, null);
  } else if (property.isEnum()) {
    writePrimitiveValue(property.getName(), type, property.asEnum(),
        isNullable, maxLength, precision, scale, isUnicode, json);
  } else {
    throw new SerializerException("Inconsistent property type!",
        SerializerException.MessageKeys.INCONSISTENT_PROPERTY_TYPE, property.getName());
  }
}
 
Example #8
Source File: ODataXmlSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void writePrimitive(final EdmPrimitiveType type, final Property property,
    final Boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale,
    final Boolean isUnicode, final String xml10InvalidCharReplacement, final XMLStreamWriter writer)
    throws EdmPrimitiveTypeException, XMLStreamException, SerializerException {
  if (property.isPrimitive()) {
    if (type != EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.String)) {
      writer.writeAttribute(METADATA, NS_METADATA, Constants.ATTR_TYPE,
          type.getKind() == EdmTypeKind.DEFINITION ?
              "#" + type.getFullQualifiedName().getFullQualifiedNameAsString() :
              type.getName());
    }
    writePrimitiveValue(type, property.asPrimitive(),
        isNullable, maxLength, precision, scale, isUnicode, xml10InvalidCharReplacement, writer);
  } else if (property.isGeospatial()) {
    throw new SerializerException("Property type not yet supported!",
        SerializerException.MessageKeys.UNSUPPORTED_PROPERTY_TYPE, property.getName());
  } else if (property.isEnum()) {
    writer.writeAttribute(METADATA, NS_METADATA, Constants.ATTR_TYPE,
        "#" + type.getFullQualifiedName().getFullQualifiedNameAsString());
    writePrimitiveValue(type, property.asEnum(),
        isNullable, maxLength, precision, scale, isUnicode, xml10InvalidCharReplacement, writer);
  } else {
    throw new SerializerException("Inconsistent property type!",
        SerializerException.MessageKeys.INCONSISTENT_PROPERTY_TYPE, property.getName());
  }
}
 
Example #9
Source File: AbstractODataSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected void closeCircleStreamBufferOutput(final OutputStream outputStream,
    final SerializerException cachedException)
    throws SerializerException {
  if (outputStream != null) {
    try {
      outputStream.close();
    } catch (IOException e) {
      if (cachedException != null) {
        throw cachedException;
      } else {
        throw new SerializerException(IO_EXCEPTION_TEXT, e,
            SerializerException.MessageKeys.IO_EXCEPTION);
      }
    }
  }
}
 
Example #10
Source File: JsonDeltaSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void writeComplexCollection(final ServiceMetadata metadata, final EdmComplexType type,
    final Property property,
    final Set<List<String>> selectedPaths, final JsonGenerator json)
    throws IOException, SerializerException {
  json.writeStartArray();
  for (Object value : property.asCollection()) {
    switch (property.getValueType()) {
    case COLLECTION_COMPLEX:
      json.writeStartObject();
      if (isODataMetadataFull) {
        json.writeStringField(Constants.JSON_TYPE, "#" +
            type.getFullQualifiedName().getFullQualifiedNameAsString());
      }
      writeComplexValue(metadata, type, ((ComplexValue) value).getValue(), selectedPaths, json);
      json.writeEndObject();
      break;
    default:
      throw new SerializerException("Property type not yet supported!",
          SerializerException.MessageKeys.UNSUPPORTED_PROPERTY_TYPE, property.getName());
    }
  }
  json.writeEndArray();
}
 
Example #11
Source File: JsonDeltaSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void writePrimitive(final EdmPrimitiveType type, final Property property,
    final Boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale,
    final Boolean isUnicode, final JsonGenerator json)
    throws EdmPrimitiveTypeException, IOException, SerializerException {
  if (property.isPrimitive()) {
    writePrimitiveValue(property.getName(), type, property.asPrimitive(),
        isNullable, maxLength, precision, scale, isUnicode, json);
  } else if (property.isGeospatial()) {
    throw new SerializerException("Property type not yet supported!",
        SerializerException.MessageKeys.UNSUPPORTED_PROPERTY_TYPE, property.getName());
  } else if (property.isEnum()) {
    writePrimitiveValue(property.getName(), type, property.asEnum(),
        isNullable, maxLength, precision, scale, isUnicode, json);
  } else {
    throw new SerializerException("Inconsistent property type!",
        SerializerException.MessageKeys.INCONSISTENT_PROPERTY_TYPE, property.getName());
  }
}
 
Example #12
Source File: JsonDeltaSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test(expected = SerializerException.class)
public void negativeDeltaDeletedEntityTest2() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESDelta");
  Delta delta = new Delta();   
    
  List<DeletedEntity> deletedEntity = new ArrayList<DeletedEntity>();
  DeletedEntity delEntity1 = new DeletedEntity();
  delEntity1.setId(new URI("ESDelta(100)"));
 
  deletedEntity.add(delEntity1);
  delta.getDeletedEntities().addAll(deletedEntity);    
 
  ser.entityCollection(metadata, edmEntitySet.getEntityType(), delta ,
      EntityCollectionSerializerOptions.with()
      .contextURL(ContextURL.with().entitySet(edmEntitySet).build())
      .build()).getContent();
    
   }
 
Example #13
Source File: JsonDeltaSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test(expected = SerializerException.class)
public void negativeLinkDeltaTest1() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESDelta");
  Delta delta = new Delta();
  
  List<DeltaLink> addedLinks = new ArrayList<DeltaLink>();
  DeltaLink link1 = new DeltaLink();
  link1.setSource(new URI("ESDelta(100)"));
  link1.setTarget(new URI("ESAllPrim(0)"));
  addedLinks.add(link1 );
  delta.getAddedLinks().addAll(addedLinks );
     
  ser.entityCollection(metadata, edmEntitySet.getEntityType(), delta ,
      EntityCollectionSerializerOptions.with()
      .contextURL(ContextURL.with().entitySet(edmEntitySet).build())
      .build()).getContent();      
   }
 
Example #14
Source File: JsonDeltaSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test(expected = SerializerException.class)
public void negativeDeltaEntityTest() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESDelta");
  Delta delta = new Delta();
  
  final Entity entity2 = data.readAll(edmEntitySet).getEntities().get(1);
  List<Entity> addedEntity = new ArrayList<Entity>();
  Entity changedEntity = new Entity();
  changedEntity.addProperty(entity2.getProperty("PropertyString"));
  addedEntity.add(changedEntity);
  delta.getEntities().addAll(addedEntity);
   ser.entityCollection(metadata, edmEntitySet.getEntityType(), delta ,
      EntityCollectionSerializerOptions.with()
      .contextURL(ContextURL.with().entitySet(edmEntitySet).build())
      .build()).getContent();
    
   }
 
Example #15
Source File: ODataJsonSerializerv01Test.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void entityWrongData() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESAllPrim");
  Entity entity = data.readAll(edmEntitySet).getEntities().get(0);
  entity.getProperties().get(0).setValue(ValueType.PRIMITIVE, false);
  try {
    serializer.entity(metadata, edmEntitySet.getEntityType(), entity,
        EntitySerializerOptions.with()
            .contextURL(ContextURL.with().entitySet(edmEntitySet).suffix(Suffix.ENTITY).build())
            .build());
    Assert.fail("Expected exception not thrown!");
  } catch (final SerializerException e) {
    Assert.assertEquals(SerializerException.MessageKeys.WRONG_PROPERTY_VALUE, e.getMessageKey());
    final String message = e.getLocalizedMessage();
    Assert.assertThat(message, CoreMatchers.containsString("PropertyInt16"));
    Assert.assertThat(message, CoreMatchers.containsString("false"));
  }
}
 
Example #16
Source File: EdmAssistedJsonSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
protected void doSerialize(final EdmEntityType entityType, final AbstractEntityCollection entityCollection,
    final String contextURLString, final String metadataETag, JsonGenerator json)
    throws IOException, SerializerException {

  json.writeStartObject();

  metadata(contextURLString, metadataETag, null, null, entityCollection.getId(), false, json);

  if (entityCollection.getCount() != null) {
    if (isIEEE754Compatible) {
      json.writeStringField(Constants.JSON_COUNT, Integer.toString(entityCollection.getCount()));
    } else {
      json.writeNumberField(Constants.JSON_COUNT, entityCollection.getCount());
    }
  }
  if (entityCollection.getDeltaLink() != null) {
    json.writeStringField(Constants.JSON_DELTA_LINK, entityCollection.getDeltaLink().toASCIIString());
  }

  for (final Annotation annotation : entityCollection.getAnnotations()) {
    valuable(json, annotation, '@' + annotation.getTerm(), null, null);
  }

  json.writeArrayFieldStart(Constants.VALUE);
  for (final Entity entity : entityCollection) {
    doSerialize(entityType, entity, null, null, json);
  }
  json.writeEndArray();

  if (entityCollection.getNext() != null) {
    json.writeStringField(Constants.JSON_NEXT_LINK, entityCollection.getNext().toASCIIString());
  }

  json.writeEndObject();
}
 
Example #17
Source File: CarsProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void readPrimitiveValue(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType format)
        throws ODataApplicationException, SerializerException {
  // First we have to figure out which entity set the requested entity is in
  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo.asUriInfoResource());
  // Next we fetch the requested entity from the database
  final Entity entity;
  try {
    entity = readEntityInternal(uriInfo.asUriInfoResource(), edmEntitySet);
  } catch (DataProviderException e) {
    throw new ODataApplicationException(e.getMessage(), 500, Locale.ENGLISH);
  }
  if (entity == null) {
    // If no entity was found for the given key we throw an exception.
    throw new ODataApplicationException("No entity found for this key", HttpStatusCode.NOT_FOUND
            .getStatusCode(), Locale.ENGLISH);
  } else {
    // Next we get the property value from the entity and pass the value to serialization
    UriResourceProperty uriProperty = (UriResourceProperty) uriInfo
            .getUriResourceParts().get(uriInfo.getUriResourceParts().size() - 1);
    EdmProperty edmProperty = uriProperty.getProperty();
    Property property = entity.getProperty(edmProperty.getName());
    if (property == null) {
      throw new ODataApplicationException("No property found", HttpStatusCode.NOT_FOUND
              .getStatusCode(), Locale.ENGLISH);
    } else {
      if (property.getValue() == null) {
        response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
      } else {
        String value = String.valueOf(property.getValue());
        ByteArrayInputStream serializerContent = new ByteArrayInputStream(
                value.getBytes(Charset.forName("UTF-8")));
        response.setContent(serializerContent);
        response.setStatusCode(HttpStatusCode.OK.getStatusCode());
        response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.TEXT_PLAIN.toContentTypeString());
      }
    }
  }
}
 
Example #18
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void readFunctionImportCollection(final ODataRequest request, final ODataResponse response, 
    final UriInfo uriInfo, final ContentType responseFormat) throws ODataApplicationException, SerializerException {
  
  // 1st step: Analyze the URI and fetch the entity collection returned by the function import
  // Function Imports are always the first segment of the resource path
  final UriResource firstSegment = uriInfo.getUriResourceParts().get(0);
  
  if(!(firstSegment instanceof UriResourceFunction)) {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), 
        Locale.ENGLISH);
  }
  
  final UriResourceFunction uriResourceFunction = (UriResourceFunction) firstSegment;
  final EntityCollection entityCol = storage.readFunctionImportCollection(uriResourceFunction, serviceMetadata);
  
  // 2nd step: Serialize the response entity
  final EdmEntityType edmEntityType = (EdmEntityType) uriResourceFunction.getFunction().getReturnType().getType();
  final ContextURL contextURL = ContextURL.with().asCollection().type(edmEntityType).build();
  EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with().contextURL(contextURL).build();
  final ODataSerializer serializer = odata.createSerializer(responseFormat);
  final SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, entityCol, 
      opts); 

  // 3rd configure the response object
  response.setContent(serializerResult.getContent());
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #19
Source File: JsonDeltaSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void writeComplex(final ServiceMetadata metadata, final EdmComplexType type,
    final Property property, final Set<List<String>> selectedPaths, final JsonGenerator json)
    throws IOException, SerializerException {
  json.writeStartObject();
  String derivedName = property.getType();
  final EdmComplexType resolvedType = resolveComplexType(metadata, (EdmComplexType) type, derivedName);
  if (!isODataMetadataNone && !resolvedType.equals(type) || isODataMetadataFull) {
    json.writeStringField(Constants.JSON_TYPE, "#" + property.getType());
  }
  writeComplexValue(metadata, resolvedType, property.asComplex().getValue(), selectedPaths,
      json);
  json.writeEndObject();
}
 
Example #20
Source File: AsyncResponseSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public InputStream serialize(final ODataResponse response) throws SerializerException {
  try {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    appendStatusLine(response, buffer);
    appendResponseHeader(response, buffer);
    append(CRLF, buffer);
    appendBody(response, buffer);

    buffer.flush();
    return new ByteArrayInputStream(buffer.toByteArray(), 0, buffer.size());
  } catch (IOException e) {
    throw new SerializerException("Exception occurred during serialization of asynchronous response.",
        e, SerializerException.MessageKeys.IO_EXCEPTION);
  }
}
 
Example #21
Source File: EntityResponse.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void writeCreatedEntity(EdmEntitySet entitySet, Entity entity)
    throws SerializerException {
  // upsert/insert must created a entity, otherwise should have throw an
  // exception
  assert (entity != null);
  
  String locationHeader;
  try {
    locationHeader = buildLocation(this.baseURL, entity, entitySet.getName(), entitySet.getEntityType());
  } catch (EdmPrimitiveTypeException e) {
    throw new SerializerException(e.getMessage(), e, SerializerException.MessageKeys.WRONG_PRIMITIVE_VALUE);
  }

  // Note that if media written just like Stream, but on entity URL

  // 8.2.8.7
  if (this.returnRepresentation == ReturnRepresentation.MINIMAL) {
    writeNoContent(false);
    writeHeader(HttpHeader.LOCATION, locationHeader);
    writeHeader("Preference-Applied", "return=minimal"); //$NON-NLS-1$ //$NON-NLS-2$
    // 8.3.3
    writeHeader("OData-EntityId", entity.getId().toASCIIString()); //$NON-NLS-1$
    close();
    return;
  }

  // return the content of the created entity
  this.response.setContent(this.serializer.entity(this.metadata, entitySet.getEntityType(), entity, this.options)
      .getContent());
  writeCreated(false);
  writeHeader(HttpHeader.LOCATION, locationHeader);
  if (this.returnRepresentation != ReturnRepresentation.NONE) {
    writeHeader("Preference-Applied", "return=representation"); //$NON-NLS-1$ //$NON-NLS-2$
  }
  writeHeader(HttpHeader.CONTENT_TYPE, this.responseContentType.toContentTypeString());
  close();
}
 
Example #22
Source File: MetadataDocumentJsonSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void appendNotExpression(final JsonGenerator json, final EdmNot exp) 
    throws SerializerException, IOException {
  json.writeStartObject();
  appendExpression(json, exp.getLeftExpression(), DOLLAR + exp.getExpressionName());
  appendAnnotations(json, exp, null);
  json.writeEndObject();
}
 
Example #23
Source File: ODataXmlSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void writeComplex(final ServiceMetadata metadata,
    final EdmProperty edmProperty, final Property property,
    final Set<List<String>> selectedPaths,
    final String xml10InvalidCharReplacement, final XMLStreamWriter writer, 
    Set<List<String>> expandedPaths, Linked linked, ExpandOption expand) 
        throws XMLStreamException, SerializerException{
    
     writer.writeAttribute(METADATA, NS_METADATA, Constants.ATTR_TYPE,
            "#" + complexType(metadata, (EdmComplexType) edmProperty.getType(), 
                    property.getType()));
      String derivedName = property.getType();
     final EdmComplexType resolvedType = resolveComplexType(metadata,
      (EdmComplexType) edmProperty.getType(), derivedName);
     
     if (null != linked) {
       if (linked instanceof Entity) {
         linked = ((Entity)linked).getProperty(property.getName()).asComplex();
       } else if (linked instanceof ComplexValue) {
         List<Property> complexProperties = ((ComplexValue)linked).getValue();
         for (Property prop : complexProperties) {
           if (prop.getName().equals(property.getName())) {
             linked = prop.asComplex();
             break;
           }
         }
       }
       expandedPaths = expandedPaths == null || expandedPaths.isEmpty() ? null :
         ExpandSelectHelper.getReducedExpandItemsPaths(expandedPaths, property.getName());
     }
     
      writeComplexValue(metadata, resolvedType, property.asComplex().getValue(),
         selectedPaths, xml10InvalidCharReplacement, writer, expandedPaths, linked, expand, property.getName());
}
 
Example #24
Source File: ODataJsonSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
ContextURL checkContextURL(final ContextURL contextURL) throws SerializerException {
  if (isODataMetadataNone) {
    return null;
  } else if (contextURL == null) {
    throw new SerializerException("ContextURL null!", SerializerException.MessageKeys.NO_CONTEXT_URL);
  }
  return contextURL;
}
 
Example #25
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
												 ContentType requestFormat, ContentType responseFormat)
			throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity type from the URI 
	EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. create the data in backend 
	// 2.1. retrieve the payload from the POST request for the entity to create and deserialize it
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the creation in backend, which returns the newly created entity
	Entity createdEntity = storage.createEntityData(edmEntitySet, requestEntity);
	
	// 3. serialize the response (we have to return the created entity)
	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build(); 
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build(); // expand and select currently not supported 
	
	ODataSerializer serializer = odata.createSerializer(responseFormat);
	SerializerResult serializedResponse = serializer.entity(serviceMetadata, edmEntityType, createdEntity, options);
	
	//4. configure the response object
	response.setContent(serializedResponse.getContent());
	response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #26
Source File: MetadataDocumentJsonSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public MetadataDocumentJsonSerializer(final ServiceMetadata serviceMetadata) throws SerializerException {
  if (serviceMetadata == null || serviceMetadata.getEdm() == null) {
    throw new SerializerException("Service Metadata and EDM must not be null for a service.",
        SerializerException.MessageKeys.NULL_METADATA_OR_EDM);
  }
  this.serviceMetadata = serviceMetadata;
}
 
Example #27
Source File: JsonDeltaSerializerWithNavigations.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
protected void writeProperty(final ServiceMetadata metadata,
    final EdmProperty edmProperty, final Property property,
    final Set<List<String>> selectedPaths, final JsonGenerator json)
    throws IOException, SerializerException {
  boolean isStreamProperty = isStreamProperty(edmProperty);
  if (property != null) {
    if (!isStreamProperty) {
      json.writeFieldName(edmProperty.getName());
    }
    writePropertyValue(metadata, edmProperty, property, selectedPaths, json);
  }
}
 
Example #28
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
     throws ODataApplicationException, SerializerException {
	
	// 1. retrieve the Entity Type 
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	// Note: only in our example we can assume that the first segment is the EntitySet
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); 
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
	
	// 2. retrieve the data from backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	Entity entity = storage.readEntityData(edmEntitySet, keyPredicates);
	
	// 3. serialize
	EdmEntityType entityType = edmEntitySet.getEntityType();
	
	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).suffix(ContextURL.Suffix.ENTITY).build();
 	// expand and select currently not supported
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build();

	ODataSerializer serializer = this.odata.createSerializer(responseFormat);
	SerializerResult result = serializer.entity(serviceMetadata, entityType, entity, options);
	
	//4. configure the response object
	response.setContent(result.getContent());
	response.setStatusCode(HttpStatusCode.OK.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #29
Source File: ExpandSelectHelper.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public static Set<String> getExpandedPropertyNames(final List<ExpandItem> expandItems)
    throws SerializerException {
  Set<String> expanded = new HashSet<>();
  for (final ExpandItem item : expandItems) {
    final List<UriResource> resourceParts = item.getResourcePath().getUriResourceParts();
    final UriResource resource = resourceParts.get(0);
    if (resource instanceof UriResourceNavigation) {
      expanded.add(((UriResourceNavigation) resource).getProperty().getName());
    }
  }
  return expanded;
}
 
Example #30
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
												 ContentType requestFormat, ContentType responseFormat)
			throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity type from the URI 
	EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. create the data in backend 
	// 2.1. retrieve the payload from the POST request for the entity to create and deserialize it
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = this.odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the creation in backend, which returns the newly created entity
	Entity createdEntity = storage.createEntityData(edmEntitySet, requestEntity);
	
	// 3. serialize the response (we have to return the created entity)
	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build(); 
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build(); // expand and select currently not supported 
	
	ODataSerializer serializer = this.odata.createSerializer(responseFormat);
	SerializerResult serializedResponse = serializer.entity(serviceMetadata, edmEntityType, createdEntity, options);
	
	//4. configure the response object
	response.setContent(serializedResponse.getContent());
	response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}