All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.joinedworkz.common.helper.OpenApiHelper Maven / Gradle / Ivy

There is a newer version: 1.3.46
Show newest version
package org.joinedworkz.common.helper;

import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.eclipse.xtext.xbase.lib.Extension;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.joinedworkz.common.adapter.ComponentResourcesAdapter;
import org.joinedworkz.common.adapter.MergedOperationInfoAdapterForOperation;
import org.joinedworkz.common.adapter.MergedOperationInfosAdapter;
import org.joinedworkz.common.adapter.ResourceProvideAdapter;
import org.joinedworkz.common.context.CommonGeneratorContext;
import org.joinedworkz.common.info.MergedResourceOperationInfo;
import org.joinedworkz.common.info.MergedResourceOperationPart;
import org.joinedworkz.common.info.ResourceOperationInfo;
import org.joinedworkz.common.info.ResponseInfo;
import org.joinedworkz.core.model.CmnComplexType;
import org.joinedworkz.core.model.CmnComponent;
import org.joinedworkz.core.model.CmnContent;
import org.joinedworkz.core.model.CmnElement;
import org.joinedworkz.core.model.CmnField;
import org.joinedworkz.core.model.CmnModel;
import org.joinedworkz.core.model.CmnNamedObject;
import org.joinedworkz.core.model.CmnObject;
import org.joinedworkz.core.model.CmnOperationParameter;
import org.joinedworkz.core.model.CmnProperty;
import org.joinedworkz.core.model.CmnProvidedResource;
import org.joinedworkz.core.model.CmnResource;
import org.joinedworkz.core.model.CmnResourceOperation;
import org.joinedworkz.core.model.CmnResponse;
import org.joinedworkz.core.model.CmnService;
import org.joinedworkz.core.model.CmnType;
import org.joinedworkz.core.model.Verb;

@Singleton
@SuppressWarnings("all")
public class OpenApiHelper {
  private static final char SLASH = '/';

  @Inject
  @Extension
  private NameHelper _nameHelper;

  @Inject
  @Extension
  private CmnModelHelper _cmnModelHelper;

  @Inject
  @Extension
  private VariableHelper _variableHelper;

  @Inject
  private Inflector inflector;

  public boolean isMultiple(final CmnContent content) {
    if ((content != null)) {
      Integer _maxOccurs = content.getMaxOccurs();
      boolean _tripleNotEquals = (_maxOccurs != null);
      if (_tripleNotEquals) {
        return (((content.getMaxOccurs()).intValue() < 0) || ((content.getMaxOccurs()).intValue() > 1));
      }
    }
    return false;
  }

  public String fullQualifiedTypeName(final CmnType type) {
    String _xblockexpression = null;
    {
      final String schemaName = this.schemaName(type);
      String _xifexpression = null;
      boolean _contains = schemaName.contains(".");
      if (_contains) {
        StringConcatenation _builder = new StringConcatenation();
        String _schemaName = this.schemaName(type);
        _builder.append(_schemaName);
        _xifexpression = _builder.toString();
      } else {
        StringConcatenation _builder_1 = new StringConcatenation();
        String _schemaNamespace = this.schemaNamespace(this._cmnModelHelper.getModel(type));
        _builder_1.append(_schemaNamespace);
        _builder_1.append(".");
        String _schemaName_1 = this.schemaName(type);
        _builder_1.append(_schemaName_1);
        _xifexpression = _builder_1.toString();
      }
      _xblockexpression = _xifexpression;
    }
    return _xblockexpression;
  }

  public String generateContentType(final CmnType defaultRepresentation, final CmnType representation, final String contentType, final boolean multiple, final boolean hasContext) {
    final Set contentTypes = this.generateContentTypes(defaultRepresentation, representation, contentType, multiple, hasContext, false);
    String _head = null;
    if (contentTypes!=null) {
      _head=IterableExtensions.head(contentTypes);
    }
    return _head;
  }

  public Set generateContentTypes(final CmnType defaultRepresentation, final CmnType representation, final String contentType, final boolean multiple, final boolean hasContext, final boolean additionallyWithDefault) {
    if ((representation instanceof CmnComplexType)) {
      if (((!hasContext) && Objects.equals(defaultRepresentation, representation))) {
        if (((contentType != null) && (!contentType.startsWith("*")))) {
          return Collections.unmodifiableSet(CollectionLiterals.newHashSet(contentType));
        } else {
          boolean _equals = Objects.equals(contentType, "**");
          if (_equals) {
            return Collections.unmodifiableSet(CollectionLiterals.newHashSet("text/plain"));
          } else {
            if (additionallyWithDefault) {
              final String contentTypeForRepresentation = this.vendorSpecificContentType(representation, multiple);
              if ((contentTypeForRepresentation != null)) {
                return Collections.unmodifiableSet(CollectionLiterals.newHashSet("application/json", contentTypeForRepresentation));
              }
            } else {
              return Collections.unmodifiableSet(CollectionLiterals.newHashSet("application/json"));
            }
          }
        }
      } else {
        if ((representation != null)) {
          final String contentTypeForRepresentation_1 = this.vendorSpecificContentType(representation, multiple);
          if ((contentTypeForRepresentation_1 != null)) {
            return Collections.unmodifiableSet(CollectionLiterals.newHashSet(contentTypeForRepresentation_1));
          }
        }
      }
    }
    if ((contentType != null)) {
      boolean _startsWith = contentType.startsWith("*");
      boolean _not = (!_startsWith);
      if (_not) {
        return Collections.unmodifiableSet(CollectionLiterals.newHashSet(contentType));
      } else {
        return null;
      }
    } else {
      return Collections.unmodifiableSet(CollectionLiterals.newHashSet("text/plain"));
    }
  }

  public CmnType responseContentTypeFor(final MergedResourceOperationPart operationPart, final CmnType representedEntity) {
    CmnContent _produces = operationPart.getProduces();
    CmnType _type = null;
    if (_produces!=null) {
      _type=_produces.getType();
    }
    boolean _tripleNotEquals = (_type != null);
    if (_tripleNotEquals) {
      CmnContent _produces_1 = operationPart.getProduces();
      CmnType _type_1 = null;
      if (_produces_1!=null) {
        _type_1=_produces_1.getType();
      }
      return _type_1;
    }
    return null;
  }

  public ResponseInfo createResponseInfo(final CmnResponse response, final CmnResourceOperation operation) {
    final ResponseInfo responseInfo = new ResponseInfo(operation, response);
    responseInfo.setResponseContext(this.getResponseContext(operation));
    responseInfo.setResponseWrapper(operation.getString("responseWrapper"));
    return responseInfo;
  }

  public CmnComplexType getResponseContext(final CmnResourceOperation operation) {
    final CmnProperty fieldFilters = operation.getProperty("responseContext");
    if ((fieldFilters != null)) {
      final Object value = fieldFilters.getValue();
      if ((value instanceof CmnComplexType)) {
        return ((CmnComplexType)value);
      }
    }
    return null;
  }

  public String simpleRepresentationTypeName(final CmnType type, final boolean returnsMultiple) {
    if ((type instanceof CmnComplexType)) {
      String _xifexpression = null;
      if (returnsMultiple) {
        _xifexpression = this.inflector.pluralize(this.schemaName(type));
      } else {
        _xifexpression = this.schemaName(type);
      }
      return _xifexpression;
    }
    return null;
  }

  public String schemaNamespace(final CmnModel model) {
    final String schemaName = model.getString("schemaNamespace");
    if ((schemaName != null)) {
      return schemaName;
    } else {
      return model.getNamespace();
    }
  }

  public String vendorSpecificContentType(final CmnType representation, final boolean multiple) {
    final String representationSchemaName = this.simpleRepresentationTypeName(representation, multiple);
    if ((representationSchemaName != null)) {
      final CmnModel resourceModel = this._cmnModelHelper.getModel(representation);
      return this.vendorSpecificContentType(this.schemaNamespace(resourceModel), representationSchemaName);
    }
    return null;
  }

  public String vendorSpecificContentType(final String namespace, final String typeName) {
    int lastDotIndex = typeName.lastIndexOf(".");
    if ((lastDotIndex >= 0)) {
      String namespacePart = typeName.substring(0, lastDotIndex);
      String namePart = typeName.substring((lastDotIndex + 1));
      String _lowerCase = this._nameHelper.camelCaseToDashSeperated(namePart).toLowerCase();
      String _plus = ((("application/vnd." + namespacePart) + ".") + _lowerCase);
      return (_plus + "+json");
    } else {
      String _lowerCase_1 = this._nameHelper.camelCaseToDashSeperated(typeName).toLowerCase();
      String _plus_1 = ((("application/vnd." + namespace) + ".") + _lowerCase_1);
      return (_plus_1 + "+json");
    }
  }

  public void createProvidedResourceAdapters(final Iterable components) {
    for (final CmnComponent component : components) {
      this.createProvidedResourceAdaptersForComponent(component);
    }
  }

  public Set createProvidedResourceAdaptersForComponent(final CmnComponent component) {
    ComponentResourcesAdapter componentResourcesAdapter = component.getAdapter(ComponentResourcesAdapter.class);
    final LinkedHashSet resourcesForApi = CollectionLiterals.newLinkedHashSet();
    Iterable _filter = Iterables.filter(component.getFeatures(), CmnProvidedResource.class);
    for (final CmnProvidedResource providedResource : _filter) {
      {
        final CmnResource headResource = IterableExtensions.head(providedResource.getResourcePath());
        final CmnResource lastResource = IterableExtensions.last(providedResource.getResourcePath());
        ResourceProvideAdapter resourceProvidedAdapter = lastResource.getAdapter(ResourceProvideAdapter.class);
        if ((resourceProvidedAdapter == null)) {
          ResourceProvideAdapter _resourceProvideAdapter = new ResourceProvideAdapter();
          resourceProvidedAdapter = _resourceProvideAdapter;
          lastResource.putAdapter(resourceProvidedAdapter);
        }
        resourceProvidedAdapter.putProvidedResource(component, providedResource);
        resourcesForApi.add(headResource);
      }
    }
    if ((componentResourcesAdapter == null)) {
      ComponentResourcesAdapter _componentResourcesAdapter = new ComponentResourcesAdapter();
      componentResourcesAdapter = _componentResourcesAdapter;
      component.putAdapter(componentResourcesAdapter);
    }
    componentResourcesAdapter.setResourcesForApi(resourcesForApi);
    return componentResourcesAdapter.getResourcesForApi();
  }

  public Map> createMergedResourceOperationInfos(final CmnComponent component, final CmnResource it, final CommonGeneratorContext ctx) {
    return this.createMergedResourceOperationInfos(component, it, true, ctx);
  }

  public String determineControllerTag(final CmnProvidedResource it) {
    final String controllerName = this.composeControllerName(it);
    if ((controllerName != null)) {
      final int lastDotIndex = controllerName.lastIndexOf(".");
      if ((lastDotIndex >= 0)) {
        final String shortName = controllerName.substring((lastDotIndex + 1));
        return this._nameHelper.camelCaseToDashSeperated(shortName);
      } else {
        return this._nameHelper.camelCaseToDashSeperated(controllerName);
      }
    }
    return null;
  }

  public String composeControllerName(final CmnProvidedResource providedResource) {
    String controllerName = this.getQualifiedControllerNameFromProperty(providedResource);
    if ((controllerName == null)) {
      final CmnResource lastResourceInPath = IterableExtensions.last(providedResource.getResourcePath());
      final String singularResourceName = this.inflector.singularize(lastResourceInPath.getName());
      String _firstUpper = this._nameHelper.toFirstUpper(this._nameHelper.dashSeperatedToCamelCase(singularResourceName));
      String _plus = (_firstUpper + "Controller");
      controllerName = _plus;
    }
    return controllerName;
  }

  public String getQualifiedControllerNameFromProperty(final CmnElement it) {
    final CmnProperty controller = it.getProperty("controller");
    if (((controller != null) && (controller.getValue() != null))) {
      final Object controllerValue = controller.getValue();
      if ((controllerValue instanceof CmnService)) {
        return this._cmnModelHelper.qualifiedName(((CmnNamedObject)controllerValue));
      } else {
        return controllerValue.toString();
      }
    }
    return null;
  }

  public CmnType determineRepresentation(final CmnResourceOperation it) {
    final CmnProperty representationProperty = it.getProperty("representation");
    Object _value = null;
    if (representationProperty!=null) {
      _value=representationProperty.getValue();
    }
    if ((_value instanceof CmnType)) {
      Object _value_1 = representationProperty.getValue();
      return ((CmnType) _value_1);
    }
    CmnObject _container = it.getContainer();
    if ((_container instanceof CmnResource)) {
      CmnObject _container_1 = it.getContainer();
      final CmnResource resource = ((CmnResource) _container_1);
      return this.determineRepresentation(resource);
    }
    return null;
  }

  public CmnType determineRepresentation(final CmnResource it) {
    CmnType _xifexpression = null;
    CmnType _representation = it.getRepresentation();
    boolean _tripleNotEquals = (_representation != null);
    if (_tripleNotEquals) {
      return it.getRepresentation();
    } else {
      CmnResource _parentResource = this.parentResource(it);
      CmnType _determineRepresentation = null;
      if (_parentResource!=null) {
        _determineRepresentation=this.determineRepresentation(_parentResource);
      }
      _xifexpression = _determineRepresentation;
    }
    return _xifexpression;
  }

  public CmnResource getContainingResource(final CmnObject it) {
    Object _xblockexpression = null;
    {
      final CmnResource containingResource = this.parentResource(it);
      Object _xifexpression = null;
      if ((containingResource == null)) {
        throw new RuntimeException("No parent found for resource: ");
      }
      _xblockexpression = _xifexpression;
    }
    return ((CmnResource)_xblockexpression);
  }

  public CmnResource parentResource(final CmnObject it) {
    CmnResource _xifexpression = null;
    CmnObject _container = it.getContainer();
    if ((_container instanceof CmnResource)) {
      CmnObject _container_1 = it.getContainer();
      return ((CmnResource) _container_1);
    } else {
      CmnResource _xifexpression_1 = null;
      CmnObject _container_2 = it.getContainer();
      boolean _tripleNotEquals = (_container_2 != null);
      if (_tripleNotEquals) {
        _xifexpression_1 = this.parentResource(it.getContainer());
      }
      _xifexpression = _xifexpression_1;
    }
    return _xifexpression;
  }

  public CmnProvidedResource getProvidedResource(final CmnResource it, final CmnComponent component) {
    if ((it != null)) {
      final ResourceProvideAdapter resourceProvideAdapter = it.getAdapter(ResourceProvideAdapter.class);
      if ((resourceProvideAdapter != null)) {
        return resourceProvideAdapter.getProvidedResource(component);
      }
    }
    return null;
  }

  public Map> createMergedResourceOperationInfos(final CmnComponent component, final CmnResource it, final boolean recursive, final CommonGeneratorContext ctx) {
    try {
      final Map> collectedOperationInfos = CollectionLiterals.>newLinkedHashMap();
      this.collectOperationInfos(collectedOperationInfos, "", "", CollectionLiterals.newArrayList(), component, it, null, recursive);
      return this.mergeOperations(collectedOperationInfos, ctx);
    } catch (final Throwable _t) {
      if (_t instanceof Exception) {
        final Exception ex = (Exception)_t;
        String _name = component.getName();
        String _plus = ("Failed to create merged operation infos for component: " + _name);
        throw new RuntimeException(_plus, ex);
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  }

  public List resourceAndSubResources(final CmnResource it) {
    final ArrayList resources = CollectionLiterals.newArrayList();
    this.addResourcesRecursive(resources, it);
    return resources;
  }

  public void addResourcesRecursive(final List resources, final CmnResource it) {
    resources.add(it);
    List _subResources = it.getSubResources();
    boolean _tripleNotEquals = (_subResources != null);
    if (_tripleNotEquals) {
      List _subResources_1 = it.getSubResources();
      for (final CmnResource subResource : _subResources_1) {
        this.addResourcesRecursive(resources, subResource);
      }
    }
  }

  public void collectOperationInfos(final Map> operationInfos, final String parentPath, final String idPrefix, final List parentPathParameters, final CmnComponent component, final CmnResource resource, final CmnProvidedResource providedResourceOfParent, final boolean recursive) {
    final CharSequence pathParameters = this.formattedPathParameters(resource);
    final CmnProvidedResource providedSubResource = this.getProvidedResource(resource, component);
    CmnProvidedResource _xifexpression = null;
    if ((providedSubResource != null)) {
      _xifexpression = providedSubResource;
    } else {
      _xifexpression = providedResourceOfParent;
    }
    final CmnProvidedResource providedResource = _xifexpression;
    List _operations = resource.getOperations();
    Iterable _filter = null;
    if (_operations!=null) {
      final Function1 _function = (CmnResourceOperation it) -> {
        Boolean _instanceOperation = it.getInstanceOperation();
        return Boolean.valueOf((!(_instanceOperation).booleanValue()));
      };
      _filter=IterableExtensions.filter(_operations, _function);
    }
    final List collectionOperations = this.iterableToList(_filter);
    this.addOperations(operationInfos, resource, providedResource, collectionOperations, parentPath, idPrefix, pathParameters, parentPathParameters);
    if (recursive) {
      List _subResources = resource.getSubResources();
      Iterable _filter_1 = null;
      if (_subResources!=null) {
        final Function1 _function_1 = (CmnResource it) -> {
          return Boolean.valueOf(((it.getInstanceResource() == null) || (!(it.getInstanceResource()).booleanValue())));
        };
        _filter_1=IterableExtensions.filter(_subResources, _function_1);
      }
      final List collectionSubResources = this.iterableToList(_filter_1);
      if ((collectionSubResources != null)) {
        final Consumer _function_2 = (CmnResource it) -> {
          final String subIdPrefix = this.composeSubIdPrefix(resource, idPrefix, false);
          String _name = resource.getName();
          final boolean forInstanceOperation = (_name == null);
          final CharSequence relativePath = this.composeRelativePath(resource, pathParameters, forInstanceOperation);
          this.collectOperationInfos(operationInfos, this.mergePaths(parentPath, relativePath), subIdPrefix, parentPathParameters, component, it, providedResource, recursive);
        };
        collectionSubResources.forEach(_function_2);
      }
    }
    List _operations_1 = resource.getOperations();
    Iterable _filter_2 = null;
    if (_operations_1!=null) {
      final Function1 _function_3 = (CmnResourceOperation it) -> {
        return it.getInstanceOperation();
      };
      _filter_2=IterableExtensions.filter(_operations_1, _function_3);
    }
    final List instanceOperations = this.iterableToList(_filter_2);
    this.addOperations(operationInfos, resource, providedResource, instanceOperations, parentPath, idPrefix, pathParameters, parentPathParameters);
    if (recursive) {
      List _subResources_1 = resource.getSubResources();
      Iterable _filter_3 = null;
      if (_subResources_1!=null) {
        final Function1 _function_4 = (CmnResource it) -> {
          return Boolean.valueOf(((it.getInstanceResource() != null) && (it.getInstanceResource()).booleanValue()));
        };
        _filter_3=IterableExtensions.filter(_subResources_1, _function_4);
      }
      final List instanceSubResources = this.iterableToList(_filter_3);
      boolean _isEmpty = instanceSubResources.isEmpty();
      boolean _not = (!_isEmpty);
      if (_not) {
        final List currentPathParameters = CollectionLiterals.newArrayList();
        currentPathParameters.addAll(parentPathParameters);
        List _identifiers = resource.getIdentifiers();
        boolean _tripleNotEquals = (_identifiers != null);
        if (_tripleNotEquals) {
          currentPathParameters.addAll(resource.getIdentifiers());
        }
        final Consumer _function_5 = (CmnResource it) -> {
          final String subIdPrefix = this.composeSubIdPrefix(resource, idPrefix, true);
          final CharSequence relativePath = this.composeRelativePath(resource, pathParameters, true);
          this.collectOperationInfos(operationInfos, this.mergePaths(parentPath, relativePath), subIdPrefix, currentPathParameters, component, it, providedResource, recursive);
        };
        instanceSubResources.forEach(_function_5);
      }
    }
  }

  public String subPathForPath(final String rootPath, final String path) {
    if ((path != null)) {
      final String rootPathWithLeadingSlash = ("/" + rootPath);
      String subPathWithLeadingSlash = path;
      boolean _startsWith = path.startsWith(rootPathWithLeadingSlash);
      if (_startsWith) {
        subPathWithLeadingSlash = path.substring(rootPathWithLeadingSlash.length());
      }
      String remainingSubPath = subPathWithLeadingSlash;
      boolean _startsWith_1 = subPathWithLeadingSlash.startsWith("/");
      if (_startsWith_1) {
        remainingSubPath = subPathWithLeadingSlash.substring(1);
      }
      boolean _isEmpty = remainingSubPath.isEmpty();
      boolean _not = (!_isEmpty);
      if (_not) {
        return remainingSubPath;
      }
    }
    return null;
  }

  public String schemaName(final CmnType type) {
    final String schemaName = type.getString("schemaName");
    if ((schemaName != null)) {
      return schemaName;
    } else {
      return type.getName();
    }
  }

  public CharSequence formattedPathParameters(final CmnResource it) {
    CharSequence _xifexpression = null;
    if (((it.getIdentifiers() != null) && (!it.getIdentifiers().isEmpty()))) {
      StringConcatenation _builder = new StringConcatenation();
      {
        List _identifiers = it.getIdentifiers();
        for(final CmnOperationParameter identifier : _identifiers) {
          _builder.append("/{");
          String _identifierName = this.identifierName(identifier);
          _builder.append(_identifierName);
          _builder.append("}");
        }
      }
      _xifexpression = _builder;
    } else {
      return "";
    }
    return _xifexpression;
  }

  public String identifierName(final CmnOperationParameter it) {
    String _name = it.getName();
    boolean _tripleNotEquals = (_name != null);
    if (_tripleNotEquals) {
      return it.getName();
    } else {
      CmnField _referencedField = it.getReferencedField();
      boolean _tripleNotEquals_1 = (_referencedField != null);
      if (_tripleNotEquals_1) {
        return it.getReferencedField().getName();
      }
    }
    return null;
  }

  public void addOperations(final Map> operationInfos, final CmnResource resource, final CmnProvidedResource providedResource, final List operations, final String parentPath, final String idPrefix, final CharSequence formattedPathParameters, final List parentPathParameters) {
    for (final CmnResourceOperation operation : operations) {
      {
        final ResourceOperationInfo operationInfo = this.createOperationInfo(parentPath, idPrefix, resource, providedResource, formattedPathParameters, parentPathParameters, operation);
        List operationInfoList = operationInfos.get(operationInfo.getPath());
        if ((operationInfoList == null)) {
          operationInfoList = CollectionLiterals.newArrayList();
          operationInfos.put(operationInfo.getPath(), operationInfoList);
        }
        operationInfoList.add(operationInfo);
      }
    }
  }

  public CharSequence generateOperationId(final MergedResourceOperationInfo it) {
    CharSequence _xblockexpression = null;
    {
      final String operationId = this.determineOperationId(it);
      StringConcatenation _builder = new StringConcatenation();
      _builder.append("operationId: ");
      _builder.append(operationId);
      _xblockexpression = _builder;
    }
    return _xblockexpression;
  }

  public CmnType determineRepresentedEntity(final MergedResourceOperationInfo mergedOperationInfo) {
    final CmnResourceOperation operation = IterableExtensions.head(mergedOperationInfo.getOperations());
    return this.determineRepresentation(operation);
  }

  public CmnProperty getOperationProperty(final MergedResourceOperationInfo mergedOperationInfo, final String propertyName) {
    final CmnResourceOperation operation = IterableExtensions.head(mergedOperationInfo.getOperations());
    return operation.getProperty(propertyName);
  }

  public String determineOperationName(final MergedResourceOperationInfo it, final MergedResourceOperationPart operationPart) {
    final String explicitName = operationPart.getOperation().getName();
    if ((explicitName != null)) {
      return explicitName;
    }
    CmnProperty _property = operationPart.getOperation().getProperty("operationName");
    Object _value = null;
    if (_property!=null) {
      _value=_property.getValue();
    }
    String _string = null;
    if (_value!=null) {
      _string=_value.toString();
    }
    final String operationNameProperty = _string;
    if ((operationNameProperty != null)) {
      int _indexOf = operationNameProperty.indexOf("$");
      boolean _greaterThan = (_indexOf > (-1));
      if (_greaterThan) {
        final UnaryOperator variables = new UnaryOperator() {
          @Override
          public String apply(final String variableName) {
            final boolean plural = variableName.endsWith("[]");
            String _xifexpression = null;
            if (plural) {
              int _length = variableName.length();
              int _minus = (_length - 2);
              _xifexpression = variableName.substring(0, _minus);
            } else {
              _xifexpression = variableName;
            }
            final String postProcessedVariableName = _xifexpression;
            if (postProcessedVariableName != null) {
              switch (postProcessedVariableName) {
                case "entity":
                  final String typeName = OpenApiHelper.this.determineRepresentedEntity(it).getName();
                  if (plural) {
                    return OpenApiHelper.this.inflector.pluralize(typeName);
                  } else {
                    return typeName;
                  }
                case "resource":
                  String _name = it.getResource().getName();
                  String _firstUpper = null;
                  if (_name!=null) {
                    _firstUpper=OpenApiHelper.this._nameHelper.toFirstUpper(_name);
                  }
                  return _firstUpper;
                case "consumes":
                  CmnContent _consumes = operationPart.getConsumes();
                  CmnType _type = null;
                  if (_consumes!=null) {
                    _type=_consumes.getType();
                  }
                  String _name_1 = null;
                  if (_type!=null) {
                    _name_1=_type.getName();
                  }
                  final String typeName_1 = _name_1;
                  if (plural) {
                    return OpenApiHelper.this.inflector.pluralize(typeName_1);
                  } else {
                    return typeName_1;
                  }
                case "produces":
                  CmnContent _produces = operationPart.getProduces();
                  CmnType _type_1 = null;
                  if (_produces!=null) {
                    _type_1=_produces.getType();
                  }
                  String _name_2 = null;
                  if (_type_1!=null) {
                    _name_2=_type_1.getName();
                  }
                  final String typeName_2 = _name_2;
                  if (plural) {
                    return OpenApiHelper.this.inflector.pluralize(typeName_2);
                  } else {
                    return typeName_2;
                  }
              }
            }
            return null;
          }
        };
        return this._variableHelper.replaceVariables(operationNameProperty, variables);
      } else {
        return operationNameProperty;
      }
    }
    final String operationId = this.determineIndividualOperationId(it, operationPart);
    if ((operationId != null)) {
      return this._cmnModelHelper.lastSegment(operationId);
    }
    return "do";
  }

  public String determineOperationId(final MergedResourceOperationInfo it) {
    return this.determineIndividualOperationId(it, null);
  }

  public String determineIndividualOperationId(final MergedResourceOperationInfo it, final MergedResourceOperationPart operationPart) {
    final boolean takeRepresentationName = (this.isCollectionResource(it.getResource()) && (!it.returnsMultiple()));
    final CmnProperty operationIdProperty = it.getProperty("operationId");
    CmnResourceOperation _xifexpression = null;
    if ((operationPart != null)) {
      _xifexpression = operationPart.getOperation();
    } else {
      Set _operations = it.getOperations();
      CmnResourceOperation _head = null;
      if (_operations!=null) {
        _head=IterableExtensions.head(_operations);
      }
      _xifexpression = _head;
    }
    final CmnResourceOperation operation = _xifexpression;
    final String operationName = operation.getName();
    CmnContent _xifexpression_1 = null;
    if (((operationPart != null) && (operationPart.getConsumes() != null))) {
      _xifexpression_1 = operationPart.getConsumes();
    } else {
      _xifexpression_1 = IterableExtensions.head(it.getConsumes());
    }
    final CmnContent consumes = _xifexpression_1;
    String _xifexpression_2 = null;
    if ((operationPart != null)) {
      _xifexpression_2 = operation.getOperationType();
    } else {
      _xifexpression_2 = it.getOperationType();
    }
    final String operationType = _xifexpression_2;
    if ((operationIdProperty != null)) {
      String operationId = operationIdProperty.getValue().toString();
      int _indexOf = operationId.indexOf("$");
      boolean _greaterThan = (_indexOf > (-1));
      if (_greaterThan) {
        final UnaryOperator variables = new UnaryOperator() {
          @Override
          public String apply(final String variableName) {
            if (variableName != null) {
              switch (variableName) {
                case "entity":
                  return OpenApiHelper.this.determineRepresentedEntity(it).getName();
                case "resource":
                  String _name = it.getResource().getName();
                  String _firstUpper = null;
                  if (_name!=null) {
                    _firstUpper=OpenApiHelper.this._nameHelper.toFirstUpper(_name);
                  }
                  return _firstUpper;
                case "consumes":
                  if (((consumes != null) && (consumes.getType() != null))) {
                    return consumes.getType().getName();
                  } else {
                    final CmnProperty producesProperty = operation.getProperty("produces");
                    if ((producesProperty != null)) {
                      Object _value = producesProperty.getValue();
                      return ((String) _value);
                    }
                  }
                  break;
                case "produces":
                  if (((operation != null) && (operation.getResponses() != null))) {
                    List _responses = operation.getResponses();
                    CmnResponse _head = null;
                    if (_responses!=null) {
                      _head=IterableExtensions.head(_responses);
                    }
                    CmnContent _content = null;
                    if (_head!=null) {
                      _content=_head.getContent();
                    }
                    final CmnContent content = _content;
                    if (((content != null) && (content.getType() != null))) {
                      return content.getType().getName();
                    }
                  }
                  break;
              }
            }
            return null;
          }
        };
        operationId = this._variableHelper.replaceVariables(operationId, variables);
      }
      return operationId;
    }
    if ((operationName != null)) {
      return operationName;
    }
    String _xifexpression_3 = null;
    String _name = it.getResource().getName();
    boolean _tripleNotEquals = (_name != null);
    if (_tripleNotEquals) {
      _xifexpression_3 = it.getResource().getName();
    } else {
      String _firstUpper = this._nameHelper.toFirstUpper(this.composeResourceName(it.getResource()));
      _xifexpression_3 = ("By" + _firstUpper);
    }
    final String resourceName = _xifexpression_3;
    String _xifexpression_4 = null;
    if (takeRepresentationName) {
      _xifexpression_4 = it.getResource().getRepresentation().getName();
    } else {
      _xifexpression_4 = resourceName;
    }
    final String namePostFix = _xifexpression_4;
    String _charSeperatedToCamelCase = this._nameHelper.charSeperatedToCamelCase(this._nameHelper.toFirstUpper(namePostFix), '-', true);
    final String name = (operationType + _charSeperatedToCamelCase);
    String _xifexpression_5 = null;
    if (((it.getIdPrefix() != null) && (it.getIdPrefix().length() > 0))) {
      String _idPrefix = it.getIdPrefix();
      String _plus = (_idPrefix + ".");
      _xifexpression_5 = (_plus + name);
    } else {
      _xifexpression_5 = name;
    }
    return _xifexpression_5;
  }

  /**
   * just for debugging
   */
  public String stringRepresentation(final MergedResourceOperationInfo it) {
    final String operationId = this.determineOperationId(it);
    String _path = it.getPath();
    String _plus = (_path + " ");
    Verb _verb = it.getVerb();
    String _plus_1 = (_plus + _verb);
    String _plus_2 = (_plus_1 + " (");
    String _plus_3 = (_plus_2 + operationId);
    return (_plus_3 + ")");
  }

  public boolean isCollectionResource(final CmnResource it) {
    return (((it != null) && (it.getMaxOccurs() != null)) && ((it.getMaxOccurs()).intValue() != 1));
  }

  public String composeSubIdPrefix(final CmnResource resource, final String parentIdPrefix, final boolean instanceOperation) {
    String _xblockexpression = null;
    {
      String _xifexpression = null;
      if ((instanceOperation && this.isCollectionResource(resource))) {
        _xifexpression = resource.getRepresentation().getName();
      } else {
        _xifexpression = this.composeResourceName(resource);
      }
      final String name = _xifexpression;
      String _xifexpression_1 = null;
      if (((parentIdPrefix != null) && (parentIdPrefix.length() > 0))) {
        _xifexpression_1 = ((parentIdPrefix + ".") + name);
      } else {
        _xifexpression_1 = name;
      }
      _xblockexpression = _xifexpression_1;
    }
    return _xblockexpression;
  }

  public String composeResourceName(final CmnResource resource) {
    String _name = resource.getName();
    boolean _tripleNotEquals = (_name != null);
    if (_tripleNotEquals) {
      return resource.getName();
    } else {
      List _identifiers = resource.getIdentifiers();
      boolean _tripleNotEquals_1 = (_identifiers != null);
      if (_tripleNotEquals_1) {
        final StringBuilder buffer = new StringBuilder();
        boolean first = true;
        List _identifiers_1 = resource.getIdentifiers();
        for (final CmnOperationParameter identifier : _identifiers_1) {
          {
            if (first) {
              first = false;
            } else {
              buffer.append("-");
            }
            buffer.append(identifier.getName());
          }
        }
        return buffer.toString();
      }
    }
    return null;
  }

  public Map> mergeOperations(final Map> map, final CommonGeneratorContext ctx) {
    final Map> mergedInfos = CollectionLiterals.>newLinkedHashMap();
    if ((map != null)) {
      Set>> _entrySet = map.entrySet();
      for (final Map.Entry> entry : _entrySet) {
        {
          final String path = entry.getKey();
          final Map mergedInfosForVerb = CollectionLiterals.newLinkedHashMap();
          List _value = entry.getValue();
          for (final ResourceOperationInfo info : _value) {
            {
              MergedResourceOperationInfo mergedInfo = mergedInfosForVerb.get(info.getVerb());
              if ((mergedInfo == null)) {
                MergedResourceOperationInfo _mergedResourceOperationInfo = new MergedResourceOperationInfo(info);
                mergedInfo = _mergedResourceOperationInfo;
                mergedInfo.addParentPathParameters(info.getParentParameters());
                mergedInfosForVerb.put(info.getVerb(), mergedInfo);
              }
              List _consumes = info.getOperation().getConsumes();
              boolean _tripleNotEquals = (_consumes != null);
              if (_tripleNotEquals) {
                mergedInfo.getConsumes().addAll(info.getOperation().getConsumes());
              }
              mergedInfo.addOperation(info.getOperation());
              boolean _hasAdapter = info.getOperation().hasAdapter(MergedOperationInfoAdapterForOperation.class);
              boolean _not = (!_hasAdapter);
              if (_not) {
                MergedOperationInfoAdapterForOperation _mergedOperationInfoAdapterForOperation = new MergedOperationInfoAdapterForOperation(mergedInfo);
                info.getOperation().putAdapter(_mergedOperationInfoAdapterForOperation);
              }
            }
          }
          final List mergedOperationInfoList = IterableExtensions.toList(mergedInfosForVerb.values());
          for (final MergedResourceOperationInfo mergedOperationInfo : mergedOperationInfoList) {
            {
              mergedOperationInfo.getOperationParts().addAll(this.createMergedResourceOperationParts(mergedOperationInfo));
              mergedOperationInfo.setup();
            }
          }
          mergedInfos.put(path, mergedOperationInfoList);
          for (final MergedResourceOperationInfo mergedOperationInfo_1 : mergedOperationInfoList) {
            {
              final CmnResource resource = mergedOperationInfo_1.getResource();
              MergedOperationInfosAdapter adapter = resource.getAdapter(MergedOperationInfosAdapter.class);
              if ((adapter == null)) {
                MergedOperationInfosAdapter _mergedOperationInfosAdapter = new MergedOperationInfosAdapter();
                adapter = _mergedOperationInfosAdapter;
                resource.putAdapter(adapter);
                ctx.addObjectWithAdatper(resource);
              }
              adapter.getOperationInfos().add(mergedOperationInfo_1);
            }
          }
        }
      }
    }
    return mergedInfos;
  }

  public List createMergedResourceOperationParts(final MergedResourceOperationInfo mergedResourceOperationInfo) {
    if (((mergedResourceOperationInfo.getOperations() != null) && (!mergedResourceOperationInfo.getOperations().isEmpty()))) {
      final ArrayList operationParts = new ArrayList();
      Set _operations = mergedResourceOperationInfo.getOperations();
      for (final CmnResourceOperation operation : _operations) {
        {
          final boolean hasConsumes = ((operation.getConsumes() != null) && (!operation.getConsumes().isEmpty()));
          final boolean hasResponses = ((operation.getResponses() != null) && (!operation.getResponses().isEmpty()));
          Iterable _xifexpression = null;
          if (hasResponses) {
            final Function1 _function = (CmnResponse it) -> {
              return Boolean.valueOf((((it.getStatusCode()).intValue() < 300) && (it.getContent() != null)));
            };
            final Function1 _function_1 = (CmnResponse it) -> {
              return it.getContent();
            };
            _xifexpression = IterableExtensions.map(IterableExtensions.filter(operation.getResponses(), _function), _function_1);
          } else {
            _xifexpression = CollectionLiterals.emptyList();
          }
          final Iterable producesOfOperation = _xifexpression;
          boolean _isEmpty = IterableExtensions.isEmpty(producesOfOperation);
          final boolean hasProduces = (!_isEmpty);
          if (hasConsumes) {
            List _consumes = operation.getConsumes();
            for (final CmnContent consumes : _consumes) {
              if (hasProduces) {
                for (final CmnContent produces : producesOfOperation) {
                  boolean _isDerivedFromRepresentation = produces.isDerivedFromRepresentation();
                  boolean _not = (!_isDerivedFromRepresentation);
                  if (_not) {
                    final MergedResourceOperationPart part = this.createMergedResourceOperationPart(operation, consumes, produces);
                    operationParts.add(part);
                  } else {
                    if (((!consumes.isDerivedFromRepresentation()) || (consumes.getType() == produces.getType()))) {
                      final MergedResourceOperationPart part_1 = this.createMergedResourceOperationPart(operation, consumes, produces);
                      operationParts.add(part_1);
                    }
                  }
                }
              } else {
                final MergedResourceOperationPart part_2 = this.createMergedResourceOperationPart(operation, consumes, null);
                operationParts.add(part_2);
              }
            }
          } else {
            if (hasProduces) {
              for (final CmnContent produces_1 : producesOfOperation) {
                {
                  final MergedResourceOperationPart part_3 = this.createMergedResourceOperationPart(operation, null, produces_1);
                  operationParts.add(part_3);
                }
              }
            } else {
              final MergedResourceOperationPart part_3 = this.createMergedResourceOperationPart(operation, null, null);
              operationParts.add(part_3);
            }
          }
        }
      }
      return operationParts;
    }
    return CollectionLiterals.emptyList();
  }

  public MergedResourceOperationPart createMergedResourceOperationPart(final CmnResourceOperation operation, final CmnContent consumes, final CmnContent produces) {
    return new MergedResourceOperationPart(operation, consumes, produces);
  }

  public void MergedOperationInfoAdapterForOperation(final MergedResourceOperationInfo info) {
    throw new UnsupportedOperationException("TODO: auto-generated method stub");
  }

  public List getMergedOperationInfos(final CmnResource resource) {
    final MergedOperationInfosAdapter adapter = resource.getAdapter(MergedOperationInfosAdapter.class);
    List _xifexpression = null;
    if ((adapter != null)) {
      _xifexpression = adapter.getOperationInfos();
    } else {
      _xifexpression = CollectionLiterals.emptyList();
    }
    return _xifexpression;
  }

  public ResourceOperationInfo createOperationInfo(final String parentPath, final String idPrefix, final CmnResource resource, final CmnProvidedResource providedResource, final CharSequence pathParameters, final List parentPathParameters, final CmnResourceOperation operation) {
    final ResourceOperationInfo operationInfo = new ResourceOperationInfo(parentPath, operation, idPrefix);
    boolean _or = false;
    Boolean _instanceOperation = null;
    if (operation!=null) {
      _instanceOperation=operation.getInstanceOperation();
    }
    if ((_instanceOperation).booleanValue()) {
      _or = true;
    } else {
      String _name = resource.getName();
      boolean _tripleEquals = (_name == null);
      _or = _tripleEquals;
    }
    final boolean forInstanceOperation = _or;
    final CharSequence relativePath = this.composeRelativePath(resource, pathParameters, forInstanceOperation);
    operationInfo.setPath(this.mergePaths(parentPath, relativePath));
    String _path = operationInfo.getPath();
    boolean _tripleEquals_1 = (_path == null);
    if (_tripleEquals_1) {
      throw new RuntimeException("OperationInfo path is null");
    }
    operationInfo.setResource(resource);
    operationInfo.setProvidedResource(providedResource);
    operationInfo.addParentPathParameters(parentPathParameters);
    return operationInfo;
  }

  public CharSequence composeRelativePath(final CmnResource it, final CharSequence pathParameters, final boolean forInstanceOperation) {
    final String resourcePath = this.pathSegment(it);
    if ((resourcePath == null)) {
      CharSequence _xifexpression = null;
      if (forInstanceOperation) {
        _xifexpression = pathParameters;
      } else {
        _xifexpression = "";
      }
      return _xifexpression;
    } else {
      String _xifexpression_1 = null;
      if (forInstanceOperation) {
        _xifexpression_1 = (resourcePath + pathParameters);
      } else {
        _xifexpression_1 = resourcePath;
      }
      return _xifexpression_1;
    }
  }

  public String mergePaths(final CharSequence parentPath, final CharSequence subPath) {
    if (((subPath != null) && (subPath.length() > 0))) {
      char _charAt = subPath.charAt(0);
      boolean _tripleEquals = (_charAt == OpenApiHelper.SLASH);
      if (_tripleEquals) {
        String _string = subPath.toString();
        return (parentPath + _string);
      } else {
        String _plus = (parentPath + "/");
        return (_plus + subPath);
      }
    } else {
      return parentPath.toString();
    }
  }

  public String pathSegment(final CmnResource it) {
    return it.getName();
  }

  public  List iterableToList(final Iterable it) {
    List _xifexpression = null;
    if ((it != null)) {
      _xifexpression = IterableExtensions.toList(it);
    } else {
      _xifexpression = CollectionLiterals.emptyList();
    }
    return _xifexpression;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy