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

JavaSpring.apiDelegate2.refactor.mustache Maven / Gradle / Ivy

There is a newer version: 0.9.25
Show newest version
package {{package}};

{{#imports}}import {{import}};
{{/imports}}
{{#jdk8}}
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.JsonMappingException;
{{/jdk8}}
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import org.json.*;
{{#jdk8}}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
{{/jdk8}}
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
{{#jdk8}}
import java.io.IOException;
{{/jdk8}}

{{#jdk8}}
import javax.servlet.http.HttpServletRequest;
{{/jdk8}}
import java.util.List;
{{#jdk8}}
{{/jdk8}}
{{^jdk8}}
    {{#useOptional}}
import java.util.Optional;
    {{/useOptional}}
{{/jdk8}}
{{#async}}
import java.util.concurrent.{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture{{/jdk8}};
{{/async}}

{{#operations}}
/**
 * A delegate to be called by the {@link {{classname}}Controller}}.
 * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class.
 *
 {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
 ############################## DO NOT EDIT: GENERATED FILE ##############################

    Generated by Starter StackGen: http://stackgen.io
    Powered by Swagger Codegen: http://swagger.io
    
    Template file: JavaSpring/apiDelegate.mustache

############################## DO NOT EDIT: GENERATED FILE ##############################
 */
{{>generatedAnnotation}}
@EnableWebMvc
public interface {{classname}}Delegate {
{{#jdk8}}

    Logger log = LoggerFactory.getLogger({{classname}}Delegate.class);

    ObjectMapper getObjectMapper();
    
    HttpServletRequest getHttpServletRequest();

    String getAcceptHeader();
    
   
    // Starter StackGen Persistence methods
    
    public void setId(Long idVal);
    
    public int insert();
    
    public int update();

    public int delete();
    
    public String toJSON();
    
    public void setBean(Object o);
    
    public Object getBean();
    
    public List<{{classname}}Delegate> list();
    
    public {{classname}}Delegate load();
    
	// End Starter StackGen Persistence methods
    
{{/jdk8}}

{{#operation}}
    /**
     * dispatch the delegate method and handle response
     
     * @see {{classname}}#{{operationId}}
     */
    {{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{^isFile}} {{>optionalDataType}} {{/isFile}}{{#isFile}}MultipartFile{{/isFile}} {{paramName}}{{#hasMore}},
        {{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} {
        if(getObjectMapper() != null && getAcceptHeader() != null) {
        
	        // {{operationId}}({{paramName}});
			try {
				Object ret = callMethod("{{operationId}}"{{#allParams}}, {{paramName}}{{#hasMore}} {{/hasMore}}{{/allParams}});
				Object handled = handleResponse(ret);
				if(	handled instanceof ResponseEntity){
					return (ResponseEntity<{{>returnTypes}}>) handled;
				} else {
					String stx = handled.toString();
					List r = jsonArrayToObjectList(stx,List.class);
					return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(r, HttpStatus.OK){{#async}}){{/async}};
				}
			} catch (Exception e) {
				log.error("Failure running method {{classname}}.{{operationId}}: "
						+ e);
				return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
			}
        {{#examples}}
        // TODO: implement examples
        {{/examples}}
        
        } else {
            log.warn("ObjectMapper or HttpServletRequest not configured in default {{classname}} interface so no example is generated");
        }
        return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED){{#async}}){{/async}};
    }{{/jdk8}}
    
{{/operation}}

    
    /**
    * handle serialization issues
    */
    default  List jsonArrayToObjectList(String json, Class tClass) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass);
        List ts = mapper.readValue(json, listType);
        log.debug("class name: {}", ts.get(0).getClass().getName());
        return ts;
    }

	/**
	 * Handle the response based upon the data results 
	 * 
	 * @param ret
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 */
	default Object handleResponse(Object ret) throws JSONException, IOException, JsonParseException, JsonMappingException {
		if (ret != null) {
			if (ret instanceof List) {
				if (((List) ret).size() > 0) {
					Object rx = ((List) ret).get(0);
					if (!(rx instanceof Long)) {
						List re = new ArrayList();
						for(Object r : (List)ret) {
							re.add(new JSONObject(r).toString(1));
						}
						return re;					
					} else {
						if ((Long) rx > -1) {
							return new ResponseEntity<>(HttpStatus.OK);
						} else {
							return new ResponseEntity<>(HttpStatus.NOT_FOUND);
						}
					}
				} else {
					return new ResponseEntity<>(HttpStatus.NOT_FOUND);
				}
			} else {
				// handle return from delete
				if (ret instanceof Integer) {
					if ((Integer) ret > -1) {
						return new ResponseEntity<>(HttpStatus.OK);
					} else {
						return new ResponseEntity<>(HttpStatus.NOT_FOUND);
					}
				}

				if (ret instanceof Long) {
					if ((Long) ret > -1) {
						return new ResponseEntity<>(HttpStatus.OK);
					} else {
						return new ResponseEntity<>(HttpStatus.NOT_FOUND);
					}
				}

				// returns single result
				JSONObject job = new JSONObject(
						((ItemApiDelegate) ret).getBean());
				return new ResponseEntity<>(
						getObjectMapper().readValue(job.toString(), List.class),
						HttpStatus.NOT_IMPLEMENTED);
			}
		} else {
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}
	}

	/** 
	* Handle calling the data method on the Starter StackGen Delegate
	*/
	default Object callMethod(String string, Object... args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		
		if ("update".equals(string) && args.length == 2) {
			this.setBean(args[1]);
		}

		// hande id
		try {
			Long id = Long.parseLong(args[0].toString());
			// TODO: copy vals
			setId(id);

			// TODO: implement ModelCache

		} catch (Exception e) {
			// other type NP
			setBean(args[0]);
		}

		Method method = this.getClass().getDeclaredMethod(string);
		Object rx = method.invoke(this);

		List ret = null;
		if (rx != null && "list".equals(string)) {
			// if it *is* a list, don't return empty
			if (rx instanceof List) {
				if (((List) rx).size() > 0) {
					return rx;
				} else {
					return null;
				}
			} else {
				ret = new ArrayList();
				ret.add(rx);
				return ret;
			}
		}
		return rx;
	}
}


/* TODO: implement examples
    if (getAcceptHeader().contains("{{{contentType}}}")) {
        try {
                return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(getObjectMapper().readValue("{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{>exampleReturnTypes}}.class), HttpStatus.NOT_IMPLEMENTED){{#async}}){{/async}};
        } catch (IOException e) {
            log.error("Couldn't serialize response for content type {{{contentType}}}", e);
            return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR){{#async}}){{/async}};
        }
    }
*/    
{{/operations}}