com.reprezen.genflow.rapidml.jaxrs.XGenerateJaxRsResource Maven / Gradle / Ivy
The newest version!
/**
* Copyright © 2013, 2016 Modelsolv, Inc.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains the property
* of ModelSolv, Inc. See the file license.html in the root directory of
* this project for further information.
*/
package com.reprezen.genflow.rapidml.jaxrs;
import com.google.common.base.Objects;
import com.google.common.collect.Collections2;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Table;
import com.reprezen.genflow.api.trace.GenTemplateTrace;
import com.reprezen.genflow.api.trace.GenTemplateTraceItem;
import com.reprezen.genflow.api.trace.GenTemplateTraceSourceItem;
import com.reprezen.genflow.api.trace.GenTemplateTraceUtils;
import com.reprezen.genflow.api.zenmodel.ZenModelLocator;
import com.reprezen.genflow.rapidml.jaxrs.JavaXtendTemplate;
import com.reprezen.genflow.rapidml.jaxrs.JaxRsGenTemplate;
import com.reprezen.rapidml.HTTPMethods;
import com.reprezen.rapidml.HttpMessageParameterLocation;
import com.reprezen.rapidml.MatrixParameter;
import com.reprezen.rapidml.MediaType;
import com.reprezen.rapidml.MessageParameter;
import com.reprezen.rapidml.Method;
import com.reprezen.rapidml.Parameter;
import com.reprezen.rapidml.PrimitiveType;
import com.reprezen.rapidml.ResourceDefinition;
import com.reprezen.rapidml.ServiceDataResource;
import com.reprezen.rapidml.SourceReference;
import com.reprezen.rapidml.TemplateParameter;
import com.reprezen.rapidml.TypedMessage;
import com.reprezen.rapidml.TypedRequest;
import com.reprezen.rapidml.TypedResponse;
import com.reprezen.rapidml.URI;
import com.reprezen.rapidml.URIParameter;
import com.reprezen.rapidml.ZenModel;
import com.reprezen.rapidml.util.PrimitiveTypes;
import java.lang.annotation.Annotation;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
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.Functions.Function1;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.ListExtensions;
import org.eclipse.xtext.xbase.lib.Pair;
import org.eclipse.xtext.xbase.lib.StringExtensions;
@SuppressWarnings("all")
public class XGenerateJaxRsResource extends JavaXtendTemplate {
private Map> httpMethods = CollectionLiterals.>newHashMap(
Pair.>of(HTTPMethods.GET, GET.class),
Pair.>of(HTTPMethods.POST, POST.class),
Pair.>of(HTTPMethods.PUT, PUT.class),
Pair.>of(HTTPMethods.DELETE, DELETE.class),
Pair.>of(HTTPMethods.OPTIONS, OPTIONS.class),
Pair.>of(HTTPMethods.HEAD, HEAD.class));
private Table zenElement2ClassQName = HashBasedTable.create();
@Override
public String generate(final ZenModel model, final ServiceDataResource serviceDataResource) {
this.initZenElement2ClassName(model, serviceDataResource.eResource());
StringConcatenation _builder = new StringConcatenation();
_builder.append("package ");
String _packageName = XGenerateJaxRsResource.getPackageName(serviceDataResource);
_builder.append(_packageName);
_builder.append(";");
final String packageDeclaration = _builder.toString();
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("@");
String _typeName = this.getTypeName(Path.class);
_builder_1.append(_typeName);
_builder_1.append("(\"");
URI _uRI = serviceDataResource.getURI();
_builder_1.append(_uRI);
_builder_1.append("\")");
_builder_1.newLineIfNotEmpty();
_builder_1.append("public interface ");
String _className = XGenerateJaxRsResource.getClassName(serviceDataResource);
_builder_1.append(_className);
_builder_1.append(" {");
_builder_1.newLineIfNotEmpty();
_builder_1.append("\t\t\t");
_builder_1.newLine();
{
EList _methods = serviceDataResource.getMethods();
for(final Method method : _methods) {
_builder_1.append("\t");
CharSequence _generateMethod = this.generateMethod(method);
_builder_1.append(_generateMethod, "\t");
_builder_1.newLineIfNotEmpty();
_builder_1.append("\t");
_builder_1.newLine();
}
}
_builder_1.append("\t\t");
_builder_1.newLine();
_builder_1.append("}");
final String body = _builder_1.toString();
final String imports = this.generateImports();
StringConcatenation _builder_2 = new StringConcatenation();
_builder_2.append(packageDeclaration);
_builder_2.newLineIfNotEmpty();
_builder_2.newLine();
_builder_2.append(imports);
_builder_2.newLineIfNotEmpty();
_builder_2.newLine();
_builder_2.append(body);
_builder_2.newLineIfNotEmpty();
return _builder_2.toString();
}
protected CharSequence generateMethod(final Method method) {
StringConcatenation _builder = new StringConcatenation();
CharSequence _generateHttpMethodAnnotation = this.generateHttpMethodAnnotation(method);
_builder.append(_generateHttpMethodAnnotation);
_builder.newLineIfNotEmpty();
String _generateConsumesAnnotation = this.generateConsumesAnnotation(method);
_builder.append(_generateConsumesAnnotation);
_builder.newLineIfNotEmpty();
String _generateProducesAnnotation = this.generateProducesAnnotation(method);
_builder.append(_generateProducesAnnotation);
_builder.newLineIfNotEmpty();
String _responseType = this.getResponseType(this.getOKResponse(method));
_builder.append(_responseType);
_builder.append(" ");
String _javaMethodName = this.getJavaMethodName(method);
_builder.append(_javaMethodName);
_builder.append("(");
String _join = IterableExtensions.join(this.generateRequestParameters(method), ", ");
_builder.append(_join);
_builder.append(");");
_builder.newLineIfNotEmpty();
return _builder;
}
protected CharSequence generateHttpMethodAnnotation(final Method method) {
StringConcatenation _builder = new StringConcatenation();
_builder.append("@");
String _typeName = this.getTypeName(this.httpMethods.get(method.getHttpMethod()));
_builder.append(_typeName);
return _builder;
}
protected List generateRequestParameters(final Method method) {
final List parameters = CollectionLiterals.newArrayList();
URI _uRI = method.getContainingResourceDefinition().getURI();
EList _uriParameters = null;
if (_uRI!=null) {
_uriParameters=_uRI.getUriParameters();
}
for (final URIParameter uriParam : _uriParameters) {
{
final Class> paramType = this.getPrimitiveType(this.getSourceReferenceType(uriParam.getSourceReference()));
StringConcatenation _builder = new StringConcatenation();
_builder.append("@");
String _typeName = this.getTypeName(this.getParameterType(uriParam));
_builder.append(_typeName);
_builder.append("(\"");
String _name = uriParam.getName();
_builder.append(_name);
_builder.append("\") ");
String _typeName_1 = this.getTypeName(paramType);
_builder.append(_typeName_1);
_builder.append(" ");
String _escapeJavaKeywords = this.escapeJavaKeywords(
uriParam.getName());
_builder.append(_escapeJavaKeywords);
parameters.add(_builder.toString());
}
}
final String requestType = this.getRequestType(method.getRequest());
if ((requestType != null)) {
StringConcatenation _builder = new StringConcatenation();
_builder.append(requestType);
_builder.append(" ");
String _escapeJavaKeywords = this.escapeJavaKeywords(StringExtensions.toFirstLower(requestType));
_builder.append(_escapeJavaKeywords);
final String requestInput = _builder.toString();
parameters.add(requestInput);
}
return parameters;
}
protected PrimitiveType getSourceReferenceType(final SourceReference propertyReference) {
return propertyReference.getPrimitiveType();
}
protected Class extends Annotation> getParameterType(final Parameter parameter) {
if ((parameter instanceof TemplateParameter)) {
return PathParam.class;
}
if ((parameter instanceof MatrixParameter)) {
return MatrixParam.class;
}
if ((parameter instanceof MessageParameter)) {
final MessageParameter _switchValue = ((MessageParameter) parameter);
boolean _matched = false;
if (Objects.equal(_switchValue, HttpMessageParameterLocation.QUERY)) {
_matched=true;
return QueryParam.class;
}
if (!_matched) {
if (Objects.equal(_switchValue, HttpMessageParameterLocation.HEADER)) {
_matched=true;
return HeaderParam.class;
}
}
}
return null;
}
protected Class> getPrimitiveType(final PrimitiveType zenType) {
PrimitiveTypes _byTypeName = PrimitiveTypes.getByTypeName(zenType.getName());
if (_byTypeName != null) {
switch (_byTypeName) {
case STRING:
return String.class;
case INTEGER:
return BigInteger.class;
case INT:
return int.class;
case BOOLEAN:
return boolean.class;
case DATE:
return Date.class;
case DATETIME:
return XMLGregorianCalendar.class;
case DECIMAL:
return BigDecimal.class;
case DURATION:
return Duration.class;
case LONG:
return long.class;
case NCNAME:
return int.class;
case QNAME:
return QName.class;
case TIME:
return Date.class;
case FLOAT:
return float.class;
case DOUBLE:
return double.class;
case ANYURI:
return String.class;
case BASE64BINARY:
return byte[].class;
case GDAY:
return XMLGregorianCalendar.class;
case GMONTH:
return XMLGregorianCalendar.class;
case GMONTHDAY:
return XMLGregorianCalendar.class;
case GYEAR:
return XMLGregorianCalendar.class;
case GYEARMONTH:
return XMLGregorianCalendar.class;
default:
break;
}
}
return null;
}
protected String generateConsumesAnnotation(final Method method) {
StringConcatenation _builder = new StringConcatenation();
{
if ((((method.getRequest() != null) && (!method.getRequest().getMediaTypes().isEmpty())) && this.hasDataType(method.getRequest()))) {
_builder.newLineIfNotEmpty();
_builder.append("@");
String _typeName = this.getTypeName(Consumes.class);
_builder.append(_typeName);
_builder.append("(");
final Function1 _function = (MediaType it) -> {
return it.getName();
};
String _annotationParameter = this.toAnnotationParameter(ListExtensions.map(method.getRequest().getMediaTypes(), _function));
_builder.append(_annotationParameter);
_builder.append(")");
_builder.newLineIfNotEmpty();
_builder.append("\t\t");
}
}
return _builder.toString();
}
protected String generateProducesAnnotation(final Method method) {
String _xblockexpression = null;
{
final TypedResponse response = this.getOKResponse(method);
StringConcatenation _builder = new StringConcatenation();
{
if ((((response != null) && (!response.getMediaTypes().isEmpty())) && this.hasDataType(response))) {
_builder.newLineIfNotEmpty();
_builder.append("@");
String _typeName = this.getTypeName(Produces.class);
_builder.append(_typeName);
_builder.append("(");
final Function1 _function = (MediaType it) -> {
return it.getName();
};
String _annotationParameter = this.toAnnotationParameter(ListExtensions.map(response.getMediaTypes(), _function));
_builder.append(_annotationParameter);
_builder.append(")");
_builder.newLineIfNotEmpty();
_builder.append("\t\t");
}
}
_xblockexpression = _builder.toString();
}
return _xblockexpression;
}
protected void initZenElement2ClassName(final ZenModel model, final Resource resource) {
try {
final GenTemplateTrace trace = this.context.getPrerequisiteTrace(JaxRsGenTemplate.JAXB_DEPENDENCY);
final Collection jaxbClassItems = GenTemplateTraceUtils.getTraceItemsOfType(trace, "jaxbClass");
final ZenModelLocator zenModelLocator = new ZenModelLocator(model);
for (final GenTemplateTraceItem item : jaxbClassItems) {
{
final String jaxbClassName = item.getProperties().get("jaxbClassName");
final String jaxbPackageName = item.getProperties().get("jaxbPackageName");
final Collection sourceItems = Collections2.filter(item.getSources(),
GenTemplateTraceUtils.hasSourceRole("sourceData"));
final GenTemplateTraceSourceItem sourceItem = Iterables.getFirst(sourceItems, null);
if ((sourceItem != null)) {
final String locator = sourceItem.getLocator();
final EObject zenElement = zenModelLocator.dereferenceEObject(locator);
this.zenElement2ClassQName.put(zenElement, "jaxbClassName", jaxbClassName);
this.zenElement2ClassQName.put(zenElement, "jaxbPackageName", jaxbPackageName);
}
}
}
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
protected String getResponseType(final TypedResponse response) {
return this.getMessageType(response, Response.class, "void");
}
protected String getRequestType(final TypedRequest response) {
return this.getMessageType(response, null, null);
}
protected String getMessageType(final TypedMessage message, final Class> defaultValue, final String nullValue) {
if ((message == null)) {
return nullValue;
}
EObject _xifexpression = null;
ResourceDefinition _resourceType = message.getResourceType();
boolean _tripleNotEquals = (_resourceType != null);
if (_tripleNotEquals) {
_xifexpression = message.getResourceType();
} else {
_xifexpression = message.getDataType();
}
final Object zenMessageType = _xifexpression;
if ((zenMessageType != null)) {
boolean _containsRow = this.zenElement2ClassQName.containsRow(zenMessageType);
boolean _not = (!_containsRow);
if (_not) {
return this.getTypeName(defaultValue);
}
final String className = this.zenElement2ClassQName.get(zenMessageType, "jaxbClassName");
String _get = this.zenElement2ClassQName.get(zenMessageType, "jaxbPackageName");
String _plus = (_get + ".");
String _plus_1 = (_plus + className);
this.addImport(_plus_1);
return className;
}
return this.getTypeName(defaultValue);
}
protected String toAnnotationParameter(final Collection elements) {
String _xblockexpression = null;
{
String _xifexpression = null;
int _size = elements.size();
boolean _greaterThan = (_size > 0);
if (_greaterThan) {
_xifexpression = "{";
} else {
_xifexpression = "";
}
final String opening = _xifexpression;
String _xifexpression_1 = null;
int _size_1 = elements.size();
boolean _greaterThan_1 = (_size_1 > 0);
if (_greaterThan_1) {
_xifexpression_1 = "}";
} else {
_xifexpression_1 = "";
}
final String closing = _xifexpression_1;
StringConcatenation _builder = new StringConcatenation();
_builder.append(opening);
final Function1 _function = (String it) -> {
return (("\"" + it) + "\"");
};
String _join = IterableExtensions.join(IterableExtensions.map(elements, _function), ", ");
_builder.append(_join);
_builder.append(closing);
_xblockexpression = _builder.toString();
}
return _xblockexpression;
}
protected TypedResponse getOKResponse(final Method method) {
final Function1 _function = (TypedResponse it) -> {
return Boolean.valueOf(((it.getStatusCode() >= 200) && (it.getStatusCode() < 300)));
};
return IterableExtensions.findFirst(method.getResponses(), _function);
}
protected String getJavaMethodName(final Method method) {
return method.getName();
}
private boolean hasDataType(final TypedMessage message) {
return ((message.getActualType() != null) || (message.getResourceType() != null));
}
public static String getPackageName(final ServiceDataResource inputElement) {
StringConcatenation _builder = new StringConcatenation();
_builder.append("com.modelsolv.reprezen.resources.");
EObject _eContainer = inputElement.eContainer().eContainer();
String _lowerCase = ((ZenModel) _eContainer).getName().toLowerCase();
_builder.append(_lowerCase);
return _builder.toString();
}
public static String getClassName(final ServiceDataResource inputElement) {
StringConcatenation _builder = new StringConcatenation();
String _name = inputElement.getName();
_builder.append(_name);
_builder.append("Resource");
return _builder.toString();
}
public static String getFilePath(final ServiceDataResource inputElement) {
String _replaceAll = XGenerateJaxRsResource.getPackageName(inputElement).replaceAll("\\.", "/");
String _plus = (_replaceAll + "/");
String _className = XGenerateJaxRsResource.getClassName(inputElement);
String _plus_1 = (_plus + _className);
return (_plus_1 + ".java");
}
}