提交 a5680144 编写于 作者: xignzi006's avatar xignzi006

update:客户端模板

上级 0ec874ff
**.ibizlab-generator-ignore
**.DS_Store
**@macro/**
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{packageName}}</groupId>
<artifactId>{{projectName}}-apiclient-{{lowerCase api.codeName}}</artifactId>
<name>{{projectDesc}} Microservice {{lowerCase api.codeName}}</name>
<description> microservice</description>
<version>0.0.1</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 阿里sentinel熔断器 -->
<alibaba-sentinel.version>2.1.1.RELEASE</alibaba-sentinel.version>
</properties>
<dependencies>
<dependency>
<groupId>net.ibizsys.central.r8</groupId>
<artifactId>ibiz-central-r8</artifactId>
<version>0.2.52</version>
</dependency>
<!-- Alibaba Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>${alibaba-sentinel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.27</version>
<scope>compile</scope>
</dependency>
</dependencies>
<distributionManagement>
<repository>
<id>ibzi5DeploymentRepo</id>
<url>http://172.16.150.220:8081/nexus/content/repositories/releases</url>
</repository>
<snapshotRepository>
<id>ibzi5DeploymentRepo</id>
<url>http://172.16.150.220:8081/nexus/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
<repositories>
<repository>
<id>ibizmvnrepository</id>
<name>ibizmvnrepository</name>
<url>http://172.16.240.220:8081/nexus/content/groups/public/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version>
<configuration>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version>
<configuration>
<!-- 更新元数据 -->
<updateReleaseInfo>true</updateReleaseInfo>
</configuration>
</plugin>
</plugins>
</build>
</project>
package {{packageName}}.client.{{apis}}.feign.dto;
import java.sql.Timestamp;
import java.util.List;
import java.math.BigDecimal;
import net.ibizsys.central.util.EntityDTO;
import com.fasterxml.jackson.annotation.JsonIgnore;
import net.ibizsys.runtime.util.DataTypeUtils;
public class {{apiDto.codeName}} extends EntityDTO {
{{#each apiDto.apiDtoFields as |field|}}
/**
* {{field.logicName}}
*/
public final static String FIELD_{{upperCase field.codeName}} = "{{field.codeName}}";
/**
* 设置「{{field.logicName}}
*
* @param {{camelCase codeName}}
*/
@JsonIgnore
public {{apiDto.codeName}} set{{pascalCase codeName}}({{javaType}} {{camelCase codeName}}) {
this._set(FIELD_{{upperCase field.codeName}}, {{camelCase codeName}});
return this;
}
/**
* 获取「{{field.logicName}}」值
*
*/
@JsonIgnore
public {{javaType}} get{{pascalCase codeName}}() {
{{#if (or (eq javaType 'Integer') (eq javaType 'Long') (eq javaType 'Double') (eq javaType 'BigInteger') (eq javaType 'BigDecimal') (eq javaType 'Timestamp'))}}
try{
{{#if (eq javaType 'Timestamp')}}
return DataTypeUtils.getDateTimeValue(this._get(FIELD_{{upperCase field.codeName}}),null);
{{else}}
return DataTypeUtils.get{{javaType}}Value(this._get(FIELD_{{upperCase field.codeName}}),null);
{{/if}}
}catch (Exception e){
throw new RuntimeException(e);
}
{{else}}
return ({{javaType}}) this._get(FIELD_{{upperCase field.codeName}});
{{/if}}
}
/**
* 判断 「{{field.logicName}}」是否有值
*
*/
@JsonIgnore
public boolean contains{{pascalCase codeName}}() {
return this._contains(FIELD_{{upperCase field.codeName}});
}
/**
* 重置 「{{field.logicName}}
*
*/
@JsonIgnore
public {{apiDto.codeName}} reset{{pascalCase codeName}}() {
this._reset(FIELD_{{upperCase field.codeName}});
return this;
}
{{/each}}
}
package net.ibizsys.api.helper;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import feign.codec.Decoder;
import feign.optionals.OptionalDecoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfiguration {
@Bean
public Decoder feignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
return new OptionalDecoder(
new ResponseEntityDecoder(new FeignDecoder(messageConverters)));
}
@Bean
public feign.QueryMapEncoder feignEncoder(){
return new FeignEncoder();
}
@Bean
@ConditionalOnProperty(name = "feign.hystrix.enabled")
public HystrixConcurrencyStrategy hystrixConcurrencyStrategy() {
return new RequestContextHystrixConcurrencyStrategy();
}
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase api.codeName}}.feign.helper;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import feign.codec.Decoder;
import feign.optionals.OptionalDecoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfiguration {
@Bean
public Decoder feignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
return new OptionalDecoder(
new ResponseEntityDecoder(new FeignDecoder(messageConverters)));
}
@Bean
public feign.QueryMapEncoder feignEncoder(){
return new FeignEncoder();
}
@Bean
@ConditionalOnProperty(name = "feign.hystrix.enabled")
public HystrixConcurrencyStrategy hystrixConcurrencyStrategy() {
return new RequestContextHystrixStrategy();
}
}
\ No newline at end of file
package net.ibizsys.api.helper;
import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import com.google.common.collect.Lists;
import feign.FeignException;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
@Slf4j
public class FeignDecoder extends SpringDecoder {
public FeignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
super(messageConverters);
}
@Override
public Object decode(final Response response, Type type)
throws IOException, FeignException {
if (type instanceof ParameterizedType && ((ParameterizedType) type).getRawType() == Page.class) {
try {
((ParameterizedType) type).getActualTypeArguments()[0].getClass();
ParameterizedTypeImpl ss = new ParameterizedTypeImpl(((ParameterizedType) type).getActualTypeArguments(), null, List.class);
Object ret = super.decode(response, ss);
return new PageImpl((List) ret,
PageRequest.of(
Integer.parseInt(response.headers().get("x-page").toArray()[0].toString()),
Integer.parseInt(response.headers().get("x-per-page").toArray()[0].toString()))
, Long.parseLong(response.headers().get("x-total").toArray()[0].toString()));
} catch (Exception e) {
log.error("FeignDecode转换Page发生错误:" + e.getMessage());
return new PageImpl(Lists.newArrayList(), PageRequest.of(0, 0), 0);
}
}
return super.decode(response, type);
}
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase api.codeName}}.feign.helper;
import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import com.google.common.collect.Lists;
import feign.FeignException;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
@Slf4j
public class FeignDecoder extends SpringDecoder {
public FeignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
super(messageConverters);
}
@Override
public Object decode(final Response response, Type type)
throws IOException, FeignException {
if (type instanceof ParameterizedType && ((ParameterizedType) type).getRawType() == Page.class) {
try {
((ParameterizedType) type).getActualTypeArguments()[0].getClass();
ParameterizedTypeImpl ss = new ParameterizedTypeImpl(((ParameterizedType) type).getActualTypeArguments(), null, List.class);
Object ret = super.decode(response, ss);
return new PageImpl((List) ret,
PageRequest.of(
Integer.parseInt(response.headers().get("x-page").toArray()[0].toString()),
Integer.parseInt(response.headers().get("x-per-page").toArray()[0].toString()))
, Long.parseLong(response.headers().get("x-total").toArray()[0].toString()));
} catch (Exception e) {
log.error("FeignDecode转换Page发生错误:" + e.getMessage());
return new PageImpl(Lists.newArrayList(), PageRequest.of(0, 0), 0);
}
}
return super.decode(response, type);
}
}
\ No newline at end of file
package net.ibizsys.api.helper;
import feign.QueryMapEncoder;
import feign.codec.EncodeException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
/**
* 用于将searchContext中的param参数拼接在地址栏中
*/
public class FeignEncoder implements QueryMapEncoder {
private final Map<Class<?>, ObjectParamMetadata> classToMetadata = new HashMap<>();
@Override
public Map<String, Object> encode(Object object) throws EncodeException {
try {
ObjectParamMetadata metadata = getMetadata(object.getClass());
Map<String, Object> fieldNameToValue = new HashMap<String, Object>();
for (Field field : metadata.objectFields) {
Object value = field.get(object);
if (value != null && value != object) {
if(value instanceof Map){
fieldNameToValue.putAll((Map<String,Object>)value);
continue;
}
fieldNameToValue.put(field.getName(), value);
}
}
return fieldNameToValue;
} catch (IllegalAccessException e) {
throw new EncodeException("Failure encoding object into query map", e);
}
}
private ObjectParamMetadata getMetadata(Class<?> objectType) {
ObjectParamMetadata metadata = classToMetadata.get(objectType);
if (metadata == null) {
metadata = ObjectParamMetadata.parseObjectType(objectType);
classToMetadata.put(objectType, metadata);
}
return metadata;
}
private static class ObjectParamMetadata {
private final List<Field> objectFields;
private ObjectParamMetadata(List<Field> objectFields) {
this.objectFields = Collections.unmodifiableList(objectFields);
}
private static ObjectParamMetadata parseObjectType(Class<?> type) {
List<Field> allFields = new ArrayList<>();
for (Class<?> currentClass = type; currentClass != null; currentClass =
currentClass.getSuperclass()) {
Collections.addAll(allFields, currentClass.getDeclaredFields());
}
return new ObjectParamMetadata(allFields.stream()
.filter(field -> !field.isSynthetic())
.peek(field -> field.setAccessible(true))
.collect(Collectors.toList()));
}
}
}
package {{packageName}}.client.{{lowerCase api.codeName}}.feign.helper;
import feign.QueryMapEncoder;
import feign.codec.EncodeException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
/**
* 用于将searchContext中的param参数拼接在地址栏中
*/
public class FeignEncoder implements QueryMapEncoder {
private final Map<Class<?>, ObjectParamMetadata> classToMetadata = new HashMap<>();
@Override
public Map<String, Object> encode(Object object) throws EncodeException {
try {
ObjectParamMetadata metadata = getMetadata(object.getClass());
Map<String, Object> fieldNameToValue = new HashMap<String, Object>();
for (Field field : metadata.objectFields) {
Object value = field.get(object);
if (value != null && value != object) {
if(value instanceof Map){
fieldNameToValue.putAll((Map<String,Object>)value);
continue;
}
fieldNameToValue.put(field.getName(), value);
}
}
return fieldNameToValue;
} catch (IllegalAccessException e) {
throw new EncodeException("Failure encoding object into query map", e);
}
}
private ObjectParamMetadata getMetadata(Class<?> objectType) {
ObjectParamMetadata metadata = classToMetadata.get(objectType);
if (metadata == null) {
metadata = ObjectParamMetadata.parseObjectType(objectType);
classToMetadata.put(objectType, metadata);
}
return metadata;
}
private static class ObjectParamMetadata {
private final List<Field> objectFields;
private ObjectParamMetadata(List<Field> objectFields) {
this.objectFields = Collections.unmodifiableList(objectFields);
}
private static ObjectParamMetadata parseObjectType(Class<?> type) {
List<Field> allFields = new ArrayList<>();
for (Class<?> currentClass = type; currentClass != null; currentClass =
currentClass.getSuperclass()) {
Collections.addAll(allFields, currentClass.getDeclaredFields());
}
return new ObjectParamMetadata(allFields.stream()
.filter(field -> !field.isSynthetic())
.peek(field -> field.setAccessible(true))
.collect(Collectors.toList()));
}
}
}
package net.ibizsys.api.helper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import net.ibizsys.central.r8.security.AuthTokenUtil;
import net.ibizsys.central.r8.security.AuthenticationInfo;
import net.ibizsys.central.r8.security.AuthorizationLogin;
import net.ibizsys.central.r8.util.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
/**
* 忽略权限系统级调用
*/
public class IgnorePrivInterceptor implements RequestInterceptor {
private String authUser;
private String authPassword;
private String token;
private AuthenticationInfo authenticationInfo;
private SuperLoginClient superLoginClient;
private final Logger logger = LoggerFactory.getLogger(getClass());
public IgnorePrivInterceptor(SuperLoginClient superLoginClient, String authUser, String authPassword) {
this.authUser = authUser;
this.authPassword = authPassword;
this.superLoginClient = superLoginClient;
}
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
HttpServletRequest request = requestAttributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
requestTemplate.header("Authorization", Collections.emptyList());
requestTemplate.header("Authorization", "Bearer " + getToken());
}else {
requestTemplate.header("Authorization", Collections.emptyList());
requestTemplate.header("Authorization", "Bearer " + getToken());
requestTemplate.header("srforgid", Collections.emptyList());
requestTemplate.header("srforgid", this.authenticationInfo.getUser().getOrgid());
}
}
public String getToken() {
AuthTokenUtil authTokenUtil = SpringContextHolder.getBean(AuthTokenUtil.class);
if (StringUtils.isNotBlank(this.token)) {
try {
Date expirationDate = authTokenUtil.getExpirationDateFromToken(this.token);
if (expirationDate.after(new Date())) {
return this.token;
}
} catch (Exception e) {
logger.error(String.format("解析忽略接口权限认证token发生错误:%s", e.getMessage()));
}
}
AuthorizationLogin login = new AuthorizationLogin();
login.setLoginname(authUser);
login.setPassword(authPassword);
try {
AuthenticationInfo info = superLoginClient.login(login);
this.token = info.getToken();
this.authenticationInfo = info;
return this.token;
} catch (Exception e) {
throw new RuntimeException(String.format("忽略接口权限认证发生错误[%s]-[%s]:%s", authUser, authPassword, e.getMessage()));
}
}
public AuthenticationInfo getAuthenticationInfo() {
AuthorizationLogin login = new AuthorizationLogin();
login.setLoginname(authUser);
login.setPassword(authPassword);
try {
AuthenticationInfo info = superLoginClient.login(login);
this.token = info.getToken();
this.authenticationInfo = info;
return authenticationInfo;
} catch (Exception e) {
throw new RuntimeException(String.format("忽略接口权限认证发生错误[%s]-[%s]:%s", authUser, authPassword, e.getMessage()));
}
}
}
package {{packageName}}.client.{{lowerCase api.codeName}}.feign.helper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import net.ibizsys.central.r8.security.AuthTokenUtil;
import net.ibizsys.central.r8.security.AuthenticationInfo;
import net.ibizsys.central.r8.security.AuthorizationLogin;
import net.ibizsys.central.r8.util.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
/**
* 忽略权限系统级调用
*/
public class IgnorePrivInterceptor implements RequestInterceptor {
private String authUser;
private String authPassword;
private String token;
private AuthenticationInfo authenticationInfo;
private SuperLoginClient superLoginClient;
private final Logger logger = LoggerFactory.getLogger(getClass());
public IgnorePrivInterceptor(SuperLoginClient superLoginClient, String authUser, String authPassword) {
this.authUser = authUser;
this.authPassword = authPassword;
this.superLoginClient = superLoginClient;
}
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
HttpServletRequest request = requestAttributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
requestTemplate.header("Authorization", Collections.emptyList());
requestTemplate.header("Authorization", "Bearer " + getToken());
}else {
requestTemplate.header("Authorization", Collections.emptyList());
requestTemplate.header("Authorization", "Bearer " + getToken());
requestTemplate.header("srforgid", Collections.emptyList());
requestTemplate.header("srforgid", this.authenticationInfo.getUser().getOrgid());
}
}
public String getToken() {
AuthTokenUtil authTokenUtil = SpringContextHolder.getBean(AuthTokenUtil.class);
if (StringUtils.isNotBlank(this.token)) {
try {
Date expirationDate = authTokenUtil.getExpirationDateFromToken(this.token);
if (expirationDate.after(new Date())) {
return this.token;
}
} catch (Exception e) {
logger.error(String.format("解析忽略接口权限认证token发生错误:%s", e.getMessage()));
}
}
AuthorizationLogin login = new AuthorizationLogin();
login.setLoginname(authUser);
login.setPassword(authPassword);
try {
AuthenticationInfo info = superLoginClient.login(login);
this.token = info.getToken();
this.authenticationInfo = info;
return this.token;
} catch (Exception e) {
throw new RuntimeException(String.format("忽略接口权限认证发生错误[%s]-[%s]:%s", authUser, authPassword, e.getMessage()));
}
}
public AuthenticationInfo getAuthenticationInfo() {
AuthorizationLogin login = new AuthorizationLogin();
login.setLoginname(authUser);
login.setPassword(authPassword);
try {
AuthenticationInfo info = superLoginClient.login(login);
this.token = info.getToken();
this.authenticationInfo = info;
return authenticationInfo;
} catch (Exception e) {
throw new RuntimeException(String.format("忽略接口权限认证发生错误[%s]-[%s]:%s", authUser, authPassword, e.getMessage()));
}
}
}
package net.ibizsys.api.helper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import feign.*;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.hystrix.FallbackFactory;
import org.apache.commons.collections.keyvalue.MultiKey;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* 外部接口访问工具类 Feign接口定义
*/
@Component
public class OutsideAccessorUtils {
@Autowired
ApplicationContext applicationContext;
@Autowired
Contract contract;
@Autowired
Encoder encoder;
@Autowired
Decoder decoder;
@Autowired
Client client;
@Autowired
List<RequestInterceptor> defaultInterceptors;
/**
* 启用熔断
*/
@Value(value = "${feign.hystrix.enabled:false}")
private boolean hystrix;
/**
* 缓存
*/
private final Cache<MultiKey, Object> cache = CacheBuilder.newBuilder().weakValues().build();
/**
* @param accessInterface
* @param accessfallback
* @param server
* @param <T>
* @return
*/
public <T> T buildAccessor(Class<T> accessInterface, FallbackFactory accessfallback, String server) {
try {
return (T) cache.get(new MultiKey(accessInterface, server), () -> construct(accessInterface, accessfallback, server, null));
} catch (Exception e) {
throw new RuntimeException("");
}
}
public <T> T buildAccessor(Class<T> accessInterface, FallbackFactory accessfallback, String server, List<RequestInterceptor> interceptors) {
try {
return (T) cache.get(new MultiKey(accessInterface, server), () -> construct(accessInterface, accessfallback, server, interceptors));
} catch (Exception e) {
throw new RuntimeException("");
}
}
private <T> T construct(Class<T> accessInterface, FallbackFactory accessfallback, String server, List<RequestInterceptor> interceptors) throws Exception {
if (server.startsWith("http")) {
if (client instanceof LoadBalancerFeignClient) { // 无需均衡负载
client = ((LoadBalancerFeignClient) client).getDelegate();
}
}
Feign.Builder builder = Feign.builder().client(client).contract(contract).encoder(encoder).decoder(decoder);
builder.invocationHandlerFactory(new InvocationHandlerFactory() {
@Override
public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
if (accessfallback != null && hystrix) {
return new OutsideInvocationHandler(target, dispatch, accessfallback);
} else {
return new OutsideInvocationHandler(target, dispatch);
}
}
}
);
List<RequestInterceptor> requestInterceptors = null;
if (interceptors != null) {
requestInterceptors = ListUtils.union(defaultInterceptors, interceptors);
} else {
requestInterceptors = defaultInterceptors;
}
builder.requestInterceptors(requestInterceptors);
return builder.target(accessInterface, server.startsWith("http") ? server : "http" + "://" + server);
}
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase api.codeName}}.feign.helper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import feign.*;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.hystrix.FallbackFactory;
import org.apache.commons.collections.keyvalue.MultiKey;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* 外部接口访问工具类 Feign接口定义
*/
@Component
public class OutsideAccessorUtils {
@Autowired
ApplicationContext applicationContext;
@Autowired
Contract contract;
@Autowired
Encoder encoder;
@Autowired
Decoder decoder;
@Autowired
Client client;
@Autowired
List<RequestInterceptor> defaultInterceptors;
/**
* 启用熔断
*/
@Value(value = "${feign.hystrix.enabled:false}")
private boolean hystrix;
/**
* 缓存
*/
private final Cache<MultiKey, Object> cache = CacheBuilder.newBuilder().weakValues().build();
/**
* @param accessInterface
* @param accessfallback
* @param server
* @param <T>
* @return
*/
public <T> T buildAccessor(Class<T> accessInterface, FallbackFactory accessfallback, String server) {
try {
return (T) cache.get(new MultiKey(accessInterface, server), () -> construct(accessInterface, accessfallback, server, null));
} catch (Exception e) {
throw new RuntimeException("");
}
}
public <T> T buildAccessor(Class<T> accessInterface, FallbackFactory accessfallback, String server, List<RequestInterceptor> interceptors) {
try {
return (T) cache.get(new MultiKey(accessInterface, server), () -> construct(accessInterface, accessfallback, server, interceptors));
} catch (Exception e) {
throw new RuntimeException("");
}
}
private <T> T construct(Class<T> accessInterface, FallbackFactory accessfallback, String server, List<RequestInterceptor> interceptors) throws Exception {
if (server.startsWith("http")) {
if (client instanceof LoadBalancerFeignClient) { // 无需均衡负载
client = ((LoadBalancerFeignClient) client).getDelegate();
}
}
Feign.Builder builder = Feign.builder().client(client).contract(contract).encoder(encoder).decoder(decoder);
builder.invocationHandlerFactory(new InvocationHandlerFactory() {
@Override
public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
if (accessfallback != null && hystrix) {
return new OutsideInvocationHandler(target, dispatch, accessfallback);
} else {
return new OutsideInvocationHandler(target, dispatch);
}
}
}
);
List<RequestInterceptor> requestInterceptors = null;
if (interceptors != null) {
requestInterceptors = ListUtils.union(defaultInterceptors, interceptors);
} else {
requestInterceptors = defaultInterceptors;
}
builder.requestInterceptors(requestInterceptors);
return builder.target(accessInterface, server.startsWith("http") ? server : "http" + "://" + server);
}
}
\ No newline at end of file
package net.ibizsys.api.helper;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import feign.InvocationHandlerFactory;
import feign.Target;
import feign.Util;
import feign.hystrix.FallbackFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.Map;
public class OutsideInvocationHandler implements InvocationHandler {
private final Target target;
private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;
FallbackFactory fallbackFactory;
private Map<Method, Method> fallbackMethodMap;
public OutsideInvocationHandler(Target target, Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
this.target = Util.checkNotNull(target, "target");
this.dispatch = Util.checkNotNull(dispatch, "dispatch for %s", target);
}
public OutsideInvocationHandler(Target target, Map<Method, InvocationHandlerFactory.MethodHandler> dispatch, FallbackFactory fallbackFactory) {
this.target = Util.checkNotNull(target, "target");
this.dispatch = Util.checkNotNull(dispatch, "dispatch for %s", target);
this.fallbackFactory = fallbackFactory;
this.fallbackMethodMap = toFallbackMethod(dispatch);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("equals".equals(method.getName())) {
try {
Object otherHandler =
args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
return equals(otherHandler);
} catch (IllegalArgumentException e) {
return false;
}
} else if ("hashCode".equals(method.getName())) {
return hashCode();
} else if ("toString".equals(method.getName())) {
return toString();
}
Object result;
InvocationHandlerFactory.MethodHandler methodHandler = this.dispatch.get(method);
// only handle by HardCodedTarget
if (target instanceof Target.HardCodedTarget) {
try {
result = methodHandler.invoke(args);
}
catch (Throwable ex) {
// fallback handle
if (!BlockException.isBlockException(ex)) {
Tracer.trace(ex);
}
if (fallbackFactory != null) {
try {
Object fallbackResult = fallbackMethodMap.get(method)
.invoke(fallbackFactory.create(ex), args);
return fallbackResult;
}
catch (IllegalAccessException e) {
// shouldn't happen as method is public due to being an
// interface
throw new AssertionError(e);
}
catch (InvocationTargetException e) {
throw new AssertionError(e.getCause());
}
}
else {
// throw exception if fallbackFactory is null
throw ex;
}
}
finally {
ContextUtil.exit();
}
}
else {
// other target type using default strategy
result = methodHandler.invoke(args);
}
return result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof OutsideInvocationHandler) {
OutsideInvocationHandler other = (OutsideInvocationHandler) obj;
return target.equals(other.target);
}
return false;
}
@Override
public int hashCode() {
return target.hashCode();
}
@Override
public String toString() {
return target.toString();
}
static Map<Method, Method> toFallbackMethod(Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
Map<Method, Method> result = new LinkedHashMap<>();
for (Method method : dispatch.keySet()) {
method.setAccessible(true);
result.put(method, method);
}
return result;
}
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase api.codeName}}.feign.helper;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import feign.InvocationHandlerFactory;
import feign.Target;
import feign.Util;
import feign.hystrix.FallbackFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.Map;
public class OutsideInvocationHandler implements InvocationHandler {
private final Target target;
private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;
FallbackFactory fallbackFactory;
private Map<Method, Method> fallbackMethodMap;
public OutsideInvocationHandler(Target target, Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
this.target = Util.checkNotNull(target, "target");
this.dispatch = Util.checkNotNull(dispatch, "dispatch for %s", target);
}
public OutsideInvocationHandler(Target target, Map<Method, InvocationHandlerFactory.MethodHandler> dispatch, FallbackFactory fallbackFactory) {
this.target = Util.checkNotNull(target, "target");
this.dispatch = Util.checkNotNull(dispatch, "dispatch for %s", target);
this.fallbackFactory = fallbackFactory;
this.fallbackMethodMap = toFallbackMethod(dispatch);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("equals".equals(method.getName())) {
try {
Object otherHandler =
args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
return equals(otherHandler);
} catch (IllegalArgumentException e) {
return false;
}
} else if ("hashCode".equals(method.getName())) {
return hashCode();
} else if ("toString".equals(method.getName())) {
return toString();
}
Object result;
InvocationHandlerFactory.MethodHandler methodHandler = this.dispatch.get(method);
// only handle by HardCodedTarget
if (target instanceof Target.HardCodedTarget) {
try {
result = methodHandler.invoke(args);
}
catch (Throwable ex) {
// fallback handle
if (!BlockException.isBlockException(ex)) {
Tracer.trace(ex);
}
if (fallbackFactory != null) {
try {
Object fallbackResult = fallbackMethodMap.get(method)
.invoke(fallbackFactory.create(ex), args);
return fallbackResult;
}
catch (IllegalAccessException e) {
// shouldn't happen as method is public due to being an
// interface
throw new AssertionError(e);
}
catch (InvocationTargetException e) {
throw new AssertionError(e.getCause());
}
}
else {
// throw exception if fallbackFactory is null
throw ex;
}
}
finally {
ContextUtil.exit();
}
}
else {
// other target type using default strategy
result = methodHandler.invoke(args);
}
return result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof OutsideInvocationHandler) {
OutsideInvocationHandler other = (OutsideInvocationHandler) obj;
return target.equals(other.target);
}
return false;
}
@Override
public int hashCode() {
return target.hashCode();
}
@Override
public String toString() {
return target.toString();
}
static Map<Method, Method> toFallbackMethod(Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
Map<Method, Method> result = new LinkedHashMap<>();
for (Method method : dispatch.keySet()) {
method.setAccessible(true);
result.put(method, method);
}
return result;
}
}
\ No newline at end of file
package net.ibizsys.api.helper;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import java.util.concurrent.Callable;
/**
* 熔断隔离策略
* 解决RequestContextHolder.getRequestAttributes() null 问题
*
*/
public class RequestContextHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
@Override
public <T> Callable<T> wrapCallable(Callable<T> callable) {
return new RequestAttributeAwareCallable<>(callable, RequestContextHolder.getRequestAttributes());
}
static class RequestAttributeAwareCallable<T> implements Callable<T> {
private final Callable<T> delegate;
private final RequestAttributes requestAttributes;
public RequestAttributeAwareCallable(Callable<T> callable, RequestAttributes requestAttributes) {
this.delegate = callable;
this.requestAttributes = requestAttributes;
}
@Override
public T call() throws Exception {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
return delegate.call();
} finally {
RequestContextHolder.resetRequestAttributes();
}
}
}
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase api.codeName}}.feign.helper;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import java.util.concurrent.Callable;
/**
* 熔断隔离策略
* 解决RequestContextHolder.getRequestAttributes() null 问题
*
*/
public class RequestContextHystrixStrategy extends HystrixConcurrencyStrategy {
@Override
public <T> Callable<T> wrapCallable(Callable<T> callable) {
return new RequestAttributeAwareCallable<>(callable, RequestContextHolder.getRequestAttributes());
}
static class RequestAttributeAwareCallable<T> implements Callable<T> {
private final Callable<T> delegate;
private final RequestAttributes requestAttributes;
public RequestAttributeAwareCallable(Callable<T> callable, RequestAttributes requestAttributes) {
this.delegate = callable;
this.requestAttributes = requestAttributes;
}
@Override
public T call() throws Exception {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
return delegate.call();
} finally {
RequestContextHolder.resetRequestAttributes();
}
}
}
}
\ No newline at end of file
package net.ibizsys.api.helper;
import net.ibizsys.central.r8.security.AuthenticationInfo;
import net.ibizsys.central.r8.security.AuthorizationLogin;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
/**
* 实体[PSDevUser] 服务对象接口
*/
public interface SuperLoginClient {
@PostMapping(value = "/v7/login")
public AuthenticationInfo login(@Validated @RequestBody AuthorizationLogin authorizationLogin);
}
package {{packageName}}.client.{{lowerCase api.codeName}}.feign.helper;
import net.ibizsys.central.r8.security.AuthenticationInfo;
import net.ibizsys.central.r8.security.AuthorizationLogin;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
/**
* 实体[PSDevUser] 服务对象接口
*/
public interface SuperLoginClient {
@PostMapping(value = "/v7/login")
public AuthenticationInfo login(@Validated @RequestBody AuthorizationLogin authorizationLogin);
}
package {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign;
import {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign.dto.{{apiEntity.codeName}}DTO;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import feign.FeignException;
import feign.hystrix.FallbackFactory;
import net.ibizsys.central.util.SearchContextDTO;
import net.ibizsys.runtime.dataentity.DataEntityRuntimeException;
import net.ibizsys.runtime.util.Errors;
import org.springframework.data.domain.Page;
import java.util.Collection;
import java.util.List;
/**
* 实体[{{apiEntity.codeName}}] 服务对象接口
*
*/
public class {{apiEntity.codeName}}Fallback implements FallbackFactory<{{apiEntity.codeName}}FeignClient> {
@Override
public {{apiEntity.codeName}}FeignClient create(Throwable cause) {
String errorMessage = "";
if (cause instanceof FeignException) {
FeignException ex = (FeignException) cause;
errorMessage = "[iBizRT客户端]调用异常,错误状态:" + ex.status() + "." + cause.getMessage();
} else if (cause instanceof HystrixTimeoutException) {
errorMessage = "[RT服务接口]调用超时。";
} else {
errorMessage = "[iBizRT客户端]异常,错误:" + cause.getMessage();
}
String finalErrorMessage = errorMessage;
return new {{apiEntity.codeName}}FeignClient(){
{{#each apiEntity.methods}}
{{!行为}}
{{#eq methodType "DEACTION"}}
public {{#eq return.type "DTO"}}{{apiEntity.codeName}}DTO{{/eq}}{{#eq return.type "DTOS"}}Page<{{apiEntity.codeName}}DTO>{{/eq}}{{#eq return.type "SIMPLE"}}Integer{{/eq}}{{#eq return.type "KEYFIELD"}}{{/eq}}{{#eq return.type "VOID"}}void{{/eq}}{{#eq return.type "USER"}}Object{{/eq}} {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}{{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}{{#eq input.type "DTO"}}{{body}}{{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}{{body}}{{/eq}}{{/eq}}{{#eq input.type "DTOS"}}List<{{body}}>{{/eq}} {{#eq input.type "DTO"}}{{camelCase body}}{{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}{{camelCase body}}{{/eq}}{{/eq}}{{#eq input.type "DTOS"}}list{{/eq}}{{/if}}){
throw new DataEntityRuntimeException(null,finalErrorMessage, Errors.INTERNALERROR, null);
}
{{/eq}}
{{!数据集}}
{{#eq methodType "FETCH"}}
public Page<{{apiEntity.codeName}}DTO> {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}{{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}SearchContextDTO context{{/if}}){
throw new DataEntityRuntimeException(null,finalErrorMessage, Errors.INTERNALERROR, null);
}
{{/eq}}
{{!SELECT法}}
{{#eq methodType "SELECT"}}
public Page<{{apiEntity.codeName}}DTO> {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}{{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}SearchContextDTO context{{/if}}){
throw new DataEntityRuntimeException(null,finalErrorMessage, Errors.INTERNALERROR, null);
}
{{/eq}}
{{/each}}
};
}
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign;
import {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign.dto.{{apiEntity.codeName}}DTO;
import net.ibizsys.central.util.SearchContextDTO;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Collection;
import java.util.List;
/**
* 实体[{{apiEntity.codeName}}] 服务对象接口
*
*/
public interface {{apiEntity.codeName}}FeignClient {
{{#each apiEntity.methods}}
@RequestMapping(method = RequestMethod.{{requestMethod}}, value = "{{requestPath}}")
{{!行为}}
{{#eq methodType "DEACTION"}}
{{#eq return.type "DTO"}}{{apiEntity.codeName}}DTO{{/eq}}{{#eq return.type "DTOS"}}Page<{{apiEntity.codeName}}DTO>{{/eq}}{{#eq return.type "SIMPLE"}}Integer{{/eq}}{{#eq return.type "KEYFIELD"}}{{/eq}}{{#eq return.type "VOID"}}void{{/eq}}{{#eq return.type "USER"}}Object{{/eq}} {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}@PathVariable("{{camelCase name}}") {{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}@RequestBody {{#eq input.type "DTO"}}{{body}}{{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}{{body}}{{/eq}}{{/eq}}{{#eq input.type "DTOS"}}List<{{body}}>{{/eq}} {{#eq input.type "DTO"}}{{camelCase body}}{{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}{{camelCase body}}{{/eq}}{{/eq}}{{#eq input.type "DTOS"}}list{{/eq}}{{/if}});
{{/eq}}
{{!数据集}}
{{#eq methodType "FETCH"}}
Page<{{apiEntity.codeName}}DTO> {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}@PathVariable("{{camelCase name}}") {{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}@RequestBody SearchContextDTO context{{/if}});
{{/eq}}
{{!SELECT法}}
{{#eq methodType "SELECT"}}
Page<{{apiEntity.codeName}}DTO> {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}@PathVariable("{{camelCase name}}") {{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}@RequestBody SearchContextDTO context{{/if}});
{{/eq}}
{{/each}}
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign;
import {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign.helper.IgnorePrivInterceptor;
import {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign.helper.OutsideAccessorUtils;
import {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign.helper.SuperLoginClient;
import feign.Feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* {{apiEntity.entity.logicName}}
*
*/
@Configuration
public class {{apiEntity.codeName}}FeignClientConfiguration {
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.name:ibizrt4ebsx-rt4ebsx}")
String serviceValue;
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.system:f7ad7e05-9031-11eb-b882-00163e06e68c}")
String serviceSystem;
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.super:false}")
boolean superapi;
@Value("${ibiz.ref.service.uaa:ibizrt4ebsx-rt4ebsx}")
String uaaservice;
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.login:}")
String login;
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.password:}")
String password;
@Autowired
Feign.Builder builder;
@Autowired
OutsideAccessorUtils outsideAccessorUtils;
@Autowired
List<RequestInterceptor> defaultInterceptors;
@Bean
public {{apiEntity.codeName}}FeignClient {{camelCase apiEntity.codeName}}FeignClient() {
List<RequestInterceptor> requestInterceptors = new ArrayList<>();
requestInterceptors.addAll(defaultInterceptors);
RequestInterceptor systemInterceptor = new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
requestTemplate.header("srfsystemid", Collections.emptyList());
requestTemplate.header("srfsystemid", serviceSystem);
}
};
requestInterceptors.add(systemInterceptor);
//忽略权限
if (superapi) {
SuperLoginClient superLoginClient = outsideAccessorUtils.buildAccessor(SuperLoginClient.class, null, uaaservice, Arrays.asList(new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("srfsystemid", Collections.emptyList());
requestTemplate.header("srforgid", Collections.emptyList());
requestTemplate.header("Authorization", Collections.emptyList());
}
}));
RequestInterceptor ignorePrivInterceptor = new IgnorePrivInterceptor(superLoginClient, login, password);
requestInterceptors.add(ignorePrivInterceptor);
}
return outsideAccessorUtils.buildAccessor({{apiEntity.codeName}}FeignClient.class, new {{apiEntity.codeName}}Fallback(), serviceValue, requestInterceptors);
}
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.runtime.service.dataentity;
import net.ibizsys.central.r8.util.SpringContextHolder;
import net.ibizsys.central.util.ISearchContextDTO;
import {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign.dto.{{apiEntity.codeName}}DTO;
import {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.feign.{{apiEntity.codeName}}FeignClient;
import net.ibizsys.central.dataentity.IDataEntityRuntime;
import net.ibizsys.central.util.IEntityDTO;
import net.ibizsys.central.util.SearchContextDTO;
import net.ibizsys.model.dataentity.action.IPSDEAction;
import net.ibizsys.model.dataentity.ds.IPSDEDataSet;
import net.ibizsys.model.service.IPSSubSysServiceAPIDEMethod;
import net.ibizsys.runtime.util.DataTypeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* 实体[{{apiEntity.codeName}}] 对象
*
*/
public class {{apiEntity.codeName}}SubSysServiceAPIDERuntime extends {{packageName}}.client.{{lowerCase apiEntity.api.codeName}}.runtime.service.{{apiEntity.api.codeName}}R8SubSysServiceAPIDERuntime{
private {{apiEntity.codeName}}FeignClient getClient() {
return SpringContextHolder.getBean({{apiEntity.codeName}}FeignClient.class);
}
@Override
public Object invokeMethod(IPSSubSysServiceAPIDEMethod iPSSubSysServiceAPIDEMethod, Map<String, Object> context, IDataEntityRuntime iDataEntityRuntime, IPSDEAction iPSDEAction, Object[] args) throws Throwable {
Object key;
if (args[0] instanceof IEntityDTO) {
key = ((IEntityDTO) args[0]).get(iDataEntityRuntime.getKeyPSDEField().getName().toLowerCase());
} else {
key = args[0];
}
Object obj = null;
String strActionName = iPSDEAction.getName().toLowerCase();
switch (strActionName) {
{{#each apiEntity.pSDataEntity.allPSDEActions as |deAction|}}
case "{{lowerCase deAction.name}}":
{{#each apiEntity.methods as |method|}}
{{#if (and (eq methodType "DEACTION") (eq method.pSDEServiceAPIMethod.pSDEAction.name deAction.name))}}
{{#each method.parentApiEntities as |parent|}}
{{#if (and (eq @index 0) @last)}}
if (context != null && context.containsKey("{{parent.majorPSDEServiceAPI.name}}")) {
{{#eq return.type "DTO"}}obj = {{/eq}}{{#eq return.type "SIMPLE"}}obj = {{/eq}}{{#eq return.type "USER"}}obj = {{/eq}}getClient().{{camelCase method.name}}{{#each pathVariables as |pathVariable|}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase pathVariable.name}}{{/each}}({{#each pathVariables as |pathVariable|}}{{#unless @first}}, {{/unless}}({{type.java}}) key{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}{{#eq input.type "DTO"}}({{body}}){{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}({{body}}){{/eq}}{{/eq}}{{#eq input.type "DTOS"}}(List<{{body}}>){{/eq}}args[0]{{/if}});
break;
}
{{/if}}
{{/each}}
{{/if}}
{{/each}}
{{#each apiEntity.methods as |method|}}
{{#if (and (eq methodType "DEACTION") (eq method.pSDEServiceAPIMethod.pSDEAction.name deAction.name))}}
{{#unless method.parentApiEntities}}
{{#eq return.type "DTO"}}obj = {{/eq}}{{#eq return.type "SIMPLE"}}obj = {{/eq}}{{#eq return.type "USER"}}obj = {{/eq}}getClient().{{camelCase method.name}}{{#each pathVariables as |pathVariables|}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase pathVariables.name}}{{/each}}({{#each pathVariables as |pathVariable|}}{{#unless @first}}, {{/unless}}({{type.java}}) key{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}{{#eq input.type "DTO"}}({{body}}){{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}({{body}}){{/eq}}{{/eq}}{{#eq input.type "DTOS"}}(List<{{body}}>){{/eq}}args[0]{{/if}});
break;
{{/unless}}
{{/if}}
{{/each}}
{{/each}}
{{#each apiEntity.methods}}
{{/each}}
}
return obj;
}
@Override
public Object onInvokeMethod(IPSSubSysServiceAPIDEMethod iPSSubSysServiceAPIDEMethod, Map<String, Object> context, IDataEntityRuntime iDataEntityRuntime, IPSDEDataSet iPSDEDataSet, Object[] args) throws Throwable {
Object obj = null;
convertCondition((SearchContextDTO)args[0]);
String strActionName = iPSDEDataSet.getName().toLowerCase();
switch (strActionName) {
{{#each apiEntity.pSDataEntity.allPSDEDataSets as |dataSet|}}
case "{{lowerCase dataSet.name}}":
{{#each apiEntity.methods as |method|}}
{{#if (and (eq methodType "FETCH") (eq method.pSDEServiceAPIMethod.pSDEDataSet.name dataSet.name))}}
{{#each method.parentApiEntities as |parent|}}
{{#if (and (eq @index 0) @last)}}
if (context != null && context.containsKey("{{parent.majorPSDEServiceAPI.name}}")) {
obj = getClient().{{camelCase method.name}}{{#each method.pathVariables as |pathVariaable|}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase pathVariaable.name}}{{/each}}({{#each method.pathVariables}}{{#unless @first}}, {{/unless}}({{type.java}}) context.get("{{parent.majorPSDEServiceAPI.name}}"){{/each}}{{#if body}}{{#if method.pathVariables}}, {{/if}}(SearchContextDTO)args[0]{{/if}});
break;
}
{{/if}}
{{/each}}
{{/if}}
{{/each}}
{{#each apiEntity.methods as |method|}}
{{#if (and (eq methodType "FETCH") (eq method.pSDEServiceAPIMethod.pSDEDataSet.name dataSet.name))}}
{{#unless method.parentApiEntities}}
obj = getClient().{{camelCase method.name}}{{#each method.pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase method.name}}{{/each}}({{#each method.pathVariables}}{{#unless @first}}, {{/unless}}({{type.java}})key{{/each}}{{#if body}}{{#if method.pathVariables}}, {{/if}}(SearchContextDTO)args[0]{{/if}});
break;
{{/unless}}
{{/if}}
{{/each}}
{{/each}}
{{#each apiEntity.methods}}
{{/each}}
}
List recodes = new ArrayList();
SearchContextDTO dto = (SearchContextDTO) args[0];
if (obj != null && obj instanceof Page) {
Page ret = (Page) obj;
for (Object item : ret.getContent()) {
IEntityDTO entityDTO = iDataEntityRuntime.createEntity();
entityDTO.reload(item, true, false);
recodes.add(entityDTO);
}
return new PageImpl(recodes, dto.getPageable(), ret.getTotalElements());
}
return new PageImpl(recodes, dto.getPageable(), 0);
}
private void convertCondition(ISearchContextDTO dto){
dto.any().put("page", dto.getPageable().getPageNumber());
dto.any().put("size", dto.getPageable().getPageSize());
if (dto.getPageSort() != null&& dto.getPageSort()!=Sort.unsorted()) {
String strSort = "";
Iterator<Sort.Order> iterator = dto.getPageSort().iterator();
if (iterator.hasNext()) {
Sort.Order order = iterator.next();
if (StringUtils.isNotEmpty(strSort)) {
strSort += ";";
}
strSort += order.getProperty();
if (order.isAscending()) {
strSort += ",asc";
} else if (order.isDescending()) {
strSort += ",desc";
}
}
if (StringUtils.isNotEmpty(strSort)) {
dto.any().put("sort", strSort);
}
}
}
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase api.codeName}}.runtime.service;
import lombok.extern.slf4j.Slf4j;
import net.ibizsys.central.r8.service.R8SubSysServiceAPIDERuntime;
/**
* 提供外部容器启动服务能力
*/
@Slf4j
public class {{api.codeName}}R8SubSysServiceAPIDERuntime extends R8SubSysServiceAPIDERuntime {
}
\ No newline at end of file
package {{packageName}}.client.{{lowerCase api.codeName}}.runtime.service;
import lombok.extern.slf4j.Slf4j;
import net.ibizsys.central.r8.service.R8SubSysServiceAPIRuntime;
import net.ibizsys.central.service.ISubSysServiceAPIDERuntime;
import net.ibizsys.model.service.IPSSubSysServiceAPIDE;
import {{packageName}}.client.{{lowerCase api.codeName}}.runtime.service.dataentity.*;
/**
* 提供外部容器启动服务能力
*/
@Slf4j
public class {{api.codeName}}R8SubSysServiceAPIRuntime extends R8SubSysServiceAPIRuntime {
@Override
protected ISubSysServiceAPIDERuntime createSubSysServiceAPIDERuntime(IPSSubSysServiceAPIDE iPSSubSysServiceAPIDE) throws Exception {
String strEntityName = iPSSubSysServiceAPIDE.getName();
switch (strEntityName){
{{#each api.apiEntities}}
case "{{apiDataEntity.name}}":
return new {{apiDataEntity.codeName}}SubSysServiceAPIDERuntime();
{{/each}}
default:
return new RT4EBSXR8SubSysServiceAPIDERuntime();
}
}
}
\ No newline at end of file
package {{packageName}}.{{lowerCase apiEntity.api.codeName}}.client;
import {{packageName}}.{{lowerCase apiEntity.api.codeName}}.dto.{{apiEntity.codeName}}DTO;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import feign.FeignException;
import feign.hystrix.FallbackFactory;
import net.ibizsys.central.util.SearchContextDTO;
import net.ibizsys.runtime.dataentity.DataEntityRuntimeException;
import net.ibizsys.runtime.util.Errors;
import org.springframework.data.domain.Page;
import java.util.Collection;
import java.util.List;
/**
* 实体[{{apiEntity.codeName}}] 服务对象接口
*
*/
public class {{apiEntity.codeName}}Fallback implements FallbackFactory<{{apiEntity.codeName}}FeignClient> {
@Override
public {{apiEntity.codeName}}FeignClient create(Throwable cause) {
String errorMessage = "";
if (cause instanceof FeignException) {
FeignException ex = (FeignException) cause;
errorMessage = "[iBizRT客户端]调用异常,错误状态:" + ex.status() + "." + cause.getMessage();
} else if (cause instanceof HystrixTimeoutException) {
errorMessage = "[RT服务接口]调用超时。";
} else {
errorMessage = "[iBizRT客户端]异常,错误:" + cause.getMessage();
}
String finalErrorMessage = errorMessage;
return new {{apiEntity.codeName}}FeignClient(){
{{#each apiEntity.methods}}
{{!行为}}
{{#eq methodType "DEACTION"}}
public {{#eq return.type "DTO"}}{{apiEntity.codeName}}DTO{{/eq}}{{#eq return.type "DTOS"}}Page<{{apiEntity.codeName}}DTO>{{/eq}}{{#eq return.type "SIMPLE"}}Integer{{/eq}}{{#eq return.type "KEYFIELD"}}{{/eq}}{{#eq return.type "VOID"}}void{{/eq}}{{#eq return.type "USER"}}Object{{/eq}} {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}{{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}{{#eq input.type "DTO"}}{{body}}{{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}{{body}}{{/eq}}{{/eq}}{{#eq input.type "DTOS"}}List<{{body}}>{{/eq}} {{#eq input.type "DTO"}}{{camelCase body}}{{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}{{camelCase body}}{{/eq}}{{/eq}}{{#eq input.type "DTOS"}}list{{/eq}}{{/if}}){
throw new DataEntityRuntimeException(null,finalErrorMessage, Errors.INTERNALERROR, null);
}
{{/eq}}
{{!数据集}}
{{#eq methodType "FETCH"}}
public Page<{{apiEntity.codeName}}DTO> {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}{{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}SearchContextDTO context{{/if}}){
throw new DataEntityRuntimeException(null,finalErrorMessage, Errors.INTERNALERROR, null);
}
{{/eq}}
{{!SELECT法}}
{{#eq methodType "SELECT"}}
public Page<{{apiEntity.codeName}}DTO> {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}{{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}SearchContextDTO context{{/if}}){
throw new DataEntityRuntimeException(null,finalErrorMessage, Errors.INTERNALERROR, null);
}
{{/eq}}
{{/each}}
};
}
}
\ No newline at end of file
package {{packageName}}.{{lowerCase apiEntity.api.codeName}}.client;
import {{packageName}}.{{lowerCase apiEntity.api.codeName}}.dto.{{apiEntity.codeName}}DTO;
import net.ibizsys.central.util.SearchContextDTO;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Collection;
import java.util.List;
/**
* 实体[{{apiEntity.codeName}}] 服务对象接口
*
*/
public interface {{apiEntity.codeName}}FeignClient {
{{#each apiEntity.methods}}
@RequestMapping(method = RequestMethod.{{requestMethod}}, value = "{{requestPath}}")
{{!行为}}
{{#eq methodType "DEACTION"}}
{{#eq return.type "DTO"}}{{apiEntity.codeName}}DTO{{/eq}}{{#eq return.type "DTOS"}}Page<{{apiEntity.codeName}}DTO>{{/eq}}{{#eq return.type "SIMPLE"}}Integer{{/eq}}{{#eq return.type "KEYFIELD"}}{{/eq}}{{#eq return.type "VOID"}}void{{/eq}}{{#eq return.type "USER"}}Object{{/eq}} {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}@PathVariable("{{camelCase name}}") {{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}@RequestBody {{#eq input.type "DTO"}}{{body}}{{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}{{body}}{{/eq}}{{/eq}}{{#eq input.type "DTOS"}}List<{{body}}>{{/eq}} {{#eq input.type "DTO"}}{{camelCase body}}{{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}{{camelCase body}}{{/eq}}{{/eq}}{{#eq input.type "DTOS"}}list{{/eq}}{{/if}});
{{/eq}}
{{!数据集}}
{{#eq methodType "FETCH"}}
Page<{{apiEntity.codeName}}DTO> {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}@PathVariable("{{camelCase name}}") {{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}@RequestBody SearchContextDTO context{{/if}});
{{/eq}}
{{!SELECT法}}
{{#eq methodType "SELECT"}}
Page<{{apiEntity.codeName}}DTO> {{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}@PathVariable("{{camelCase name}}") {{type.java}} {{camelCase name}}{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}@RequestBody SearchContextDTO context{{/if}});
{{/eq}}
{{/each}}
}
\ No newline at end of file
package {{packageName}}.{{lowerCase apiEntity.api.codeName}}.client;
import net.ibizsys.api.helper.IgnorePrivInterceptor;
import net.ibizsys.api.helper.OutsideAccessorUtils;
import net.ibizsys.api.helper.SuperLoginClient;
import feign.Feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* {{apiEntity.entity.logicName}}
*
*/
@Configuration
public class {{apiEntity.codeName}}FeignClientConfiguration {
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.name:ibizrt4ebsx-rt4ebsx}")
String serviceValue;
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.system:f7ad7e05-9031-11eb-b882-00163e06e68c}")
String serviceSystem;
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.super:false}")
boolean superapi;
@Value("${ibiz.ref.service.uaa:ibizrt4ebsx-rt4ebsx}")
String uaaservice;
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.login:}")
String login;
@Value("${ibiz.ref.service.ibizrt4ebsx-rt4ebsx.password:}")
String password;
@Autowired
Feign.Builder builder;
@Autowired
OutsideAccessorUtils outsideAccessorUtils;
@Autowired
List<RequestInterceptor> defaultInterceptors;
@Bean
public {{apiEntity.codeName}}FeignClient {{camelCase apiEntity.codeName}}FeignClient() {
List<RequestInterceptor> requestInterceptors = new ArrayList<>();
requestInterceptors.addAll(defaultInterceptors);
RequestInterceptor systemInterceptor = new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
requestTemplate.header("srfsystemid", Collections.emptyList());
requestTemplate.header("srfsystemid", serviceSystem);
}
};
requestInterceptors.add(systemInterceptor);
//忽略权限
if (superapi) {
SuperLoginClient superLoginClient = outsideAccessorUtils.buildAccessor(SuperLoginClient.class, null, uaaservice, Arrays.asList(new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("srfsystemid", Collections.emptyList());
requestTemplate.header("srforgid", Collections.emptyList());
requestTemplate.header("Authorization", Collections.emptyList());
}
}));
RequestInterceptor ignorePrivInterceptor = new IgnorePrivInterceptor(superLoginClient, login, password);
requestInterceptors.add(ignorePrivInterceptor);
}
return outsideAccessorUtils.buildAccessor({{apiEntity.codeName}}FeignClient.class, new {{apiEntity.codeName}}Fallback(), serviceValue, requestInterceptors);
}
}
\ No newline at end of file
package {{packageName}}.{{lowerCase apiEntity.api.codeName}}.client;
import {{packageName}}.{{lowerCase apiEntity.api.codeName}}.dto.{{apiEntity.codeName}}DTO;
import net.ibizsys.central.dataentity.IDataEntityRuntime;
import net.ibizsys.central.util.IEntityDTO;
import net.ibizsys.central.util.SearchContextDTO;
import net.ibizsys.model.dataentity.action.IPSDEAction;
import net.ibizsys.model.dataentity.ds.IPSDEDataSet;
import net.ibizsys.model.service.IPSSubSysServiceAPIDEMethod;
import net.ibizsys.runtime.util.DataTypeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 实体[{{apiEntity.codeName}}] 对象
*
*/
public class {{apiEntity.codeName}}SubSysServiceAPIDERuntime extends {{packageName}}.{{lowerCase apiEntity.api.codeName}}.{{apiEntity.api.codeName}}R8SubSysServiceAPIDERuntime{
@Autowired
private {{apiEntity.codeName}}FeignClient client;
@Override
public Object invokeMethod(IPSSubSysServiceAPIDEMethod iPSSubSysServiceAPIDEMethod, IDataEntityRuntime iDataEntityRuntime, IPSDEAction iPSDEAction, Object[] args) throws Throwable {
Object key;
if (args[0] instanceof IEntityDTO) {
key = ((IEntityDTO) args[0]).get(iDataEntityRuntime.getKeyPSDEField().getName().toLowerCase());
} else {
key = args[0];
}
Object obj = null;
String strActionName = iPSDEAction.getName();
switch (strActionName){
{{#each apiEntity.methods}}
{{#unless parentApiEntities}}
{{#eq methodType "DEACTION"}}
case "{{name}}":
{{#eq return.type "DTO"}}obj = {{/eq}}{{#eq return.type "SIMPLE"}}obj = {{/eq}}{{#eq return.type "USER"}}obj = {{/eq}}client.{{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}({{type.java}})key{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}{{#eq input.type "DTO"}}({{body}}){{/eq}}{{#eq input.type "KEYFIELD"}}{{#eq pSDEAction.actionType "USERCUSTOM"}}({{body}}){{/eq}}{{/eq}}{{#eq input.type "DTOS"}}(List<{{body}}>){{/eq}}args[0]{{/if}});
break;
{{/eq}}
{{/unless}}
{{/each}}
}
return obj;
}
@Override
public Object invokeMethod(IPSSubSysServiceAPIDEMethod iPSSubSysServiceAPIDEMethod, IDataEntityRuntime iDataEntityRuntime, IPSDEDataSet iPSDEDataSet, Object[] args) throws Throwable {
Object obj = null;
String strActionName = iPSDEDataSet.getName();
switch (strActionName){
{{#each apiEntity.methods}}
{{#unless parentApiEntities}}
{{#eq methodType "FETCH"}}
case "{{name}}":
obj = client.{{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}({{#each pathVariables}}{{#unless @first}}, {{/unless}}({{type.java}})key{{/each}}{{#if body}}{{#if pathVariables}}, {{/if}}(SearchContextDTO)args[0]{{/if}});
break;
{{/eq}}
{{#eq methodType "SELECT"}}
case "{{name}}":
obj = client.{{camelCase name}}{{#each pathVariables}}{{#if @first}}By{{else}}And{{/if}}{{pascalCase name}}{{/each}}();
break;
{{/eq}}
{{/unless}}
{{/each}}
}
Map map = (Map) obj;
List recodes = new ArrayList();
long total = 0L;
if (map.containsKey("content")) {
List content = (List) map.get("content");
for (Object item : content) {
IEntityDTO entityDTO = iDataEntityRuntime.createEntity();
entityDTO.reload(item, true, false);
recodes.add(entityDTO);
}
}
if (map.containsKey("totalElements")) {
DataTypeUtils.getLongValue(map.get("totalElements"), 0L);
}
SearchContextDTO dto = (SearchContextDTO) args[0];
PageImpl page = new PageImpl(recodes, dto.getPageable(), total);
return page;
}
}
\ No newline at end of file
package {{packageName}}.{{apis}}.dto;
import java.sql.Timestamp;
import java.util.List;
import java.math.BigDecimal;
import net.ibizsys.central.util.EntityDTO;
import com.fasterxml.jackson.annotation.JsonIgnore;
import net.ibizsys.runtime.util.DataTypeUtils;
public class {{apiDto.codeName}} extends EntityDTO {
{{#each apiDto.apiDtoFields as |field|}}
/**
* {{field.logicName}}
*/
public final static String FIELD_{{upperCase field.codeName}} = "{{field.codeName}}";
/**
* 设置「{{field.logicName}}
*
* @param {{camelCase codeName}}
*/
@JsonIgnore
public {{apiDto.codeName}} set{{pascalCase codeName}}({{javaType}} {{camelCase codeName}}) {
this._set(FIELD_{{upperCase field.codeName}}, {{camelCase codeName}});
return this;
}
/**
* 获取「{{field.logicName}}」值
*
*/
@JsonIgnore
public {{javaType}} get{{pascalCase codeName}}() {
{{#if (or (eq javaType 'Integer') (eq javaType 'Long') (eq javaType 'Double') (eq javaType 'BigInteger') (eq javaType 'BigDecimal') (eq javaType 'Timestamp'))}}
try{
{{#if (eq javaType 'Timestamp')}}
return DataTypeUtils.getDateTimeValue(this._get(FIELD_{{upperCase field.codeName}}),null);
{{else}}
return DataTypeUtils.get{{javaType}}Value(this._get(FIELD_{{upperCase field.codeName}}),null);
{{/if}}
}catch (Exception e){
throw new RuntimeException(e);
}
{{else}}
return ({{javaType}}) this._get(FIELD_{{upperCase field.codeName}});
{{/if}}
}
/**
* 判断 「{{field.logicName}}」是否有值
*
*/
@JsonIgnore
public boolean contains{{pascalCase codeName}}() {
return this._contains(FIELD_{{upperCase field.codeName}});
}
/**
* 重置 「{{field.logicName}}
*
*/
@JsonIgnore
public {{apiDto.codeName}} reset{{pascalCase codeName}}() {
this._reset(FIELD_{{upperCase field.codeName}});
return this;
}
{{/each}}
}
package {{packageName}}.{{lowerCase api.codeName}};
import lombok.extern.slf4j.Slf4j;
import net.ibizsys.central.r8.service.R8SubSysServiceAPIDERuntime;
/**
* 提供外部容器启动服务能力
*/
@Slf4j
public class {{api.codeName}}R8SubSysServiceAPIDERuntime extends R8SubSysServiceAPIDERuntime {
}
\ No newline at end of file
package {{packageName}}.{{lowerCase api.codeName}};
import lombok.extern.slf4j.Slf4j;
import net.ibizsys.central.r8.service.R8SubSysServiceAPIRuntime;
import net.ibizsys.central.service.ISubSysServiceAPIDERuntime;
import net.ibizsys.model.service.IPSSubSysServiceAPIDE;
import net.ibizsys.api.rt4ebsx.client.*;
/**
* 提供外部容器启动服务能力
*/
@Slf4j
public class {{api.codeName}}R8SubSysServiceAPIRuntime extends R8SubSysServiceAPIRuntime {
@Override
protected ISubSysServiceAPIDERuntime createSubSysServiceAPIDERuntime(IPSSubSysServiceAPIDE iPSSubSysServiceAPIDE) throws Exception {
String strEntityName = iPSSubSysServiceAPIDE.getName();
switch (strEntityName){
{{#each api.apiEntities}}
case "{{apiDataEntity.name}}":
return new {{apiDataEntity.codeName}}SubSysServiceAPIDERuntime();
{{/each}}
default:
return new RT4EBSXR8SubSysServiceAPIDERuntime();
}
}
}
\ No newline at end of file
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册