public Entity addEntity(Entity entity) throws ApplicationException {
    if (entity == null) {
      return null;
    }

    if (entity.getEntityVersionId() != null) {
      throw new ApplicationException(
          "This entity definition already exists so it can only be updated.");
    }

    validateNameUniqueness(entity);
    try {
      entity.setUserCreatedBy(Context.getUserContext().getUser());
      Date dateCreated = new Date();
      entity.setDateCreated(dateCreated);
      for (EntityAttribute attribute : entity.getAttributes()) {
        attribute.setDateCreated(dateCreated);
        attribute.setUserCreatedBy(Context.getUserContext().getUser());
        attribute.setEntity(entity);
      }
      entityDefinitionDao.addEntity(entity);
      addToCache(entity);
      Context.notifyObserver(ObservationEventType.ENTITY_ADD_EVENT, entity);
      return entity;
    } catch (DaoException e) {
      throw new ApplicationException(e.getMessage());
    }
  }
 public void updateCustomField(CustomField field) throws ApplicationException {
   if (field == null
       || ConvertUtil.isNullOrEmpty(field.getEntityName())
       || ConvertUtil.isNullOrEmpty(field.getFieldName())
       || ConvertUtil.isNullOrEmpty(field.getSourceFieldName())) {
     log.info("The custom field to be updated is invalid: " + field);
     throw new ApplicationException(
         "Unable to update custom field with an invalid custom field definition.");
   }
   Entity entity = findLatestEntityVersionByName(field.getEntityName());
   EntityAttribute attrib = null;
   for (EntityAttribute item : entity.getAttributes()) {
     if (item.getName().equalsIgnoreCase(field.getFieldName()) && item.getDateVoided() == null) {
       attrib = item;
     }
   }
   if (attrib == null) {
     log.info("The user attempted to update a field that does not exist.");
     throw new ApplicationException("Unable to update an unknown custom field definition.");
   }
   attrib.setFunctionParameters(serializeParameters(field.getConfigurationParameters()));
   attrib.setDateChanged(new Date());
   attrib.setSourceName(field.getSourceFieldName());
   attrib.setTransformationFunction(field.getTransformationFunctionName());
   attrib.setUserChangedBy(Context.getUserContext().getUser());
   try {
     entityDefinitionDao.updateEntity(entity);
     // Generate a notification event to inform interested listeners via the lightweight mechanism
     // that this event has occurred.
     Context.notifyObserver(ObservationEventType.CUSTOM_FIELD_UPDATE_EVENT, field);
   } catch (DaoException e) {
     log.error("Failed while updating a custom field: " + e, e);
     throw new ApplicationException("Failed while updating the custom field: " + e.getMessage());
   }
 }
  /** Will export the entity passed in as the entity version id into a string. */
  public String exportEntity(Integer entityVersionId) throws ApplicationException {
    if (entityVersionId == null) {
      return "";
    }

    Entity entity = entityDefinitionDao.loadEntity(entityVersionId);

    try {
      // 1. convert Entity to EntityModel
      EntityModel entityModel = ConvertUtil.mapToEntityModel(entity, EntityModel.class);

      // 2. set group info to EntityModel
      List<EntityAttributeGroup> groups = loadEntityAttributeGroups(entity);
      entityModel = ConvertUtil.setGroupInfoToEntityModel(groups, entityModel);

      // 3. set validation info to entity attribute
      for (EntityAttribute attribute : entity.getAttributes()) {
        List<EntityAttributeValidation> validations = loadEntityAttributeValidations(attribute);

        ValidationsType validationsType = ConvertUtil.mapToEntityValidations(validations);

        // set validations info to attributeType
        AttributesType attributesType = entityModel.getAttributes();
        if (attributesType != null) {
          for (AttributeType attributeType : attributesType.getAttribute()) {
            String name = attributeType.getName();

            if (attribute.getName().equals(name)) {
              attributeType.setValidations(validationsType);
            }
          }
        }
      }

      // export to xml format
      JAXBContext jaxbContext = JAXBContext.newInstance(EntityModel.class);
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

      OutputStream outputStream = new ByteArrayOutputStream();
      jaxbMarshaller.marshal(entityModel, outputStream);

      return outputStream.toString();
    } catch (JAXBException e) {
      log.warn("Unable to serialize a Entity into a string: " + e, e);
      throw new RuntimeException(e);
    }
  }
 public void deleteEntity(Entity entity) throws ApplicationException {
   if (entity == null) {
     return;
   }
   if (entity.getEntityVersionId() == null) {
     throw new ApplicationException(
         "An entity definition must first be created before it is deleted.");
   }
   try {
     Date dateVoided = new Date();
     entity.setDateVoided(dateVoided);
     entity.setUserVoidedBy(Context.getUserContext().getUser());
     for (EntityAttribute attribute : entity.getAttributes()) {
       attribute.setDateVoided(dateVoided);
       attribute.setUserVoidedBy(Context.getUserContext().getUser());
       attribute.setEntity(entity);
     }
     entityDefinitionDao.updateEntity(entity);
     addToCache(entity);
   } catch (DaoException e) {
     throw new ApplicationException(e.getMessage());
   }
 }
 private CustomField buildCustomFieldFromAttribute(EntityAttribute attrib) {
   CustomField field = new CustomField();
   field.setEntityName(attrib.getEntity().getName());
   field.setFieldName(attrib.getName());
   field.setSourceFieldName(attrib.getSourceName());
   field.setTransformationFunctionName(attrib.getTransformationFunction());
   if (attrib.getFunctionParameters() != null) {
     field.setConfigurationParameters(deserializeParameters(attrib.getFunctionParameters()));
   }
   return field;
 }
  public Entity updateEntity(Entity entity) throws ApplicationException {
    if (entity == null) {
      return entity;
    }
    if (entity.getEntityVersionId() == null) {
      throw new ApplicationException(
          "An entity definition must first be created before it is updated.");
    }
    try {
      Date currentDate = new Date();
      entity.setDateChanged(currentDate);
      entity.setUserChangedBy(Context.getUserContext().getUser());
      for (EntityAttribute attrib : entity.getAttributes()) {
        if (attrib.getDateCreated() == null) {
          attrib.setDateCreated(currentDate);
          attrib.setUserCreatedBy(Context.getUserContext().getUser());
          // attrib.setEntity(entity);
        }
        attrib.setEntity(entity);
      }

      // Mark deletion attributes
      handleAttributeUpdates(entity);

      // remove validations for marked attribute
      for (EntityAttribute attrib : entity.getAttributes()) {
        if (attrib.getUserVoidedBy() != null) {

          // remove validations
          List<EntityAttributeValidation> existingValidations =
              loadEntityAttributeValidations(attrib);
          for (EntityAttributeValidation validation : existingValidations) {
            deleteEntityAttributeValidation(validation);
          }
        }
      }

      Entity updatedEntity = entityDefinitionDao.updateEntity(entity);
      updatedEntity = entityDefinitionDao.loadEntity(entity.getEntityVersionId());

      addToCache(updatedEntity);
      Context.notifyObserver(ObservationEventType.ENTITY_ATTRIBUTE_UPDATE_EVENT, entity);

      return updatedEntity;
    } catch (DaoException e) {
      throw new ApplicationException(e.getMessage());
    }
  }
  private void handleAttributeUpdates(Entity entity) {
    Entity existing = entityDefinitionDao.loadEntity(entity.getEntityVersionId());

    Map<Integer, EntityAttribute> newAttribById = new HashMap<Integer, EntityAttribute>();
    for (EntityAttribute attribute : entity.getAttributes()) {
      newAttribById.put(attribute.getEntityAttributeId(), attribute);
    }
    // Mark for deletion attributes that were removed
    for (EntityAttribute attrib : existing.getAttributes()) {
      if (newAttribById.get(attrib.getEntityAttributeId()) == null) {
        attrib.setDateVoided(entity.getDateChanged());
        attrib.setUserVoidedBy(Context.getUserContext().getUser());
        entity.addAttribute(attrib);
      }
    }
  }
 private EntityAttribute buildAttributeFromCustomField(Entity entity, CustomField field) {
   EntityAttribute attrib = new EntityAttribute();
   EntityAttributeDatatype type = getDatatypeByCode(EntityAttributeDatatype.STRING_DATATYPE_CD);
   attrib.setDatatype(type);
   attrib.setDateCreated(new Date());
   attrib.setDescription(field.getFieldName());
   attrib.setDisplayName(field.getFieldName());
   attrib.setDisplayOrder(1000);
   attrib.setEntity(entity);
   attrib.setFunctionParameters(serializeParameters(field.getConfigurationParameters()));
   attrib.setIndexed(false);
   attrib.setSearchable(false);
   attrib.setCaseInsensitive(false);
   attrib.setIsCustom(true);
   attrib.setName(field.getFieldName());
   attrib.setSourceName(field.getSourceFieldName());
   attrib.setTransformationFunction(field.getTransformationFunctionName());
   attrib.setUserCreatedBy(Context.getUserContext().getUser());
   return attrib;
 }