Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright 2013 SAP AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. /
 
 package com.sap.core.odata.core.ep.consumer;
 
 import java.util.List;
 import java.util.Map;
 
 
Atom/XML format reader/consumer for entries. XmlEntryConsumer instance can be reused for several readEntry(javax.xml.stream.XMLStreamReader,com.sap.core.odata.core.ep.aggregator.EntityInfoAggregator,com.sap.core.odata.api.ep.EntityProviderReadProperties) calls but be aware that the instance and their readEntry* methods are NOT THREAD SAFE.

Author(s):
SAP AG
 
 public class XmlEntryConsumer {
 
   private Map<StringObjectproperties;
 
   public ODataEntry readEntry(final XMLStreamReader readerfinal EntityInfoAggregator eiafinal EntityProviderReadProperties readPropertiesthrows EntityProviderException {
     try {
       initialize(readProperties);
 
       while (reader.hasNext() && !isEntryEndTag(reader)) {
         reader.nextTag();
         if (reader.isStartElement()) {
           handleStartedTag(readereiareadProperties);
         }
       }
 
       if (!readProperties.getMergeSemantic()) {
       }
 
       return ;
     } catch (XMLStreamException e) {
     } catch (EdmException e) {
     }
   }
 
   private boolean isEntryEndTag(final XMLStreamReader reader) {
     return reader.isEndElement()
        && ..equals(reader.getNamespaceURI())
        && ..equals(reader.getLocalName());
  }

  
Initialize the XmlEntryConsumer to be ready for read of an entry.

Parameters:
readProperties
Throws:
com.sap.core.odata.api.ep.EntityProviderException
  private void initialize(final EntityProviderReadProperties readPropertiesthrows EntityProviderException {
     = new HashMap<StringObject>();
     = EntityTypeMapping.create(readProperties.getTypeMappings());
  }

  
Validates that all mandatory properties are found and set at the readEntryResult entity. If a mandatory property is missing an com.sap.core.odata.api.ep.EntityProviderException is thrown.

Parameters:
eia entity info which contains the information which properties are mandatory
entry entry for which the mandatory properties are validated
Throws:
com.sap.core.odata.api.ep.EntityProviderException if a mandatory property is missing
    propertyInfos.removeAll(eia.getKeyPropertyInfos());
    Map<StringObjectdata = entry.getProperties();
    for (EntityPropertyInfo entityPropertyInfo : propertyInfos) {
      boolean mandatory = entityPropertyInfo.isMandatory();
      if (mandatory && !data.containsKey(entityPropertyInfo.getName())) {
        throw new EntityProviderException(..addContent(entityPropertyInfo.getName()));
      }
    }
  }
  private void handleStartedTag(final XMLStreamReader readerfinal EntityInfoAggregator eiafinal EntityProviderReadProperties readProperties)
      readId(reader);
      readEntry(reader);
      readLink(readereiareadProperties);
      readContent(readereia);
      readProperties(readereia);
    } else if (!readProperties.getMergeSemantic()) {
    } else {
      skipStartedTag(reader);
    }
  }
  private void readCustomElement(final XMLStreamReader readerfinal String tagNamefinal EntityInfoAggregator eiathrows EdmExceptionEntityProviderExceptionXMLStreamException {
    EntityPropertyInfo targetPathInfo = eia.getTargetPathInfo(tagName);
    NamespaceContext nsctx = reader.getNamespaceContext();
    boolean skipTag = true;
      if (targetPathInfo != null) {
        final String customPrefix = targetPathInfo.getCustomMapping().getFcNsPrefix();
        final String customNamespaceURI = targetPathInfo.getCustomMapping().getFcNsUri();
        if (customPrefix != null && customNamespaceURI != null) {
          String xmlPrefix = nsctx.getPrefix(customNamespaceURI);
          String xmlNamespaceUri = reader.getNamespaceURI(customPrefix);
          if (customNamespaceURI.equals(xmlNamespaceUri) && customPrefix.equals(xmlPrefix)) {
            skipTag = false;
            reader.require(.customNamespaceURItagName);
            reader.next();
            reader.require(.nullnull);
            final String text = reader.getText();
            reader.nextTag();
            reader.require(.customNamespaceURItagName);
            final EntityPropertyInfo propertyInfo = getValidatedPropertyInfo(eiatagName);
            final Class<?> typeMapping = .getMappingClass(propertyInfo.getName());
            final EdmSimpleType type = (EdmSimpleTypepropertyInfo.getType();
            final Object value = type.valueOfString(text.propertyInfo.getFacets(),
                typeMapping == null ? type.getDefaultType() : typeMapping);
            .put(tagNamevalue);
          }
        }
      } else {
      }
    }
    if (skipTag) {
      skipStartedTag(reader);
    }
  }

  
Skip the tag to which the javax.xml.stream.XMLStreamReader currently points. Therefore it is read until an end element tag with current local name is found.

Parameters:
reader
Throws:
javax.xml.stream.XMLStreamException
  private void skipStartedTag(final XMLStreamReader readerthrows XMLStreamException {
    final String name = reader.getLocalName();
    int read = 1;
    while (read > 0 && reader.hasNext()) {
      reader.next();
      if (reader.hasName() && name.equals(reader.getLocalName())) {
        if (reader.isEndElement()) {
          read--;
        } else if (reader.isStartElement()) {
          read++;
        }
      }
    }
  }
  private void readEntry(final XMLStreamReader readerthrows EntityProviderExceptionXMLStreamException {
    .setEtag(etag);
  }
  private void extractNamespacesFromTag(final XMLStreamReader readerthrows EntityProviderException {
    // collect namespaces
    int namespaceCount = reader.getNamespaceCount();
    for (int i = 0; i < namespaceCounti++) {
      String namespacePrefix = reader.getNamespacePrefix(i);
      String namespaceUri = reader.getNamespaceURI(i);
      .put(namespacePrefixnamespaceUri);
    }
  }
    }
  }

  
  private void readLink(final XMLStreamReader readerfinal EntityInfoAggregator eiafinal EntityProviderReadProperties readPropertiesthrows EntityProviderExceptionXMLStreamExceptionEdmException {
    final String rel = reader.getAttributeValue(null.);
    final String uri = reader.getAttributeValue(null.);
    final String type = reader.getAttributeValue(null.);
    // read to next tag to check if <link> contains any further tags
    reader.nextTag();
    if (reader.isEndElement()) {
      if (rel == null || uri == null) {
            . + "' and/or '" + .).addContent(.));
      } else if (rel.startsWith(.)) {
        final String navigationPropertyName = rel.substring(..length());
        .putAssociationUri(navigationPropertyNameuri);
      } else if (rel.equals(.)) {
        .setEditLink(uri);
        .setEtag(etag);
      }
    } else {
      if (rel != null && rel.startsWith(.)) {
        readInlineContent(readereiareadPropertiestyperel);
      }
    }
  }

  
Inline content was found and javax.xml.stream.XMLStreamReader already points to <m:inline> tag.

Parameters:
reader
eia
readProperties
atomLinkType the atom type attribute value of the link tag
atomLinkRel the atom rel attribute value of the link tag
Throws:
javax.xml.stream.XMLStreamException
com.sap.core.odata.api.ep.EntityProviderException
com.sap.core.odata.api.edm.EdmException
  private void readInlineContent(final XMLStreamReader readerfinal EntityInfoAggregator eiafinal EntityProviderReadProperties readProperties,
      final String atomLinkTypefinal String atomLinkRel)
    //
    String navigationPropertyName = atomLinkRel.substring(..length());
    EdmNavigationProperty navigationProperty = (EdmNavigationPropertyeia.getEntityType().getProperty(navigationPropertyName);
    EdmEntitySet entitySet = eia.getEntitySet().getRelatedEntitySet(navigationProperty);
    EntityInfoAggregator inlineEia = EntityInfoAggregator.create(entitySet);
    final EntityProviderReadProperties inlineProperties = createInlineProperties(readPropertiesnavigationProperty);
    // validations
    boolean isFeed = isInlineFeedValidated(readereiaatomLinkTypenavigationPropertyName);
    List<ODataEntryinlineEntries = new ArrayList<ODataEntry>();
    while (!(reader.isEndElement() && ..equals(reader.getNamespaceURI()) && ..equals(reader.getLocalName()))) {
      if (reader.isStartElement() && ..equals(reader.getNamespaceURI()) && ..equals(reader.getLocalName())) {
        XmlEntryConsumer xec = new XmlEntryConsumer();
        ODataEntry inlineEntry = xec.readEntry(readerinlineEiainlineProperties);
        inlineEntries.add(inlineEntry);
      }
      // next tag
      reader.next();
    }
    updateExpandSelectTree(navigationPropertyNameinlineEntries);
    updateReadProperties(readPropertiesnavigationPropertyNamenavigationPropertyisFeedinlineEntries);
  }

  
Updates the read properties (properties) for this com.sap.core.odata.api.ep.callback.ReadEntryResult (readEntryResult).

Parameters:
readProperties
navigationPropertyName
navigationProperty
isFeed
inlineEntries
Throws:
com.sap.core.odata.api.ep.EntityProviderException
  private void updateReadProperties(final EntityProviderReadProperties readPropertiesfinal String navigationPropertyName,
      final EdmNavigationProperty navigationPropertyfinal boolean isFeedfinal List<ODataEntryinlineEntriesthrows EntityProviderException {
    Object entry = extractODataEntity(isFeedinlineEntries);
    OnReadInlineContent callback = readProperties.getCallback();
    if (callback == null) {
      .put(navigationPropertyNameentry);
    } else {
      doCallback(readPropertiesnavigationPropertycallbackisFeedentry);
    }
  }

  
Updates the expand select tree (expandSelectTree) for this com.sap.core.odata.api.ep.callback.ReadEntryResult (readEntryResult).

Parameters:
navigationPropertyName
inlineEntries
Throws:
com.sap.core.odata.api.ep.EntityProviderException
  private void updateExpandSelectTree(final String navigationPropertyNamefinal List<ODataEntryinlineEntriesthrows EntityProviderException {
    ExpandSelectTreeNodeImpl subNode = getExpandSelectTreeNode(inlineEntries);
    .putLink(navigationPropertyNamesubNode);
  }

  
Get the com.sap.core.odata.core.uri.ExpandSelectTreeNodeImpl from the inlineEntries or if none exists create a new com.sap.core.odata.core.uri.ExpandSelectTreeNodeImpl.

Parameters:
inlineEntries entries which are checked for existing com.sap.core.odata.core.uri.ExpandSelectTreeNodeImpl
Returns:
com.sap.core.odata.core.uri.ExpandSelectTreeNodeImpl from the inlineEntries or if none exists create a new com.sap.core.odata.core.uri.ExpandSelectTreeNodeImpl.
Throws:
com.sap.core.odata.api.ep.EntityProviderException if an unsupported com.sap.core.odata.api.uri.ExpandSelectTreeNode implementation was found.
    if (inlineEntries.isEmpty()) {
      return new ExpandSelectTreeNodeImpl();
    } else {
      ExpandSelectTreeNode inlinedEntryEstNode = inlineEntries.get(0).getExpandSelectTree();
      if (inlinedEntryEstNode instanceof ExpandSelectTreeNodeImpl) {
        return (ExpandSelectTreeNodeImplinlinedEntryEstNode;
      } else {
            .addContent("Unsupported implementation for " + ExpandSelectTreeNode.class + " found."));
      }
    }
  }

  
Get a list of com.sap.core.odata.api.ep.entry.ODataEntry, an empty list, a single com.sap.core.odata.api.ep.entry.ODataEntry or NULL based on isFeed value and inlineEntries content.

Parameters:
isFeed
inlineEntries
Returns:
  private Object extractODataEntity(final boolean isFeedfinal List<ODataEntryinlineEntries) {
    if (isFeed) {
      //TODO: fill metadata correctly
      return new ODataFeedImpl(inlineEntriesnew FeedMetadataImpl());
    } else if (!inlineEntries.isEmpty()) {
      return inlineEntries.get(0);
    }
    return null;
  }

  
Do the callback based on given parameters.

Parameters:
readProperties
navigationProperty
callback
isFeed
entry
Throws:
com.sap.core.odata.api.ep.EntityProviderException
  private void doCallback(final EntityProviderReadProperties readPropertiesfinal EdmNavigationProperty navigationProperty,
      final OnReadInlineContent callbackfinal boolean isFeedfinal Object contentthrows EntityProviderException {
    try {
      if (isFeed) {
        ReadFeedResult callbackInfo = new ReadFeedResult(readPropertiesnavigationProperty, (ODataFeedcontent);
        callback.handleReadFeed(callbackInfo);
      } else {
        ReadEntryResult callbackInfo = new ReadEntryResult(readPropertiesnavigationProperty, (ODataEntrycontent);
        callback.handleReadEntry(callbackInfo);
      }
    } catch (ODataApplicationException e) {
    }
  }

  
Create com.sap.core.odata.api.ep.EntityProviderReadProperties which can be used for reading of inline properties/entrys of navigation links within this current read entry.

Parameters:
readProperties
navigationProperty
Returns:
Throws:
com.sap.core.odata.api.ep.EntityProviderException
    final OnReadInlineContent callback = readProperties.getCallback();
    EntityProviderReadProperties currentReadProperties = EntityProviderReadProperties.initFrom(readProperties).addValidatedPrefixes().build();
    if (callback == null) {
      return currentReadProperties;
    } else {
      try {
        return callback.receiveReadProperties(currentReadPropertiesnavigationProperty);
      } catch (ODataApplicationException e) {
      }
    }
  }

  

Inline content was found and javax.xml.stream.XMLStreamReader already points to <m:inline> tag.
ATTENTION: If javax.xml.stream.XMLStreamReader does not point to the <m:inline> tag an exception is thrown.

Check whether it is an inline Feed or Entry and validate that...

For the case that one of above validations fail an com.sap.core.odata.api.ep.EntityProviderException is thrown. If validation was successful true is returned for Feed and false for Entry multiplicity.

Parameters:
reader xml content reader which already points to <m:inline> tag
eia all necessary information about the entity
type the atom type attribute value of the link tag
navigationPropertyName the navigation property name of the entity
Returns:
true for Feed and false for Entry
Throws:
com.sap.core.odata.api.ep.EntityProviderException is thrown if at least one validation fails.
com.sap.core.odata.api.edm.EdmException if edm access fails
  private boolean isInlineFeedValidated(final XMLStreamReader readerfinal EntityInfoAggregator eiafinal String typefinal String navigationPropertyNamethrows EntityProviderExceptionEdmException {
    boolean isFeed = false;
    try {
      //
      ContentType cType = ContentType.parse(type);
      if (cType == null) {
      }
      EdmNavigationProperty navigationProperty = (EdmNavigationPropertyeia.getEntityType().getProperty(navigationPropertyName);
      EdmMultiplicity navigationMultiplicity = navigationProperty.getMultiplicity();
      switch (navigationMultiplicity) {
      case :
        validateFeedTags(readercType);
        isFeed = true;
        break;
      case :
      case :
        validateEntryTags(readercType);
        break;
      }
    } catch (XMLStreamException e) {
    }
    return isFeed;
  }
  private void validateEntryTags(final XMLStreamReader readerfinal ContentType cTypethrows XMLStreamExceptionEntityProviderException {
      int next = reader.nextTag();
      if (. == next) {
      } else {
      }
    } else {
    }
  }
  private void validateFeedTags(final XMLStreamReader readerfinal ContentType cTypethrows XMLStreamExceptionEntityProviderException {
      int next = reader.nextTag();
      if (. == next) {
      } else {
      }
    } else {
    }
  }
  private void readContent(final XMLStreamReader readerfinal EntityInfoAggregator eiathrows EntityProviderExceptionXMLStreamExceptionEdmException {
    final String contentType = reader.getAttributeValue(null.);
    final String sourceLink = reader.getAttributeValue(null.);
    reader.nextTag();
    if (reader.isStartElement() && reader.getLocalName().equals(.)) {
      readProperties(readereia);
    } else if (reader.isEndElement()) {
    } else {
          .addContent("Expected closing 'content' or starting 'properties' but found '" + reader.getLocalName() + "'."));
    }
    .setContentType(contentType);
    .setSourceLink(sourceLink);
  }
  private void readId(final XMLStreamReader readerthrows EntityProviderExceptionXMLStreamException {
    reader.next();
    if (reader.isCharacters()) {
      .setId(reader.getText());
    }
    reader.nextTag();
  }
  private void readProperties(final XMLStreamReader readerfinal EntityInfoAggregator entitySetthrows XMLStreamExceptionEdmExceptionEntityProviderException {
    // validate namespace
    if (entitySet.getEntityType().hasStream()) {
      // external properties
    } else {
      // inline properties
    }
    EntityPropertyInfo property;
    String closeTag = null;
    boolean run = true;
    reader.next();
    while (run) {
      if (reader.isStartElement() && closeTag == null) {
        closeTag = reader.getLocalName();
        if (isEdmNamespaceProperty(reader)) {
          if (.containsKey(closeTag)) {
            throw new EntityProviderException(..addContent(closeTag));
          }
          property = getValidatedPropertyInfo(entitySetcloseTag);
          final Object value = xpc.readStartedElement(readerproperty);
          .put(closeTagvalue);
          closeTag = null;
        }
      } else if (reader.isEndElement()) {
        if (reader.getLocalName().equals(closeTag)) {
          closeTag = null;
        } else if (..equals(reader.getNamespaceURI()) && ..equals(reader.getLocalName())) {
          run = false;
        }
      }
      reader.next();
    }
  }

  
Check if the currentHandledStartTagName is the same as the expectedTagName. If tag name is not as expected or if currentHandledStartTagName is not set an com.sap.core.odata.api.ep.EntityProviderException is thrown.

Parameters:
expectedTagName expected name for currentHandledStartTagName
Throws:
com.sap.core.odata.api.ep.EntityProviderException if tag name is not as expected or if currentHandledStartTagName is NULL.
  private void checkCurrentHandledStartTag(final String expectedTagNamethrows EntityProviderException {
    if ( == null) {
      throw new EntityProviderException(..addContent("No current handled start tag name set."));
    } else if (!.equals(expectedTagName)) {
    }
  }

  
Checks if property of currently read tag in javax.xml.stream.XMLStreamReader is defined in edm properties namespace com.sap.core.odata.api.edm.Edm.NAMESPACE_D_2007_08. If no namespace uri definition is found for namespace prefix of property (tag) an exception is thrown.

Parameters:
reader javax.xml.stream.XMLStreamReader with position at to checked tag
Returns:
true if property is in edm properties namespace, otherwise false.
Throws:
com.sap.core.odata.api.ep.EntityProviderException If no namespace uri definition is found for namespace prefix of property (tag).
  private boolean isEdmNamespaceProperty(final XMLStreamReader readerthrows EntityProviderException {
    final String nsUri = reader.getNamespaceURI();
    if (nsUri == null) {
    } else {
      return ..equals(nsUri);
    }
  }

  
Get validated com.sap.core.odata.core.ep.aggregator.EntityPropertyInfo for property with given name. If validation fails an com.sap.core.odata.api.ep.EntityProviderException is thrown. Currently this is the case if no com.sap.core.odata.core.ep.aggregator.EntityPropertyInfo if found for given name.

Parameters:
entitySet
name
Returns:
valid com.sap.core.odata.core.ep.aggregator.EntityPropertyInfo (which is never NULL).
Throws:
com.sap.core.odata.api.ep.EntityProviderException
  private EntityPropertyInfo getValidatedPropertyInfo(final EntityInfoAggregator entitySetfinal String namethrows EntityProviderException {
    EntityPropertyInfo info = entitySet.getPropertyInfo(name);
    if (info == null) {
    }
    return info;
  }
New to GrepCode? Check out our FAQ X