index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/controller
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/controller/helper/package-info.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * * @author wangwp */ package ai.houyi.dorado.example.controller.helper;
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/filter/DemoFilter.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ package ai.houyi.dorado.example.filter; import ai.houyi.dorado.rest.http.Filter; import ai.houyi.dorado.rest.http.HttpRequest; import ai.houyi.dorado.rest.http.HttpResponse; /** * @author weiping wang * */ public class DemoFilter implements Filter { @Override public boolean preFilter(HttpRequest request, HttpResponse response) { System.out.println("execute demo filter"); response.sendError(403, "Forbidden"); return false; } }
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/filter/package-info.java
/** * */ /** * @author marta * */ package ai.houyi.dorado.example.filter;
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/model/Campaign.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ package ai.houyi.dorado.example.model; import javax.annotation.Generated; /** * @author wangweiping * */ public class Campaign { private int id; private String name; @Generated("SparkTools") private Campaign(Builder builder) { this.id = builder.id; this.name = builder.name; } public Campaign() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * Creates builder to build {@link Campaign}. * @return created builder */ @Generated("SparkTools") public static Builder builder() { return new Builder(); } /** * Builder to build {@link Campaign}. */ @Generated("SparkTools") public static final class Builder { private int id; private String name; private Builder() { } public Builder withId(int id) { this.id = id; return this; } public Builder withName(String name) { this.name = name; return this; } public Campaign build() { return new Campaign(this); } } }
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/model/TestResp.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.example.model; import javax.annotation.Generated; /** * * @author wangwp */ public class TestResp { private int code; private String msg; private Object data; public int getCode() { return code; } public String getMsg() { return msg; } public Object getData() { return data; } @Generated("SparkTools") private TestResp(Builder builder) { this.code = builder.code; this.msg = builder.msg; this.data = builder.data; } public TestResp() { } /** * Creates builder to build {@link TestResp}. * * @return created builder */ @Generated("SparkTools") public static Builder builder() { return new Builder(); } /** * Builder to build {@link TestResp}. */ @Generated("SparkTools") public static final class Builder { private int code; private String msg; private Object data; private Builder() { } public Builder withCode(int code) { this.code = code; return this; } public Builder withMsg(String msg) { this.msg = msg; return this; } public Builder withData(Object data) { this.data = data; return this; } public TestResp build() { return new TestResp(this); } } }
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/model/package-info.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ /** * @author wangweiping * */ package ai.houyi.dorado.example.model;
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/springboot/Application.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ package ai.houyi.dorado.example.springboot; import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan; import ai.houyi.dorado.springboot.DoradoSpringBootApplication; import ai.houyi.dorado.swagger.EnableSwagger; /** * @author wangweiping * */ @DoradoSpringBootApplication @EnableSwagger @ComponentScan({"ai.houyi.dorado.example"}) public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/springboot/package-info.java
/** * */ /** * @author marta * */ package ai.houyi.dorado.example.springboot;
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/EnableSwagger.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Documented @Retention(RUNTIME) @Target(TYPE) /** * * @author wangwp */ public @interface EnableSwagger { String[] value() default {}; }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/Reader.java
package ai.houyi.dorado.swagger; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.introspect.AnnotatedParameter; import com.fasterxml.jackson.databind.type.TypeFactory; import ai.houyi.dorado.rest.annotation.Consume; import ai.houyi.dorado.rest.annotation.DELETE; import ai.houyi.dorado.rest.annotation.GET; import ai.houyi.dorado.rest.annotation.HttpMethod; import ai.houyi.dorado.rest.annotation.POST; import ai.houyi.dorado.rest.annotation.PUT; import ai.houyi.dorado.rest.annotation.Produce; import ai.houyi.dorado.rest.http.HttpResponse; import ai.houyi.dorado.rest.util.MethodDescriptor; import ai.houyi.dorado.swagger.ext.SwaggerExtension; import ai.houyi.dorado.swagger.ext.SwaggerExtensions; import ai.houyi.dorado.swagger.utils.ReaderUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiKeyAuthDefinition; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Authorization; import io.swagger.annotations.AuthorizationScope; import io.swagger.annotations.BasicAuthDefinition; import io.swagger.annotations.Example; import io.swagger.annotations.ExampleProperty; import io.swagger.annotations.Info; import io.swagger.annotations.OAuth2Definition; import io.swagger.annotations.ResponseHeader; import io.swagger.annotations.Scope; import io.swagger.annotations.SwaggerDefinition; import io.swagger.converter.ModelConverters; import io.swagger.models.Contact; import io.swagger.models.ExternalDocs; import io.swagger.models.License; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Response; import io.swagger.models.Scheme; import io.swagger.models.SecurityRequirement; import io.swagger.models.Swagger; import io.swagger.models.Tag; import io.swagger.models.auth.In; import io.swagger.models.parameters.FormParameter; import io.swagger.models.parameters.HeaderParameter; import io.swagger.models.parameters.Parameter; import io.swagger.models.parameters.PathParameter; import io.swagger.models.parameters.QueryParameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import io.swagger.util.BaseReaderUtils; import io.swagger.util.ParameterProcessor; import io.swagger.util.PathUtils; import io.swagger.util.ReflectionUtils; public class Reader { private static final Logger LOGGER = LoggerFactory.getLogger(Reader.class); private static final String SUCCESSFUL_OPERATION = "successful operation"; // private static final String PATH_DELIMITER = "/"; private Swagger swagger; public Reader(Swagger swagger) { this.swagger = swagger; } public Swagger getSwagger() { return swagger; } /** * Scans a set of classes for both ReaderListeners and Swagger annotations. All * found listeners will be instantiated before any of the classes are scanned * for Swagger annotations - so they can be invoked accordingly. * * @param classes a set of classes to scan * @return the generated Swagger definition */ public Swagger read(Set<Class<?>> classes) { Set<Class<?>> sortedClasses = new TreeSet<Class<?>>(new Comparator<Class<?>>() { @Override public int compare(Class<?> class1, Class<?> class2) { if (class1.equals(class2)) { return 0; } else if (class1.isAssignableFrom(class2)) { return -1; } else if (class2.isAssignableFrom(class1)) { return 1; } return class1.getName().compareTo(class2.getName()); } }); sortedClasses.addAll(classes); // process SwaggerDefinitions first - so we get tags in desired order for (Class<?> cls : sortedClasses) { SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class); if (swaggerDefinition != null) { readSwaggerConfig(cls, swaggerDefinition); } } for (Class<?> cls : sortedClasses) { read(cls, new LinkedHashMap<String, Tag>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); } return swagger; } /** * Scans a single class for Swagger annotations - does not invoke * ReaderListeners */ public Swagger read(Class<?> cls) { SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class); if (swaggerDefinition != null) { readSwaggerConfig(cls, swaggerDefinition); } return read(cls, new LinkedHashMap<String, Tag>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); } protected Swagger read(Class<?> cls, Map<String, Tag> parentTags, List<Parameter> parentParameters) { return read(cls, parentTags, parentParameters, new HashSet<Class<?>>()); } @SuppressWarnings("deprecation") private Swagger read(Class<?> cls, Map<String, Tag> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) { // ClassDescriptor classDescriptor = ClassDescriptor.create(cls); Map<String, Tag> tags = new LinkedHashMap<String, Tag>(); List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); String[] consumes = new String[0]; String[] produces = new String[0]; final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class); Api api = ReflectionUtils.getAnnotation(cls, Api.class); boolean hasPathAnnotation = (ReflectionUtils.getAnnotation(cls, ai.houyi.dorado.rest.annotation.Path.class) != null); boolean hasApiAnnotation = (api != null); boolean isApiHidden = hasApiAnnotation && api.hidden(); // class readable only if annotated with ((@Path and @Api) or isSubresource ) - // and @Api not hidden boolean classReadable = ((hasPathAnnotation && hasApiAnnotation)) && !isApiHidden; // readable if classReadable or scanAll boolean readable = classReadable; if (!readable) { return swagger; } // api readable only if @Api present; cannot be hidden because checked in // classReadable. // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present Set<String> tagStrings = extractTags(api); for (String tagString : tagStrings) { Tag tag = new Tag().name(tagString); tags.put(tagString, tag); } for (String tagName : tags.keySet()) { swagger.tag(tags.get(tagName)); } if (!api.produces().isEmpty()) { produces = ReaderUtils.splitContentValues(new String[] { api.produces() }); } if (!api.consumes().isEmpty()) { consumes = ReaderUtils.splitContentValues(new String[] { api.consumes() }); } globalSchemes.addAll(parseSchemes(api.protocols())); for (Authorization auth : api.authorizations()) { if (auth.value() != null && !auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (scope.scope() != null && !scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } final List<Parameter> globalParameters = new ArrayList<Parameter>(); // build class/interface level @ApiResponse list ApiResponses classResponseAnnotation = ReflectionUtils.getAnnotation(cls, ApiResponses.class); List<ApiResponse> classApiResponses = new ArrayList<ApiResponse>(); if (classResponseAnnotation != null) { classApiResponses.addAll(Arrays.asList(classResponseAnnotation.value())); } // parse the method final ai.houyi.dorado.rest.annotation.Path apiPath = ReflectionUtils.getAnnotation(cls, ai.houyi.dorado.rest.annotation.Path.class); JavaType classType = TypeFactory.defaultInstance().constructType(cls); BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType); Method methods[] = cls.getMethods(); for (Method method : methods) { AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes()); if (ReflectionUtils.isOverriddenMethod(method, cls)) { continue; } ai.houyi.dorado.rest.annotation.Path methodPath = ReflectionUtils.getAnnotation(method, ai.houyi.dorado.rest.annotation.Path.class); // if(methodPath==null) continue; String operationPath = getPath(apiPath, methodPath); Map<String, String> regexMap = new LinkedHashMap<String, String>(); operationPath = PathUtils.parsePath(operationPath, regexMap); if (operationPath != null) { if (isIgnored(operationPath)) { continue; } final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain()); if (methodPath == null && httpMethod == null) continue; Operation operation = null; if (apiOperation != null || httpMethod != null || methodPath != null) { operation = parseMethod(cls, method, annotatedMethod, globalParameters, classApiResponses); } if (operation == null) { continue; } if (parentParameters != null) { for (Parameter param : parentParameters) { operation.parameter(param); } } for (Parameter param : operation.getParameters()) { if (regexMap.get(param.getName()) != null) { String pattern = regexMap.get(param.getName()); param.setPattern(pattern); } } if (apiOperation != null) { for (Scheme scheme : parseSchemes(apiOperation.protocols())) { operation.scheme(scheme); } } if (operation.getSchemes() == null || operation.getSchemes().isEmpty()) { for (Scheme scheme : globalSchemes) { operation.scheme(scheme); } } String[] apiConsumes = consumes; String[] apiProduces = produces; // can't continue without a valid http method // httpMethod = (httpMethod == null) ? parentMethod : httpMethod; if (httpMethod != null) { if (apiOperation != null) { for (String tag : apiOperation.tags()) { if (!"".equals(tag)) { operation.tag(tag); swagger.tag(new Tag().name(tag)); } } operation.getVendorExtensions() .putAll(BaseReaderUtils.parseExtensions(apiOperation.extensions())); } if (operation.getConsumes() == null) { for (String mediaType : apiConsumes) { operation.consumes(mediaType); } } if (operation.getProduces() == null) { for (String mediaType : apiProduces) { operation.produces(mediaType); } } if (operation.getTags() == null) { for (String tagString : tags.keySet()) { operation.tag(tagString); } } // Only add global @Api securities if operation doesn't already have more // specific securities if (operation.getSecurity() == null) { for (SecurityRequirement security : securities) { operation.security(security); } } Path path = swagger.getPath(operationPath); if (path == null) { path = new Path(); swagger.path(operationPath, path); } path.set(httpMethod, operation); readImplicitParameters(method, operation); readExternalDocs(method, operation); } } } return swagger; } private void readImplicitParameters(Method method, Operation operation) { processImplicitParams(ReflectionUtils.getAnnotation(method, ApiImplicitParams.class), operation); processImplicitParams(ReflectionUtils.getAnnotation(method.getDeclaringClass(), ApiImplicitParams.class), operation); } private void processImplicitParams(ApiImplicitParams implicitParams, Operation operation) { if (implicitParams != null) { for (ApiImplicitParam param : implicitParams.value()) { Parameter p = readImplicitParam(param); if (p != null) { operation.addParameter(p); } } } } private void readExternalDocs(Method method, Operation operation) { io.swagger.annotations.ExternalDocs externalDocs = ReflectionUtils.getAnnotation(method, io.swagger.annotations.ExternalDocs.class); if (externalDocs != null) { operation.setExternalDocs(new ExternalDocs(externalDocs.value(), externalDocs.url())); } } protected Parameter readImplicitParam(ApiImplicitParam param) { final Parameter p; if (param.paramType().equalsIgnoreCase("path")) { p = new PathParameter(); } else if (param.paramType().equalsIgnoreCase("query")) { p = new QueryParameter(); } else if (param.paramType().equalsIgnoreCase("form") || param.paramType().equalsIgnoreCase("formData")) { p = new FormParameter(); } else if (param.paramType().equalsIgnoreCase("body")) { p = null; } else if (param.paramType().equalsIgnoreCase("header")) { p = new HeaderParameter(); } else { LOGGER.warn("Unknown implicit parameter type: [{}]", param.paramType()); return null; } final Type type = param.dataTypeClass() == Void.class ? ReflectionUtils.typeFromString(param.dataType()) : param.dataTypeClass(); if (type == null) { LOGGER.error( "no dataType defined for implicit param `{}`! resolved parameter will not have a type defined, and will therefore be not compliant with spec. see https://github.com/swagger-api/swagger-core/issues/2556.", param.name()); } return ParameterProcessor.applyAnnotations(swagger, p, (type == null) ? String.class : type, Arrays.<Annotation>asList(param)); } @SuppressWarnings("deprecation") protected void readSwaggerConfig(Class<?> cls, SwaggerDefinition config) { if (!config.basePath().isEmpty()) { swagger.setBasePath(config.basePath()); } if (!config.host().isEmpty()) { swagger.setHost(config.host()); } readInfoConfig(config); for (String consume : config.consumes()) { if (StringUtils.isNotEmpty(consume)) { swagger.addConsumes(consume); } } for (String produce : config.produces()) { if (StringUtils.isNotEmpty(produce)) { swagger.addProduces(produce); } } for (OAuth2Definition oAuth2Config : config.securityDefinition().oAuth2Definitions()) { io.swagger.models.auth.OAuth2Definition oAuth2Definition = new io.swagger.models.auth.OAuth2Definition(); OAuth2Definition.Flow flow = oAuth2Config.flow(); if (flow.equals(OAuth2Definition.Flow.ACCESS_CODE)) { oAuth2Definition = oAuth2Definition.accessCode(oAuth2Config.authorizationUrl(), oAuth2Config.tokenUrl()); } else if (flow.equals(OAuth2Definition.Flow.APPLICATION)) { oAuth2Definition = oAuth2Definition.application(oAuth2Config.tokenUrl()); } else if (flow.equals(OAuth2Definition.Flow.IMPLICIT)) { oAuth2Definition = oAuth2Definition.implicit(oAuth2Config.authorizationUrl()); } else { oAuth2Definition = oAuth2Definition.password(oAuth2Config.tokenUrl()); } for (Scope scope : oAuth2Config.scopes()) { oAuth2Definition.addScope(scope.name(), scope.description()); } oAuth2Definition.setDescription(oAuth2Config.description()); swagger.addSecurityDefinition(oAuth2Config.key(), oAuth2Definition); } for (ApiKeyAuthDefinition[] apiKeyAuthConfigs : new ApiKeyAuthDefinition[][] { config.securityDefinition().apiKeyAuthDefintions(), config.securityDefinition().apiKeyAuthDefinitions() }) { for (ApiKeyAuthDefinition apiKeyAuthConfig : apiKeyAuthConfigs) { io.swagger.models.auth.ApiKeyAuthDefinition apiKeyAuthDefinition = new io.swagger.models.auth.ApiKeyAuthDefinition(); apiKeyAuthDefinition.setName(apiKeyAuthConfig.name()); apiKeyAuthDefinition.setIn(In.forValue(apiKeyAuthConfig.in().toValue())); apiKeyAuthDefinition.setDescription(apiKeyAuthConfig.description()); swagger.addSecurityDefinition(apiKeyAuthConfig.key(), apiKeyAuthDefinition); } } for (BasicAuthDefinition[] basicAuthConfigs : new BasicAuthDefinition[][] { config.securityDefinition().basicAuthDefinions(), config.securityDefinition().basicAuthDefinitions() }) { for (BasicAuthDefinition basicAuthConfig : basicAuthConfigs) { io.swagger.models.auth.BasicAuthDefinition basicAuthDefinition = new io.swagger.models.auth.BasicAuthDefinition(); basicAuthDefinition.setDescription(basicAuthConfig.description()); swagger.addSecurityDefinition(basicAuthConfig.key(), basicAuthDefinition); } } if (!config.externalDocs().value().isEmpty()) { ExternalDocs externalDocs = swagger.getExternalDocs(); if (externalDocs == null) { externalDocs = new ExternalDocs(); swagger.setExternalDocs(externalDocs); } externalDocs.setDescription(config.externalDocs().value()); if (!config.externalDocs().url().isEmpty()) { externalDocs.setUrl(config.externalDocs().url()); } } for (io.swagger.annotations.Tag tagConfig : config.tags()) { if (!tagConfig.name().isEmpty()) { Tag tag = new Tag(); tag.setName(tagConfig.name()); tag.setDescription(tagConfig.description()); if (!tagConfig.externalDocs().value().isEmpty()) { tag.setExternalDocs( new ExternalDocs(tagConfig.externalDocs().value(), tagConfig.externalDocs().url())); } tag.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(tagConfig.extensions())); swagger.addTag(tag); } } for (SwaggerDefinition.Scheme scheme : config.schemes()) { if (scheme != SwaggerDefinition.Scheme.DEFAULT) { swagger.addScheme(Scheme.forValue(scheme.name())); } } } protected void readInfoConfig(SwaggerDefinition config) { Info infoConfig = config.info(); io.swagger.models.Info info = swagger.getInfo(); if (info == null) { info = new io.swagger.models.Info(); swagger.setInfo(info); } if (!infoConfig.description().isEmpty()) { info.setDescription(infoConfig.description()); } if (!infoConfig.termsOfService().isEmpty()) { info.setTermsOfService(infoConfig.termsOfService()); } if (!infoConfig.title().isEmpty()) { info.setTitle(infoConfig.title()); } if (!infoConfig.version().isEmpty()) { info.setVersion(infoConfig.version()); } if (!infoConfig.contact().name().isEmpty()) { Contact contact = info.getContact(); if (contact == null) { contact = new Contact(); info.setContact(contact); } contact.setName(infoConfig.contact().name()); if (!infoConfig.contact().email().isEmpty()) { contact.setEmail(infoConfig.contact().email()); } if (!infoConfig.contact().url().isEmpty()) { contact.setUrl(infoConfig.contact().url()); } } if (!infoConfig.license().name().isEmpty()) { License license = info.getLicense(); if (license == null) { license = new License(); info.setLicense(license); } license.setName(infoConfig.license().name()); if (!infoConfig.license().url().isEmpty()) { license.setUrl(infoConfig.license().url()); } } info.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(infoConfig.extensions())); } protected Class<?> getSubResource(Method method) { final Class<?> rawType = method.getReturnType(); final Class<?> type; if (Class.class.equals(rawType)) { type = getClassArgument(method.getGenericReturnType()); if (type == null) { return null; } } else { type = rawType; } if (type.getAnnotation(Api.class) != null) { return type; } // For sub-resources that are not annotated with @Api, look for any HttpMethods. for (Method m : type.getMethods()) { if (extractOperationMethod(null, m, null) != null) { return type; } } return null; } private static Class<?> getClassArgument(Type cls) { if (cls instanceof ParameterizedType) { final ParameterizedType parameterized = (ParameterizedType) cls; final Type[] args = parameterized.getActualTypeArguments(); if (args.length != 1) { LOGGER.error("Unexpected class definition: {}", cls); return null; } final Type first = args[0]; if (first instanceof Class) { return (Class<?>) first; } else { return null; } } else { LOGGER.error("Unknown class definition: {}", cls); return null; } } protected Set<String> extractTags(Api api) { Set<String> output = new LinkedHashSet<String>(); boolean hasExplicitTags = false; for (String tag : api.tags()) { if (!"".equals(tag)) { hasExplicitTags = true; output.add(tag); } } if (!hasExplicitTags) { // derive tag from api path + description String tagString = api.value().replace("/", ""); if (!"".equals(tagString)) { output.add(tagString); } } return output; } private String getPath(ai.houyi.dorado.rest.annotation.Path classLevelPath, ai.houyi.dorado.rest.annotation.Path methodLevelPath) { if (classLevelPath == null && methodLevelPath == null) { return null; } StringBuilder b = new StringBuilder(); if (classLevelPath != null) { b.append(classLevelPath.value()); } if (methodLevelPath != null && !"/".equals(methodLevelPath.value())) { String methodPath = methodLevelPath.value(); if (!methodPath.startsWith("/") && !b.toString().endsWith("/")) { b.append("/"); } if (methodPath.endsWith("/")) { methodPath = methodPath.substring(0, methodPath.length() - 1); } b.append(methodPath); } String output = b.toString(); if (!output.startsWith("/")) { output = "/" + output; } if (output.endsWith("/") && output.length() > 1) { return output.substring(0, output.length() - 1); } else { return output; } } private Map<String, Property> parseResponseHeaders(ResponseHeader[] headers, JsonView jsonView) { Map<String, Property> responseHeaders = null; if (headers != null) { for (ResponseHeader header : headers) { String name = header.name(); if (!"".equals(name)) { if (responseHeaders == null) { responseHeaders = new LinkedHashMap<String, Property>(); } String description = header.description(); Class<?> cls = header.response(); if (!isVoid(cls)) { final Property property = ModelConverters.getInstance().readAsProperty(cls, jsonView); if (property != null) { Property responseProperty = ContainerWrapper.wrapContainer(header.responseContainer(), property, ContainerWrapper.ARRAY, ContainerWrapper.LIST, ContainerWrapper.SET); responseProperty.setDescription(description); responseHeaders.put(name, responseProperty); appendModels(cls); } } } } } return responseHeaders; } public Operation parseMethod(Method method) { JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass()); BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType); return parseMethod(classType.getClass(), method, bd.findMethod(method.getName(), method.getParameterTypes()), Collections.<Parameter>emptyList(), Collections.<ApiResponse>emptyList()); } @SuppressWarnings("deprecation") private Operation parseMethod(Class<?> cls, Method method, AnnotatedMethod annotatedMethod, List<Parameter> globalParameters, List<ApiResponse> classApiResponses) { MethodDescriptor methodDescriptor = MethodDescriptor.create(cls, method); Operation operation = new Operation(); if (annotatedMethod != null) { method = annotatedMethod.getAnnotated(); } ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId = null; // check if it's an inherited or implemented method. boolean methodInSuperType = false; if (!cls.isInterface()) { methodInSuperType = ReflectionUtils.findMethod(method, cls.getSuperclass()) != null; } if (!methodInSuperType) { for (Class<?> implementedInterface : cls.getInterfaces()) { methodInSuperType = ReflectionUtils.findMethod(method, implementedInterface) != null; if (methodInSuperType) { break; } } } operationId = this.getOperationId(method.getName()); String responseContainer = null; Type responseType = null; Map<String, Property> defaultResponseHeaders = new LinkedHashMap<String, Property>(); JsonView jsonViewAnnotation = ReflectionUtils.getAnnotation(method, JsonView.class); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (apiOperation.ignoreJsonView()) { jsonViewAnnotation = null; } if (!apiOperation.nickname().isEmpty()) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders(), jsonViewAnnotation); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (!isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } if (!apiOperation.consumes().isEmpty()) { String[] consumesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.consumes() }); for (String consume : consumesAr) { operation.consumes(consume); } } if (!apiOperation.produces().isEmpty()) { String[] producesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.produces() }); for (String produce : producesAr) { operation.produces(produce); } } } if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) { Response response = new Response().description(SUCCESSFUL_OPERATION); response.schema(new RefProperty(apiOperation.responseReference())); operation.addResponse(String.valueOf(apiOperation.code()), response); } else if (responseType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method {}", method); responseType = method.getGenericReturnType(); } if (isValidResponse(responseType)) { final Property property = ModelConverters.getInstance().readAsProperty(responseType, jsonViewAnnotation); if (property != null) { final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property); final int responseCode = (apiOperation == null) ? 200 : apiOperation.code(); operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION) .schema(responseProperty).headers(defaultResponseHeaders)); appendModelsWithJsonView(responseType, jsonViewAnnotation); } } operation.operationId(operationId); if (operation.getConsumes() == null || operation.getConsumes().isEmpty()) { final Consume consumes = ReflectionUtils.getAnnotation(method, Consume.class); if (consumes != null) { // for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) { operation.consumes(Arrays.asList(consumes.value())); // } } else { operation.consumes(methodDescriptor.consume()); } } if (operation.getProduces() == null || operation.getProduces().isEmpty()) { final Produce produces = ReflectionUtils.getAnnotation(method, Produce.class); if (produces != null) { // for (String mediaType : ReaderUtils.splitContentValues(produces.value())) { operation.produces(produces.value()); // } } else { operation.produces(methodDescriptor.produce()); } } List<ApiResponse> apiResponses = new ArrayList<ApiResponse>(); if (responseAnnotation != null) { apiResponses.addAll(Arrays.asList(responseAnnotation.value())); } Class<?>[] exceptionTypes = method.getExceptionTypes(); for (Class<?> exceptionType : exceptionTypes) { ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class); if (exceptionResponses != null) { apiResponses.addAll(Arrays.asList(exceptionResponses.value())); } } for (ApiResponse apiResponse : apiResponses) { addResponse(operation, apiResponse, jsonViewAnnotation); } // merge class level @ApiResponse for (ApiResponse apiResponse : classApiResponses) { String key = (apiResponse.code() == 0) ? "default" : String.valueOf(apiResponse.code()); if (operation.getResponses() != null && operation.getResponses().containsKey(key)) { continue; } addResponse(operation, apiResponse, jsonViewAnnotation); } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } // process parameters for (Parameter globalParameter : globalParameters) { operation.parameter(globalParameter); } Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method); // MethodDescriptor methodDescriptor = MethodDescriptor.create(cls, method); if (annotatedMethod == null) { Type[] genericParameterTypes = method.getGenericParameterTypes(); for (int i = 0; i < genericParameterTypes.length; i++) { final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]), methodDescriptor); for (Parameter parameter : parameters) { operation.parameter(parameter); } } } else { for (int i = 0; i < annotatedMethod.getParameterCount(); i++) { AnnotatedParameter param = annotatedMethod.getParameter(i); final Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]), methodDescriptor); for (Parameter parameter : parameters) { operation.parameter(parameter); } } } if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.defaultResponse(response); } processOperationDecorator(operation, method); return operation; } private List<Parameter> getParameters(Type type, List<Annotation> annotations, MethodDescriptor methodDescriptor) { final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain(); if (!chain.hasNext()) { return Collections.emptyList(); } LOGGER.debug("getParameters for {}", type); Set<Type> typesToSkip = new HashSet<Type>(); final SwaggerExtension extension = chain.next(); LOGGER.debug("trying extension {}", extension); final List<Parameter> parameters = extension.extractParameters(annotations, type, typesToSkip, chain, methodDescriptor); if (!parameters.isEmpty()) { final List<Parameter> processed = new ArrayList<Parameter>(parameters.size()); for (Parameter parameter : parameters) { if (ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations) != null) { processed.add(parameter); } } return processed; } else { LOGGER.debug("no parameter found, looking at body params"); final List<Parameter> body = new ArrayList<Parameter>(); if (!typesToSkip.contains(type)) { Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations); if (param != null) { body.add(param); } } return body; } } private void processOperationDecorator(Operation operation, Method method) { final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain(); if (chain.hasNext()) { SwaggerExtension extension = chain.next(); LOGGER.debug("trying to decorate operation: {}", extension); extension.decorateOperation(operation, method, chain); } } @SuppressWarnings("deprecation") private void addResponse(Operation operation, ApiResponse apiResponse, JsonView jsonView) { Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders(), jsonView); Map<String, Object> examples = parseExamples(apiResponse.examples()); Response response = new Response().description(apiResponse.message()).headers(responseHeaders); response.setExamples(examples); if (apiResponse.code() == 0) { operation.defaultResponse(response); } else { operation.response(apiResponse.code(), response); } if (StringUtils.isNotEmpty(apiResponse.reference())) { response.schema(new RefProperty(apiResponse.reference())); } else if (!isVoid(apiResponse.response())) { Type responseType = apiResponse.response(); final Property property = ModelConverters.getInstance().readAsProperty(responseType, jsonView); if (property != null) { response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property)); appendModels(responseType); } } } private Map<String, Object> parseExamples(Example examples) { if (examples == null) { return null; } Map<String, Object> map = null; for (ExampleProperty prop : examples.value()) { if (prop.mediaType().equals("") && prop.value().equals("")) { continue; } map = map == null ? new LinkedHashMap<String, Object>() : map; map.put(prop.mediaType(), prop.value()); } return map; } public String extractOperationMethod(ApiOperation apiOperation, Method method, Iterator<SwaggerExtension> chain) { if (apiOperation != null && !"".equals(apiOperation.httpMethod())) { return apiOperation.httpMethod().toLowerCase(); } else if (method.getAnnotation(GET.class) != null) { return "get"; } else if (method.getAnnotation(PUT.class) != null) { return "put"; } else if (method.getAnnotation(POST.class) != null) { return "post"; } else if (method.getAnnotation(DELETE.class) != null) { return "delete"; } else if (method.getAnnotation(HttpMethod.class) != null) { HttpMethod httpMethod = method.getAnnotation(HttpMethod.class); return httpMethod.value().toLowerCase(); } else { return null; } } /* * private String getHttpMethodFromCustomAnnotations(Method method) { for * (Annotation methodAnnotation : method.getAnnotations()) { HttpMethod * httpMethod = * methodAnnotation.annotationType().getAnnotation(HttpMethod.class); if * (httpMethod != null) { return httpMethod.value().toLowerCase(); } } return * null; } */ private static Set<Scheme> parseSchemes(String schemes) { final Set<Scheme> result = EnumSet.noneOf(Scheme.class); for (String item : StringUtils.trimToEmpty(schemes).split(",")) { final Scheme scheme = Scheme.forValue(StringUtils.trimToNull(item)); if (scheme != null) { result.add(scheme); } } return result; } private void appendModels(Type type) { final Map<String, Model> models = ModelConverters.getInstance().readAll(type); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } } private void appendModelsWithJsonView(Type type, JsonView annotation) { final Map<String, Model> models = ModelConverters.getInstance().readAll(type, annotation); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } } private static boolean isVoid(Type type) { final Class<?> cls = TypeFactory.defaultInstance().constructType(type).getRawClass(); return Void.class.isAssignableFrom(cls) || Void.TYPE.isAssignableFrom(cls); } private boolean isIgnored(String path) { /* * for (String item : config.getIgnoredRoutes()) { final int length = * item.length(); if (path.startsWith(item) && (path.length() == length || * path.startsWith(PATH_DELIMITER, length))) { return true; } } */ return false; } private static boolean isValidResponse(Type type) { if (type == null) { return false; } final JavaType javaType = TypeFactory.defaultInstance().constructType(type); if (isVoid(javaType)) { return false; } final Class<?> cls = javaType.getRawClass(); return !HttpResponse.class.isAssignableFrom(cls) && !isResourceClass(cls); } private static boolean isResourceClass(Class<?> cls) { return cls.getAnnotation(Api.class) != null; } /* * public ReaderConfig getConfig() { return config; } */ enum ContainerWrapper { LIST("list") { @Override protected Property doWrap(Property property) { return new ArrayProperty(property); } }, ARRAY("array") { @Override protected Property doWrap(Property property) { return new ArrayProperty(property); } }, MAP("map") { @Override protected Property doWrap(Property property) { return new MapProperty(property); } }, SET("set") { @Override protected Property doWrap(Property property) { ArrayProperty arrayProperty = new ArrayProperty(property); arrayProperty.setUniqueItems(true); return arrayProperty; } }; private final String container; ContainerWrapper(String container) { this.container = container; } public static Property wrapContainer(String container, Property property, ContainerWrapper... allowed) { final Set<ContainerWrapper> tmp = (allowed.length > 0) ? EnumSet.copyOf(Arrays.asList(allowed)) : EnumSet.allOf(ContainerWrapper.class); for (ContainerWrapper wrapper : tmp) { final Property prop = wrapper.wrap(container, property); if (prop != null) { return prop; } } return property; } public Property wrap(String container, Property property) { if (this.container.equalsIgnoreCase(container)) { return doWrap(property); } return null; } protected abstract Property doWrap(Property property); } protected String getOperationId(String operationId) { boolean operationIdUsed = existOperationId(operationId); String operationIdToFind = null; int counter = 0; while (operationIdUsed) { operationIdToFind = String.format("%s_%d", operationId, ++counter); operationIdUsed = existOperationId(operationIdToFind); } if (operationIdToFind != null) { operationId = operationIdToFind; } return operationId; } private boolean existOperationId(String operationId) { if (swagger == null) { return false; } if (swagger.getPaths() == null || swagger.getPaths().isEmpty()) { return false; } for (Path path : swagger.getPaths().values()) { for (Operation op : path.getOperations()) { if (operationId.equalsIgnoreCase(op.getOperationId())) { return true; } } } return false; } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/SwaggerFactory.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.rest.util.PackageScanner; import ai.houyi.dorado.swagger.ext.ApiContext; import ai.houyi.dorado.swagger.ext.ApiContextBuilder; import ai.houyi.dorado.swagger.ext.ApiKey; import io.swagger.models.Scheme; import io.swagger.models.SecurityRequirement; import io.swagger.models.Swagger; import io.swagger.models.auth.ApiKeyAuthDefinition; import io.swagger.models.auth.In; /** * * @author wangwp */ public class SwaggerFactory { private static Swagger swagger; private static ApiContextBuilder apiContextBuilder; private static ApiContext apiContext; private static boolean swaggerEnable = true; static { ServiceLoader<ApiContextBuilder> apiContextBuilders = ServiceLoader.load(ApiContextBuilder.class); ApiContextBuilder default_ctx_builder = apiContextBuilders.iterator().hasNext() ? apiContextBuilders.iterator().next() : null; try { if (Dorado.isEnableSpring) { apiContextBuilder = Dorado.beanContainer.getBean(ApiContextBuilder.class); apiContext = Dorado.beanContainer.getBean("swaggerApiContext"); if (apiContextBuilder == null) apiContextBuilder = default_ctx_builder; } else { apiContextBuilder = default_ctx_builder; } if (apiContext == null && apiContextBuilder != null) { apiContext = apiContextBuilder.buildApiContext(); } if (apiContext == null) swaggerEnable = false; } catch (Throwable ex) { // ignore this exception } } public static Swagger getSwagger() { if (!swaggerEnable) return new Swagger(); if (swagger != null) return swagger; Reader reader = new Reader(new Swagger()); String[] packages = null; Class<?> mainClass = Dorado.mainClass; EnableSwagger enableSwagger = mainClass.getAnnotation(EnableSwagger.class); if (enableSwagger != null) { packages = enableSwagger.value(); } if (packages == null || packages.length == 0) { packages = Dorado.serverConfig.scanPackages(); } if (packages == null || packages.length == 0) { packages = new String[] { mainClass.getPackage().getName() }; } if (packages == null || packages.length == 0) { throw new IllegalArgumentException("缺少scanPackages设置"); } Set<Class<?>> classes = new HashSet<>(); for (String pkg : packages) { try { classes.addAll(PackageScanner.scan(pkg)); } catch (Exception ex) { // ignore this ex } } Swagger _swagger = reader.read(classes); _swagger.setSchemes(Arrays.asList(Scheme.HTTP, Scheme.HTTPS)); ApiKey apiKey = apiContext.getApiKey(); if (apiKey != null) { ApiKeyAuthDefinition apiKeyAuth = new ApiKeyAuthDefinition(apiKey.getName(), In.forValue(apiKey.getIn() == null ? "header" : apiKey.getIn())); _swagger.securityDefinition("auth", apiKeyAuth); List<SecurityRequirement> securityRequirements = new ArrayList<>(); SecurityRequirement sr = new SecurityRequirement(); sr.requirement("auth"); securityRequirements.add(sr); _swagger.setSecurity(securityRequirements); } if (apiContext.getInfo() != null) _swagger.setInfo(apiContext.getInfo()); swagger = _swagger; return _swagger; } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/SwaggerResourceRegister.java
/* * Copyright 2012 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.rest.ResourceRegister; import ai.houyi.dorado.rest.router.UriRoutingRegistry; import ai.houyi.dorado.swagger.controller.SwaggerV2Controller; /** * @author weiping wang * */ public class SwaggerResourceRegister implements ResourceRegister { @Override public void register() { Class<?> mainClass = Dorado.mainClass; EnableSwagger enableSwagger = mainClass.getAnnotation(EnableSwagger.class); //如果不启用swagger,则不需要注册swagger相关服务 if (enableSwagger == null) return; UriRoutingRegistry.getInstance().register(SwaggerV2Controller.class); } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/controller/SwaggerV2Controller.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.controller; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import ai.houyi.dorado.rest.annotation.Controller; import ai.houyi.dorado.rest.annotation.Path; import ai.houyi.dorado.rest.annotation.Produce; import ai.houyi.dorado.swagger.SwaggerFactory; import io.swagger.models.Swagger; /** * * @author wangwp */ @Controller @Path("/api-docs") public class SwaggerV2Controller { private static ObjectMapper mapper = new ObjectMapper(); static { mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } @Path @Produce("application/json") public String defaultJSON() { try { return mapper.writeValueAsString(SwaggerFactory.getSwagger()); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } @Path("/swagger.yaml") @Produce("application/yaml") public Swagger listingWithYaml() { return SwaggerFactory.getSwagger(); } @Path("/swagger.json") @Produce("application/json") public String listingWithJson() { try { return mapper.writeValueAsString(SwaggerFactory.getSwagger()); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/controller/package-info.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * * @author wangwp */ package ai.houyi.dorado.swagger.controller;
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/ext/ApiContext.java
/* * Copyright 2017-2019 The OpenAds Project * * The OpenAds Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.ext; import io.swagger.models.Info; import javax.annotation.Generated; /** * @author weiping wang */ public class ApiContext { private Info info; private ApiKey apiKey; @Generated("SparkTools") private ApiContext(Builder builder) { this.info = builder.info; this.apiKey = builder.apiKey; } public Info getInfo() { return info; } public ApiKey getApiKey() { return apiKey; } /** * Creates builder to build {@link ApiContext}. * @return created builder */ @Generated("SparkTools") public static Builder builder() { return new Builder(); } /** * Builder to build {@link ApiContext}. */ @Generated("SparkTools") public static final class Builder { private Info info; private ApiKey apiKey; private Builder() { } public Builder withInfo(Info info) { this.info = info; return this; } public Builder withApiKey(ApiKey apiKey) { this.apiKey = apiKey; return this; } public ApiContext build() { return new ApiContext(this); } } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/ext/ApiContextBuilder.java
/* * Copyright 2017-2019 The OpenAds Project * * The OpenAds Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.ext; /** * @author weiping wang * */ public interface ApiContextBuilder { ApiContext buildApiContext(); }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/ext/ApiKey.java
/* * Copyright 2017-2019 The OpenAds Project * * The OpenAds Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.ext; import javax.annotation.Generated; /** * @author weiping wang */ public class ApiKey { private String name; //header or query private String in; @Generated("SparkTools") private ApiKey(Builder builder) { this.name = builder.name; this.in = builder.in; } public String getName() { return name; } public String getIn() { return in; } /** * Creates builder to build {@link ApiKey}. * @return created builder */ @Generated("SparkTools") public static Builder builder() { return new Builder(); } /** * Builder to build {@link ApiKey}. */ @Generated("SparkTools") public static final class Builder { private String name; private String in; private Builder() { } public Builder withName(String name) { this.name = name; return this; } public Builder withIn(String in) { this.in = in; return this; } public ApiKey build() { return new ApiKey(this); } } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/ext/DefaultParameterExtension.java
package ai.houyi.dorado.swagger.ext; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import com.fasterxml.jackson.databind.ObjectMapper; import ai.houyi.dorado.rest.annotation.CookieParam; import ai.houyi.dorado.rest.annotation.HeaderParam; import ai.houyi.dorado.rest.annotation.Path; import ai.houyi.dorado.rest.annotation.PathVariable; import ai.houyi.dorado.rest.annotation.RequestParam; import ai.houyi.dorado.rest.http.MultipartFile; import ai.houyi.dorado.rest.util.MethodDescriptor; import ai.houyi.dorado.rest.util.TypeUtils; import ai.houyi.dorado.rest.util.MethodDescriptor.MethodParameter; import io.swagger.converter.ModelConverters; import io.swagger.models.parameters.CookieParameter; import io.swagger.models.parameters.FormParameter; import io.swagger.models.parameters.HeaderParameter; import io.swagger.models.parameters.Parameter; import io.swagger.models.parameters.PathParameter; import io.swagger.models.parameters.QueryParameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.FileProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; import io.swagger.util.Json; public class DefaultParameterExtension implements SwaggerExtension { final ObjectMapper mapper = Json.mapper(); /** * Adds additional annotation processing support * * @param parameters * @param annotation * @param type * @param typesToSkip */ private void handleAdditionalAnnotation(List<Parameter> parameters, Annotation annotation, final Type type, Set<Type> typesToSkip) { // DO NOTHING } private Property createProperty(Type type) { return enforcePrimitive(ModelConverters.getInstance().readAsProperty(type), 0); } private Property enforcePrimitive(Property in, int level) { if (in instanceof RefProperty) { return new StringProperty(); } if (in instanceof ArrayProperty) { if (level == 0) { final ArrayProperty array = (ArrayProperty) in; array.setItems(enforcePrimitive(array.getItems(), level + 1)); } else { return new StringProperty(); } } return in; } @Override public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain, MethodDescriptor methodDescriptor) { if (shouldIgnoreType(type, typesToSkip)) { return new ArrayList<Parameter>(); } Path methodPathAnno = methodDescriptor.getMethod().getAnnotation(Path.class); String operationPath = methodPathAnno != null ? methodPathAnno.value() : null; List<Parameter> parameters = new ArrayList<Parameter>(); for (MethodParameter _parameter : methodDescriptor.getParameters()) { Class<?> parameterType = _parameter.getType(); Parameter parameter = null; Class<?> annotationType = _parameter.getAnnotationType(); if (annotationType == MultipartFile.class) { FormParameter fp = null; if (parameterType.isArray()) { fp = new FormParameter().type("array").name(_parameter.getName()); Property property = new FileProperty(); fp.setItems(property); } else { fp = new FormParameter().type("file").name(_parameter.getName()); } parameter = fp; } else if (annotationType == RequestParam.class) { QueryParameter fp = new QueryParameter().name(_parameter.getName()); Property schema = createProperty(type); if (schema != null) { fp.setProperty(schema); } parameter = fp; } else if (annotationType == PathVariable.class) { PathParameter fp = new PathParameter().name(_parameter.getName()); Property schema = createProperty(type); if (schema != null) { fp.setProperty(schema); } parameter = fp; } else if (annotationType == HeaderParam.class) { HeaderParameter hp = new HeaderParameter().name(_parameter.getName()); Property schema = createProperty(type); if (schema != null) { hp.setProperty(schema); } parameter = hp; } else if (annotationType == CookieParam.class) { CookieParameter cp = new CookieParameter().name(_parameter.getName()); Property schema = createProperty(type); if (schema != null) { cp.setProperty(schema); } parameter = cp; } else { handleAdditionalAnnotation(parameters, _parameter.getAnnotation(), type, typesToSkip); } if (parameter == null) { if (operationPath != null && operationPath.contains(String.format("{%s}", _parameter.getName()))) { PathParameter fp = new PathParameter().name(_parameter.getName()); Property schema = createProperty(type); if (schema != null) { fp.setProperty(schema); } parameter = fp; } else if (!isRequestBodyParam(_parameter)) { // 如果不是requestbody类型的参数,默认作为queryParameter QueryParameter fp = new QueryParameter().name(_parameter.getName()); Property schema = createProperty(type); if (schema != null) { fp.setProperty(schema); } parameter = fp; } } if (parameter != null) { parameters.add(parameter); } } return parameters; } private boolean isRequestBodyParam(MethodParameter _parameter) { Class<?> type = _parameter.getType(); if (byte[].class == type || InputStream.class == type) { return true; } if (TypeUtils.isSerializableType(type)) { return true; } return false; } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/ext/SwaggerExtension.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.ext; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.type.TypeFactory; import ai.houyi.dorado.rest.util.MethodDescriptor; import io.swagger.annotations.ApiOperation; import io.swagger.models.Operation; import io.swagger.models.parameters.Parameter; /** * * @author wangwp */ public interface SwaggerExtension { default public String extractOperationMethod(ApiOperation apiOperation, Method method, Iterator<SwaggerExtension> chain) { if (chain.hasNext()) { return chain.next().extractOperationMethod(apiOperation, method, chain); } else { return null; } } default public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain) { if (chain.hasNext()) { return chain.next().extractParameters(annotations, type, typesToSkip, chain); } else { return Collections.emptyList(); } } default public void decorateOperation(Operation operation, Method method, Iterator<SwaggerExtension> chain) { if (chain.hasNext()) { chain.next().decorateOperation(operation, method, chain); } } default boolean shouldIgnoreClass(Class<?> cls) { return false; } default boolean shouldIgnoreType(Type type, Set<Type> typesToSkip) { if (typesToSkip.contains(type)) { return true; } if (shouldIgnoreClass(constructType(type).getRawClass())) { typesToSkip.add(type); return true; } return false; } default JavaType constructType(Type type) { return TypeFactory.defaultInstance().constructType(type); } public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain, MethodDescriptor methodDescriptor); }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/ext/SwaggerExtensions.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.ext; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; /** * * @author wangwp */ public class SwaggerExtensions { private static List<SwaggerExtension> extensions = null; public static List<SwaggerExtension> getExtensions() { return extensions; } public static void setExtensions(List<SwaggerExtension> ext) { extensions = ext; } public static Iterator<SwaggerExtension> chain() { return extensions.iterator(); } static { extensions = new ArrayList<SwaggerExtension>(); ServiceLoader<SwaggerExtension> loader = ServiceLoader.load(SwaggerExtension.class); for (SwaggerExtension ext : loader) { extensions.add(ext); } extensions.add(new DefaultParameterExtension()); } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/ext/package-info.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * * @author wangwp */ package ai.houyi.dorado.swagger.ext;
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/utils/ReaderUtils.java
package ai.houyi.dorado.swagger.utils; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import ai.houyi.dorado.swagger.ext.SwaggerExtension; import ai.houyi.dorado.swagger.ext.SwaggerExtensions; import io.swagger.models.Swagger; import io.swagger.models.parameters.Parameter; import io.swagger.util.ParameterProcessor; import io.swagger.util.ReflectionUtils; public class ReaderUtils { /** * Collects constructor-level parameters from class. * * @param cls is a class for collecting * @param swagger is the instance of the Swagger * @return the collection of supported parameters */ public static List<Parameter> collectConstructorParameters(Class<?> cls, Swagger swagger) { if (cls.isLocalClass() || (cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers()))) { return Collections.emptyList(); } List<Parameter> selected = Collections.emptyList(); int maxParamsCount = 0; for (Constructor<?> constructor : cls.getDeclaredConstructors()) { if (!ReflectionUtils.isConstructorCompatible(constructor) && !ReflectionUtils.isInject(Arrays.asList(constructor.getDeclaredAnnotations()))) { continue; } final Type[] genericParameterTypes = constructor.getGenericParameterTypes(); final Annotation[][] annotations = constructor.getParameterAnnotations(); int paramsCount = 0; final List<Parameter> parameters = new ArrayList<Parameter>(); for (int i = 0; i < genericParameterTypes.length; i++) { final List<Annotation> tmpAnnotations = Arrays.asList(annotations[i]); if (isContext(tmpAnnotations)) { paramsCount++; } else { final Type genericParameterType = genericParameterTypes[i]; final List<Parameter> tmpParameters = collectParameters(genericParameterType, tmpAnnotations); if (tmpParameters.size() >= 1) { for (Parameter tmpParameter : tmpParameters) { if (ParameterProcessor.applyAnnotations(swagger, tmpParameter, genericParameterType, tmpAnnotations) != null) { parameters.add(tmpParameter); } } paramsCount++; } } } if (paramsCount >= maxParamsCount) { maxParamsCount = paramsCount; selected = parameters; } } return selected; } /** * Collects field-level parameters from class. * * @param cls is a class for collecting * @param swagger is the instance of the Swagger * @return the collection of supported parameters */ public static List<Parameter> collectFieldParameters(Class<?> cls, Swagger swagger) { final List<Parameter> parameters = new ArrayList<Parameter>(); for (Field field : ReflectionUtils.getDeclaredFields(cls)) { final List<Annotation> annotations = Arrays.asList(field.getAnnotations()); final Type genericType = field.getGenericType(); for (Parameter parameter : collectParameters(genericType, annotations)) { if (ParameterProcessor.applyAnnotations(swagger, parameter, genericType, annotations) != null) { parameters.add(parameter); } } } return parameters; } /** * Splits the provided array of strings into an array, using comma as the separator. * Also removes leading and trailing whitespace and omits empty strings from the results. * * @param strings is the provided array of strings * @return the resulted array of strings */ public static String[] splitContentValues(String[] strings) { final Set<String> result = new LinkedHashSet<String>(); for (String string : strings) { Iterables.addAll(result, Splitter.on(",").trimResults().omitEmptyStrings().split(string)); } return result.toArray(new String[result.size()]); } private static List<Parameter> collectParameters(Type type, List<Annotation> annotations) { final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain(); return chain.hasNext() ? chain.next().extractParameters(annotations, type, new HashSet<Type>(), chain) : Collections.<Parameter>emptyList(); } private static boolean isContext(List<Annotation> annotations) { return false; } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/utils/package-info.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * * @author wangwp */ package ai.houyi.dorado.swagger.utils;
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/yaml/YamlMessageBodyConverter.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.yaml; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import com.fasterxml.jackson.core.JsonProcessingException; import ai.houyi.dorado.rest.MessageBodyConverter; import ai.houyi.dorado.rest.annotation.Produce; import ai.houyi.dorado.rest.util.LogUtils; import io.swagger.util.Yaml; /** * * @author wangwp */ @Produce("application/yaml") public class YamlMessageBodyConverter implements MessageBodyConverter<Object> { @Override public byte[] writeMessageBody(Object t) { try { return Yaml.mapper().writeValueAsBytes(t); } catch (JsonProcessingException ex) { LogUtils.error(ex.getMessage(), ex); } return null; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Object readMessageBody(InputStream in, Type type) { try { return Yaml.mapper().readValue(in, (Class) type); } catch (IOException ex) { LogUtils.error(ex.getMessage(), ex); } return null; } }
0
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger/0.0.51/ai/houyi/dorado/swagger/yaml/package-info.java
/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * * @author wangwp */ package ai.houyi.dorado.swagger.yaml;
0
java-sources/ai/houyi/dorado-swagger-spring-boot-starter/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger-spring-boot-starter/0.0.51/ai/houyi/dorado/swagger/springboot/SwaggerAutoConfiguration.java
/* * Copyright 2017-2019 The OpenAds Project * * The OpenAds Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.springboot; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ai.houyi.dorado.swagger.ext.ApiContext; import ai.houyi.dorado.swagger.ext.ApiKey; import ai.houyi.dorado.swagger.springboot.SwaggerProperties.Contact; import io.swagger.models.Info; import io.swagger.models.License; /** * * @author weiping wang */ @Configuration @EnableConfigurationProperties(SwaggerProperties.class) public class SwaggerAutoConfiguration { @Autowired private SwaggerProperties swaggerConfig; @Bean(name = "swaggerApiContext") public ApiContext buildApiContext() { Info info = new Info(); info.title(swaggerConfig.getTitle()).description(swaggerConfig.getDescription()) .termsOfService(swaggerConfig.getTermsOfServiceUrl()).version(swaggerConfig.getVersion()); Contact contact = swaggerConfig.getContact(); if (contact != null) info.setContact(new io.swagger.models.Contact().email(contact.getEmail()).name(contact.getName()) .url(contact.getUrl())); info.setLicense(new License().name(swaggerConfig.getLicense()).url(swaggerConfig.getLicenseUrl())); ApiContext.Builder apiContextBuilder = ApiContext.builder().withInfo(info); ai.houyi.dorado.swagger.springboot.SwaggerProperties.ApiKey apiKey = swaggerConfig.getApiKey(); if (apiKey != null) { ApiKey _apiKey = ApiKey.builder().withIn(swaggerConfig.getApiKey().getIn()) .withName(swaggerConfig.getApiKey().getName()).build(); apiContextBuilder.withApiKey(_apiKey); } return apiContextBuilder.build(); } }
0
java-sources/ai/houyi/dorado-swagger-spring-boot-starter/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger-spring-boot-starter/0.0.51/ai/houyi/dorado/swagger/springboot/SwaggerProperties.java
/* * Copyright 2017-2019 The OpenAds Project * * The OpenAds Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.springboot; import org.springframework.boot.context.properties.ConfigurationProperties; /** * * @author weiping wang */ @ConfigurationProperties("dorado.swagger") public class SwaggerProperties { private String title; private String license; private String licenseUrl; private String termsOfServiceUrl; private String description; private String version; private Contact contact; private ApiKey apiKey; /** * @return the version */ public String getVersion() { return version; } /** * @param version the version to set */ public void setVersion(String version) { this.version = version; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } public static class Contact { private String name; private String email; private String url; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the url */ public String getUrl() { return url; } /** * @param url the url to set */ public void setUrl(String url) { this.url = url; } } public static class ApiKey { private String name = "Authorization"; private String in = "header"; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the in */ public String getIn() { return in; } /** * @param in the in to set */ public void setIn(String in) { this.in = in; } } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the license */ public String getLicense() { return license; } /** * @param license the license to set */ public void setLicense(String license) { this.license = license; } /** * @return the licenseUrl */ public String getLicenseUrl() { return licenseUrl; } /** * @param licenseUrl the licenseUrl to set */ public void setLicenseUrl(String licenseUrl) { this.licenseUrl = licenseUrl; } /** * @return the termsOfServiceUrl */ public String getTermsOfServiceUrl() { return termsOfServiceUrl; } /** * @param termsOfServiceUrl the termsOfServiceUrl to set */ public void setTermsOfServiceUrl(String termsOfServiceUrl) { this.termsOfServiceUrl = termsOfServiceUrl; } /** * @return the contact */ public Contact getContact() { return contact; } /** * @param contact the contact to set */ public void setContact(Contact contact) { this.contact = contact; } /** * @return the apiKey */ public ApiKey getApiKey() { return apiKey; } /** * @param apiKey the apiKey to set */ public void setApiKey(ApiKey apiKey) { this.apiKey = apiKey; } }
0
java-sources/ai/houyi/dorado-swagger-spring-boot-starter/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger-spring-boot-starter/0.0.51/ai/houyi/dorado/swagger/springboot/package-info.java
/* * Copyright 2017-2019 The OpenAds Project * * The OpenAds Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * * @author weiping wang */ package ai.houyi.dorado.swagger.springboot;
0
java-sources/ai/houyi/dorado-swagger-ui/0.0.51/ai/houyi/dorado/swagger
java-sources/ai/houyi/dorado-swagger-ui/0.0.51/ai/houyi/dorado/swagger/ui/SwaggerUIResourceRegister.java
/* * Copyright 2012 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.ui; import ai.houyi.dorado.rest.ResourceRegister; import ai.houyi.dorado.rest.router.UriRoutingRegistry; import ai.houyi.dorado.swagger.ui.controller.SwaggerUIController; /** * @author weiping wang * */ public class SwaggerUIResourceRegister implements ResourceRegister { @Override public void register() { UriRoutingRegistry.getInstance().register(SwaggerUIController.class); } }
0
java-sources/ai/houyi/dorado-swagger-ui/0.0.51/ai/houyi/dorado/swagger/ui
java-sources/ai/houyi/dorado-swagger-ui/0.0.51/ai/houyi/dorado/swagger/ui/controller/SwaggerUIController.java
/* * Copyright 2012 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package ai.houyi.dorado.swagger.ui.controller; import ai.houyi.dorado.rest.annotation.Controller; import ai.houyi.dorado.rest.annotation.GET; import ai.houyi.dorado.rest.annotation.Path; import ai.houyi.dorado.rest.http.HttpRequest; import ai.houyi.dorado.rest.http.HttpResponse; import ai.houyi.dorado.rest.util.ClassLoaderUtils; import ai.houyi.dorado.rest.util.IOUtils; /** * @author weiping wang * */ @Controller @Path("/swagger-ui.*") public class SwaggerUIController { private static final String RESOURCE_PREFIX = "META-INF/resources/webjars/swagger-ui"; @GET public void readStaticResource(HttpRequest request, HttpResponse response) { String uri = request.getRequestURI(); String resource = String.format("%s%s", RESOURCE_PREFIX, uri); byte[] data = IOUtils.readBytes(ClassLoaderUtils.getStream(resource)); if (uri.endsWith(".css")) { response.setHeader("content-type", "text/css;charset=UTF-8"); } else if (uri.endsWith(".html")) { response.setHeader("content-type", "text/html;charset=UTF-8"); } else if (uri.endsWith(".js")) { response.setHeader("content-type", "text/javascript;charset=UTF-8"); } else if (uri.endsWith(".map")) { //DO NOTHING } response.write(data); } }
0
java-sources/ai/houyi/dorado-swagger-ui/0.0.51/ai/houyi/dorado/swagger/ui
java-sources/ai/houyi/dorado-swagger-ui/0.0.51/ai/houyi/dorado/swagger/ui/controller/package-info.java
/* * Copyright 2012 The OpenDSP Project * * The OpenDSP Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * @author weiping wang * */ package ai.houyi.dorado.swagger.ui.controller;
0
java-sources/ai/hyacinth/framework/core-service-admin-server/0.5.24/ai/hyacinth/core/service/admin/server
java-sources/ai/hyacinth/framework/core-service-admin-server/0.5.24/ai/hyacinth/core/service/admin/server/boot/AdminServerApplication.java
package ai.hyacinth.core.service.admin.server.boot; import de.codecentric.boot.admin.server.config.EnableAdminServer; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; @SpringBootApplication @EnableAdminServer public class AdminServerApplication { public static void main(String[] args) { new SpringApplicationBuilder(AdminServerApplication.class) .web(WebApplicationType.REACTIVE) .run(args); } }
0
java-sources/ai/hyacinth/framework/core-service-api-support/0.5.24/ai/hyacinth/core/service/api/support
java-sources/ai/hyacinth/framework/core-service-api-support/0.5.24/ai/hyacinth/core/service/api/support/config/DefaultConfigLoader.java
package ai.hyacinth.core.service.api.support.config; import ai.hyacinth.core.service.module.loader.ConfigLoaderPostProcessor; public class DefaultConfigLoader extends ConfigLoaderPostProcessor {}
0
java-sources/ai/hyacinth/framework/core-service-api-support/0.5.24/ai/hyacinth/core/service/api/support
java-sources/ai/hyacinth/framework/core-service-api-support/0.5.24/ai/hyacinth/core/service/api/support/config/ServiceApiConfig.java
package ai.hyacinth.core.service.api.support.config; import feign.Logger; import feign.Retryer; import feign.codec.ErrorDecoder; import org.springframework.context.annotation.Bean; public class ServiceApiConfig { @Bean public ErrorDecoder errorDecoder() { return new ServiceApiErrorDecoder(); } @Bean public Logger.Level loggerLevel() { return Logger.Level.FULL; } @Bean public Retryer retryer() { return Retryer.NEVER_RETRY; // Retryer.Default(); } }
0
java-sources/ai/hyacinth/framework/core-service-api-support/0.5.24/ai/hyacinth/core/service/api/support
java-sources/ai/hyacinth/framework/core-service-api-support/0.5.24/ai/hyacinth/core/service/api/support/config/ServiceApiErrorDecoder.java
package ai.hyacinth.core.service.api.support.config; import ai.hyacinth.core.service.web.common.ServiceApiErrorResponse; import ai.hyacinth.core.service.web.common.ServiceApiException; import ai.hyacinth.core.service.web.common.error.CommonServiceErrorCode; import com.fasterxml.jackson.databind.ObjectMapper; import feign.Response; import feign.codec.ErrorDecoder; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Collections; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; @Slf4j public class ServiceApiErrorDecoder implements ErrorDecoder { @Autowired private ObjectMapper objectMapper; @Override public Exception decode(String methodKey, Response response) { if (isJsonType(response)) { try { ServiceApiErrorResponse errorResponse = objectMapper.readValue(response.body().asInputStream(), ServiceApiErrorResponse.class); return new ServiceApiException(response.status(), errorResponse); } catch (Exception parseError) { log.warn( "API calling error occurs but error payload is incompatible to parse.", parseError); return new ServiceApiException(CommonServiceErrorCode.UNSUPPORTED_MEDIA_TYPE, parseError); } } else { String text; try { text = IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.name()); } catch (Exception encodingError) { text = "Unknown error"; } return new ServiceApiException(CommonServiceErrorCode.INTERNAL_ERROR, text); } } private static boolean isJsonType(Response response) { Collection<String> typeValues = response.headers().getOrDefault(HttpHeaders.CONTENT_TYPE, Collections.emptyList()); if (typeValues.size() > 0) { String contentType = typeValues.iterator().next(); if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) { return true; } } return false; } }
0
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support/config/BusConfig.java
package ai.hyacinth.core.service.bus.support.config; import ai.hyacinth.core.service.bus.support.event.BusEvent; import ai.hyacinth.core.service.bus.support.service.BusService; import org.springframework.amqp.core.AmqpAdmin; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.cloud.bus.jackson.RemoteApplicationEventScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @RemoteApplicationEventScan(basePackageClasses = BusEvent.class) @ComponentScan(basePackageClasses = BusService.class) public class BusConfig { // @Bean // public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) { // return new RabbitAdmin(connectionFactory) { // @Override // public void initialize() { // while (true) { // might want to give up after some number of tries // try { // super.initialize(); // break; // } // catch (Exception e) { // System.out.println("Failed to declare elements: " + e.getCause().getCause().getMessage()); // try { // Thread.sleep(1_000); // } // catch (InterruptedException e1) { // Thread.currentThread().interrupt(); // } // } // } // } // }; // } }
0
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support/config/DefaultConfigLoader.java
package ai.hyacinth.core.service.bus.support.config; import ai.hyacinth.core.service.module.loader.ConfigLoaderPostProcessor; public class DefaultConfigLoader extends ConfigLoaderPostProcessor {}
0
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support/event/BusEvent.java
package ai.hyacinth.core.service.bus.support.event; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import javax.validation.constraints.NotNull; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.cloud.bus.event.RemoteApplicationEvent; @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @JsonPropertyOrder({"payloadType", "payload"}) public class BusEvent<PayloadClass> extends RemoteApplicationEvent { private String eventType; private PayloadClass payload; private String payloadType; // optional, a indication for payload format or version public BusEvent( Object source, String originService, @NotNull String destinationService, String eventType, @NotNull PayloadClass payload, @NotNull String payloadType) { super(source, originService, destinationService); this.eventType = eventType; this.payload = payload; this.payloadType = payloadType; } public BusEvent(Object source, String originService, String destinationService) { super(source, originService, destinationService); } @Override public String toString() { final StringBuilder sb = new StringBuilder("BusEvent{"); sb.append("eventType='").append(eventType).append('\''); sb.append(", payload=").append(payload); sb.append(", payloadType='").append(payloadType).append('\''); sb.append(", timestamp=").append(getTimestamp()); sb.append(", id='").append(getId()).append('\''); sb.append(", originService='").append(getOriginService()).append('\''); sb.append(", destinationService='").append(getDestinationService()).append('\''); sb.append('}'); return sb.toString(); } }
0
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support/service/BusService.java
package ai.hyacinth.core.service.bus.support.service; import ai.hyacinth.core.service.bus.support.event.BusEvent; public interface BusService { String ALL_SERVICES = "**"; <T> void publish(String targetService, String eventType, T payload); void publish(BusEvent<?> event); }
0
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support/service
java-sources/ai/hyacinth/framework/core-service-bus-support/0.5.24/ai/hyacinth/core/service/bus/support/service/impl/BusServiceImpl.java
package ai.hyacinth.core.service.bus.support.service.impl; import ai.hyacinth.core.service.bus.support.event.BusEvent; import ai.hyacinth.core.service.bus.support.service.BusService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.bus.BusProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; @Slf4j @Service public class BusServiceImpl implements BusService { @Autowired private ApplicationContext applicationContext; @Autowired private BusProperties busProperties; @Override public <T> void publish(String targetService, String eventType, T payload) { publish(createEvent(targetService, eventType, payload)); } private <T> BusEvent createEvent(String targetService, String eventType, T payload) { BusEvent<T> event = new BusEvent<>(this, busProperties.getId(), targetService); event.setEventType(eventType); event.setPayload(payload); event.setPayloadType(getPayloadType(payload)); return event; } private <T> String getPayloadType(T payload) { return payload != null ? payload.getClass().getName() : null; } @Override public void publish(BusEvent<?> event) { applicationContext.publishEvent(event); } @EventListener public void logBusEvent(BusEvent<?> busEvent) { // busEvent.getEventType(); log.info( "Bus event received: {}, sent-by-me: {}", busEvent, busEvent.getOriginService().equals(busProperties.getId())); } }
0
java-sources/ai/hyacinth/framework/core-service-cache-support/0.5.24/ai/hyacinth/core/service/cache/support
java-sources/ai/hyacinth/framework/core-service-cache-support/0.5.24/ai/hyacinth/core/service/cache/support/config/CacheConfig.java
package ai.hyacinth.core.service.cache.support.config; import ai.hyacinth.core.service.cache.support.service.CacheProviderLogger; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableCaching @Slf4j @ComponentScan(basePackageClasses = {CacheProviderLogger.class}) public class CacheConfig { }
0
java-sources/ai/hyacinth/framework/core-service-cache-support/0.5.24/ai/hyacinth/core/service/cache/support
java-sources/ai/hyacinth/framework/core-service-cache-support/0.5.24/ai/hyacinth/core/service/cache/support/config/DefaultConfigLoader.java
package ai.hyacinth.core.service.cache.support.config; import ai.hyacinth.core.service.module.loader.ConfigLoaderPostProcessor; public class DefaultConfigLoader extends ConfigLoaderPostProcessor {}
0
java-sources/ai/hyacinth/framework/core-service-cache-support/0.5.24/ai/hyacinth/core/service/cache/support
java-sources/ai/hyacinth/framework/core-service-cache-support/0.5.24/ai/hyacinth/core/service/cache/support/service/CacheProviderLogger.java
package ai.hyacinth.core.service.cache.support.service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.cache.CacheManager; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; @Slf4j @Component public class CacheProviderLogger implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware { private ApplicationContext ctx; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.ctx = applicationContext; } @Override public void onApplicationEvent(ApplicationReadyEvent event) { ConfigurableApplicationContext ctx = event.getApplicationContext(); if (ctx.equals(this.ctx)) { String cacheTypeProp = ctx.getEnvironment().getProperty("spring.cache.type"); log.info("Cache type is currently set to: {}", cacheTypeProp); String[] cmNames = ctx.getBeanNamesForType(CacheManager.class); for (String name : cmNames) { log.info("cacheManager {} loaded.", name); } log.info("cache-names: {}", ctx.getEnvironment().getProperty("spring.cache.cache-names")); } } }
0
java-sources/ai/hyacinth/framework/core-service-config-server/0.5.24/ai/hyacinth/core/service/config
java-sources/ai/hyacinth/framework/core-service-config-server/0.5.24/ai/hyacinth/core/service/config/server/ConfigServerApplication.java
package ai.hyacinth.core.service.config.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @EnableConfigServer @SpringBootApplication public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
0
java-sources/ai/hyacinth/framework/core-service-config-support/0.5.24/ai/hyacinth/core/service/config/support
java-sources/ai/hyacinth/framework/core-service-config-support/0.5.24/ai/hyacinth/core/service/config/support/config/DefaultConfigLoader.java
package ai.hyacinth.core.service.config.support.config; import ai.hyacinth.core.service.module.loader.ConfigLoaderPostProcessor; public class DefaultConfigLoader extends ConfigLoaderPostProcessor {}
0
java-sources/ai/hyacinth/framework/core-service-discovery-server/0.5.24/ai/hyacinth/core/service/discovery/server
java-sources/ai/hyacinth/framework/core-service-discovery-server/0.5.24/ai/hyacinth/core/service/discovery/server/boot/DiscoveryServerApplication.java
package ai.hyacinth.core.service.discovery.server.boot; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class DiscoveryServerApplication { public static void main(String[] args) { new SpringApplicationBuilder(DiscoveryServerApplication.class) .web(WebApplicationType.SERVLET) .run(args); } }
0
java-sources/ai/hyacinth/framework/core-service-discovery-support/0.5.24/ai/hyacinth/core/service/discovery/support
java-sources/ai/hyacinth/framework/core-service-discovery-support/0.5.24/ai/hyacinth/core/service/discovery/support/config/DefaultConfigLoader.java
package ai.hyacinth.core.service.discovery.support.config; import ai.hyacinth.core.service.module.loader.ConfigLoaderPostProcessor; public class DefaultConfigLoader extends ConfigLoaderPostProcessor {}
0
java-sources/ai/hyacinth/framework/core-service-discovery-support/0.5.24/ai/hyacinth/core/service/discovery/support
java-sources/ai/hyacinth/framework/core-service-discovery-support/0.5.24/ai/hyacinth/core/service/discovery/support/config/DiscoveryConfig.java
package ai.hyacinth.core.service.discovery.support.config; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; @Configuration @EnableDiscoveryClient public class DiscoveryConfig {}
0
java-sources/ai/hyacinth/framework/core-service-endpoint-support/0.5.24/ai/hyacinth/core/service/endpoint/support
java-sources/ai/hyacinth/framework/core-service-endpoint-support/0.5.24/ai/hyacinth/core/service/endpoint/support/config/EndpointConfig.java
package ai.hyacinth.core.service.endpoint.support.config; import ai.hyacinth.core.service.endpoint.support.errorhandler.ServiceControllerExceptionHandler; import ai.hyacinth.core.service.swagger.support.SwaggerConfig; import ai.hyacinth.core.service.web.support.config.WebConfig; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.client.RestTemplate; @Configuration @Import({SwaggerConfig.class, WebConfig.class, SchedulingConfig.class}) @ComponentScan(basePackageClasses = ServiceControllerExceptionHandler.class) public class EndpointConfig { @ConditionalOnMissingBean @LoadBalanced @Bean RestTemplate loadBalancedRestTemplate() { return new RestTemplate(); } }
0
java-sources/ai/hyacinth/framework/core-service-endpoint-support/0.5.24/ai/hyacinth/core/service/endpoint/support
java-sources/ai/hyacinth/framework/core-service-endpoint-support/0.5.24/ai/hyacinth/core/service/endpoint/support/config/SchedulingConfig.java
package ai.hyacinth.core.service.endpoint.support.config; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableAsync @EnableScheduling public class SchedulingConfig {}
0
java-sources/ai/hyacinth/framework/core-service-endpoint-support/0.5.24/ai/hyacinth/core/service/endpoint/support
java-sources/ai/hyacinth/framework/core-service-endpoint-support/0.5.24/ai/hyacinth/core/service/endpoint/support/errorhandler/ServiceApiErrorAttributes.java
package ai.hyacinth.core.service.endpoint.support.errorhandler; import ai.hyacinth.core.service.web.common.error.CommonServiceErrorCode; import ai.hyacinth.core.service.web.common.ServiceApiConstants; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; @Order(Ordered.HIGHEST_PRECEDENCE) @Component public class ServiceApiErrorAttributes implements ErrorAttributes { private ErrorAttributes delegate = new DefaultErrorAttributes(); @Value("${spring.application.name}") private String applicationName; @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String, Object> attrs = delegate.getErrorAttributes(webRequest, includeStackTrace); // ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest; // servletWebRequest.getNativeRequest(HttpServletRequest.class); String path = (String) attrs.get("path"); // rewrite response (including #404) if (path != null && path.startsWith(ServiceApiConstants.API_PREFIX + "/")) { Map<String, Object> originalError = new HashMap<>(attrs); Optional<HttpStatus> httpStatus = getHttpStatus(attrs); if (httpStatus.isPresent()) { int httpStatusCode = httpStatus.get().value(); attrs.put("code", "E90" + httpStatusCode); attrs.put("message", httpStatus.get().name()); } else { attrs.put("code", CommonServiceErrorCode.UNKNOWN_ERROR.getCode()); attrs.put("message", CommonServiceErrorCode.UNKNOWN_ERROR.getMessage()); } attrs.put("data", Collections.singletonMap("originalErrorAttributes", originalError)); attrs.put("status", "error"); attrs.put("service", applicationName); attrs.remove("error"); } return attrs; } private Optional<HttpStatus> getHttpStatus(Map<String, Object> attrs) { try { return Optional.of(HttpStatus.valueOf((Integer)attrs.get("status"))); } catch (Exception ex) { return Optional.empty(); } } @Override public Throwable getError(WebRequest webRequest) { return delegate.getError(webRequest); } }
0
java-sources/ai/hyacinth/framework/core-service-endpoint-support/0.5.24/ai/hyacinth/core/service/endpoint/support
java-sources/ai/hyacinth/framework/core-service-endpoint-support/0.5.24/ai/hyacinth/core/service/endpoint/support/errorhandler/ServiceControllerExceptionHandler.java
package ai.hyacinth.core.service.endpoint.support.errorhandler; import ai.hyacinth.core.service.web.common.ServiceApiConstants; import ai.hyacinth.core.service.web.common.ServiceApiErrorResponse; import ai.hyacinth.core.service.web.common.ServiceApiException; import ai.hyacinth.core.service.web.common.error.CommonServiceErrorCode; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; @ControllerAdvice @RequestMapping(ServiceApiConstants.API_PREFIX) public class ServiceControllerExceptionHandler { private static Logger logger = LoggerFactory.getLogger(ServiceControllerExceptionHandler.class); @ExceptionHandler(ServiceApiException.class) public ResponseEntity<ServiceApiErrorResponse> handle( ServiceApiException ex, HttpServletRequest servletRequest) { logger.error("handle ServiceApiException", ex); return toResponseEntity(ex, servletRequest); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public ResponseEntity<ServiceApiErrorResponse> handle( HttpRequestMethodNotSupportedException ex, HttpServletRequest servletRequest) { return toResponseEntity( new ServiceApiException(CommonServiceErrorCode.METHOD_NOT_ALLOWED), servletRequest); } @ExceptionHandler({ MissingServletRequestParameterException.class }) public ResponseEntity<ServiceApiErrorResponse> handle( MissingServletRequestParameterException ex, HttpServletRequest servletRequest) { Map<String, Object> errorDetails = new LinkedHashMap<>(); errorDetails.put("parameter", ex.getParameterName()); return toResponseEntity( new ServiceApiException(CommonServiceErrorCode.REQUEST_ERROR, errorDetails), servletRequest); } @ExceptionHandler({ HttpMessageNotReadableException.class }) public ResponseEntity<ServiceApiErrorResponse> handle( HttpMessageNotReadableException ex, HttpServletRequest servletRequest) { return toResponseEntity( new ServiceApiException(CommonServiceErrorCode.REQUEST_ERROR, Collections.emptyMap()), servletRequest); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ServiceApiErrorResponse> handle( MethodArgumentNotValidException ex, HttpServletRequest servletRequest) { Map<String, Object> errorDetails = new LinkedHashMap<>(); BindingResult br = ex.getBindingResult(); if (br.hasFieldErrors()) { errorDetails.put( "field", br.getFieldErrors().stream().map(FieldError::getField).collect(Collectors.toList())); } if (br.hasGlobalErrors()) { errorDetails.put( "global", br.getGlobalErrors().stream() .map(ObjectError::getObjectName) .collect(Collectors.toList())); } return toResponseEntity( new ServiceApiException(CommonServiceErrorCode.REQUEST_ERROR, errorDetails), servletRequest); } @ExceptionHandler(Exception.class) public ResponseEntity<ServiceApiErrorResponse> handle( Exception ex, HttpServletRequest servletRequest) { logger.error("handle Exception", ex); String errorDetails = ex.getMessage(); return toResponseEntity( new ServiceApiException(CommonServiceErrorCode.UNKNOWN_ERROR, errorDetails), servletRequest); } private ResponseEntity<ServiceApiErrorResponse> toResponseEntity( ServiceApiException ex, HttpServletRequest servletRequest) { return ResponseEntity.status(ex.getHttpStatusCode()) .body(fillErrorAttributes(ex.getErrorResponse(), servletRequest)); } @Value("${spring.application.name}") private String applicationName; private ServiceApiErrorResponse fillErrorAttributes( ServiceApiErrorResponse errorResponse, HttpServletRequest servletRequest) { if (errorResponse.getPath() == null) { errorResponse.setPath(servletRequest == null ? "" : servletRequest.getRequestURI()); } if (errorResponse.getTimestamp() == null) { errorResponse.setTimestamp(new Date()); } if (errorResponse.getService() == null) { errorResponse.setService(applicationName); } return errorResponse; } }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/boot/GatewayServerApplication.java
package ai.hyacinth.core.service.gateway.server.boot; import ai.hyacinth.core.service.gateway.server.config.GatewayConfig; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Import; @SpringBootApplication @Import({GatewayConfig.class}) @Slf4j public class GatewayServerApplication { public static void main(String[] args) { SpringApplication.run(GatewayServerApplication.class, args); } }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/config/GatewayConfig.java
package ai.hyacinth.core.service.gateway.server.config; import ai.hyacinth.core.service.discovery.support.config.DiscoveryConfig; import ai.hyacinth.core.service.gateway.server.configprops.GatewayServerProperties; import ai.hyacinth.core.service.gateway.server.jwt.JwtService; import ai.hyacinth.core.service.gateway.server.ratelimiter.SimpleRateLimiter; import ai.hyacinth.core.service.gateway.server.web.GatewayController; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({DiscoveryConfig.class, RouteConfig.class, SecurityConfig.class}) @ComponentScan( basePackageClasses = { GatewayConfig.class, GatewayController.class, JwtService.class, SimpleRateLimiter.class }) @EnableConfigurationProperties({GatewayServerProperties.class}) public class GatewayConfig {}
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/config/RouteConfig.java
package ai.hyacinth.core.service.gateway.server.config; import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; import ai.hyacinth.core.service.gateway.server.configprops.GatewayRateLimiterProperties; import ai.hyacinth.core.service.gateway.server.configprops.GatewayServerProperties; import ai.hyacinth.core.service.gateway.server.configprops.ResponsePostProcessingType; import ai.hyacinth.core.service.gateway.server.jwt.JwtService; import ai.hyacinth.core.service.gateway.server.payload.ApiSuccessPayload; import ai.hyacinth.core.service.gateway.server.ratelimiter.SimpleRateLimiter; import ai.hyacinth.core.service.gateway.server.security.DefaultAuthentication; import ai.hyacinth.core.service.gateway.server.security.DefaultGrantedAuthority; import ai.hyacinth.core.service.web.common.ServiceApiConstants; import ai.hyacinth.core.service.web.common.payload.AuthenticationResult; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.PredicateSpec; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder.Builder; import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpRequestDecorator; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.web.server.context.ServerSecurityContextRepository; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriTemplate; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Slf4j @Configuration public class RouteConfig { @Autowired private ObjectMapper mapper; @Autowired private ServerSecurityContextRepository securityContextRepository; @Autowired private JwtService jwtService; @Autowired private ResourceLoader resourceLoader; @Autowired private ApplicationContext applicationContext; @Bean @RefreshScope public RouteLocator customRouteLocator( RouteLocatorBuilder builder, GatewayServerProperties gatewayConfig) { final SimpleRateLimiter globalRateLimiter = buildRateLimiter(gatewayConfig.getRateLimiter(), true); Builder routes = builder.routes(); gatewayConfig.getRules().stream() // .filter(rule -> !StringUtils.isEmpty(rule.getService())) .forEach( rule -> { routes.route( route -> { PredicateSpec start = route; if (rule.getMethod() != null) { start = route.method(rule.getMethod()).and(); } return start .path(rule.getPath()) .filters( f -> { final SimpleRateLimiter ruleRateLimiter = buildRateLimiter(rule.getRateLimiter(), false); if (ruleRateLimiter != null) { f.requestRateLimiter( (config) -> { config.setRateLimiter(ruleRateLimiter); }); } if (globalRateLimiter != null) { f.requestRateLimiter( (config) -> { config.setRateLimiter(globalRateLimiter); config.setDenyEmptyKey(false); }); } f.filter(rewriteRequestPath(rule.getUri())); // setPath(rule.getUri()); f.filter(removeSensitiveHttpHeaders()); f.filter(rewriteRequestHeader()); f.filter(rewriteRequestParams(rule.getRequestParam())); f.filter( rewriteRequestBody( rule.getRequestBody(), rule.getRequestBodyJson())); if (rule.getPostProcessing().size() > 0) { f.modifyResponseBody( String.class, String.class, rewriteSuccessPayload(rule.getPostProcessing())); } return f; }) .uri( StringUtils.isEmpty(rule.getService()) ? "forward:///" : "lb://" + rule.getService()); }); }); return routes.build(); } private SimpleRateLimiter buildRateLimiter( GatewayRateLimiterProperties rateLimiterProperties, boolean global) { SimpleRateLimiter rateLimiter = null; if (rateLimiterProperties.getReplenishRate() != null) { rateLimiter = applicationContext.getBean(SimpleRateLimiter.class); rateLimiter.setGlobal(global); rateLimiter.setReplenishPeriod(rateLimiterProperties.getReplenishPeriod()); rateLimiter.setReplenishRate(rateLimiterProperties.getReplenishRate()); } return rateLimiter; } private GatewayFilter rewriteRequestPath(final String uriTemplateText) { // please refer to class SetPathGatewayFilterFactory return (exchange, chain) -> ReactiveSecurityContextHolder.getContext() .map(context -> context.getAuthentication().getPrincipal()) .defaultIfEmpty("") .map(String::valueOf) .map( principal -> { ServerHttpRequest req = exchange.getRequest(); ServerWebExchangeUtils.addOriginalRequestUrl(exchange, req.getURI()); final UriTemplate uriTemplate = new UriTemplate( uriTemplateText.replace(PRINCIPAL_PLACEHOLDER_VAR, principal)); Map<String, String> uriVariables = ServerWebExchangeUtils.getUriTemplateVariables(exchange); URI uri = uriTemplate.expand(uriVariables); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri); String newPath = uri.getRawPath(); return req.mutate().path(newPath).build(); }) .flatMap( request -> { return chain.filter(exchange.mutate().request(request).build()); }); } private GatewayFilter rewriteRequestHeader() { return (exchange, chain) -> ReactiveSecurityContextHolder.getContext() .map(context -> String.valueOf(context.getAuthentication().getPrincipal())) .map(principle -> setPrincipleHeader(exchange, principle)) .map(request -> exchange.mutate().request(request).build()) .defaultIfEmpty(exchange) .flatMap(chain::filter); } private GatewayFilter removeSensitiveHttpHeaders() { return (exchange, chain) -> Mono.fromCallable( () -> exchange .mutate() .request(exchange.getRequest().mutate().headers(this::resetHeaders).build()) .build()) .flatMap(chain::filter); } private final List<String> RESET_HEADER_NAMES = Arrays.asList( // security ServiceApiConstants.HTTP_HEADER_AUTHENTICATED_PRINCIPLE, HttpHeaders.AUTHORIZATION, HttpHeaders.COOKIE, HttpHeaders.SET_COOKIE, // non-proxy HttpHeaders.CONNECTION, HttpHeaders.TRANSFER_ENCODING, HttpHeaders.TRAILER, HttpHeaders.UPGRADE, // others "Keep-Alive", "Proxy-Connection"); private void resetHeaders(HttpHeaders headers) { RESET_HEADER_NAMES.forEach(headers::remove); } private ServerHttpRequest setPrincipleHeader(ServerWebExchange exchange, String principleId) { return exchange .getRequest() .mutate() .headers( headers -> { headers.set(ServiceApiConstants.HTTP_HEADER_AUTHENTICATED_PRINCIPLE, principleId); }) .build(); } @SuppressWarnings("unchecked") private GatewayFilter rewriteRequestBody( final Map<String, Object> requestBody, String requestBodyJson) { return (exchange, chain) -> { if (requestBody.size() > 0 || requestBodyJson != null) { MediaType mediaType = exchange.getRequest().getHeaders().getContentType(); if (isJsonType(mediaType)) { ServerHttpRequestDecorator decorator = createRequestBodyRewriteDecorator(requestBody, exchange); return chain.filter(exchange.mutate().request(decorator).build()); } } return chain.filter(exchange); }; } private ServerHttpRequestDecorator createRequestBodyRewriteDecorator( Map<String, Object> requestBody, ServerWebExchange exchange) { return new ServerHttpRequestDecorator(exchange.getRequest()) { @Override public HttpHeaders getHeaders() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.putAll(getDelegate().getHeaders()); httpHeaders.remove(HttpHeaders.CONTENT_LENGTH); return httpHeaders; } @Override public Flux<DataBuffer> getBody() { Flux<InputStream> m1 = getDelegate() .getBody() .buffer() .map(df -> exchange.getResponse().bufferFactory().join(df).asInputStream()); Mono<Object> m2 = ReactiveSecurityContextHolder.getContext() .map(context -> context.getAuthentication().getPrincipal()) .defaultIfEmpty(""); return Flux.zip(m1, Flux.from(m2)) .map( (tuple) -> { try { @SuppressWarnings("unchecked") Map<String, Object> originalBody = mapper.readValue(tuple.getT1(), Map.class); requestBody.forEach( (key, value) -> { Object jsonValue = value; if (value instanceof String) { String valueText = (String) value; boolean placeholderOnly = valueText.equals(PRINCIPAL_PLACEHOLDER_VAR); if (placeholderOnly) { jsonValue = tuple.getT2(); } else { jsonValue = valueText.replace( PRINCIPAL_PLACEHOLDER_VAR, String.valueOf(tuple.getT2())); } } originalBody.put(key, jsonValue); }); byte[] content = mapper.writeValueAsBytes(originalBody); return exchange.getResponse().bufferFactory().wrap(content); } catch (Exception ex) { log.error("request payload json injection failed.", ex); throw new IllegalStateException(); // abort } }); } }; } private static final String PRINCIPAL_PLACEHOLDER_VAR = "${" + ServiceApiConstants.HTTP_HEADER_AUTHENTICATED_PRINCIPLE + "}"; private GatewayFilter rewriteRequestParams(final Map<String, String> requestParameters) { return (exchange, chain) -> { if (requestParameters.size() > 0) { return ReactiveSecurityContextHolder.getContext() .map(context -> context.getAuthentication().getPrincipal()) .map(String::valueOf) .defaultIfEmpty("") .map( principal -> { MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); LinkedMultiValueMap<String, String> mutatedQueryParams = new LinkedMultiValueMap<>(queryParams); requestParameters.forEach( (key, value) -> { mutatedQueryParams.remove(key); mutatedQueryParams.add( key, String.valueOf(value).replace(PRINCIPAL_PLACEHOLDER_VAR, principal)); }); URI mutatedUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()) .replaceQueryParams(mutatedQueryParams) .build() .toUri(); return mutatedUri; }) .map(mutatedUri -> exchange.getRequest().mutate().uri(mutatedUri).build()) .flatMap( mutatedRequest -> chain.filter(exchange.mutate().request(mutatedRequest).build())); } else { return chain.filter(exchange); } }; } private RewriteFunction<String, String> rewriteSuccessPayload( final List<ResponsePostProcessingType> processingList) { boolean authCookie = processingList.contains(ResponsePostProcessingType.AUTHENTICATION_COOKIE); boolean authJwt = processingList.contains(ResponsePostProcessingType.AUTHENTICATION_JWT); boolean apiWrapping = processingList.contains(ResponsePostProcessingType.API); boolean payloadAsAuth = authCookie || authJwt; return (exchange, input) -> { HttpStatus statusCode = exchange.getResponse().getStatusCode(); if (statusCode.is2xxSuccessful()) { HttpHeaders headers = exchange.getResponse().getHeaders(); MediaType contentType = headers.getContentType(); if (isJsonType(contentType)) { if (input.length() > 0) { try { Mono<Void> saveMono = Mono.empty(); String data = input; // fast-mode raw json string if (payloadAsAuth) { AuthenticationResult<?> payload = fromJson(input, AuthenticationResult.class); DefaultAuthentication authentication = new DefaultAuthentication(); authentication.setAuthenticated(true); authentication.setPrincipal(payload.getPrincipal()); authentication.setName(String.valueOf(payload.getPrincipal())); authentication.setAuthorities( payload.getAuthorities().stream() .map(DefaultGrantedAuthority::new) .collect(Collectors.toList())); if (authCookie) { SecurityContext securityContext = new SecurityContextImpl(authentication); saveMono = securityContextRepository .save(exchange, securityContext) .subscriberContext( ReactiveSecurityContextHolder.withSecurityContext( Mono.just(securityContext))); data = null; // clear authentication details } if (authJwt) { String token = jwtService.createToken(authentication); data = String.format("{\"token\":\"%s\"}", token); } } if (apiWrapping) { ApiSuccessPayload response = new ApiSuccessPayload(); response.setData(data); data = mapper.writeValueAsString(response); } return saveMono.then(Mono.just(data)); } catch (JsonProcessingException e) { log.error("error while wrapping successful response payload: {}", input); } } } } else if (statusCode.is4xxClientError()) { // always set http status to 2xx while api calls pass through gateway // {"status":"error"} is set in response payload when error occurs in service endpoint. // refer to web-support module exchange.getResponse().setStatusCode(HttpStatus.OK); } else { log.warn("unknown status code: {}, content: {}", statusCode.toString(), input); } return Mono.just(input); }; } private <T> T fromJson(String input, Class<T> inputClass) { try { return mapper.readValue(input, inputClass); } catch (Exception ex) { throw new IllegalStateException("input payload cannot be parsed into " + inputClass, ex); } } private boolean isJsonType(MediaType contentType) { return contentType != null && (contentType.equals(MediaType.APPLICATION_JSON) || contentType.equals(MediaType.APPLICATION_JSON_UTF8)); } }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/config/SecurityConfig.java
package ai.hyacinth.core.service.gateway.server.config; import ai.hyacinth.core.service.gateway.server.configprops.GatewaySecurityProperties; import ai.hyacinth.core.service.gateway.server.configprops.GatewayServerProperties; import ai.hyacinth.core.service.gateway.server.jwt.JwtAuthenticationWebFilter; import java.util.List; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.security.authorization.AuthorizationDecision; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.SecurityWebFiltersOrder; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.config.web.server.ServerHttpSecurity.AuthorizeExchangeSpec; import org.springframework.security.config.web.server.ServerHttpSecurity.AuthorizeExchangeSpec.Access; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.WebFilterExchange; import org.springframework.security.web.server.authentication.logout.HttpStatusReturningServerLogoutSuccessHandler; import org.springframework.security.web.server.context.ServerSecurityContextRepository; import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository; import org.springframework.util.StringUtils; import reactor.core.publisher.Mono; @EnableWebFluxSecurity @Slf4j public class SecurityConfig { /** * ANY is artificial authority used to be applied on route rules instead of being assigned on a * user. */ private static final String ANY_AUTHORITY = "ANY"; @Bean public ServerSecurityContextRepository serverSecurityContextRepository() { return new WebSessionServerSecurityContextRepository(); } @Bean @RefreshScope public SecurityWebFilterChain configureSecurityFilterChain( ServerHttpSecurity http, ApplicationContext applicationContext, ServerSecurityContextRepository serverSecurityContextRepository, GatewayServerProperties gatewayServerProperties) { JwtAuthenticationWebFilter jwtAuthenticationWebFilter = new JwtAuthenticationWebFilter(); applicationContext.getAutowireCapableBeanFactory().autowireBean(jwtAuthenticationWebFilter); http.addFilterAt(jwtAuthenticationWebFilter, SecurityWebFiltersOrder.HTTP_BASIC); AuthorizeExchangeSpec authExchange = http.authorizeExchange(); final GatewaySecurityProperties securityProperties = gatewayServerProperties.getSecurity(); gatewayServerProperties .getRules() .forEach( r -> { List<String> ruleAuthorities = r.getAuthority().stream().map(String::toUpperCase).collect(Collectors.toList()); Access xs = r.getMethod() != null ? authExchange.pathMatchers(r.getMethod(), r.getPath()) : authExchange.pathMatchers(r.getPath()); if (ruleAuthorities.contains(ANY_AUTHORITY)) { xs.permitAll(); } else { if (ruleAuthorities.isEmpty()) { if (securityProperties.isAuthenticatedRequired()) { xs.authenticated(); } else { xs.permitAll(); } } else if (ruleAuthorities.size() == 1) { xs.hasAuthority(ruleAuthorities.get(0)); } else { xs.access( (authentication, e) -> authentication .filter(Authentication::isAuthenticated) .flatMapIterable(Authentication::getAuthorities) .map(GrantedAuthority::getAuthority) .filter(ruleAuthorities::contains) .hasElements() .map(AuthorizationDecision::new) .defaultIfEmpty(new AuthorizationDecision(false))); } } }); authExchange.anyExchange().denyAll(); http.csrf().disable().httpBasic().disable().formLogin().disable(); if (!StringUtils.isEmpty(securityProperties.getLogoutUrl())) { http.logout() .logoutUrl(securityProperties.getLogoutUrl()) .logoutSuccessHandler( new HttpStatusReturningServerLogoutSuccessHandler() { @Override public Mono<Void> onLogoutSuccess( WebFilterExchange exchange, Authentication authentication) { exchange.getExchange().getResponse().setStatusCode(HttpStatus.OK); return exchange .getExchange() .getResponse() .writeWith( Mono.just( exchange .getExchange() .getResponse() .bufferFactory() .wrap(securityProperties.getLogoutPayload().getBytes()))); } }); } return http.securityContextRepository(serverSecurityContextRepository).build(); } }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/configprops/GatewayJwtProperties.java
package ai.hyacinth.core.service.gateway.server.configprops; import io.jsonwebtoken.SignatureAlgorithm; import java.time.Duration; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties @NoArgsConstructor @Data public class GatewayJwtProperties { private boolean enabled = false; private SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512; private Duration expiration = Duration.ofHours(1); /** key file resource location */ private String signingKeyFile; /** signingKey in base64 string */ private String signingKey; /** optional iss claim */ private String issuer; /** token version to invalidate old token **/ public Integer tokenVersion; }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/configprops/GatewayRateLimiterProperties.java
package ai.hyacinth.core.service.gateway.server.configprops; import java.time.Duration; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.boot.context.properties.ConfigurationProperties; @Data @NoArgsConstructor @ConfigurationProperties public class GatewayRateLimiterProperties { private Long replenishRate; // disabled if rate == null private Duration replenishPeriod = Duration.ofMinutes(1); }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/configprops/GatewayRuleProperties.java
package ai.hyacinth.core.service.gateway.server.configprops; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.validation.constraints.NotNull; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.http.HttpMethod; @Data @NoArgsConstructor public class GatewayRuleProperties { /** predicate */ @NotNull private String path; private HttpMethod method; // empty means no restriction private GatewayRateLimiterProperties rateLimiter = new GatewayRateLimiterProperties(); private List<String> authority = new ArrayList<>(); /** route */ private String service; private String uri; /** request rewrite */ private Map<String, String> requestParam = new LinkedHashMap<>(); private Map<String, Object> requestBody = new LinkedHashMap<>(); /** not implemented. request body json inject. */ private String requestBodyJson; /** response rewrite with http status reset */ private List<ResponsePostProcessingType> postProcessing = new LinkedList<>(); /** * no effect on current implementation. secure headers is achieved by spring-security instead of * gateway filter. */ private boolean secureHttpHeaders = true; }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/configprops/GatewaySecurityProperties.java
package ai.hyacinth.core.service.gateway.server.configprops; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class GatewaySecurityProperties { /** * this switch determines different behavior when the authority of a rule is not specified */ private boolean authenticatedRequired = true; private String logoutUrl = "/logout"; private String logoutPayload = "{\"status\":\"success\"}"; }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/configprops/GatewayServerProperties.java
package ai.hyacinth.core.service.gateway.server.configprops; import java.util.ArrayList; import java.util.List; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("ai.hyacinth.core.service.gateway.server") @Data @NoArgsConstructor public class GatewayServerProperties { private GatewaySecurityProperties security = new GatewaySecurityProperties(); private GatewayJwtProperties jwt = new GatewayJwtProperties(); private List<GatewayRuleProperties> rules = new ArrayList<>(); private GatewayRateLimiterProperties rateLimiter = new GatewayRateLimiterProperties(); }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/configprops/ResponsePostProcessingType.java
package ai.hyacinth.core.service.gateway.server.configprops; public enum ResponsePostProcessingType { NONE, AUTHENTICATION_COOKIE, AUTHENTICATION_JWT, API, }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/jwt/JwtAuthenticationManager.java
package ai.hyacinth.core.service.gateway.server.jwt; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.core.Authentication; import reactor.core.publisher.Mono; public class JwtAuthenticationManager implements ReactiveAuthenticationManager { public JwtAuthenticationManager() { } @Override public Mono<Authentication> authenticate(Authentication authentication) { // for jwt authentication, as long as it is created, it is a valid token. authentication.setAuthenticated(true); return Mono.just(authentication); } }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/jwt/JwtAuthenticationWebFilter.java
package ai.hyacinth.core.service.gateway.server.jwt; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.security.core.Authentication; import org.springframework.security.web.server.authentication.AuthenticationWebFilter; import org.springframework.security.web.server.authentication.ServerAuthenticationConverter; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Mono; /** * do not initialise this bean as @Component * Otherwise, it is a global Webflux @WebFilter instance. */ public class JwtAuthenticationWebFilter extends AuthenticationWebFilter { @Autowired private JwtService jwtService; public JwtAuthenticationWebFilter() { super(new JwtAuthenticationManager()); this.setServerAuthenticationConverter(new JwtAuthenticationConverter()); } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return super.filter(exchange, chain); } private class JwtAuthenticationConverter implements ServerAuthenticationConverter { @Override public Mono<Authentication> convert(ServerWebExchange exchange) { String authHeader = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION); Authentication data = jwtService.parseHeader(authHeader); return data == null ? Mono.empty() : Mono.just(data); } } }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/jwt/JwtService.java
package ai.hyacinth.core.service.gateway.server.jwt; import ai.hyacinth.core.service.gateway.server.configprops.GatewayServerProperties; import ai.hyacinth.core.service.gateway.server.security.DefaultAuthentication; import ai.hyacinth.core.service.gateway.server.security.DefaultGrantedAuthority; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; import java.io.IOException; import java.security.Key; import java.util.Base64; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @Service @Slf4j public class JwtService { private static final String JWT_CLAIM_AUTHORITIES = "authority"; private static final String JWT_CLAIM_PRINCIPAL = "principal"; private static final String JWT_CLAIM_VERSION = "version"; @Autowired private GatewayServerProperties gatewayConfig; @Autowired private ResourceLoader resourceLoader; private Key jwtSigningKey; public JwtService() {} @PostConstruct public void loadKeys() { this.jwtSigningKey = loadJwtSigningKey(); } public Authentication parseHeader(String authHeader) { if (authHeader != null && authHeader.startsWith("Bearer ")) { String bearerToken = authHeader.substring(7).trim(); return parseToken(bearerToken); } return null; } @SuppressWarnings("unchecked") public Authentication parseToken(String token) { try { Jws<Claims> claims = Jwts.parser().setSigningKey(jwtSigningKey).parseClaimsJws(token); if (validateClaims(claims)) { DefaultAuthentication auth = new DefaultAuthentication(); auth.setDetails(claims); auth.setName(claims.getBody().getSubject()); auth.setAuthenticated(false); auth.setPrincipal(claims.getBody().get(JWT_CLAIM_PRINCIPAL)); auth.setAuthorities( ((List<String>) claims.getBody().get(JWT_CLAIM_AUTHORITIES)) .stream().map(DefaultGrantedAuthority::new).collect(Collectors.toList())); return auth; } } catch (Exception ex) { log.warn("token parsing error", ex); // any exception is regarded as token error and ignore } return null; } private boolean validateClaims(Jws<Claims> claims) { if (gatewayConfig.getJwt().getTokenVersion() != null) { Integer tokenVersion = claims.getBody().get(JWT_CLAIM_VERSION, Integer.class); if (tokenVersion == null || !tokenVersion.equals(gatewayConfig.getJwt().getTokenVersion())) { return false; } } if (claims.getBody().getExpiration().after(new Date())) { return true; } return false; } public String createToken(Authentication authentication) { return Jwts.builder() .signWith(jwtSigningKey, gatewayConfig.getJwt().getSignatureAlgorithm()) .setHeaderParam("typ", "JWT") .setSubject(authentication.getName()) .setIssuedAt(new Date()) .setIssuer(gatewayConfig.getJwt().getIssuer()) .setExpiration( new Date( System.currentTimeMillis() + gatewayConfig.getJwt().getExpiration().toMillis())) .claim( JWT_CLAIM_AUTHORITIES, authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList())) .claim(JWT_CLAIM_PRINCIPAL, authentication.getPrincipal()) .claim(JWT_CLAIM_VERSION, gatewayConfig.getJwt().getTokenVersion()) .compact(); } private Key loadJwtSigningKey() { if (gatewayConfig.getJwt().isEnabled()) { String key = gatewayConfig.getJwt().getSigningKey(); if (!StringUtils.isEmpty(key)) { return Keys.hmacShaKeyFor(Base64.getDecoder().decode(key)); } String keyLocation = gatewayConfig.getJwt().getSigningKeyFile(); if (!StringUtils.isEmpty(keyLocation)) { Resource resource = resourceLoader.getResource(keyLocation); try { byte[] content = resource.getInputStream().readAllBytes(); return Keys.hmacShaKeyFor(content); } catch (IOException e) { log.error("cannot read jwt signing key", e); throw new RuntimeException(e); } } } return null; } }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/payload/ApiSuccessPayload.java
package ai.hyacinth.core.service.gateway.server.payload; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonRawValue; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class ApiSuccessPayload { private String status = "success"; @JsonRawValue @JsonInclude(Include.NON_NULL) protected String data; }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/ratelimiter/SimpleKeyResolver.java
package ai.hyacinth.core.service.gateway.server.ratelimiter; import java.security.Principal; import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; /** * Not used now any more. The original default KeyResolver is effective. Once it generates a * "ANONYMOUS" tag for statistics in RateLimiter. */ // @Component // @Primary public class SimpleKeyResolver implements KeyResolver { private static final String ANONYMOUS = "ANONYMOUS"; public static boolean isAnonymous(String key) { return key != null && key.startsWith(SimpleKeyResolver.ANONYMOUS); } @Override public Mono<String> resolve(ServerWebExchange exchange) { // + "/" + exchange.getRequest().getRemoteAddress().getHostString() return exchange.getPrincipal().map(Principal::getName).switchIfEmpty(Mono.just(ANONYMOUS)); } }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/ratelimiter/SimpleRateLimiter.java
package ai.hyacinth.core.service.gateway.server.ratelimiter; import ai.hyacinth.core.service.gateway.server.ratelimiter.SimpleRateLimiter.SimpleRateLimiterConfig; import io.lettuce.core.RedisClient; import io.lettuce.core.api.reactive.RedisReactiveCommands; import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.Map; import javax.annotation.PostConstruct; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Scope; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.security.util.FieldUtils; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; /** * current implementation points: * * <p>1. use localtime instead of redis server time to reduce 1 time() call * * <p>2. if api-call count could not be retrieved correctly due to redis connection, the result * is "allow". * * <p>3. anonymous accessible API always pass the rate limiter check. * * <p>4. in future version, for anonymous access, IP could be a key to restrict access. */ @Slf4j @Data @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Primary public class SimpleRateLimiter implements RateLimiter<SimpleRateLimiterConfig> { public SimpleRateLimiter() {} @Autowired private LettuceConnectionFactory lettuceConnectionFactory; private Long replenishRate; private Duration replenishPeriod; private boolean global; // global or route-level private RedisClient redisClient; @PostConstruct public void fetchRedisClient() { try { redisClient = (RedisClient) FieldUtils.getFieldValue(lettuceConnectionFactory, "client"); } catch (IllegalAccessException e) { throw new UnsupportedOperationException("Could not get redisClient"); } } private Response POSITIVE = new Response(true, Collections.emptyMap()); private Response NEGATIVE = new Response(false, Collections.emptyMap()); @Override public Mono<Response> isAllowed(String routeId, String key) { final long currentSeconds = Instant.now().getEpochSecond(); final long windowSeconds = replenishPeriod.toSeconds(); final long windowId = currentSeconds / windowSeconds; final String redisKey = String.format( "core.service.gateway.rate-limiter/%s/%s/%s/%s", global ? "GLOBAL" : routeId, replenishPeriod.toString(), key, windowId); log.info("rateLimiter redisKey: {}", redisKey); RedisReactiveCommands<String, String> reactive = redisClient.connect().reactive(); return reactive .multi() .flatMap( result -> { reactive.incr(redisKey).subscribe(); // reactive.time().subscribe(); reactive.expire(redisKey, windowSeconds).subscribe(); return reactive.exec(); }) .map( txResult -> { // String secondsText = ((List<String>)txResult.get(1)).get(0); return (Long) txResult.get(0); }) .onErrorResume( (ex) -> { log.error("Redis command execution error.", ex); reactive.discard().subscribe(); return Mono.just(0L); }) .map(count -> count <= replenishRate) .map(allowed -> allowed ? POSITIVE : NEGATIVE); } @Override public Map<String, SimpleRateLimiterConfig> getConfig() { return Collections.emptyMap(); } @Override public Class<SimpleRateLimiterConfig> getConfigClass() { return SimpleRateLimiterConfig.class; } @Override public SimpleRateLimiterConfig newConfig() { return new SimpleRateLimiterConfig(); } @Data @NoArgsConstructor static class SimpleRateLimiterConfig {} }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/security/DefaultAuthentication.java
package ai.hyacinth.core.service.gateway.server.security; import java.util.ArrayList; import java.util.Collection; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.security.core.Authentication; @Data @NoArgsConstructor public class DefaultAuthentication implements Authentication { private static final long serialVersionUID = 383300673565185225L; boolean authenticated; Object credentials; Object details; Object principal; String name; Collection<DefaultGrantedAuthority> authorities = new ArrayList<>(); }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/security/DefaultGrantedAuthority.java
package ai.hyacinth.core.service.gateway.server.security; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.security.core.GrantedAuthority; @Data @NoArgsConstructor @AllArgsConstructor public class DefaultGrantedAuthority implements GrantedAuthority { private String authority; }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/support/DataURIStringConverter.java
package ai.hyacinth.core.service.gateway.server.support; import java.util.Base64; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.ConditionalConverter; import org.springframework.core.convert.converter.Converter; //@Component //@ConfigurationPropertiesBinding //@Slf4j public class DataURIStringConverter implements Converter<String, byte[]>, ConditionalConverter { public DataURIStringConverter() {} @Override public byte[] convert(String source) { if (source.startsWith("data:")) { int comma = source.indexOf(','); String base64 = source.substring(comma + 1); return Base64.getDecoder().decode(base64); } else { return source.getBytes(); } } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return true; } }
0
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server
java-sources/ai/hyacinth/framework/core-service-gateway-server/0.5.24/ai/hyacinth/core/service/gateway/server/web/GatewayController.java
package ai.hyacinth.core.service.gateway.server.web; import ai.hyacinth.core.service.web.common.ServiceApiConstants; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @RequestMapping(ServiceApiConstants.API_PREFIX) @Controller public class GatewayController { @GetMapping("/ping") @ResponseBody public String ping() { return "pong"; } }
0
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa/config/DefaultConfigLoader.java
package ai.hyacinth.core.service.jpa.config; import ai.hyacinth.core.service.module.loader.ConfigLoaderPostProcessor; public class DefaultConfigLoader extends ConfigLoaderPostProcessor {}
0
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa/config/JpaConfig.java
package ai.hyacinth.core.service.jpa.config; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableJpaAuditing @EnableTransactionManagement public class JpaConfig {}
0
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa/converter/AbstractJsonConverter.java
package ai.hyacinth.core.service.jpa.converter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Map; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; @Slf4j @Converter @NoArgsConstructor public abstract class AbstractJsonConverter<T> implements AttributeConverter<T, String> { @Autowired private ObjectMapper objectMapper; @SuppressWarnings("unchecked") protected Class<T> targetClass = (Class<T>) Map.class; public AbstractJsonConverter(Class<T> targetClass) { this.targetClass = targetClass; } @Override public String convertToDatabaseColumn(T data) { try { return objectMapper.writeValueAsString(data); } catch (final JsonProcessingException e) { log.error("JSON writing error", e); throw new UnsupportedOperationException(e); } } @Override public T convertToEntityAttribute(String dataJson) { try { return objectMapper.readValue(dataJson, targetClass); } catch (final IOException e) { log.error("JSON reading error", e); throw new UnsupportedOperationException(e); } } }
0
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa/converter/Map2JsonConverter.java
package ai.hyacinth.core.service.jpa.converter; import java.util.Map; import javax.persistence.Converter; @Converter public class Map2JsonConverter extends AbstractJsonConverter<Map> { public Map2JsonConverter() { super(Map.class); } }
0
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa/domain/BaseAuditingEntity.java
package ai.hyacinth.core.service.jpa.domain; import com.vladmihalcea.hibernate.type.json.JsonBinaryType; import com.vladmihalcea.hibernate.type.json.JsonNodeStringType; import com.vladmihalcea.hibernate.type.json.JsonStringType; import javax.persistence.Version; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.Column; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; import javax.persistence.Temporal; import java.util.Date; import static javax.persistence.TemporalType.TIMESTAMP; @MappedSuperclass @Data @NoArgsConstructor @EntityListeners(AuditingEntityListener.class) @TypeDefs({ @TypeDef(name = "json", typeClass = JsonStringType.class), @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class), @TypeDef(name = "json-node", typeClass = JsonNodeStringType.class) }) public class BaseAuditingEntity { // implements Auditable<Long, Long, Date> { @CreatedDate @Temporal(TIMESTAMP) @Column(name = "created_date") protected Date createdDate; @LastModifiedDate @Temporal(TIMESTAMP) @Column(name = "last_modified_date") protected Date lastModifiedDate; @Version protected Integer version; }
0
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa/hibernate
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa/hibernate/dialect/MySQLDialect.java
package ai.hyacinth.core.service.jpa.hibernate.dialect; import org.hibernate.dialect.MySQL57Dialect; @Deprecated /** * could be replaced by "org.hibernate.dialect.MySQL57InnoDBDialect" */ public class MySQLDialect extends MySQL57Dialect { @Override public String getTableTypeString() { return " ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; } }
0
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa/repo/BaseEnhancedRepository.java
package ai.hyacinth.core.service.jpa.repo; import org.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean public interface BaseEnhancedRepository<T, K> { T lockAndRefresh(K id); }
0
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa
java-sources/ai/hyacinth/framework/core-service-jpa-support/0.5.24/ai/hyacinth/core/service/jpa/repo/BaseEnhancedRepositoryImpl.java
package ai.hyacinth.core.service.jpa.repo; import org.springframework.beans.factory.annotation.Autowired; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class BaseEnhancedRepositoryImpl<T, K> implements BaseEnhancedRepository<T, K> { @Autowired private EntityManager entityManager; private Class<T> entityClass; public BaseEnhancedRepositoryImpl(Class<T> entityClass) { this.entityClass = entityClass; } public BaseEnhancedRepositoryImpl() { this.entityClass = probeGenericInterfaceEntityType(); } @SuppressWarnings("unchecked") private Class<T> probeGenericInterfaceEntityType() { Type[] genericInterfaces = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments(); return (Class<T>) genericInterfaces[0]; } @Override public T lockAndRefresh(K id) { T pe = entityManager.find(entityClass, id, LockModeType.PESSIMISTIC_WRITE, null); entityManager.refresh(pe); return pe; } }
0
java-sources/ai/hyacinth/framework/core-service-logging-support/0.5.24/ai/hyacinth/core/service/logging/support
java-sources/ai/hyacinth/framework/core-service-logging-support/0.5.24/ai/hyacinth/core/service/logging/support/config/DefaultConfigLoader.java
package ai.hyacinth.core.service.logging.support.config; import ai.hyacinth.core.service.module.loader.ConfigLoaderPostProcessor; public class DefaultConfigLoader extends ConfigLoaderPostProcessor {}
0
java-sources/ai/hyacinth/framework/core-service-module/0.5.24/ai/hyacinth/core/service/module
java-sources/ai/hyacinth/framework/core-service-module/0.5.24/ai/hyacinth/core/service/module/factory/YamlPropertySourceFactory.java
package ai.hyacinth.core.service.module.factory; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import java.io.IOException; import java.util.Properties; public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean(); factoryBean.setResources(resource.getResource()); factoryBean.getObject(); factoryBean.afterPropertiesSet(); Properties propertiesFromYaml = factoryBean.getObject(); String resourceFullName = resource.getResource().getURI().toString(); return new PropertiesPropertySource(resourceFullName, propertiesFromYaml); } }
0
java-sources/ai/hyacinth/framework/core-service-module/0.5.24/ai/hyacinth/core/service/module
java-sources/ai/hyacinth/framework/core-service-module/0.5.24/ai/hyacinth/core/service/module/loader/ConfigLoaderPostProcessor.java
package ai.hyacinth.core.service.module.loader; import java.util.Collections; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.annotation.Order; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.PropertySource; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.StringUtils; @Slf4j @Order public class ConfigLoaderPostProcessor implements EnvironmentPostProcessor { private static final String DOCUMENT_PROFILES_PROPERTY = "spring.profiles"; private String configLocation; public ConfigLoaderPostProcessor() { detectConfigLocation(); } public ConfigLoaderPostProcessor(String configLocation) { this.configLocation = configLocation; } @Override public void postProcessEnvironment( ConfigurableEnvironment environment, SpringApplication application) { ResourceLoader resourceLoader = new DefaultResourceLoader(); Resource resource = resourceLoader.getResource(configLocation); YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader(); final String name = String.format("ServiceModuleConfiguration [%s]", configLocation); try { List<PropertySource<?>> yalPropertiesList = sourceLoader.load(name, resource); if (yalPropertiesList != null && yalPropertiesList.size() > 0) { Collections.reverse(yalPropertiesList); for (PropertySource propertySource : yalPropertiesList) { if (matchActiveProfile( propertySource.getProperty(DOCUMENT_PROFILES_PROPERTY), environment.getActiveProfiles(), environment.getDefaultProfiles())) { if (!environment.getPropertySources().contains(propertySource.getName())) { environment.getPropertySources().addLast(propertySource); } } else { log.info("profile not match. skip loading {}", propertySource); } } } log.info("load from {} successfully", configLocation); } catch (Exception e) { log.error("error to load config file: " + configLocation); } } private boolean matchActiveProfile( Object property, String[] activeProfiles, String defaultProfiles[]) { if (activeProfiles.length == 0) { return false; } if (property == null) { return true; // document has no restriction } else { String docProfile = property.toString(); for (String activeProfile : activeProfiles) { if (docProfile.equals(activeProfile)) { return true; } } } return false; } private void detectConfigLocation() { if (StringUtils.isEmpty(configLocation)) { String pkPath = this.getClass().getPackage().getName().replace(".", "/"); configLocation = "classpath:" + pkPath + "/config.yml"; } } }
0
java-sources/ai/hyacinth/framework/core-service-swagger-support/0.5.24/ai/hyacinth/core/service/swagger
java-sources/ai/hyacinth/framework/core-service-swagger-support/0.5.24/ai/hyacinth/core/service/swagger/support/SwaggerConfig.java
package ai.hyacinth.core.service.swagger.support; import com.google.common.base.Predicates; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @EnableSwagger2 public class SwaggerConfig { @Value("${spring.application.name}") private String applicationName; @Value("${spring.application.version:}") private String applicationVersion; @Value("${spring.application.description:}") private String applicationDescription; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(createApiInfo()) .select() .apis( // RequestHandlerSelectors.basePackage("com.appsdeveloperblog.app.ws") Predicates.and( Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")), Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.cloud")))) .paths(PathSelectors.any()) .build(); } private ApiInfo createApiInfo() { return new ApiInfoBuilder() .title(applicationName) .description(applicationDescription) .termsOfServiceUrl("") .license("") .licenseUrl("") .version(applicationVersion) .build(); } }
0
java-sources/ai/hyacinth/framework/core-service-tracing-support/0.5.24/ai/hyacinth/core/service/tracing/support
java-sources/ai/hyacinth/framework/core-service-tracing-support/0.5.24/ai/hyacinth/core/service/tracing/support/config/DefaultConfigLoader.java
package ai.hyacinth.core.service.tracing.support.config; import ai.hyacinth.core.service.module.loader.ConfigLoaderPostProcessor; public class DefaultConfigLoader extends ConfigLoaderPostProcessor {}
0
java-sources/ai/hyacinth/framework/core-service-tracing-support/0.5.24/ai/hyacinth/core/service/tracing/support
java-sources/ai/hyacinth/framework/core-service-tracing-support/0.5.24/ai/hyacinth/core/service/tracing/support/config/TracingConfig.java
package ai.hyacinth.core.service.tracing.support.config; import org.springframework.context.annotation.Configuration; @Configuration public class TracingConfig {}
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/boot/TriggerApplication.java
package ai.hyacinth.core.service.trigger.server.boot; import ai.hyacinth.core.service.trigger.server.config.TriggerApplicationConfig; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableDiscoveryClient @Configuration @EnableScheduling @EnableAsync @Import(TriggerApplicationConfig.class) public class TriggerApplication { public static void main(String[] args) { new SpringApplicationBuilder(TriggerApplication.class) .web(WebApplicationType.SERVLET) .run(args); } }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/config/TriggerApplicationConfig.java
package ai.hyacinth.core.service.trigger.server.config; import ai.hyacinth.core.service.discovery.support.config.DiscoveryConfig; import ai.hyacinth.core.service.endpoint.support.config.EndpointConfig; import ai.hyacinth.core.service.jpa.config.JpaConfig; import ai.hyacinth.core.service.trigger.server.domain.ServiceTrigger; import ai.hyacinth.core.service.trigger.server.repo.ServiceTriggerRepository; import ai.hyacinth.core.service.trigger.server.service.TriggerService; import ai.hyacinth.core.service.trigger.server.service.impl.SpringBeanJobFactory; import ai.hyacinth.core.service.trigger.server.web.TriggerController; import java.util.Properties; import javax.sql.DataSource; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.web.reactive.function.client.WebClient; @Configuration @Import({JpaConfig.class, EndpointConfig.class, DiscoveryConfig.class}) @ComponentScan(basePackageClasses = {TriggerService.class, TriggerController.class}) @EnableJpaRepositories(basePackageClasses = {ServiceTriggerRepository.class}) @EntityScan(basePackageClasses = ServiceTrigger.class) @EnableCaching public class TriggerApplicationConfig { private Properties quartzProperties() { Properties prop = new Properties(); prop.put("org.quartz.scheduler.instanceId", "AUTO"); prop.put("org.quartz.scheduler.jmx.export", "true"); prop.put( "org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX"); // org.quartz.simpl.RAMJobStore prop.put("org.quartz.jobStore.isClustered", "true"); return prop; } @Bean public SchedulerFactoryBean schedulerFactoryBean( DataSource dataSource, SpringBeanJobFactory jobFactory) { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setQuartzProperties(quartzProperties()); factory.setOverwriteExistingJobs(false); factory.setDataSource(dataSource); factory.setJobFactory(jobFactory); factory.setAutoStartup(true); return factory; } @Bean @LoadBalanced @ConditionalOnMissingBean(WebClient.Builder.class) public WebClient.Builder loadBalancedWebClientBuilder() { return WebClient.builder(); } }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/domain/ServiceTrigger.java
package ai.hyacinth.core.service.trigger.server.domain; import ai.hyacinth.core.service.jpa.domain.BaseAuditingEntity; import ai.hyacinth.core.service.trigger.server.dto.type.ServiceTriggerMethodType; import java.time.Duration; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.hibernate.annotations.NaturalId; import org.hibernate.annotations.Type; import org.springframework.http.HttpMethod; @Builder @NoArgsConstructor @AllArgsConstructor @Data @Entity //@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"service", "name"})}) @EqualsAndHashCode(callSuper = false) public class ServiceTrigger extends BaseAuditingEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NaturalId @NotNull private String service; @NaturalId @NotNull private String name; @NotNull private ServiceTriggerMethodType triggerMethod; private HttpMethod httpMethod; private String url; @Type(type = "json") @Column(columnDefinition = "varchar(500)") private Map<String, Object> params; @NotNull private String cron; private Duration timeout; @NotNull private Boolean enabled; }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto/TriggerChangeResult.java
package ai.hyacinth.core.service.trigger.server.dto; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class TriggerChangeResult { private Long id; private boolean completed; }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto/TriggerCreationRequest.java
package ai.hyacinth.core.service.trigger.server.dto; import ai.hyacinth.core.service.trigger.server.dto.type.ServiceTriggerMethodType; import io.swagger.annotations.ApiModelProperty; import java.time.Duration; import java.util.LinkedHashMap; import java.util.Map; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.springframework.http.HttpMethod; @Data @Builder @NoArgsConstructor @AllArgsConstructor @ToString public class TriggerCreationRequest { @NotNull private String name; private String service; private ServiceTriggerMethodType triggerMethod; @NotNull @Builder.Default private HttpMethod httpMethod = HttpMethod.GET; private String url; private Map<String, Object> params; @ApiModelProperty("Quartz cron expression. Try '0 0/2 * ? * * *' for every 2 minutes.") @NotNull private String cron; @ApiModelProperty("Not used now.") private Duration timeout; @Builder.Default @NotNull private Boolean enabled = Boolean.TRUE; }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto/TriggerInfo.java
package ai.hyacinth.core.service.trigger.server.dto; import ai.hyacinth.core.service.trigger.server.dto.type.ServiceTriggerMethodType; import java.time.Duration; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.http.HttpMethod; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class TriggerInfo { private Long id; private String service; private String name; private ServiceTriggerMethodType triggerMethod; private HttpMethod httpMethod; private String url; private String cron; private Duration timeout; private boolean enabled; private Map<String, Object> params; }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto/TriggerQueryRequest.java
package ai.hyacinth.core.service.trigger.server.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class TriggerQueryRequest { private Long id; private String name; private String service; private Boolean enabled; }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto/TriggerRemovalRequest.java
package ai.hyacinth.core.service.trigger.server.dto; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class TriggerRemovalRequest { private Long id; }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto/TriggerUpdateRequest.java
package ai.hyacinth.core.service.trigger.server.dto; import java.time.Duration; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class TriggerUpdateRequest { private String cron; private Duration timeout; private Boolean enabled; }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto/type/ServiceTriggerExecutionStatus.java
package ai.hyacinth.core.service.trigger.server.dto.type; public enum ServiceTriggerExecutionStatus { WAITING, STARTED, COMPLETED, TIMEOUT, ABORTED, UNKNOWN, }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/dto/type/ServiceTriggerMethodType.java
package ai.hyacinth.core.service.trigger.server.dto.type; public enum ServiceTriggerMethodType { SERVICE_URL, URL, BUS_EVENT, LOG, // just log, nothing else }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/error/TriggerServiceErrorCode.java
package ai.hyacinth.core.service.trigger.server.error; import ai.hyacinth.core.service.web.common.ServiceApiErrorCode; import lombok.AllArgsConstructor; import lombok.Getter; import org.springframework.http.HttpStatus; @Getter @AllArgsConstructor public enum TriggerServiceErrorCode implements ServiceApiErrorCode { TRIGGER_EXISTS(HttpStatus.CONFLICT, "100000"), WRONG_CRON_EXPRESSION(HttpStatus.BAD_REQUEST, "100001"), TIMEOUT_REQUIRED(HttpStatus.BAD_REQUEST, "100002"), TRIGGER_NOT_FOUND(HttpStatus.NOT_FOUND, "100003"), QUARTZ_ERROR(HttpStatus.BAD_REQUEST, "100004"); private HttpStatus httpStatus; private String code; @Override public int getHttpStatusCode() { return httpStatus.value(); } }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/repo/ServiceTriggerRepository.java
package ai.hyacinth.core.service.trigger.server.repo; import ai.hyacinth.core.service.trigger.server.domain.ServiceTrigger; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; public interface ServiceTriggerRepository extends JpaRepository<ServiceTrigger, Long> { Optional<ServiceTrigger> findByServiceAndName(String service, String name); }
0
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server
java-sources/ai/hyacinth/framework/core-service-trigger-server/0.5.24/ai/hyacinth/core/service/trigger/server/service/TriggerService.java
package ai.hyacinth.core.service.trigger.server.service; import ai.hyacinth.core.service.trigger.server.dto.TriggerChangeResult; import ai.hyacinth.core.service.trigger.server.dto.TriggerCreationRequest; import ai.hyacinth.core.service.trigger.server.dto.TriggerInfo; import ai.hyacinth.core.service.trigger.server.dto.TriggerQueryRequest; import ai.hyacinth.core.service.trigger.server.dto.TriggerUpdateRequest; import java.util.List; import org.springframework.lang.NonNull; public interface TriggerService { @NonNull TriggerChangeResult removeTrigger(Long triggerId); @NonNull TriggerInfo createTrigger(TriggerCreationRequest createRequest); TriggerInfo findTriggerById(Long id); TriggerInfo findTriggerByServiceAndName(String service, String name); @NonNull List<TriggerInfo> findAllTriggers(TriggerQueryRequest queryRequest); @NonNull TriggerInfo updateTrigger(Long id, TriggerUpdateRequest updateRequest); }