/*
  * Find the entity set name for this resource
  */
 public String getEntitySet(ResourceState state) {
   String entitySetName = null;
   String fqTargetEntityName =
       metadata.getModelName() + Metadata.MODEL_SUFFIX + "." + state.getEntityName();
   try {
     EdmEntityType targetEntityType =
         (EdmEntityType) getEdmDataService().findEdmEntityType(fqTargetEntityName);
     if (targetEntityType != null) {
       EdmEntitySet targetEntitySet = getEdmDataService().getEdmEntitySet(targetEntityType);
       if (targetEntitySet != null) entitySetName = targetEntitySet.getName();
     }
   } catch (NotFoundException e) {
   }
   if (entitySetName == null) {
     try {
       entitySetName = getEdmEntitySet(state.getEntityName()).getName();
     } catch (NotFoundException e) {
       logger.warn("Entity [" + fqTargetEntityName + "] is not an entity set.");
     }
     if (entitySetName == null) {
       entitySetName = state.getName();
     }
   }
   return entitySetName;
 }
Beispiel #2
0
  /**
   * Generate project artefacts from conceptual interaction and metadata models.
   *
   * @param metadata metadata model
   * @param interactionModel Conceptual interaction model
   * @param commands Commands
   * @param srcOutputPath Path to output directory
   * @param configOutputPath Path to configuration files directory
   * @param generateMockResponder Indicates whether to generate artifacts for a mock responder
   * @return true if successful, false otherwise
   */
  public boolean generateArtifacts(
      Metadata metadata,
      InteractionModel interactionModel,
      Commands commands,
      File srcOutputPath,
      File configOutputPath,
      boolean generateMockResponder) {
    // Create the entity model
    String modelName = metadata.getModelName();
    EntityModel entityModel = createEntityModelFromMetadata(modelName, metadata);

    // Add error entities
    for (IMState state : interactionModel.getErrorHandlerStates()) {
      EMEntity emEntity = new EMEntity(state.getName());
      EMProperty empErrorMvGroup = new EMProperty("ErrorsMvGroup");
      empErrorMvGroup.addVocabularyTerm(new EMTerm(TermIdField.TERM_NAME, "true"));
      empErrorMvGroup.addVocabularyTerm(new EMTerm(TermListType.TERM_NAME, "true"));
      empErrorMvGroup.addVocabularyTerm(new EMTerm(TermComplexType.TERM_NAME, "true"));
      emEntity.addProperty(empErrorMvGroup);
      EMProperty empCode = new EMProperty("Code");
      empCode.addVocabularyTerm(new EMTerm(TermComplexGroup.TERM_NAME, "ErrorsMvGroup"));
      emEntity.addProperty(empCode);
      EMProperty empInfo = new EMProperty("Info");
      empInfo.addVocabularyTerm(new EMTerm(TermComplexGroup.TERM_NAME, "ErrorsMvGroup"));
      emEntity.addProperty(empInfo);
      EMProperty empText = new EMProperty("Text");
      empText.addVocabularyTerm(new EMTerm(TermComplexGroup.TERM_NAME, "ErrorsMvGroup"));
      emEntity.addProperty(empText);
      EMProperty empType = new EMProperty("Type");
      empType.addVocabularyTerm(new EMTerm(TermComplexGroup.TERM_NAME, "ErrorsMvGroup"));
      emEntity.addProperty(empType);
      entityModel.addEntity(emEntity);
    }

    // Obtain resource information
    String namespace = modelName + Metadata.MODEL_SUFFIX;
    List<EntityInfo> entitiesInfo = new ArrayList<EntityInfo>();
    for (EntityMetadata entityMetadata : metadata.getEntitiesMetadata().values()) {
      EntityInfo entityInfo = createEntityInfoFromEntityMetadata(namespace, entityMetadata);
      addNavPropertiesToEntityInfo(entityInfo, interactionModel);
      entitiesInfo.add(entityInfo);
    }

    return generateArtifacts(
        entityModel,
        interactionModel,
        commands,
        entitiesInfo,
        srcOutputPath,
        configOutputPath,
        generateMockResponder);
  }
  protected void writeEntry(
      StreamWriter writer,
      String entityName,
      Entity entity,
      Collection<Link> entityLinks,
      Map<Transition, RESTResource> embeddedResources,
      String baseUri,
      String absoluteId,
      String updated) {
    assert (entityName != null);

    // entity name could be different between entity resource and underlying entity
    // e.g., for Errors entity, entity resource would have the request entity name
    String entityMetadataName = entity != null ? entity.getName() : entityName;

    EntityMetadata entityMetadata = metadata.getEntityMetadata(entityMetadataName);
    String modelName = metadata.getModelName();
    writer.writeId(absoluteId);
    OAtomEntity oae = getAtomInfo(entity);

    writer.writeTitle(oae.getAtomEntityTitle());
    String summary = oae.getAtomEntitySummary();
    if (!summary.isEmpty()) {
      writer.writeSummary(summary);
    }

    LocalDateTime updatedTime = oae.getAtomEntityUpdated();
    if (updatedTime != null) {
      updated = InternalUtil.toString(updatedTime.toDateTime(DateTimeZone.UTC));
    }

    writer.writeUpdated(updated);
    writer.writeAuthor(oae.getAtomEntityAuthor());

    if (entityLinks != null) {
      for (Link link : entityLinks) {
        String type =
            (link.getTransition().getTarget() instanceof CollectionResourceState)
                ? atom_feed_content_type
                : atom_entry_content_type;
        String href = link.getRelativeHref(baseUri);
        String rel = link.getRel();
        writer.startLink(href, rel);

        if ("self".equals(link.getRel())) {
          ResourceState target = link.getTransition().getTarget();
          writer.writeAttribute("profile", target.getRel());
        }

        if (!"self".equals(link.getRel()) && !"edit".equals(link.getRel())) {
          writer.writeAttribute("type", type);
        }
        writer.writeAttribute("title", link.getTitle());
        if (embeddedResources != null && embeddedResources.get(link.getTransition()) != null) {
          String embeddedAbsoluteId = link.getHref();
          writeLinkInline(
              writer,
              metadata,
              link,
              embeddedResources.get(link.getTransition()),
              link.getHref(),
              baseUri,
              embeddedAbsoluteId,
              updated);
        }
        String linkId = link.getLinkId();
        if (linkId != null && linkId.length() > 0) {
          writer.writeAttribute("id", linkId);
        }
        writer.endLink();
      }
    }

    writer.writeCategory(modelName + Metadata.MODEL_SUFFIX + "." + entityName, scheme);
    writer.flush();

    writer.startContent(MediaType.APPLICATION_XML);

    writer.startElement(new QName(m, "properties", "m"));
    if (entity != null) {
      writeProperties(writer, entityMetadata, entity.getProperties(), modelName);
    }
    writer.endElement();

    writer.endContent();
  }
  /**
   * Writes a Atom (OData) representation of {@link EntityResource} to the output stream.
   *
   * @precondition supplied {@link EntityResource} is non null
   * @precondition {@link EntityResource#getEntity()} returns a valid OEntity, this provider only
   *     supports serialising OEntities
   * @postcondition non null Atom (OData) XML document written to OutputStream
   * @invariant valid OutputStream
   */
  @SuppressWarnings("unchecked")
  @Override
  public void writeTo(
      RESTResource resource,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream)
      throws IOException, WebApplicationException {
    assert (resource != null);
    assert (uriInfo != null);
    // Set response headers
    if (httpHeaders != null) {
      httpHeaders.putSingle(
          HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML); // Workaround for
      // https://issues.apache.org/jira/browse/WINK-374
    }

    try {
      RESTResource restResource = processLinks((RESTResource) resource);
      Collection<Link> processedLinks = restResource.getLinks();
      if (ResourceTypeHelper.isType(type, genericType, EntityResource.class, OEntity.class)) {
        EntityResource<OEntity> entityResource = (EntityResource<OEntity>) resource;
        OEntity tempEntity = entityResource.getEntity();
        EdmEntitySet entitySet = getEdmEntitySet(entityResource.getEntityName());
        List<OLink> olinks = formOLinks(entityResource);
        // Write entry
        // create OEntity with our EdmEntitySet see issue
        // https://github.com/aphethean/IRIS/issues/20
        OEntity oentity =
            OEntities.create(
                entitySet, tempEntity.getEntityKey(), tempEntity.getProperties(), null);
        entryWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            Responses.entity(oentity),
            entitySet,
            olinks);
      } else if (ResourceTypeHelper.isType(type, genericType, EntityResource.class, Entity.class)) {
        EntityResource<Entity> entityResource = (EntityResource<Entity>) resource;
        // Write entry
        Entity entity = entityResource.getEntity();
        String entityName = entityResource.getEntityName();
        // Write Entity object with Abdera implementation
        entityEntryWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            entityName,
            entity,
            processedLinks,
            entityResource.getEmbedded());
      } else if (ResourceTypeHelper.isType(type, genericType, EntityResource.class)) {
        EntityResource<Object> entityResource = (EntityResource<Object>) resource;
        // Links and entity properties
        Object entity = entityResource.getEntity();
        String entityName = entityResource.getEntityName();
        EntityProperties props = new EntityProperties();
        if (entity != null) {
          Map<String, Object> objProps =
              (transformer != null ? transformer : new BeanTransformer()).transform(entity);
          if (objProps != null) {
            for (String propName : objProps.keySet()) {
              props.setProperty(new EntityProperty(propName, objProps.get(propName)));
            }
          }
        }
        entityEntryWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            entityName,
            new Entity(entityName, props),
            processedLinks,
            entityResource.getEmbedded());
      } else if (ResourceTypeHelper.isType(
          type, genericType, CollectionResource.class, OEntity.class)) {
        CollectionResource<OEntity> collectionResource = ((CollectionResource<OEntity>) resource);
        EdmEntitySet entitySet = getEdmEntitySet(collectionResource.getEntityName());
        List<EntityResource<OEntity>> collectionEntities =
            (List<EntityResource<OEntity>>) collectionResource.getEntities();
        List<OEntity> entities = new ArrayList<OEntity>();
        Map<OEntity, Collection<Link>> linkId = new HashMap<OEntity, Collection<Link>>();
        for (EntityResource<OEntity> collectionEntity : collectionEntities) {
          // create OEntity with our EdmEntitySet see issue
          // https://github.com/aphethean/IRIS/issues/20
          OEntity tempEntity = collectionEntity.getEntity();
          List<OLink> olinks = formOLinks(collectionEntity);
          Collection<Link> links = collectionEntity.getLinks();
          OEntity entity =
              OEntities.create(
                  entitySet,
                  null,
                  tempEntity.getEntityKey(),
                  tempEntity.getEntityTag(),
                  tempEntity.getProperties(),
                  olinks);
          entities.add(entity);
          linkId.put(entity, links);
        }
        // TODO implement collection properties and get transient values for inlinecount and
        // skiptoken
        Integer inlineCount = null;
        String skipToken = null;
        feedWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            processedLinks,
            Responses.entities(entities, entitySet, inlineCount, skipToken),
            metadata.getModelName(),
            linkId);
      } else if (ResourceTypeHelper.isType(
          type, genericType, CollectionResource.class, Entity.class)) {
        CollectionResource<Entity> collectionResource = ((CollectionResource<Entity>) resource);

        // TODO implement collection properties and get transient values for inlinecount and
        // skiptoken
        Integer inlineCount = null;
        String skipToken = null;
        // Write feed
        AtomEntityFeedFormatWriter entityFeedWriter =
            new AtomEntityFeedFormatWriter(serviceDocument, metadata);
        entityFeedWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            collectionResource,
            inlineCount,
            skipToken,
            metadata.getModelName());
      } else {
        logger.error(
            "Accepted object for writing in isWriteable, but type not supported in writeTo method");
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
      }
    } catch (ODataProducerException e) {
      logger.error("An error occurred while writing " + mediaType + " resource representation", e);
    }
  }