Java Code Examples for org.apache.olingo.commons.api.edm.EdmEntityType#getKeyPredicateNames()

The following examples show how to use org.apache.olingo.commons.api.edm.EdmEntityType#getKeyPredicateNames() . 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: 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 2
Source File: JsonDeltaSerializerWithNavigations.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * Get the ascii representation of the entity id
 * or thrown an {@link SerializerException} if id is <code>null</code>.
 *
 * @param entity the entity
 * @return ascii representation of the entity id
 */
private String getEntityId(Entity entity, EdmEntityType entityType, String name) throws SerializerException {
  try {
    if (entity != null) {
      if (entity.getId() == null) {
        if (entityType == null || entityType.getKeyPredicateNames() == null
            || name == null) {
          throw new SerializerException("Entity id is null.", SerializerException.MessageKeys.MISSING_ID);
        } else {
          final UriHelper uriHelper = new UriHelperImpl();
          entity.setId(URI.create(name + '(' + uriHelper.buildKeyPredicate(entityType, entity) + ')'));
          return entity.getId().toASCIIString();
        }
      } else {
        return entity.getId().toASCIIString();
      }
    }
    return null;
  } catch (Exception e) {
    throw new SerializerException("Entity id is null.", SerializerException.MessageKeys.MISSING_ID);
  }
}
 
Example 3
Source File: JsonDeltaSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * Get the ascii representation of the entity id
 * or thrown an {@link SerializerException} if id is <code>null</code>.
 *
 * @param entity the entity
 * @return ascii representation of the entity id
 */
private String getEntityId(Entity entity, EdmEntityType entityType, String name) throws SerializerException {
  try {
    if (entity != null) {
      if (entity.getId() == null) {
        if (entityType == null || entityType.getKeyPredicateNames() == null
            || name == null) {
          throw new SerializerException("Entity id is null.", SerializerException.MessageKeys.MISSING_ID);
        } else {
          final UriHelper uriHelper = new UriHelperImpl();
          entity.setId(URI.create(name + '(' + uriHelper.buildKeyPredicate(entityType, entity) + ')'));
          return entity.getId().toASCIIString();
        }
      } else {
        return entity.getId().toASCIIString();
      }
    } 
    return null;
  } catch (Exception e) {
    throw new SerializerException("Entity id is null.", SerializerException.MessageKeys.MISSING_ID);
  }
}
 
Example 4
Source File: ODataAdapter.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private ODataEntry getKeyPredicatesFromEntity(EdmEntityType entityType, Entity entity)
        throws ODataApplicationException {
    ODataEntry keyPredicates = new ODataEntry();
    for (String key : entityType.getKeyPredicateNames()) {
        EdmProperty propertyType = (EdmProperty) entityType.getProperty(key);
        keyPredicates.addValue(key, readPrimitiveValueInString(propertyType, entity.getProperty(key).getValue()));
    }
    return keyPredicates;
}
 
Example 5
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void update(final String rawBaseUri, final EdmEntitySet edmEntitySet, Entity entity,
    final Entity changedEntity, final boolean patch, final boolean isInsert) throws DataProviderException {

  final EdmEntityType entityType = changedEntity.getType()!=null ?
      edm.getEntityType(new FullQualifiedName(changedEntity.getType())):edmEntitySet.getEntityType();
  final List<String> keyNames = entityType.getKeyPredicateNames();

  // Update Properties
  for (final String propertyName : entityType.getPropertyNames()) {
    if (!keyNames.contains(propertyName)) {
      updateProperty(entityType.getStructuralProperty(propertyName),
          entity.getProperty(propertyName),
          changedEntity.getProperty(propertyName),
          patch);
    }
  }

  // For insert operations collection navigation property bind operations and deep insert operations can be combined.
  // In this case, the bind operations MUST appear before the deep insert operations in the payload.
  // => Apply bindings first
  final boolean navigationBindingsAvailable = !changedEntity.getNavigationBindings().isEmpty();
  if (navigationBindingsAvailable) {
    applyNavigationBinding(rawBaseUri, edmEntitySet, entity, changedEntity.getNavigationBindings());
  }

  // Deep insert (only if not an update)
  if (isInsert) {
    handleDeepInsert(rawBaseUri, edmEntitySet, entity, changedEntity);
  } else {
    handleDeleteSingleNavigationProperties(edmEntitySet, entity, changedEntity);
  }

  // Update the ETag if present.
  updateETag(entity);
}
 
Example 6
Source File: ParserHelper.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private static List<UriParameter> compoundKey(UriTokenizer tokenizer, final EdmEntityType edmEntityType,
    final Edm edm, final EdmType referringType, final Map<String, AliasQueryOption> aliases)
    throws UriParserException, UriValidationException {

  List<UriParameter> parameters = new ArrayList<>();
  List<String> parameterNames = new ArrayList<>();

  // To validate that each key predicate is exactly specified once, we use a list to pick from.
  List<String> remainingKeyNames = new ArrayList<String>(edmEntityType.getKeyPredicateNames());

  // At least one key predicate is mandatory.  Try to fetch all.
  boolean hasComma = false;
  do {
    final String keyPredicateName = tokenizer.getText();
    if (parameterNames.contains(keyPredicateName)) {
      throw new UriValidationException("Duplicated key property " + keyPredicateName,
          UriValidationException.MessageKeys.DOUBLE_KEY_PROPERTY, keyPredicateName);
    }
    if (remainingKeyNames.isEmpty()) {
      throw new UriParserSemanticException("Too many key properties.",
          UriParserSemanticException.MessageKeys.WRONG_NUMBER_OF_KEY_PROPERTIES,
          Integer.toString(parameters.size()), Integer.toString(parameters.size() + 1));
    }
    if (!remainingKeyNames.remove(keyPredicateName)) {
      throw new UriValidationException("Unknown key property " + keyPredicateName,
          UriValidationException.MessageKeys.INVALID_KEY_PROPERTY, keyPredicateName);
    }
    parameters.add(keyValuePair(tokenizer, keyPredicateName, edmEntityType, edm, referringType, aliases));
    parameterNames.add(keyPredicateName);
    hasComma = tokenizer.next(TokenKind.COMMA);
    if (hasComma) {
      ParserHelper.requireNext(tokenizer, TokenKind.ODataIdentifier);
    }
  } while (hasComma);
  ParserHelper.requireNext(tokenizer, TokenKind.CLOSE);

  return parameters;
}
 
Example 7
Source File: UriHelperImpl.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public String buildKeyPredicate(final EdmEntityType edmEntityType, final Entity entity) throws SerializerException {
  StringBuilder result = new StringBuilder();
  final List<String> keyNames = edmEntityType.getKeyPredicateNames();
  boolean first = true;
  for (final String keyName : keyNames) {
    EdmKeyPropertyRef refType = edmEntityType.getKeyPropertyRef(keyName);
    if (first) {
      first = false;
    } else {
      result.append(',');
    }
    if (keyNames.size() > 1) {
      result.append(Encoder.encode(keyName)).append('=');
    }
    final EdmProperty edmProperty =  refType.getProperty();
    if (edmProperty == null) {
      throw new SerializerException("Property not found (possibly an alias): " + keyName,
          SerializerException.MessageKeys.MISSING_PROPERTY, keyName);
    }
    final EdmPrimitiveType type = (EdmPrimitiveType) edmProperty.getType();
    final Object propertyValue = findPropertyRefValue(entity, refType);
    try {
      final String value = type.toUriLiteral(
          type.valueToString(propertyValue,
              edmProperty.isNullable(), edmProperty.getMaxLength(),
              edmProperty.getPrecision(), edmProperty.getScale(), edmProperty.isUnicode()));
      result.append(Encoder.encode(value));
    } catch (final EdmPrimitiveTypeException e) {
      throw new SerializerException("Wrong key value!", e,
          SerializerException.MessageKeys.WRONG_PROPERTY_VALUE, edmProperty.getName(), 
          propertyValue != null ? propertyValue.toString(): null);
    }
  }
  return result.toString();
}
 
Example 8
Source File: ODataJsonSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
/**
 * Get the ascii representation of the entity id
 * or thrown an {@link SerializerException} if id is <code>null</code>.
 *
 * @param entity the entity
 * @param entityType 
 * @param name 
 * @return ascii representation of the entity id
 */
private String getEntityId(Entity entity, EdmEntityType entityType, String name) throws SerializerException {
  if(entity != null && entity.getId() == null) {
    if(entityType == null || entityType.getKeyPredicateNames() == null 
        || name == null) {
      throw new SerializerException("Entity id is null.", SerializerException.MessageKeys.MISSING_ID);
    }else{
      final UriHelper uriHelper = new UriHelperImpl(); 
      entity.setId(URI.create(name + '(' + uriHelper.buildKeyPredicate(entityType, entity) + ')'));
    }
  }
  return entity.getId().toASCIIString();
}
 
Example 9
Source File: ODataJsonSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private boolean areKeyPredicateNamesSelected(SelectOption select, EdmEntityType type) {
  if (select == null || ExpandSelectHelper.isAll(select)) {
    return true;
  }
  final Set<String> selected = ExpandSelectHelper.getSelectedPropertyNames(select.getSelectItems());
  for (String key : type.getKeyPredicateNames()) {
    if (!selected.contains(key)) {
      return false;
    }
  }
  return true;
}
 
Example 10
Source File: ODataXmlSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
/**
 * Get the ascii representation of the entity id
 * or thrown an {@link SerializerException} if id is <code>null</code>.
 *
 * @param entity the entity
 * @param entityType the entity Type
 * @param name the entity name
 * @return ascii representation of the entity id
 */
private String getEntityId(Entity entity, EdmEntityType entityType, String name) throws SerializerException {
  if(entity.getId() == null) {
    if((entity == null || entityType == null || entityType.getKeyPredicateNames() == null 
        || name == null)) {
      throw new SerializerException("Entity id is null.", SerializerException.MessageKeys.MISSING_ID);
    }else{
      final UriHelper uriHelper = new UriHelperImpl(); 
      entity.setId(URI.create(name + '(' + uriHelper.buildKeyPredicate(entityType, entity) + ')'));
    }
  }
  return entity.getId().toASCIIString();
}
 
Example 11
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private Map<String, Object> findFreeComposedKey(final List<Entity> entities, final EdmEntityType entityType)
    throws DataProviderException {
  // Weak key construction
  final HashMap<String, Object> keys = new HashMap<String, Object>();
  List<String> keyPredicateNames = entityType.getKeyPredicateNames();
  for (final String keyName : keyPredicateNames) {
    EdmType type = entityType.getProperty(keyName).getType();
    FullQualifiedName typeName = type.getFullQualifiedName();
    if (type instanceof EdmTypeDefinition) {
      typeName = ((EdmTypeDefinition) type).getUnderlyingType().getFullQualifiedName();
    }
    Object newValue;

    if (EdmPrimitiveTypeKind.Int16.getFullQualifiedName().equals(typeName)) {
      newValue = (short) KEY_INT_16.incrementAndGet();

      while (!isFree(newValue, keyName, entities)) {
        newValue = (short) KEY_INT_16.incrementAndGet();
      }
    } else if (EdmPrimitiveTypeKind.Int32.getFullQualifiedName().equals(typeName)) {
      newValue = KEY_INT_32.incrementAndGet();

      while (!isFree(newValue, keyName, entities)) {
        newValue = KEY_INT_32.incrementAndGet();
      }
    } else if (EdmPrimitiveTypeKind.Int64.getFullQualifiedName().equals(typeName)) {
      // Integer keys
      newValue = KEY_INT_64.incrementAndGet();

      while (!isFree(newValue, keyName, entities)) {
        newValue = KEY_INT_64.incrementAndGet();
      }
    } else if (EdmPrimitiveTypeKind.String.getFullQualifiedName().equals(typeName)) {
      // String keys
      newValue = String.valueOf(KEY_STRING.incrementAndGet());

      while (!isFree(newValue, keyName, entities)) {
        newValue = String.valueOf(KEY_STRING.incrementAndGet());
      }
    } else if (type instanceof EdmEnumType) {
      /* In case of an enum key we only support composite keys. This way we can 0 as a key */
      if (keyPredicateNames.size() <= 1) {
        throw new DataProviderException("Single Enum as key not supported", HttpStatusCode.NOT_IMPLEMENTED);
      }
      newValue = new Short((short) 1);
    } else {
      throw new DataProviderException("Key type not supported", HttpStatusCode.NOT_IMPLEMENTED);
    }

    keys.put(keyName, newValue);
  }

  return keys;
}
 
Example 12
Source File: EntityResponse.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public static String buildLocation(String baseURL, Entity entity, String enitySetName, EdmEntityType type) 
    throws EdmPrimitiveTypeException {
  StringBuilder location = new StringBuilder();

  location.append(baseURL).append("/").append(enitySetName);
  
  int i = 0;
  boolean usename = type.getKeyPredicateNames().size() > 1;
  location.append("(");
  for (String key : type.getKeyPredicateNames()) {
    if (i > 0) {
      location.append(",");
    }
    i++;
    if (usename) {
      location.append(key).append("=");
    }
    
    EdmProperty property = (EdmProperty)type.getProperty(key);
    String propertyType = entity.getProperty(key).getType();
    Object propertyValue = entity.getProperty(key).getValue();
    
    if (propertyValue == null) {
      throw new EdmPrimitiveTypeException("The key value for property "+key+" is invalid; Key value cannot be null");
    }
    
    if(propertyType.startsWith("Edm.")) {
      propertyType = propertyType.substring(4);
    }
    EdmPrimitiveTypeKind kind = EdmPrimitiveTypeKind.valueOf(propertyType);
    String value =  EdmPrimitiveTypeFactory.getInstance(kind).valueToString(
        propertyValue, property.isNullable(), property.getMaxLength(), property.getPrecision(), property.getScale(), 
        property.isUnicode());
    if (kind == EdmPrimitiveTypeKind.String) {
        value = EdmString.getInstance().toUriLiteral(Encoder.encode(value));
    }
    location.append(value);
  }
  location.append(")");
  return location.toString();
}