index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/ResourceRegisters.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.rest; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; /** * @author weiping wang * */ public class ResourceRegisters { private static ResourceRegisters instance = new ResourceRegisters(); private static List<ResourceRegister> resourceRegisters = new ArrayList<>(); static { ServiceLoader<ResourceRegister> serviceLoader = ServiceLoader.load(ResourceRegister.class); for(ResourceRegister register: serviceLoader) { resourceRegisters.add(register); } } public static ResourceRegisters getInstance() { return instance; } public List<ResourceRegister> getResourceRegisters(){ return Collections.unmodifiableList(resourceRegisters); } public void addResourceRegister(ResourceRegister resourceRegister) { resourceRegisters.add(resourceRegister); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/Consume.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.rest.annotation; import static java.lang.annotation.ElementType.METHOD; 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; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target({ TYPE, METHOD }) public @interface Consume { String value() default "*/*"; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/Controller.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.rest.annotation; 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 Controller { }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/CookieParam.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.rest.annotation; import static java.lang.annotation.ElementType.PARAMETER; 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(PARAMETER) /** * * @author wangwp */ public @interface CookieParam { String value() default ""; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/DELETE.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.rest.annotation; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target(METHOD) @HttpMethod(HttpMethod.DELETE) public @interface DELETE { }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/ExceptionAdvice.java
/* * Copyright 2017 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.rest.annotation; 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 weiping wang * */ public @interface ExceptionAdvice { }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/ExceptionType.java
/* * Copyright 2017 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.rest.annotation; import static java.lang.annotation.ElementType.METHOD; 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(METHOD) /** * @author weiping wang * */ public @interface ExceptionType { Class<? extends Throwable> value(); }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/FilterPath.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.rest.annotation; 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 weiping wang * */ public @interface FilterPath { String[] exclude() default {}; String[] include() default {}; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/GET.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.rest.annotation; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target(METHOD) @HttpMethod(HttpMethod.GET) public @interface GET { }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/HeaderParam.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.rest.annotation; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target(PARAMETER) public @interface HeaderParam { String value() default ""; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/HttpMethod.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.rest.annotation; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target({ METHOD, ANNOTATION_TYPE }) public @interface HttpMethod { /** * HTTP GET method */ public static final String GET = "GET"; /** * HTTP POST method */ public static final String POST = "POST"; /** * HTTP PUT method */ public static final String PUT = "PUT"; /** * HTTP DELETE method */ public static final String DELETE = "DELETE"; /** * HTTP HEAD method */ public static final String HEAD = "HEAD"; /** * HTTP OPTIONS method */ public static final String OPTIONS = "OPTIONS"; String value(); }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/POST.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.rest.annotation; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target(METHOD) @HttpMethod(HttpMethod.POST) public @interface POST { }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/PUT.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.rest.annotation; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target(METHOD) @HttpMethod(HttpMethod.PUT) public @interface PUT { }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/Path.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.rest.annotation; import static java.lang.annotation.ElementType.METHOD; 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, METHOD }) /** * * @author wangwp */ public @interface Path { String value() default ""; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/PathVariable.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.rest.annotation; import static java.lang.annotation.ElementType.PARAMETER; 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(PARAMETER) /** * * @author wangwp */ public @interface PathVariable { String value() default ""; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/Produce.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.rest.annotation; import static java.lang.annotation.ElementType.METHOD; 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; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target({ TYPE, METHOD }) public @interface Produce { String value() default "*/*"; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/RequestBody.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.rest.annotation; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target(PARAMETER) public @interface RequestBody { }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/RequestParam.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.rest.annotation; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target(PARAMETER) public @interface RequestParam { String value() default ""; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/annotation/Status.java
/** * */ package ai.houyi.dorado.rest.annotation; import static java.lang.annotation.ElementType.METHOD; 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(METHOD) /** * @author marta * */ public @interface Status { int value(); }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/controller/DoradoStatus.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.rest.controller; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import com.alibaba.fastjson.annotation.JSONField; import ai.houyi.dorado.rest.util.TracingThreadPoolExecutor; /** * * @author wangwp */ public class DoradoStatus { private static DoradoStatus INSTANCE = new DoradoStatus(); private AtomicInteger connections = new AtomicInteger(0); private AtomicInteger pendingRequests = new AtomicInteger(0); private AtomicLong totalRequests = new AtomicLong(0); private AtomicLong handledRequests = new AtomicLong(0); private int workerPoolSize; private int activePoolSize; @JSONField(serialize = false) private TracingThreadPoolExecutor workerPool; private DoradoStatus() { } public static DoradoStatus get() { return INSTANCE; } public DoradoStatus totalRequestsIncrement() { totalRequests.incrementAndGet(); return this; } public DoradoStatus handledRequestsIncrement() { handledRequests.incrementAndGet(); return this; } public DoradoStatus connectionIncrement() { connections.incrementAndGet(); return this; } public DoradoStatus connectionDecrement() { connections.decrementAndGet(); return this; } public DoradoStatus pendingRequestsIncrement() { pendingRequests.incrementAndGet(); return this; } public DoradoStatus pendingRequestsDecrement() { pendingRequests.decrementAndGet(); return this; } public int getConnections() { return connections.get(); } public int getPendingRequests() { return pendingRequests.get(); } public long getTotalRequests() { return totalRequests.get(); } public long getHandledRequests() { return handledRequests.get(); } public int getWorkerPoolSize() { this.workerPoolSize = workerPool.getPoolSize(); return workerPoolSize; } public int getActivePoolSize() { this.activePoolSize = workerPool.getActiveCount(); return activePoolSize; } public void workerPool(TracingThreadPoolExecutor workerPool) { this.workerPool = workerPool; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/controller/RestService.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.rest.controller; import javax.annotation.Generated; /** * * @author wangwp */ public class RestService { private String path; private String method; private String desc; public RestService() { } @Generated("SparkTools") private RestService(Builder builder) { this.path = builder.path; this.method = builder.method; this.desc = builder.desc; } /** * Creates builder to build {@link RestService}. * * @return created builder */ @Generated("SparkTools") public static Builder builder() { return new Builder(); } public String getPath() { return path; } public String getMethod() { return method; } public String getDesc() { return desc; } /** * Builder to build {@link RestService}. */ @Generated("SparkTools") public static final class Builder { private String path; private String method; private String desc; private Builder() { } public Builder withPath(String path) { this.path = path; return this; } public Builder withMethod(String method) { this.method = method; return this; } public Builder withDesc(String desc) { this.desc = desc; return this; } public RestService build() { return new RestService(this); } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/controller/RootController.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.rest.controller; import java.util.ArrayList; import java.util.List; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.rest.annotation.Controller; import ai.houyi.dorado.rest.annotation.Path; import ai.houyi.dorado.rest.router.UriRoutingPath; import ai.houyi.dorado.rest.router.UriRoutingRegistry; import ai.houyi.dorado.rest.router.UriRoutingRegistry.UriRouting; import ai.houyi.dorado.rest.server.DoradoServerBuilder; import ai.houyi.dorado.rest.util.StringUtils; /** * * @author wangwp */ @Controller @Path("/") public class RootController { private static final String DORADO_WELCOME = "Welcome to dorado!"; @Path public String index() { return DORADO_WELCOME; } @Path("status") public DoradoStatus status() { return DoradoStatus.get(); } @Path("services") public List<RestService> services() { List<RestService> serviceList = new ArrayList<>(); List<UriRouting> uriRoutings = UriRoutingRegistry.getInstance().uriRoutings(); for (UriRouting uriRouting : uriRoutings) { UriRoutingPath routingPath = uriRouting.uriRoutingPath(); String path = routingPath.routingPath(); String method = StringUtils.defaultString(routingPath.httpMethod(), "*"); serviceList.add(RestService.builder().withPath(path).withMethod(method).build()); } return serviceList; } @Path("config") public DoradoServerBuilder config() { return Dorado.serverConfig; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/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.rest.controller;
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/Cookie.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.rest.http; /** * * @author wangwp */ public interface Cookie { long UNDEFINED_MAX_AGE = Long.MIN_VALUE; String name(); String value(); void setValue(String value); boolean wrap(); void setWrap(boolean wrap); String domain(); void setDomain(String domain); String path(); void setPath(String path); long maxAge(); void setMaxAge(long maxAge); boolean isSecure(); void setSecure(boolean secure); boolean isHttpOnly(); void setHttpOnly(boolean httpOnly); }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/Filter.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.rest.http; /** * 请求过滤器,比如做统一的访问权限校验以及获取授权信息 * * @author wangwp */ public interface Filter { default boolean preFilter(HttpRequest request, HttpResponse response) { return true; } default void postFilter(HttpRequest request, HttpResponse response) { } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/HttpRequest.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.rest.http; import java.io.InputStream; import java.util.List; import java.util.Map; /** * * @author wangwp */ public interface HttpRequest { String getParameter(String name); String[] getParameterValues(String name); Map<String, List<String>> getParameters(); String getRemoteAddr(); Cookie[] getCookies(); String getHeader(String name); String[] getHeaders(String name); String getMethod(); String getQueryString(); String getRequestURI(); InputStream getInputStream(); MultipartFile getFile(); MultipartFile[] getFiles(); }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/HttpResponse.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.rest.http; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import ai.houyi.dorado.rest.http.impl.OutputStreamImpl; /** * * @author wangwp */ public interface HttpResponse { void setHeader(String name, String value); void addHeader(String name, String value); void sendRedirect(String location); void sendError(int sc, String msg); void sendError(int sc); void setStatus(int sc); OutputStreamImpl getOutputStream() throws IOException; PrintWriter getWriter() throws IOException; void write(byte[] content); /** * Status code (100) indicating the client can continue. */ public static final int SC_CONTINUE = 100; /** * Status code (101) indicating the server is switching protocols according to * Upgrade header. */ public static final int SC_SWITCHING_PROTOCOLS = 101; /** * Status code (200) indicating the request succeeded normally. */ public static final int SC_OK = 200; /** * Status code (201) indicating the request succeeded and created a new resource * on the server. */ public static final int SC_CREATED = 201; /** * Status code (202) indicating that a request was accepted for processing, but * was not completed. */ public static final int SC_ACCEPTED = 202; /** * Status code (203) indicating that the meta information presented by the * client did not originate from the server. */ public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; /** * Status code (204) indicating that the request succeeded but that there was no * new information to return. */ public static final int SC_NO_CONTENT = 204; /** * Status code (205) indicating that the agent <em>SHOULD</em> reset the * document view which caused the request to be sent. */ public static final int SC_RESET_CONTENT = 205; /** * Status code (206) indicating that the server has fulfilled the partial GET * request for the resource. */ public static final int SC_PARTIAL_CONTENT = 206; /** * Status code (300) indicating that the requested resource corresponds to any * one of a set of representations, each with its own specific location. */ public static final int SC_MULTIPLE_CHOICES = 300; /** * Status code (301) indicating that the resource has permanently moved to a new * location, and that future references should use a new URI with their * requests. */ public static final int SC_MOVED_PERMANENTLY = 301; /** * Status code (302) indicating that the resource has temporarily moved to * another location, but that future references should still use the original * URI to access the resource. * * This definition is being retained for backwards compatibility. SC_FOUND is * now the preferred definition. */ public static final int SC_MOVED_TEMPORARILY = 302; /** * Status code (302) indicating that the resource reside temporarily under a * different URI. Since the redirection might be altered on occasion, the client * should continue to use the Request-URI for future requests.(HTTP/1.1) To * represent the status code (302), it is recommended to use this variable. */ public static final int SC_FOUND = 302; /** * Status code (303) indicating that the response to the request can be found * under a different URI. */ public static final int SC_SEE_OTHER = 303; /** * Status code (304) indicating that a conditional GET operation found that the * resource was available and not modified. */ public static final int SC_NOT_MODIFIED = 304; /** * Status code (305) indicating that the requested resource <em>MUST</em> be * accessed through the proxy given by the <code><em>Location</em></code> field. */ public static final int SC_USE_PROXY = 305; /** * Status code (307) indicating that the requested resource resides temporarily * under a different URI. The temporary URI <em>SHOULD</em> be given by the * <code><em>Location</em></code> field in the response. */ public static final int SC_TEMPORARY_REDIRECT = 307; /** * Status code (400) indicating the request sent by the client was syntactically * incorrect. */ public static final int SC_BAD_REQUEST = 400; /** * Status code (401) indicating that the request requires HTTP authentication. */ public static final int SC_UNAUTHORIZED = 401; /** * Status code (402) reserved for future use. */ public static final int SC_PAYMENT_REQUIRED = 402; /** * Status code (403) indicating the server understood the request but refused to * fulfill it. */ public static final int SC_FORBIDDEN = 403; /** * Status code (404) indicating that the requested resource is not available. */ public static final int SC_NOT_FOUND = 404; /** * Status code (405) indicating that the method specified in the * <code><em>Request-Line</em></code> is not allowed for the resource identified * by the <code><em>Request-URI</em></code>. */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** * Status code (406) indicating that the resource identified by the request is * only capable of generating response entities which have content * characteristics not acceptable according to the accept headers sent in the * request. */ public static final int SC_NOT_ACCEPTABLE = 406; /** * Status code (407) indicating that the client <em>MUST</em> first authenticate * itself with the proxy. */ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** * Status code (408) indicating that the client did not produce a request within * the time that the server was prepared to wait. */ public static final int SC_REQUEST_TIMEOUT = 408; /** * Status code (409) indicating that the request could not be completed due to a * conflict with the current state of the resource. */ public static final int SC_CONFLICT = 409; /** * Status code (410) indicating that the resource is no longer available at the * server and no forwarding address is known. This condition <em>SHOULD</em> be * considered permanent. */ public static final int SC_GONE = 410; /** * Status code (411) indicating that the request cannot be handled without a * defined <code><em>Content-Length</em></code>. */ public static final int SC_LENGTH_REQUIRED = 411; /** * Status code (412) indicating that the precondition given in one or more of * the request-header fields evaluated to false when it was tested on the * server. */ public static final int SC_PRECONDITION_FAILED = 412; /** * Status code (413) indicating that the server is refusing to process the * request because the request entity is larger than the server is willing or * able to process. */ public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413; /** * Status code (414) indicating that the server is refusing to service the * request because the <code><em>Request-URI</em></code> is longer than the * server is willing to interpret. */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** * Status code (415) indicating that the server is refusing to service the * request because the entity of the request is in a format not supported by the * requested resource for the requested method. */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** * Status code (416) indicating that the server cannot serve the requested byte * range. */ public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** * Status code (417) indicating that the server could not meet the expectation * given in the Expect request header. */ public static final int SC_EXPECTATION_FAILED = 417; /** * Status code (500) indicating an error inside the HTTP server which prevented * it from fulfilling the request. */ public static final int SC_INTERNAL_SERVER_ERROR = 500; /** * Status code (501) indicating the HTTP server does not support the * functionality needed to fulfill the request. */ public static final int SC_NOT_IMPLEMENTED = 501; /** * Status code (502) indicating that the HTTP server received an invalid * response from a server it consulted when acting as a proxy or gateway. */ public static final int SC_BAD_GATEWAY = 502; /** * Status code (503) indicating that the HTTP server is temporarily overloaded, * and unable to handle the request. */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** * Status code (504) indicating that the server did not receive a timely * response from the upstream server while acting as a gateway or proxy. */ public static final int SC_GATEWAY_TIMEOUT = 504; /** * Status code (505) indicating that the server does not support or refuses to * support the HTTP protocol version that was used in the request message. */ public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505; void writeStringUtf8(String invokeResult); void write(InputStream invokeResult); }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/MethodReturnValueHandler.java
/* * Copyright 2017 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.rest.http; import ai.houyi.dorado.rest.util.MethodDescriptor; /** * @author weiping wang * */ public interface MethodReturnValueHandler { /** * 方法调用正常返回结果处理器 * * @param value 方法执行结果 * @param methodDescriptor 方法描述 * @return 处理后的返回结果 */ Object handleMethodReturnValue(Object value, MethodDescriptor methodDescriptor); /** * 判断指定返回类型是否需要被此handler支持 * * @param returnType the MethodDescriptor for this method * @return {@code true} if this handler supports the supplied return type; * {@code false} otherwise */ public boolean supportsReturnType(MethodDescriptor returnType); }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/MethodReturnValueHandlerConfig.java
/* * Copyright 2017 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.rest.http; import java.util.ArrayList; import java.util.List; import ai.houyi.dorado.rest.util.PathMatcher; import ai.houyi.dorado.rest.util.PathMatchers; /** * @author weiping wang * */ public class MethodReturnValueHandlerConfig { private static final PathMatcher pathMatcher = PathMatchers.getPathMatcher(); private MethodReturnValueHandler returnValueHandler; private final List<String> excludePaths; public MethodReturnValueHandlerConfig(MethodReturnValueHandler handler) { this.excludePaths = new ArrayList<>(); this.excludePaths.add("/"); this.excludePaths.add("/status"); this.excludePaths.add("/config"); this.excludePaths.add("/services"); this.excludePaths.add("/swagger*"); this.excludePaths.add("/api-docs/*"); this.excludePaths.add("/api-docs*"); this.returnValueHandler = handler; } public void addExcludePath(String path) { this.excludePaths.add(path); } public boolean exclude(String url) { for (String excludePath : excludePaths) { if (pathMatcher.match(excludePath, url)) { return true; } } return false; } public MethodReturnValueHandler getHandler() { return returnValueHandler; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/MultipartFile.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.rest.http; import java.io.InputStream; /** * @author weiping wang * */ public class MultipartFile { private String name; private String contentType; private byte[] content; private InputStream stream; private long size; public String getName() { return name; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public void setName(String name) { this.name = name; } @Override public String toString() { return "MultipartFile [name=" + name + ", contentType=" + contentType + ", size=" + size + "]"; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public InputStream getStream() { return stream; } public void setStream(InputStream stream) { this.stream = stream; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/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.rest.http;
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/ChannelHolder.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.rest.http.impl; import io.netty.channel.Channel; public class ChannelHolder { public static final ThreadLocal<Channel> _channelHolder = new ThreadLocal<Channel>(); public static void set(Channel channel) { _channelHolder.set(channel); } public static void unset() { _channelHolder.remove(); } public static Channel get() { return _channelHolder.get(); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/CookieImpl.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.rest.http.impl; import ai.houyi.dorado.rest.http.Cookie; /** * * @author wangwp */ public class CookieImpl implements Cookie { private final io.netty.handler.codec.http.cookie.Cookie cookie; public CookieImpl(io.netty.handler.codec.http.cookie.Cookie cookie) { this.cookie = cookie; } @Override public String name() { return cookie.name(); } @Override public String value() { return cookie.value(); } @Override public void setValue(String value) { cookie.setValue(value); } @Override public boolean wrap() { return cookie.wrap(); } @Override public void setWrap(boolean wrap) { cookie.setWrap(wrap); } @Override public String domain() { return cookie.domain(); } @Override public void setDomain(String domain) { cookie.setDomain(domain); } @Override public String path() { return cookie.path(); } @Override public void setPath(String path) { cookie.setPath(path); } @Override public long maxAge() { return cookie.maxAge(); } @Override public void setMaxAge(long maxAge) { cookie.setMaxAge(maxAge); } @Override public boolean isSecure() { return cookie.isSecure(); } @Override public void setSecure(boolean secure) { cookie.setSecure(secure); } @Override public boolean isHttpOnly() { return cookie.isHttpOnly(); } @Override public void setHttpOnly(boolean httpOnly) { cookie.setHttpOnly(httpOnly); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/ExceptionHandler.java
/* * Copyright 2017 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.rest.http.impl; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import ai.houyi.dorado.exception.DoradoException; import ai.houyi.dorado.rest.annotation.Status; import ai.houyi.dorado.rest.util.MethodDescriptor; /** * @author weiping wang * */ public class ExceptionHandler { private final Method exceptionHandleMethod; private final Object exceptionAdvicor; private final MethodDescriptor descriptor; private ExceptionHandler(Object exceptionAdvicor, Method exceptionHandleMethod) { this.exceptionAdvicor = exceptionAdvicor; this.exceptionHandleMethod = exceptionHandleMethod; this.descriptor = MethodDescriptor.create(exceptionAdvicor.getClass(), exceptionHandleMethod); if (!exceptionHandleMethod.isAccessible()) { exceptionHandleMethod.setAccessible(true); } } public static ExceptionHandler newExceptionHandler(Object exceptionAdvicor, Method exceptionHandleMethod) { return new ExceptionHandler(exceptionAdvicor, exceptionHandleMethod); } public Status status() { Annotation[] annotations = descriptor.getAnnotations(); for (Annotation annotation : annotations) { if (annotation.annotationType() == Status.class) return (Status) annotation; } return null; } public String produce() { return descriptor.produce(); } public Object handleException(Throwable throwable) { try { return exceptionHandleMethod.invoke(exceptionAdvicor, throwable); } catch (Throwable ex) { throw new DoradoException(ex); } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/FilterConfiguration.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.rest.http.impl; import java.util.List; import javax.annotation.Generated; import ai.houyi.dorado.rest.http.Filter; import java.util.Collections; /** * @author wangweiping * */ public class FilterConfiguration { private Filter filter; private List<String> pathPatterns; private List<String> excludePathPatterns; public Filter getFilter() { return filter; } public List<String> getPathPatterns() { return pathPatterns; } public List<String> getExcludePathPatterns() { return excludePathPatterns; } @Generated("SparkTools") private FilterConfiguration(Builder builder) { this.filter = builder.filter; this.pathPatterns = builder.pathPatterns; this.excludePathPatterns = builder.excludePathPatterns; } /** * Creates builder to build {@link FilterConfiguration}. * @return created builder */ @Generated("SparkTools") public static Builder builder() { return new Builder(); } /** * Builder to build {@link FilterConfiguration}. */ @Generated("SparkTools") public static final class Builder { private Filter filter; private List<String> pathPatterns = Collections.emptyList(); private List<String> excludePathPatterns = Collections.emptyList(); private Builder() { } public Builder withFilter(Filter filter) { this.filter = filter; return this; } public Builder withPathPatterns(List<String> pathPatterns) { this.pathPatterns = pathPatterns; return this; } public Builder withExcludePathPatterns(List<String> excludePathPatterns) { this.excludePathPatterns = excludePathPatterns; return this; } public FilterConfiguration build() { return new FilterConfiguration(this); } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/FilterManager.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ package ai.houyi.dorado.rest.http.impl; import java.util.ArrayList; import java.util.List; import ai.houyi.dorado.rest.http.Filter; import ai.houyi.dorado.rest.util.AntPathMatcher; /** * @author wangweiping * */ public class FilterManager { private static final FilterManager instance = new FilterManager(); private final List<FilterConfiguration> filterConfigurations; private final AntPathMatcher pathMatcher; private FilterManager() { this.filterConfigurations = new ArrayList<>(); this.pathMatcher = new AntPathMatcher(); } public static FilterManager getInstance() { return instance; } public void addFilterConfiguration(FilterConfiguration filterConfiguration) { this.filterConfigurations.add(filterConfiguration); } public List<Filter> match(String uri) { List<Filter> filters = new ArrayList<>(); filterLoop: for (FilterConfiguration config : filterConfigurations) { List<String> excludePathPatterns = config.getExcludePathPatterns(); List<String> pathPatterns = config.getPathPatterns(); // 如果在排除路径中忽略 if (excludePathPatterns != null && !excludePathPatterns.isEmpty()) { for (String excluePathPattern : excludePathPatterns) { if (pathMatcher.match(excluePathPattern, uri)) { continue filterLoop; } } } // 如果只有排除路径没有include路径的话直接加入此过滤器 if (pathPatterns == null || pathPatterns.isEmpty()) { filters.add(config.getFilter()); continue filterLoop; } // 如果存在include路径,则再判断是否匹配include路径,匹配则加入 for (String pathPattern : pathPatterns) { if (pathMatcher.match(pathPattern, uri)) { filters.add(config.getFilter()); } } } return filters; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/HttpHeaderNames.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.rest.http.impl; /** * * @author wangwp */ public class HttpHeaderNames { public static final String CONTENT_TYPE = "content-type"; public static final String ACCEPT = "accept"; public static final String CONTENT_LENGTH = "content-length"; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/HttpRequestImpl.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.rest.http.impl; import java.io.InputStream; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import ai.houyi.dorado.netty.ext.HttpPostRequestDecoder; import ai.houyi.dorado.rest.http.HttpRequest; import ai.houyi.dorado.rest.http.MultipartFile; import ai.houyi.dorado.rest.util.LogUtils; import ai.houyi.dorado.rest.util.NetUtils; import ai.houyi.dorado.rest.util.StringUtils; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.ServerCookieDecoder; import io.netty.handler.codec.http.multipart.Attribute; import io.netty.handler.codec.http.multipart.FileUpload; import io.netty.handler.codec.http.multipart.InterfaceHttpData; import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType; /** * * @author wangwp */ public class HttpRequestImpl implements HttpRequest { private final FullHttpRequest request; private final InputStreamImpl in; private final QueryStringDecoder queryStringDecoder; private final URIParser uriParser; private final Map<String, List<String>> parameters; private final HttpHeaders headers; private final List<MultipartFile> multipartFiles; public HttpRequestImpl(FullHttpRequest request) { this.request = request; this.parameters = new HashMap<>(); this.headers = request.headers(); this.multipartFiles = new ArrayList<>(); this.uriParser = new URIParser(); // 解析querystring上面的参数 queryStringDecoder = new QueryStringDecoder(request.uri()); uriParser.parse(queryStringDecoder.path()); parameters.putAll(queryStringDecoder.parameters()); in = new InputStreamImpl(request); if (request.method() == HttpMethod.POST) { parseHttpPostRequest(request); } } private void parseHttpPostRequest(FullHttpRequest request) { HttpPostRequestDecoder decoder = null; try { decoder = new HttpPostRequestDecoder(request); for (InterfaceHttpData httpData : decoder.getBodyHttpDatas()) { HttpDataType _type = httpData.getHttpDataType(); if (_type == HttpDataType.Attribute) { Attribute attribute = (Attribute) httpData; parseAttribute(attribute); } else if (_type == HttpDataType.FileUpload) { FileUpload upload = (FileUpload) httpData; multipartFiles.add(MultipartFileFactory.create(upload)); } } } catch (Exception ex) { LogUtils.warn(ex.getMessage()); } finally { // 注意这个地方,一定要调用destroy方法,如果不调用会导致内存泄漏 if (decoder != null) decoder.destroy(); } } private void parseAttribute(Attribute attribute) throws Exception { if (this.parameters.containsKey(attribute.getName())) { this.parameters.get(attribute.getName()).add(attribute.getValue()); } else { List<String> values = new ArrayList<>(); values.add(attribute.getValue()); this.parameters.put(attribute.getName(), values); } } @Override public String getParameter(String key) { List<String> parameterValues = parameters.get(key); return (parameterValues == null || parameterValues.isEmpty()) ? null : parameterValues.get(0); } @Override public String[] getParameterValues(String key) { return this.parameters.get(key).toArray(new String[] {}); } @Override public Map<String, List<String>> getParameters() { return this.parameters; } @Override public String getRemoteAddr() { InetSocketAddress addr = (InetSocketAddress) ChannelHolder.get().remoteAddress(); String fallbackAddr = addr.getAddress().getHostAddress(); String xForwardFor = headers.get("X-Forwarded-For"); if (xForwardFor == null || StringUtils.isBlank(xForwardFor)) { return fallbackAddr; } String[] proxyIpList = xForwardFor.split(","); for (int i = proxyIpList.length - 1; i >= 0; i--) { String proxyIp = proxyIpList[i]; if (!NetUtils.isInternalIp(proxyIp)) { return proxyIp; } } return fallbackAddr; } @Override public ai.houyi.dorado.rest.http.Cookie[] getCookies() { String cookieString = this.request.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString); return cookies.stream().map(cookie -> new CookieImpl(cookie)).collect(Collectors.toList()) .toArray(new CookieImpl[] {}); } return null; } @Override public String getHeader(String name) { return headers.get(name); } @Override public String[] getHeaders(String name) { return headers.getAll(name).toArray(new String[] {}); } @Override public String getQueryString() { return uriParser.getQueryString(); } @Override public String getRequestURI() { return uriParser.getRequestUri(); } @Override public String getMethod() { return this.request.method().name(); } @Override public InputStream getInputStream() { return this.in; } public MultipartFile getFile() { if (multipartFiles != null && !multipartFiles.isEmpty()) { return multipartFiles.get(0); } return null; } public MultipartFile[] getFiles() { if (multipartFiles != null && !multipartFiles.isEmpty()) { return multipartFiles.toArray(new MultipartFile[] {}); } return null; } public List<MultipartFile> getFileList() { return multipartFiles; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/HttpResponseImpl.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.rest.http.impl; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import ai.houyi.dorado.exception.DoradoException; import ai.houyi.dorado.rest.http.HttpResponse; import io.netty.buffer.ByteBufUtil; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpResponseStatus; /** * * @author wangwp */ public class HttpResponseImpl implements HttpResponse { private FullHttpResponse originalHttpResponse; private OutputStreamImpl out; private PrintWriterImpl writer; public HttpResponseImpl(FullHttpResponse response) { this.originalHttpResponse = response; //out = new OutputStreamImpl(response); //writer = new PrintWriterImpl(out); } @Override public void setHeader(String name, String value) { originalHttpResponse.headers().set(name, value); } @Override public void addHeader(String name, String value) { originalHttpResponse.headers().add(name, value); } @Override public void sendRedirect(String location) { originalHttpResponse.setStatus(HttpResponseStatus.FOUND); originalHttpResponse.headers().set(HttpHeaderNames.LOCATION, location); } @Override public void sendError(int sc, String msg) { originalHttpResponse.setStatus(HttpResponseStatus.valueOf(sc, msg)); } @Override public void sendError(int sc) { originalHttpResponse.setStatus(HttpResponseStatus.valueOf(sc)); } @Override public void setStatus(int sc) { originalHttpResponse.setStatus(HttpResponseStatus.valueOf(sc)); } @Override public OutputStreamImpl getOutputStream() throws IOException { return out; } @Override public PrintWriter getWriter() throws IOException { return writer; } @Override public void write(byte[] content) { originalHttpResponse.content().writeBytes(content); } @Override public void writeStringUtf8(String str) { ByteBufUtil.writeUtf8(originalHttpResponse.content(), str); } @Override public void write(InputStream in) { try { originalHttpResponse.content().writeBytes(in, in.available()); } catch (IOException ex) { throw new DoradoException(ex); } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/InputStreamImpl.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.rest.http.impl; import java.io.IOException; import java.io.InputStream; import io.netty.buffer.ByteBufInputStream; import io.netty.handler.codec.http.FullHttpRequest; /** * * @author wangwp */ public class InputStreamImpl extends InputStream { private final ByteBufInputStream in; public InputStreamImpl(FullHttpRequest request) { this.in = new ByteBufInputStream(request.content()); } @Override public int read() throws IOException { return this.in.read(); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/MultipartFileFactory.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.rest.http.impl; import ai.houyi.dorado.rest.http.MultipartFile; import io.netty.handler.codec.http.multipart.FileUpload; /** * @author weiping wang * */ public final class MultipartFileFactory { public static MultipartFile create(FileUpload fileUpload) { try { MultipartFile _file = new MultipartFile(); _file.setContent(fileUpload.get()); _file.setContentType(fileUpload.getContentType()); _file.setSize(fileUpload.length()); _file.setName(fileUpload.getFilename()); return _file; } catch (Exception ex) { // ignore exception } return null; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/OutputStreamImpl.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.rest.http.impl; import java.io.IOException; import java.io.OutputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.handler.codec.http.FullHttpResponse; /** * * @author wangwp */ public class OutputStreamImpl extends OutputStream { private ByteBufOutputStream out; public OutputStreamImpl(FullHttpResponse response) { this.out = new ByteBufOutputStream(response.content()); } @Override public void write(int b) throws IOException { this.out.write(b); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/PrintWriterImpl.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.rest.http.impl; import java.io.OutputStream; import java.io.PrintWriter; /** * * @author wangwp */ public class PrintWriterImpl extends PrintWriter { private boolean flushed; public PrintWriterImpl(OutputStream out) { super(out); } @Override public void flush() { super.flush(); this.flushed = true; } public boolean isFlushed() { return flushed; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/ResponseEntity.java
/* * Copyright 2017 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.rest.http.impl; /** * @author weiping wang * */ public class ResponseEntity { private int status; private String location; private Object body; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Object getBody() { return body; } public void setBody(Object body) { this.body = body; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/URIParser.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.rest.http.impl; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.rest.util.StringUtils; /** * * @author wangwp */ public class URIParser { private String requestUri; private String queryString; private String contextPath; public URIParser() { this(Dorado.serverConfig.getContextPath()); } public URIParser(String contextPath) { this.contextPath = contextPath; } public void parse(String uri) { int indx = uri.indexOf('?'); if (indx != -1) { this.queryString = uri.substring(indx + 1); this.requestUri = uri.substring(0, indx); } else { this.requestUri = uri; } if (requestUri.startsWith(contextPath)) { this.requestUri = this.requestUri.substring(contextPath.length()); } if (this.requestUri.endsWith("/")) this.requestUri = this.requestUri.substring(this.requestUri.length() - 1); if (StringUtils.EMPTY.equals(this.requestUri)) { this.requestUri = "/"; } } public String getQueryString() { return queryString; } public String getRequestUri() { return requestUri; } public static void main(String[] args) throws Exception { URIParser parser = new URIParser("/api"); parser.parse("/api/"); System.out.println(parser.getRequestUri()); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/WebComponentRegistry.java
/* * Copyright 2017 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.rest.http.impl; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.rest.annotation.ExceptionAdvice; import ai.houyi.dorado.rest.annotation.ExceptionType; /** * @author weiping wang * */ public final class WebComponentRegistry { private static final WebComponentRegistry registry = new WebComponentRegistry(); private final ConcurrentMap<Class<? extends Throwable>, ExceptionHandler> exceptionHandlerRegistry = new ConcurrentHashMap<>(); private WebComponentRegistry() { } public static WebComponentRegistry getWebComponentRegistry() { return registry; } public ExceptionHandler getExceptionHandler(Class<? extends Throwable> exceptionType) { ExceptionHandler handler = exceptionHandlerRegistry.get(exceptionType); if (Exception.class.isAssignableFrom(exceptionType)) { return getExceptionHandler(); } if (Error.class.isAssignableFrom(exceptionType)) { return getErrorHandler(); } return handler; } private ExceptionHandler getExceptionHandler() { ExceptionHandler handler = exceptionHandlerRegistry.get(Exception.class); if (handler == null) { return exceptionHandlerRegistry.get(Throwable.class); } return handler; } private ExceptionHandler getErrorHandler() { ExceptionHandler handler = exceptionHandlerRegistry.get(Error.class); if (handler == null) { return exceptionHandlerRegistry.get(Throwable.class); } return handler; } public void registerExceptionHandlers(Class<?> type) { Annotation exceptionAdvice = type.getAnnotation(ExceptionAdvice.class); if (exceptionAdvice == null) { return; } Object exceptionAdvicor = Dorado.beanContainer.getBean(type); Method[] methods = type.getMethods(); for (Method method : methods) { ExceptionType exceptionType = method.getAnnotation(ExceptionType.class); if (exceptionType == null) { continue; } ExceptionHandler handler = ExceptionHandler.newExceptionHandler(exceptionAdvicor, method); exceptionHandlerRegistry.put(exceptionType.value(), handler); } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/Webapp.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.rest.http.impl; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.exception.DoradoException; import ai.houyi.dorado.rest.ResourceRegister; import ai.houyi.dorado.rest.ResourceRegisters; import ai.houyi.dorado.rest.annotation.ExceptionAdvice; import ai.houyi.dorado.rest.annotation.FilterPath; import ai.houyi.dorado.rest.controller.RootController; import ai.houyi.dorado.rest.http.Filter; import ai.houyi.dorado.rest.http.MethodReturnValueHandler; import ai.houyi.dorado.rest.http.MethodReturnValueHandlerConfig; import ai.houyi.dorado.rest.router.UriRoutingRegistry; import ai.houyi.dorado.rest.util.LogUtils; import ai.houyi.dorado.rest.util.PackageScanner; /** * * @author wangwp */ public class Webapp { private static Webapp webapp; private final String[] packages; private MethodReturnValueHandlerConfig methodReturnValueHandlerConfig; private Webapp(String[] packages, boolean springOn) { this.packages = packages; } public static synchronized void create(String[] packages) { create(packages, false); } public static synchronized void create(String[] packages, boolean springOn) { webapp = new Webapp(packages, springOn); webapp.initialize(); } public static Webapp get() { if (webapp == null) { throw new IllegalStateException("webapp not initialized, please create it first"); } return webapp; } public MethodReturnValueHandlerConfig getMethodReturnValueHandlerConfig() { return this.methodReturnValueHandlerConfig; } public void initialize() { List<Class<?>> classes = new ArrayList<>(); for (ResourceRegister resourceRegister : ResourceRegisters.getInstance().getResourceRegisters()) { resourceRegister.register(); } try { for (String scanPackage : packages) { classes.addAll(PackageScanner.scan(scanPackage)); } initializeUriRouting(RootController.class); classes.forEach(clazz -> { registerWebComponent(clazz); }); UriRoutingRegistry registry = getUriRoutingRegistry(); if (registry.uriRoutings().isEmpty()) { LogUtils.warn("No Controller are registered, please check first"); } } catch (Exception ex) { throw new DoradoException(ex); } }; private void registerWebComponent(Class<?> type) { Annotation exceptionAdvice = type.getAnnotation(ExceptionAdvice.class); if (exceptionAdvice != null) { registerExceptionAdvice(type); } if (MethodReturnValueHandler.class.isAssignableFrom(type)) { if (this.methodReturnValueHandlerConfig != null) { throw new IllegalStateException("Only one instance for [MethodReturnValueHandler] is allowed"); } MethodReturnValueHandler returnValueHandler = (MethodReturnValueHandler) Dorado.beanContainer.getBean(type); this.methodReturnValueHandlerConfig = new MethodReturnValueHandlerConfig(returnValueHandler); } if (Filter.class.isAssignableFrom(type)) { FilterPath filterPath = type.getAnnotation(FilterPath.class); if (filterPath == null) { return; } String[] include = filterPath.include(); String[] exclude = filterPath.exclude(); if (include == null && exclude == null) { return; } FilterConfiguration.Builder fcb = FilterConfiguration.builder(); if (include != null && include.length > 0) { fcb.withPathPatterns(Arrays.asList(include)); } if (exclude != null && exclude.length > 0) { fcb.withExcludePathPatterns(Arrays.asList(exclude)); } fcb.withFilter((Filter) Dorado.beanContainer.getBean(type)); FilterManager.getInstance().addFilterConfiguration(fcb.build()); } else { initializeUriRouting(type); } } private void registerExceptionAdvice(Class<?> type) { WebComponentRegistry.getWebComponentRegistry().registerExceptionHandlers(type); } private void initializeUriRouting(Class<?> c) { UriRoutingRegistry.getInstance().register(c); } public UriRoutingRegistry getUriRoutingRegistry() { return UriRoutingRegistry.getInstance(); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/http/impl/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.rest.http.impl;
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/router/Router.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.rest.router; import java.util.ArrayList; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import ai.houyi.dorado.exception.DoradoException; import ai.houyi.dorado.rest.http.Filter; import ai.houyi.dorado.rest.http.HttpRequest; import ai.houyi.dorado.rest.http.HttpResponse; /** * * @author wangwp */ public class Router { private final UriRoutingController controller; private final String[] pathVariables; private final String httpMethod; private final List<Filter> filters; private Router(UriRoutingController controller, MatchResult matchResult, String httpMethod) { this.filters = new ArrayList<>(); this.httpMethod = httpMethod; this.controller = controller; pathVariables = new String[matchResult.groupCount()]; for (int i = 0; i < pathVariables.length; i++) { pathVariables[i] = matchResult.group(i + 1); } } public static Router create(UriRoutingController controller, Matcher matchResult, String httpMethod) { return new Router(controller, matchResult, httpMethod); } public UriRoutingController controller() { return this.controller; } public void addFilters(List<Filter> filters) { this.filters.addAll(filters); } public Object invoke(HttpRequest request, HttpResponse response) { try { for (Filter filter : filters) { if (!filter.preFilter(request, response)) { return null; } } return this.controller.invoke(request, response, pathVariables); } catch (Exception ex) { throw new DoradoException(ex); } finally { for (Filter filter : filters) { filter.postFilter(request, response); } } } public String getHttpMethod() { return httpMethod; } public String pathVariable(int index) { if (index <= 0 || index > pathVariables.length) { throw new IndexOutOfBoundsException(); } return pathVariables[index - 1]; } public String[] pathVariables() { return this.pathVariables; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/router/UriRoutingController.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.rest.router; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import ai.houyi.dorado.exception.DoradoException; import ai.houyi.dorado.rest.MediaType; import ai.houyi.dorado.rest.MessageBodyConverter; import ai.houyi.dorado.rest.MessageBodyConverters; import ai.houyi.dorado.rest.ParameterValueResolver; import ai.houyi.dorado.rest.ParameterValueResolvers; import ai.houyi.dorado.rest.annotation.Status; import ai.houyi.dorado.rest.http.HttpRequest; import ai.houyi.dorado.rest.http.HttpResponse; import ai.houyi.dorado.rest.http.MethodReturnValueHandler; import ai.houyi.dorado.rest.http.MethodReturnValueHandlerConfig; import ai.houyi.dorado.rest.http.impl.ExceptionHandler; import ai.houyi.dorado.rest.http.impl.HttpHeaderNames; import ai.houyi.dorado.rest.http.impl.WebComponentRegistry; import ai.houyi.dorado.rest.http.impl.Webapp; import ai.houyi.dorado.rest.util.MediaTypeUtils; import ai.houyi.dorado.rest.util.MethodDescriptor; import ai.houyi.dorado.rest.util.MethodDescriptor.MethodParameter; import io.netty.handler.codec.http.HttpMethod; /** * * @author wangwp */ public class UriRoutingController { private final MethodDescriptor methodDescriptor; private final UriRoutingPath uriRoutingPath; private UriRoutingController(UriRoutingPath uriRoutingPath, Class<?> clazz, Method method) { methodDescriptor = MethodDescriptor.create(clazz, method); this.uriRoutingPath = uriRoutingPath; } public static UriRoutingController create(UriRoutingPath uriRoutingPath, Class<?> clazz, Method method) { return new UriRoutingController(uriRoutingPath, clazz, method); } public Object invoke(HttpRequest request, HttpResponse response, String[] pathVariables) throws Exception { Method invokeMethod = methodDescriptor.getMethod(); MediaType expectedMediaType = MediaType.valueOf(methodDescriptor.consume()); // 如果非GET、DELETE请求需要验证请求的内容类型是否匹配 if (!HttpMethod.GET.name().equals(request.getMethod()) && !HttpMethod.DELETE.name().equals(request.getMethod()) && (!expectedMediaType.isWildcardType())) { String contentType = request.getHeader(HttpHeaderNames.CONTENT_TYPE); MediaType requestMediaType = MediaType.valueOf(contentType); if (requestMediaType != null && !requestMediaType.isCompatible(expectedMediaType)) { throw new DoradoException(String.format("Invalid request content_type, expected: [%s], actual: [%s]", methodDescriptor.consume(), contentType)); } } Object[] args = resolveParameters(request, response, pathVariables); MethodReturnValueHandlerConfig methodReturnValueHandlerConfig = Webapp.get() .getMethodReturnValueHandlerConfig(); try { Object invokeResult = invokeMethod.invoke(methodDescriptor.getInvokeTarget(), args); // 支持对controller返回结果进行统一处理 MediaType mediaType = MediaTypeUtils.defaultForType(methodDescriptor.getReturnType(), methodDescriptor.produce()); if (supportHandleMethodReturnValue(request, methodDescriptor, methodReturnValueHandlerConfig)) { invokeResult = methodReturnValueHandlerConfig.getHandler().handleMethodReturnValue(invokeResult, methodDescriptor); if (invokeResult != null) { mediaType = MediaTypeUtils.defaultForType(invokeResult.getClass(), null); } } if (methodReturnValueHandlerConfig != null && !methodReturnValueHandlerConfig.exclude(request.getRequestURI())) { } writeResponseBody(invokeResult, mediaType, response); } catch (Exception ex) { handleException(ex, request, response); } return null; } private boolean supportHandleMethodReturnValue(HttpRequest request, MethodDescriptor methodDescriptor, MethodReturnValueHandlerConfig methodReturnValueHandlerConfig) { if (methodReturnValueHandlerConfig == null) return false; MethodReturnValueHandler handler = methodReturnValueHandlerConfig.getHandler(); if (!methodReturnValueHandlerConfig.exclude(request.getRequestURI()) && handler.supportsReturnType(methodDescriptor)) { return true; } return false; } private void handleException(Exception ex, HttpRequest request, HttpResponse response) { Throwable targetException = ex; if (ex instanceof InvocationTargetException) { targetException = ((InvocationTargetException) ex).getTargetException(); } ExceptionHandler exceptionHandler = WebComponentRegistry.getWebComponentRegistry() .getExceptionHandler(targetException.getClass()); if (exceptionHandler == null) { throw new DoradoException(targetException); } Object exceptionHandleResult = exceptionHandler.handleException(targetException); if (exceptionHandleResult == null) { throw new DoradoException(targetException); } MediaType mediaType = MediaTypeUtils.defaultForType(exceptionHandleResult.getClass(), exceptionHandler.produce()); Status status = exceptionHandler.status(); if (status != null) response.setStatus(status.value()); writeResponseBody(exceptionHandleResult, mediaType, response); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void writeResponseBody(Object body, MediaType mediaType, HttpResponse response) { if (body == null) return; MessageBodyConverter messageBodyConverter = MessageBodyConverters.getMessageBodyConverter(mediaType); response.setHeader(HttpHeaderNames.CONTENT_TYPE, mediaType.toString()); response.write(messageBodyConverter.writeMessageBody(body)); } private Object[] resolveParameters(HttpRequest request, HttpResponse response, String[] pathVariables) { MethodParameter[] methodParameters = methodDescriptor.getParameters(); if (methodParameters.length == 0) return null; Object[] methodArgs = new Object[methodParameters.length]; for (int i = 0; i < methodArgs.length; i++) { int pathVariableIndex = uriRoutingPath.resolvePathIndex(methodParameters[i].getName()); methodArgs[i] = resolveMethodArg(request, response, methodDescriptor, methodParameters[i], pathVariableIndex == -1 ? null : pathVariables[pathVariableIndex]); } return methodArgs; } private Object resolveMethodArg(HttpRequest request, HttpResponse response, MethodDescriptor desc, MethodParameter methodParameter, String pathVariable) { Class<?> parameterAnnotationType = methodParameter.getAnnotationType(); ParameterValueResolver parameterValueResolver = ParameterValueResolvers .getParameterValueResolver(parameterAnnotationType); return parameterValueResolver.resolveParameterValue(request, response, desc, methodParameter, pathVariable); } @Override public String toString() { return "RouteController [methodDescriptor=" + methodDescriptor + "]"; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/router/UriRoutingPath.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.rest.router; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import ai.houyi.dorado.rest.annotation.HttpMethod; /** * * @author wangwp */ public class UriRoutingPath implements Comparable<UriRoutingPath> { private static final Pattern pathVariablePattern = Pattern.compile("\\{([^{}]*)\\}"); private static final String defaultPathVariableRegex = "[^/]+"; private String routingPath; private Pattern routingPathPattern; private HttpMethod httpMethod; private Map<String, Integer> pathVariableIndexHolder = new ConcurrentHashMap<>(); private UriRoutingPath(String routingPath, HttpMethod httpMethod) { this.httpMethod = httpMethod; this.routingPath = routingPath; Matcher matchResult = pathVariablePattern.matcher(routingPath); int pathVariableIndex = 0; StringBuffer routingPathRegex = new StringBuffer(); while (matchResult.find()) { String pathVariableExpression = matchResult.group(1); String[] pathVariableSegments = pathVariableExpression.split(":"); String pathVariableRegex = pathVariableSegments.length == 2 ? pathVariableSegments[1] : defaultPathVariableRegex; String pathVariableName = pathVariableSegments[0]; matchResult.appendReplacement(routingPathRegex, String.format("(%s)", pathVariableRegex)); pathVariableIndexHolder.put(pathVariableName, pathVariableIndex); pathVariableIndex++; } matchResult.appendTail(routingPathRegex); routingPathPattern = Pattern.compile(routingPathRegex.toString()); } public static UriRoutingPath create(String uri, HttpMethod httpMethod) { return new UriRoutingPath(uri, httpMethod); } public Pattern routingPathPattern() { return this.routingPathPattern; } public int resolvePathIndex(String parameterName) { Integer pathIndex = pathVariableIndexHolder.get(parameterName); return pathIndex == null ? -1 : pathIndex; } public String routingPath() { return this.routingPath; } public String httpMethod() { return httpMethod == null ? null : httpMethod.value(); } @Override public int hashCode() { final int prime = 31; int hash = 1; hash = prime * hash + ((httpMethod == null) ? 0 : httpMethod.hashCode()); hash = prime * hash + ((routingPath == null) ? 0 : routingPath.hashCode()); return hash; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UriRoutingPath other = (UriRoutingPath) obj; if (httpMethod == null) { if (other.httpMethod != null) return false; } else if (!httpMethod.equals(other.httpMethod)) return false; if (routingPath == null) { if (other.routingPath != null) return false; } else if (!routingPath.equals(other.routingPath)) return false; return true; } @Override public String toString() { return "UriRoutingPath [routingPath=" + routingPath + ", routingPathPattern=" + routingPathPattern + ", httpMethod=" + httpMethod + ", pathVariableIndexHolder=" + pathVariableIndexHolder + "]"; } @Override public int compareTo(UriRoutingPath o) { int targetPathSegments = o.routingPath.split("/").length; int thisPathSegments = routingPath.split("/").length; if (targetPathSegments != thisPathSegments) { return targetPathSegments - thisPathSegments; } return pathVariableIndexHolder.size() - o.pathVariableIndexHolder.size(); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/router/UriRoutingRegistry.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.rest.router; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import ai.houyi.dorado.rest.annotation.Controller; import ai.houyi.dorado.rest.annotation.HttpMethod; import ai.houyi.dorado.rest.annotation.Path; import ai.houyi.dorado.rest.http.HttpRequest; import ai.houyi.dorado.rest.http.impl.FilterManager; import ai.houyi.dorado.rest.util.SimpleLRUCache; import ai.houyi.dorado.rest.util.StringUtils; /** * * @author wangwp */ public class UriRoutingRegistry { private static final UriRoutingRegistry _instance = new UriRoutingRegistry(); private List<UriRouting> uriRoutingRegistry = new ArrayList<>(); private final SimpleLRUCache<RoutingCacheKey, Router> cache = SimpleLRUCache.create(512); private UriRoutingRegistry() { } public static UriRoutingRegistry getInstance() { return _instance; } public void register(Class<?> type) { Controller controller = type.getAnnotation(Controller.class); if (controller == null) { return; } Path classLevelPath = type.getAnnotation(Path.class); String controllerPath = classLevelPath == null ? StringUtils.EMPTY : classLevelPath.value(); Method[] controllerMethods = type.getDeclaredMethods(); for (Method method : controllerMethods) { if (Modifier.isStatic(method.getModifiers()) || method.getAnnotations().length == 0 || !Modifier.isPublic(method.getModifiers())) { continue; } Path methodLevelPath = method.getAnnotation(Path.class); HttpMethod httpMethod = getHttpMethod(method.getAnnotations()); String methodPath = methodLevelPath == null ? StringUtils.EMPTY : methodLevelPath.value(); UriRoutingPath uriRoutingPath = UriRoutingPath.create(String.format("%s%s", controllerPath, methodPath), httpMethod); UriRoutingController routeController = UriRoutingController.create(uriRoutingPath, type, method); register(uriRoutingPath, routeController); } } private HttpMethod getHttpMethod(Annotation[] annotations) { HttpMethod httpMethod = null; for (Annotation annotation : annotations) { httpMethod = annotation.annotationType().getAnnotation(HttpMethod.class); if (httpMethod != null) { return httpMethod; } } return null; } public void register(UriRoutingPath routeMapping, UriRoutingController controller) { uriRoutingRegistry.add(UriRouting.create(routeMapping, controller)); uriRoutingRegistry.sort((a, b) -> a.path.compareTo(b.path)); } public Router findRouteController(HttpRequest request) { Matcher matchResult = null; String routingMethod = null; RoutingCacheKey key = new RoutingCacheKey(request.getRequestURI(), request.getMethod()); Router router = cache.get(key); if (router != null) { return router; } for (UriRouting uriRouting : uriRoutingRegistry) { routingMethod = uriRouting.path.httpMethod(); matchResult = uriRouting.path.routingPathPattern().matcher(request.getRequestURI()); if (matchResult.matches() && matchMethod(routingMethod, request.getMethod())) { router = Router.create(uriRouting.controller, matchResult, request.getMethod()); router.addFilters(FilterManager.getInstance().match(request.getRequestURI())); cache.put(key, router); return router; } } return null; } private boolean matchMethod(String routingMethod, String method) { return routingMethod == null || method.equals(routingMethod); } public List<UriRouting> uriRoutings() { return Collections.unmodifiableList(uriRoutingRegistry); } @Override public String toString() { return "UriRoutingRegistry [uriRouteMappingRegistry=" + uriRoutingRegistry + "]"; } public static class UriRouting { private final UriRoutingPath path; private final UriRoutingController controller; private UriRouting(UriRoutingPath path, UriRoutingController controller) { this.path = path; this.controller = controller; } public static UriRouting create(UriRoutingPath path, UriRoutingController controller) { return new UriRouting(path, controller); } public UriRoutingPath uriRoutingPath() { return path; } public UriRoutingController controller() { return controller; } @Override public String toString() { return "UriRouting [path=" + path + ", controller=" + controller + "]"; } } public void clear() { uriRoutingRegistry.clear(); } private class RoutingCacheKey { private String uri; private String method; public RoutingCacheKey(String uri, String method) { this.uri = uri; this.method = method; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((method == null) ? 0 : method.hashCode()); result = prime * result + ((uri == null) ? 0 : uri.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } RoutingCacheKey other = (RoutingCacheKey) obj; if (!getOuterType().equals(other.getOuterType())) { return false; } if (method == null) { if (other.method != null) { return false; } } else if (!method.equals(other.method)) { return false; } if (uri == null) { if (other.uri != null) { return false; } } else if (!uri.equals(other.uri)) { return false; } return true; } private UriRoutingRegistry getOuterType() { return UriRoutingRegistry.this; } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/router/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.rest.router;
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/server/DoradoServer.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.rest.server; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.rest.http.impl.Webapp; import ai.houyi.dorado.rest.util.ClassLoaderUtils; import ai.houyi.dorado.rest.util.LogUtils; import ai.houyi.dorado.spring.SpringContainer; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.timeout.IdleStateHandler; /** * * @author wangwp */ public class DoradoServer { private final DoradoServerBuilder builder; public DoradoServer(DoradoServerBuilder builder) { this.builder = builder; } public void start() { // print dorado ascii-art logo,use figlet generate ascii-art logo if (!Dorado.springInitialized) { System.out.println(ClassLoaderUtils.getResoureAsString("dorado-ascii")); System.out.println(); } if (builder.isSpringOn() && !Dorado.springInitialized) { SpringContainer.create(builder.scanPackages()); } Webapp.create(builder.scanPackages(), builder.isSpringOn()); EventLoopGroup acceptor = new NioEventLoopGroup(builder.getAcceptors()); EventLoopGroup worker = new NioEventLoopGroup(builder.getIoWorkers()); ServerBootstrap bootstrap = null; try { bootstrap = new ServerBootstrap().group(acceptor, worker).channel(NioServerSocketChannel.class) .childHandler(new DoradoChannelInitializer(builder)); bootstrap.option(ChannelOption.SO_BACKLOG, builder.getBacklog()); bootstrap.childOption(ChannelOption.TCP_NODELAY, true); bootstrap.childOption(ChannelOption.SO_SNDBUF, builder.getSendBuffer()); bootstrap.childOption(ChannelOption.SO_RCVBUF, builder.getRecvBuffer()); ChannelFuture f = bootstrap.bind(builder.getPort()).sync(); LogUtils.info(String.format("Dorado application initialized with port: %d (http)", builder.getPort())); f.channel().closeFuture().sync(); } catch (Throwable ex) { LogUtils.error("Start dorado application failed, cause: " + ex.getMessage(), ex); } finally { worker.shutdownGracefully(); acceptor.shutdownGracefully(); } } static class DoradoChannelInitializer extends ChannelInitializer<Channel> { private final DoradoServerBuilder builder; public DoradoChannelInitializer(DoradoServerBuilder builder) { this.builder = builder; } @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(builder.getMaxPacketLength())); pipeline.addLast(new IdleStateHandler(builder.getMaxIdleTime(), 0, 0)); pipeline.addLast(DoradoServerHandler.create(builder)); } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/server/DoradoServerBuilder.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.rest.server; import java.util.concurrent.LinkedBlockingQueue; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.rest.util.Constant; import ai.houyi.dorado.rest.util.LogUtils; import ai.houyi.dorado.rest.util.StringUtils; import ai.houyi.dorado.rest.util.TracingThreadPoolExecutor; /** * * @author wangwp */ public final class DoradoServerBuilder { private int backlog = Constant.DEFAULT_BACKLOG; private int acceptors = Constant.DEFAULT_ACCEPTOR_COUNT; private int ioWorkers = Constant.DEFAULT_IO_WORKER_COUNT; private int minWorkers = Constant.DEFAULT_MIN_WORKER_THREAD; private int maxWorkers = Constant.DEFAULT_MAX_WORKER_THREAD; private int maxConnection = Integer.MAX_VALUE; private int maxPendingRequest = Constant.DEFAULT_MAX_PENDING_REQUEST; private int maxIdleTime = Constant.DEFAULT_MAX_IDLE_TIME; // 以下参数用于accept到服务器的socket private int sendBuffer = Constant.DEFAULT_SEND_BUFFER_SIZE; private int recvBuffer = Constant.DEFAULT_RECV_BUFFER_SIZE; private int maxPacketLength = Constant.DEFAULT_MAX_PACKET_LENGTH; private String[] scanPackages; private boolean devMode; private boolean springOn; private boolean filterOn; private String contextPath = StringUtils.EMPTY; private TracingThreadPoolExecutor executor; private final int port; private DoradoServerBuilder(int port) { this.port = port; } public boolean isFilterOn() { return filterOn; } public static DoradoServerBuilder forPort(int port) { return new DoradoServerBuilder(port); } public DoradoServerBuilder backlog(int backlog) { this.backlog = backlog; return this; } public DoradoServerBuilder acceptors(int acceptors) { this.acceptors = acceptors; return this; } public DoradoServerBuilder ioWorkers(int ioWorkers) { this.ioWorkers = ioWorkers; return this; } public DoradoServerBuilder minWorkers(int minWorkers) { this.minWorkers = minWorkers; return this; } public DoradoServerBuilder maxWorkers(int maxWorkers) { this.maxWorkers = maxWorkers; return this; } public DoradoServerBuilder maxIdleTime(int maxIdleTime) { this.maxIdleTime = maxIdleTime; return this; } public DoradoServerBuilder sendBuffer(int sendBuffer) { this.sendBuffer = sendBuffer; return this; } public DoradoServerBuilder recvBuffer(int recvBuffer) { this.recvBuffer = recvBuffer; return this; } public DoradoServerBuilder maxConnection(int maxConnection) { this.maxConnection = maxConnection; return this; } public DoradoServerBuilder maxPendingRequest(int maxPendingRequest) { this.maxPendingRequest = maxPendingRequest; return this; } public DoradoServerBuilder maxPacketLength(int maxPacketLength) { this.maxPacketLength = maxPacketLength; return this; } public DoradoServerBuilder scanPackages(String... packages) { this.scanPackages = packages; return this; } public DoradoServerBuilder devMode(boolean devMode) { this.devMode = devMode; return this; } public DoradoServerBuilder springOn() { this.springOn = true; return this; } public DoradoServerBuilder filterOn() { this.filterOn = true; return this; } public DoradoServerBuilder contextPath(String contextPath) { this.contextPath = contextPath; return this; } public int getBacklog() { return backlog; } public int getAcceptors() { return acceptors; } public int getIoWorkers() { return ioWorkers; } public int getMinWorkers() { return minWorkers; } public int getMaxWorkers() { return maxWorkers; } public int getMaxConnection() { return maxConnection; } public int getMaxPendingRequest() { return maxPendingRequest; } public boolean isDevMode() { return devMode; } public boolean isSpringOn() { return this.springOn; } public int getMaxIdleTime() { return maxIdleTime; } public int getSendBuffer() { return sendBuffer; } public int getRecvBuffer() { return recvBuffer; } public int getMaxPacketLength() { return maxPacketLength; } public String[] scanPackages() { return this.scanPackages; } public TracingThreadPoolExecutor executor() { return this.executor; } public int getPort() { return port; } public String getContextPath() { return contextPath; } public DoradoServer build() { Class<?> mainClass = resolveMainClass(); if (minWorkers > maxWorkers) { throw new IllegalArgumentException("minWorkers is greater than maxWorkers"); } if (maxPendingRequest <= 0) { throw new IllegalArgumentException("maxPendingRequest must be greater than 0"); } executor = new TracingThreadPoolExecutor(minWorkers, maxWorkers, new LinkedBlockingQueue<>(maxPendingRequest)); if (!devMode) { executor.prestartAllCoreThreads(); } if ((scanPackages == null || scanPackages.length == 0) && mainClass != null) { String defaultPackage = mainClass.getPackage().getName(); LogUtils.warn(String.format("Not setting scanPackages property, get default: %s", defaultPackage)); scanPackages = new String[] { defaultPackage }; } if (scanPackages == null || scanPackages.length == 0) { throw new IllegalArgumentException("scanPackages must be not null"); } Dorado.serverConfig = this; return new DoradoServer(this); } private Class<?> resolveMainClass() { Class<?> mainClass = null; try { StackTraceElement[] stackTrace = new RuntimeException().getStackTrace(); for (StackTraceElement stackTraceElement : stackTrace) { if ("main".equals(stackTraceElement.getMethodName())) { mainClass = Class.forName(stackTraceElement.getClassName()); Dorado.mainClass = mainClass; break; } } } catch (Exception ex) { // ignore this ex } return mainClass; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/server/DoradoServerHandler.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.rest.server; import static ai.houyi.dorado.rest.http.impl.ChannelHolder.set; import static ai.houyi.dorado.rest.http.impl.ChannelHolder.unset; import ai.houyi.dorado.rest.controller.DoradoStatus; import ai.houyi.dorado.rest.http.HttpRequest; import ai.houyi.dorado.rest.http.HttpResponse; import ai.houyi.dorado.rest.http.impl.HttpRequestImpl; import ai.houyi.dorado.rest.http.impl.HttpResponseImpl; import ai.houyi.dorado.rest.http.impl.Webapp; import ai.houyi.dorado.rest.router.Router; import ai.houyi.dorado.rest.util.ExceptionUtils; import ai.houyi.dorado.rest.util.LogUtils; import ai.houyi.dorado.rest.util.TracingThreadPoolExecutor; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.ReferenceCountUtil; /** * * @author wangwp */ public class DoradoServerHandler extends ChannelInboundHandlerAdapter { private final TracingThreadPoolExecutor asyncExecutor; private final Webapp webapp; private final DoradoStatus status; private DoradoServerHandler(DoradoServerBuilder builder) { this.webapp = Webapp.get(); this.asyncExecutor = (TracingThreadPoolExecutor) builder.executor(); this.status = DoradoStatus.get(); } public static DoradoServerHandler create(DoradoServerBuilder builder) { return new DoradoServerHandler(builder); } public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { status.totalRequestsIncrement(); if (asyncExecutor == null) { handleHttpRequest(ctx, msg); return; } asyncExecutor.execute(() -> { handleHttpRequest(ctx, msg); }); } private void handleHttpRequest(ChannelHandlerContext ctx, Object msg) { FullHttpRequest request = (FullHttpRequest) msg; FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK); boolean isKeepAlive = HttpUtil.isKeepAlive(request); HttpUtil.setKeepAlive(response, isKeepAlive); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8"); response.headers().set(HttpHeaderNames.SERVER, "Dorado"); ChannelFuture channelFuture = null; try { set(ctx.channel()); HttpRequest _request = new HttpRequestImpl(request); HttpResponse _response = new HttpResponseImpl(response); Router router = webapp.getUriRoutingRegistry().findRouteController(_request); if (router == null) { response.setStatus(HttpResponseStatus.NOT_FOUND); ByteBufUtil.writeUtf8(response.content(), String.format("Resource not found, url: [%s], http_method: [%s]", _request.getRequestURI(), _request.getMethod())); } else { router.invoke(_request, _response); } } catch (Throwable ex) { LogUtils.error("handle http request error", ex); response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); ByteBufUtil.writeUtf8(response.content(), ExceptionUtils.toString(ex)); } finally { unset(); if (isKeepAlive) { HttpUtil.setContentLength(response, response.content().readableBytes()); } channelFuture = ctx.channel().writeAndFlush(response); if (!isKeepAlive && channelFuture != null) { channelFuture.addListener(ChannelFutureListener.CLOSE); } ReferenceCountUtil.release(msg); status.handledRequestsIncrement(); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; if (e == IdleStateEvent.READER_IDLE_STATE_EVENT) { ctx.channel().close(); } } super.userEventTriggered(ctx, evt); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { status.connectionIncrement(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { status.connectionDecrement(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LogUtils.error(cause.getMessage(), cause); ctx.channel().close(); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/server/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.rest.server;
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/AntPathMatcher.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed 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.rest.util; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * {@link PathMatcher} implementation for Ant-style path patterns. * * @author Alef Arendsen * @author Juergen Hoeller * @author Rob Harrop * @author Arjen Poutsma * @author Rossen Stoyanchev * @author Sam Brannen * @since 16.07.2003 */ public class AntPathMatcher implements PathMatcher { /** Default path separator: "/" */ public static final String DEFAULT_PATH_SEPARATOR = "/"; private static final int CACHE_TURNOFF_THRESHOLD = 65536; private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}"); private static final char[] WILDCARD_CHARS = { '*', '?', '{' }; private String pathSeparator; private PathSeparatorPatternCache pathSeparatorPatternCache; private boolean caseSensitive = true; private boolean trimTokens = false; private volatile Boolean cachePatterns; private final Map<String, String[]> tokenizedPatternCache = new ConcurrentHashMap<String, String[]>(256); final Map<String, AntPathStringMatcher> stringMatcherCache = new ConcurrentHashMap<String, AntPathStringMatcher>( 256); /** * Create a new instance with the {@link #DEFAULT_PATH_SEPARATOR}. */ public AntPathMatcher() { this.pathSeparator = DEFAULT_PATH_SEPARATOR; this.pathSeparatorPatternCache = new PathSeparatorPatternCache(DEFAULT_PATH_SEPARATOR); } public AntPathMatcher(String pathSeparator) { if (StringUtils.isBlank(pathSeparator)) { throw new IllegalArgumentException("pathSeparator' is required"); } this.pathSeparator = pathSeparator; this.pathSeparatorPatternCache = new PathSeparatorPatternCache(pathSeparator); } public void setPathSeparator(String pathSeparator) { this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR); this.pathSeparatorPatternCache = new PathSeparatorPatternCache(this.pathSeparator); } public void setCaseSensitive(boolean caseSensitive) { this.caseSensitive = caseSensitive; } public void setTrimTokens(boolean trimTokens) { this.trimTokens = trimTokens; } public void setCachePatterns(boolean cachePatterns) { this.cachePatterns = cachePatterns; } private void deactivatePatternCache() { this.cachePatterns = false; this.tokenizedPatternCache.clear(); this.stringMatcherCache.clear(); } @Override public boolean isPattern(String path) { return (path.indexOf('*') != -1 || path.indexOf('?') != -1); } @Override public boolean match(String pattern, String path) { return doMatch(pattern, path, true, null); } @Override public boolean matchStart(String pattern, String path) { return doMatch(pattern, path, false, null); } protected boolean doMatch(String pattern, String path, boolean fullMatch, Map<String, String> uriTemplateVariables) { if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) { return false; } String[] pattDirs = tokenizePattern(pattern); if (fullMatch && this.caseSensitive && !isPotentialMatch(path, pattDirs)) { return false; } String[] pathDirs = tokenizePath(path); int pattIdxStart = 0; int pattIdxEnd = pattDirs.length - 1; int pathIdxStart = 0; int pathIdxEnd = pathDirs.length - 1; // Match all elements up to the first ** while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { String pattDir = pattDirs[pattIdxStart]; if ("**".equals(pattDir)) { break; } if (!matchStrings(pattDir, pathDirs[pathIdxStart], uriTemplateVariables)) { return false; } pattIdxStart++; pathIdxStart++; } if (pathIdxStart > pathIdxEnd) { // Path is exhausted, only match if rest of pattern is * or **'s if (pattIdxStart > pattIdxEnd) { return (pattern.endsWith(this.pathSeparator) == path.endsWith(this.pathSeparator)); } if (!fullMatch) { return true; } if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") && path.endsWith(this.pathSeparator)) { return true; } for (int i = pattIdxStart; i <= pattIdxEnd; i++) { if (!pattDirs[i].equals("**")) { return false; } } return true; } else if (pattIdxStart > pattIdxEnd) { // String not exhausted, but pattern is. Failure. return false; } else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) { // Path start definitely matches due to "**" part in pattern. return true; } // up to last '**' while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { String pattDir = pattDirs[pattIdxEnd]; if (pattDir.equals("**")) { break; } if (!matchStrings(pattDir, pathDirs[pathIdxEnd], uriTemplateVariables)) { return false; } pattIdxEnd--; pathIdxEnd--; } if (pathIdxStart > pathIdxEnd) { // String is exhausted for (int i = pattIdxStart; i <= pattIdxEnd; i++) { if (!pattDirs[i].equals("**")) { return false; } } return true; } while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) { int patIdxTmp = -1; for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) { if (pattDirs[i].equals("**")) { patIdxTmp = i; break; } } if (patIdxTmp == pattIdxStart + 1) { // '**/**' situation, so skip one pattIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd int patLength = (patIdxTmp - pattIdxStart - 1); int strLength = (pathIdxEnd - pathIdxStart + 1); int foundIdx = -1; strLoop: for (int i = 0; i <= strLength - patLength; i++) { for (int j = 0; j < patLength; j++) { String subPat = pattDirs[pattIdxStart + j + 1]; String subStr = pathDirs[pathIdxStart + i + j]; if (!matchStrings(subPat, subStr, uriTemplateVariables)) { continue strLoop; } } foundIdx = pathIdxStart + i; break; } if (foundIdx == -1) { return false; } pattIdxStart = patIdxTmp; pathIdxStart = foundIdx + patLength; } for (int i = pattIdxStart; i <= pattIdxEnd; i++) { if (!pattDirs[i].equals("**")) { return false; } } return true; } private boolean isPotentialMatch(String path, String[] pattDirs) { if (!this.trimTokens) { int pos = 0; for (String pattDir : pattDirs) { int skipped = skipSeparator(path, pos, this.pathSeparator); pos += skipped; skipped = skipSegment(path, pos, pattDir); if (skipped < pattDir.length()) { return (skipped > 0 || (pattDir.length() > 0 && isWildcardChar(pattDir.charAt(0)))); } pos += skipped; } } return true; } private int skipSegment(String path, int pos, String prefix) { int skipped = 0; for (int i = 0; i < prefix.length(); i++) { char c = prefix.charAt(i); if (isWildcardChar(c)) { return skipped; } int currPos = pos + skipped; if (currPos >= path.length()) { return 0; } if (c == path.charAt(currPos)) { skipped++; } } return skipped; } private int skipSeparator(String path, int pos, String separator) { int skipped = 0; while (path.startsWith(separator, pos + skipped)) { skipped += separator.length(); } return skipped; } private boolean isWildcardChar(char c) { for (char candidate : WILDCARD_CHARS) { if (c == candidate) { return true; } } return false; } protected String[] tokenizePattern(String pattern) { String[] tokenized = null; Boolean cachePatterns = this.cachePatterns; if (cachePatterns == null || cachePatterns.booleanValue()) { tokenized = this.tokenizedPatternCache.get(pattern); } if (tokenized == null) { tokenized = tokenizePath(pattern); if (cachePatterns == null && this.tokenizedPatternCache.size() >= CACHE_TURNOFF_THRESHOLD) { // Try to adapt to the runtime situation that we're encountering: // There are obviously too many different patterns coming in here... // So let's turn off the cache since the patterns are unlikely to be // reoccurring. deactivatePatternCache(); return tokenized; } if (cachePatterns == null || cachePatterns.booleanValue()) { this.tokenizedPatternCache.put(pattern, tokenized); } } return tokenized; } protected String[] tokenizePath(String path) { return StringUtils.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true); } private boolean matchStrings(String pattern, String str, Map<String, String> uriTemplateVariables) { return getStringMatcher(pattern).matchStrings(str, uriTemplateVariables); } protected AntPathStringMatcher getStringMatcher(String pattern) { AntPathStringMatcher matcher = null; Boolean cachePatterns = this.cachePatterns; if (cachePatterns == null || cachePatterns.booleanValue()) { matcher = this.stringMatcherCache.get(pattern); } if (matcher == null) { matcher = new AntPathStringMatcher(pattern, this.caseSensitive); if (cachePatterns == null && this.stringMatcherCache.size() >= CACHE_TURNOFF_THRESHOLD) { // Try to adapt to the runtime situation that we're encountering: // There are obviously too many different patterns coming in here... // So let's turn off the cache since the patterns are unlikely to be // reoccurring. deactivatePatternCache(); return matcher; } if (cachePatterns == null || cachePatterns.booleanValue()) { this.stringMatcherCache.put(pattern, matcher); } } return matcher; } @Override public String extractPathWithinPattern(String pattern, String path) { String[] patternParts = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator, this.trimTokens, true); String[] pathParts = StringUtils.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true); StringBuilder builder = new StringBuilder(); boolean pathStarted = false; for (int segment = 0; segment < patternParts.length; segment++) { String patternPart = patternParts[segment]; if (patternPart.indexOf('*') > -1 || patternPart.indexOf('?') > -1) { for (; segment < pathParts.length; segment++) { if (pathStarted || (segment == 0 && !pattern.startsWith(this.pathSeparator))) { builder.append(this.pathSeparator); } builder.append(pathParts[segment]); pathStarted = true; } } } return builder.toString(); } @Override public Map<String, String> extractUriTemplateVariables(String pattern, String path) { Map<String, String> variables = new LinkedHashMap<String, String>(); boolean result = doMatch(pattern, path, true, variables); if (!result) { throw new IllegalStateException("Pattern \"" + pattern + "\" is not a match for \"" + path + "\""); } return variables; } @Override public String combine(String pattern1, String pattern2) { if (!StringUtils.hasText(pattern1) && !StringUtils.hasText(pattern2)) { return ""; } if (!StringUtils.hasText(pattern1)) { return pattern2; } if (!StringUtils.hasText(pattern2)) { return pattern1; } boolean pattern1ContainsUriVar = (pattern1.indexOf('{') != -1); if (!pattern1.equals(pattern2) && !pattern1ContainsUriVar && match(pattern1, pattern2)) { // /* + /hotel -> /hotel ; "/*.*" + "/*.html" -> /*.html // However /user + /user -> /usr/user ; /{foo} + /bar -> /{foo}/bar return pattern2; } // /hotels/* + /booking -> /hotels/booking // /hotels/* + booking -> /hotels/booking if (pattern1.endsWith(this.pathSeparatorPatternCache.getEndsOnWildCard())) { return concat(pattern1.substring(0, pattern1.length() - 2), pattern2); } // /hotels/** + /booking -> /hotels/**/booking // /hotels/** + booking -> /hotels/**/booking if (pattern1.endsWith(this.pathSeparatorPatternCache.getEndsOnDoubleWildCard())) { return concat(pattern1, pattern2); } int starDotPos1 = pattern1.indexOf("*."); if (pattern1ContainsUriVar || starDotPos1 == -1 || this.pathSeparator.equals(".")) { // simply concatenate the two patterns return concat(pattern1, pattern2); } String ext1 = pattern1.substring(starDotPos1 + 1); int dotPos2 = pattern2.indexOf('.'); String file2 = (dotPos2 == -1 ? pattern2 : pattern2.substring(0, dotPos2)); String ext2 = (dotPos2 == -1 ? "" : pattern2.substring(dotPos2)); boolean ext1All = (ext1.equals(".*") || ext1.equals("")); boolean ext2All = (ext2.equals(".*") || ext2.equals("")); if (!ext1All && !ext2All) { throw new IllegalArgumentException("Cannot combine patterns: " + pattern1 + " vs " + pattern2); } String ext = (ext1All ? ext2 : ext1); return file2 + ext; } private String concat(String path1, String path2) { boolean path1EndsWithSeparator = path1.endsWith(this.pathSeparator); boolean path2StartsWithSeparator = path2.startsWith(this.pathSeparator); if (path1EndsWithSeparator && path2StartsWithSeparator) { return path1 + path2.substring(1); } else if (path1EndsWithSeparator || path2StartsWithSeparator) { return path1 + path2; } else { return path1 + this.pathSeparator + path2; } } @Override public Comparator<String> getPatternComparator(String path) { return new AntPatternComparator(path); } protected static class AntPathStringMatcher { private static final Pattern GLOB_PATTERN = Pattern .compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}"); private static final String DEFAULT_VARIABLE_PATTERN = "(.*)"; private final Pattern pattern; private final List<String> variableNames = new LinkedList<String>(); public AntPathStringMatcher(String pattern) { this(pattern, true); } public AntPathStringMatcher(String pattern, boolean caseSensitive) { StringBuilder patternBuilder = new StringBuilder(); Matcher matcher = GLOB_PATTERN.matcher(pattern); int end = 0; while (matcher.find()) { patternBuilder.append(quote(pattern, end, matcher.start())); String match = matcher.group(); if ("?".equals(match)) { patternBuilder.append('.'); } else if ("*".equals(match)) { patternBuilder.append(".*"); } else if (match.startsWith("{") && match.endsWith("}")) { int colonIdx = match.indexOf(':'); if (colonIdx == -1) { patternBuilder.append(DEFAULT_VARIABLE_PATTERN); this.variableNames.add(matcher.group(1)); } else { String variablePattern = match.substring(colonIdx + 1, match.length() - 1); patternBuilder.append('('); patternBuilder.append(variablePattern); patternBuilder.append(')'); String variableName = match.substring(1, colonIdx); this.variableNames.add(variableName); } } end = matcher.end(); } patternBuilder.append(quote(pattern, end, pattern.length())); this.pattern = (caseSensitive ? Pattern.compile(patternBuilder.toString()) : Pattern.compile(patternBuilder.toString(), Pattern.CASE_INSENSITIVE)); } private String quote(String s, int start, int end) { if (start == end) { return ""; } return Pattern.quote(s.substring(start, end)); } public boolean matchStrings(String str, Map<String, String> uriTemplateVariables) { Matcher matcher = this.pattern.matcher(str); if (matcher.matches()) { if (uriTemplateVariables != null) { // SPR-8455 if (this.variableNames.size() != matcher.groupCount()) { throw new IllegalArgumentException("The number of capturing groups in the pattern segment " + this.pattern + " does not match the number of URI template variables it defines, " + "which can occur if capturing groups are used in a URI template regex. " + "Use non-capturing groups instead."); } for (int i = 1; i <= matcher.groupCount(); i++) { String name = this.variableNames.get(i - 1); String value = matcher.group(i); uriTemplateVariables.put(name, value); } } return true; } else { return false; } } } protected static class AntPatternComparator implements Comparator<String> { private final String path; public AntPatternComparator(String path) { this.path = path; } @Override public int compare(String pattern1, String pattern2) { PatternInfo info1 = new PatternInfo(pattern1); PatternInfo info2 = new PatternInfo(pattern2); if (info1.isLeastSpecific() && info2.isLeastSpecific()) { return 0; } else if (info1.isLeastSpecific()) { return 1; } else if (info2.isLeastSpecific()) { return -1; } boolean pattern1EqualsPath = pattern1.equals(path); boolean pattern2EqualsPath = pattern2.equals(path); if (pattern1EqualsPath && pattern2EqualsPath) { return 0; } else if (pattern1EqualsPath) { return -1; } else if (pattern2EqualsPath) { return 1; } if (info1.isPrefixPattern() && info2.getDoubleWildcards() == 0) { return 1; } else if (info2.isPrefixPattern() && info1.getDoubleWildcards() == 0) { return -1; } if (info1.getTotalCount() != info2.getTotalCount()) { return info1.getTotalCount() - info2.getTotalCount(); } if (info1.getLength() != info2.getLength()) { return info2.getLength() - info1.getLength(); } if (info1.getSingleWildcards() < info2.getSingleWildcards()) { return -1; } else if (info2.getSingleWildcards() < info1.getSingleWildcards()) { return 1; } if (info1.getUriVars() < info2.getUriVars()) { return -1; } else if (info2.getUriVars() < info1.getUriVars()) { return 1; } return 0; } private static class PatternInfo { private final String pattern; private int uriVars; private int singleWildcards; private int doubleWildcards; private boolean catchAllPattern; private boolean prefixPattern; private Integer length; public PatternInfo(String pattern) { this.pattern = pattern; if (this.pattern != null) { initCounters(); this.catchAllPattern = this.pattern.equals("/**"); this.prefixPattern = !this.catchAllPattern && this.pattern.endsWith("/**"); } if (this.uriVars == 0) { this.length = (this.pattern != null ? this.pattern.length() : 0); } } protected void initCounters() { int pos = 0; while (pos < this.pattern.length()) { if (this.pattern.charAt(pos) == '{') { this.uriVars++; pos++; } else if (this.pattern.charAt(pos) == '*') { if (pos + 1 < this.pattern.length() && this.pattern.charAt(pos + 1) == '*') { this.doubleWildcards++; pos += 2; } else if (pos > 0 && !this.pattern.substring(pos - 1).equals(".*")) { this.singleWildcards++; pos++; } else { pos++; } } else { pos++; } } } public int getUriVars() { return this.uriVars; } public int getSingleWildcards() { return this.singleWildcards; } public int getDoubleWildcards() { return this.doubleWildcards; } public boolean isLeastSpecific() { return (this.pattern == null || this.catchAllPattern); } public boolean isPrefixPattern() { return this.prefixPattern; } public int getTotalCount() { return this.uriVars + this.singleWildcards + (2 * this.doubleWildcards); } /** * Returns the length of the given pattern, where template variables are * considered to be 1 long. */ public int getLength() { if (this.length == null) { this.length = VARIABLE_PATTERN.matcher(this.pattern).replaceAll("#").length(); } return this.length; } } } /** * A simple cache for patterns that depend on the configured path separator. */ private static class PathSeparatorPatternCache { private final String endsOnWildCard; private final String endsOnDoubleWildCard; public PathSeparatorPatternCache(String pathSeparator) { this.endsOnWildCard = pathSeparator + "*"; this.endsOnDoubleWildCard = pathSeparator + "**"; } public String getEndsOnWildCard() { return this.endsOnWildCard; } public String getEndsOnDoubleWildCard() { return this.endsOnDoubleWildCard; } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/ClassDescriptor.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.rest.util; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; /** * * @author wangwp */ public class ClassDescriptor { private Class<?> type; private String name; private Annotation[] annotations; private List<MethodDescriptor> methodDescriptors; public ClassDescriptor(Class<?> type) { this.type = type; this.name = type.getName(); this.annotations = type.getAnnotations(); methodDescriptors = getMethods(); } private List<MethodDescriptor> getMethods() { List<MethodDescriptor> methodDescriptors = new ArrayList<>(); Method[] methods = type.getDeclaredMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) || method.getAnnotations().length == 0 || !Modifier.isPublic(method.getModifiers())) { continue; } methodDescriptors.add(MethodDescriptor.create(type, method)); } return methodDescriptors; } public static ClassDescriptor create(Class<?> type) { return new ClassDescriptor(type); } public Class<?> getType() { return type; } public String getName() { return name; } public Annotation[] getAnnotations() { return annotations; } public List<MethodDescriptor> getMethodDescriptors() { return methodDescriptors; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/ClassLoaderUtils.java
/* * Copyright 2000-2015 f2time.com All right reserved. */ package ai.houyi.dorado.rest.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * * @author wangweiping * */ public abstract class ClassLoaderUtils { private static final Properties EMPTY_PROPERTIES = new Properties(); private static ClassLoader classLoader; /** * 获得资源真实文件路径 * * @param resource * 资源 * @return 资源文件路径 */ public static String getPath(String resource) { return getPath(getClassLoader(), resource); } /** * 从指定类加载器中获得资源真实文件路径 * * @param resource * 资源 * @param classLoader * 当前类加载器 * @return 资源文件路径 */ public static String getPath(ClassLoader classLoader, String resource) { try { return new File(classLoader.getResource(resource).toURI()).getPath(); } catch (Exception ex) { throw new RuntimeException(ex); } } public static URL getURL(String resource) { return getClassLoader().getResource(resource); } /** * 创建指定类的实例 * * @param clazzName * 类名 * @return 类实例 */ public static Object getInstance(String clazzName) { try { return loadClass(clazzName).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } public static Object newInstance(Class<?> clazz) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { ex.printStackTrace(); } return null; } /** * 根据指定的类名加载类 * * @param name * 类名 * @return 加载指定类 */ public static Class<?> loadClass(String name) { try { return getClassLoader().loadClass(name); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } } public static ClassLoader getClassLoader() { if (classLoader != null) { return classLoader; } classLoader = Thread.currentThread().getContextClassLoader(); return classLoader; } /** * 将资源文件加载到输入流中 * * @param resource * 资源文件 * @return 获得资源流 */ public static InputStream getStream(String resource) { return getClassLoader().getResourceAsStream(resource); } public static InputStream getStreamNoJvmCache(String resource) { try { return getClassLoader().getResource(resource).openStream(); } catch (IOException ex) { LogUtils.error("", ex); } return null; } /** * 将资源文件转化为Properties对象 * * @param resource * 资源文件 * @return 从资源文件加载属性 */ public static Properties getProperties(String resource) { Properties properties = new Properties(); try { InputStream is = getStream(resource); if (is == null) return EMPTY_PROPERTIES; properties.load(is); return properties; } catch (IOException ex) { return EMPTY_PROPERTIES; } } /** * 将资源文件转化为Reader * * @param resource * 资源文件 * @return 资源reader实例 */ public static Reader getReader(String resource) { InputStream is = getStream(resource); if (is == null) { return null; } return new BufferedReader(new InputStreamReader(is)); } /** * 将资源文件的内容转化为List实例 * * @param resource * 资源文件 * @return 获得资源文件内容 */ public static List<String> getList(String resource) { List<String> list = new ArrayList<String>(); BufferedReader reader = (BufferedReader) getReader(resource); if (null == reader) { return list; } String line = ""; try { while ((line = reader.readLine()) != null) { list.add(line); } } catch (IOException ex) { LogUtils.error("将资源文件转化为list出现异常", ex); } finally { if (reader != null) try { reader.close(); } catch (IOException ex) { LogUtils.warn(ex.getMessage()); } } return list; } public static String getResoureAsString(String resource) { return IOUtils.toString(getStream(resource)); } public static byte[] getResoureAsStream(String format) { return null; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/Constant.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.rest.util; /** * * @author wangwp */ public final class Constant { public static final int NCPU = Runtime.getRuntime().availableProcessors(); public static final int DEFAULT_SEND_BUFFER_SIZE = 256 * 1024; public static final int DEFAULT_RECV_BUFFER_SIZE = 256 * 1024; public static final int DEFAULT_CONNECTION_SIZE = 1; public static final int DEFAULT_ACCEPTOR_COUNT = NCPU * 2; public static final int DEFAULT_IO_WORKER_COUNT = NCPU * 2; public static final int DEFAULT_CONNECT_TIMEOUT = 3000; public static final int DEFAULT_SO_TIMEOUT = 3000; public static final int DEFAULT_MIN_WORKER_THREAD = 100; public static final int DEFAULT_MAX_WORKER_THREAD = 100; public static final int DEFAULT_BACKLOG = 1024; public static final int DEFAULT_MAX_PENDING_REQUEST = 10000; public static final String SIGN_COLON = ":"; public static final int DEFAULT_MAX_IDLE_TIME = 10; public static final int MAX_FRAME_LENGTH = 1048576 * 5; public static final String SERVER_NAME = "Dorado"; public static final int DEFAULT_MAX_PACKET_LENGTH = 1024 * 1024; public static final String BLANK_STRING = ""; public static final int DEFAULT_LISTEN_PORT = 8080; public static final String CLASS_SUFFIX = ".class"; public static final int CLASS_SUFFIX_LENGTH = 6; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/ExceptionUtils.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.rest.util; import java.io.PrintWriter; import java.io.StringWriter; /** * * @author wangwp */ public final class ExceptionUtils { public static String toString(Throwable ex) { StringWriter strWriter = new StringWriter(); ex.printStackTrace(new PrintWriter(strWriter, true)); return strWriter.toString(); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/FileUtils.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.rest.util; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; /** * * @author wangwp */ public final class FileUtils { public static List<File> listFiles(final File dir, final String suffix, final boolean recursive) { List<File> files = new ArrayList<>(); if (!dir.isDirectory()) return files; File[] childrenFiles = dir.listFiles(f -> f.isDirectory() || (f.isFile() && f.getName().endsWith(suffix))); for (File childFile : childrenFiles) { if (childFile.isFile()) files.add(childFile); files.addAll(listFiles(childFile, suffix, recursive)); } return files; } public static List<Path> recurseListDirs(Path root) throws IOException { final List<java.nio.file.Path> results = new ArrayList<>(); try (Stream<java.nio.file.Path> pathStream = Files.walk(root)) { pathStream.filter(p -> p.toFile().isDirectory()).forEach(p -> results.add(p)); } catch (IOException ex) { throw ex; } return results; } public static void main(String[] args) throws Exception { System.out.println(recurseListDirs(Paths.get(ClassLoaderUtils.getPath("")))); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/IOUtils.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.rest.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; /** * I/O操作实用工具类 * * @author wangweiping * */ public class IOUtils { /** * The default buffer size to use. */ private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; private IOUtils() { } public static String toString(InputStream in) { StringWriter writer = new StringWriter(); InputStreamReader inputStreamReader = new InputStreamReader(in); try { copyLarge(inputStreamReader, writer); return writer.toString(); } catch (IOException ex) { LogUtils.error("", ex); } finally { closeQuietly(inputStreamReader); } return null; } public static String toString(InputStream in, String encoding) { if (encoding == null) { return toString(in); } StringWriter writer = new StringWriter(); InputStreamReader reader = null; try { reader = new InputStreamReader(in, encoding); copyLarge(reader, writer); return writer.toString(); } catch (IOException ex) { LogUtils.error("", ex); } finally { closeQuietly(reader); } return null; } public static void closeQuietly(Reader reader) { try { if (reader != null) { reader.close(); } } catch (IOException ex) { // ignore ex } } public static void closeQuietly(Writer writer) { try { if (writer != null) { writer.close(); } } catch (IOException ex) { // ignore ex } } public static void closeQuietly(InputStream in) { try { if (in != null) { in.close(); } } catch (IOException ex) { // ignore ex } } public static void closeQuietly(OutputStream out) { try { if (out != null) { out.close(); } } catch (IOException ex) { // ignore ex } } /** * Copy chars from a large (over 2GB) <code>Reader</code> to a * <code>Writer</code>. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedReader</code>. * * @param input * the <code>Reader</code> to read from * @param output * the <code>Writer</code> to write to * @return the number of characters copied * @throws NullPointerException * if the input or output is null * @throws IOException * if an I/O error occurs * @since Commons IO 1.3 */ public static long copyLarge(Reader input, Writer output) throws IOException { char[] buffer = new char[DEFAULT_BUFFER_SIZE]; long count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } public static byte[] readBytes(InputStream input) { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } return output.toByteArray(); } catch (Exception ex) { // ignore this ex } return null; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/LogUtils.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.rest.util; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; /** * * @author wangwp */ public class LogUtils { public static final InternalLogger LOG = InternalLoggerFactory.getInstance("Dorado"); public static void info(String msg) { LOG.info(msg); } public static void info(String format, Object... args) { LOG.info(format, args); } public static void debug(String msg) { LOG.debug(msg); } public static void debug(String format, Object... args) { LOG.debug(format, args); } public static void error(String msg, Throwable cause) { LOG.error(msg, cause); } public static void error(String format, Object... args) { LOG.error(format, args); } public static void warn(String msg) { LOG.warn(msg); } public static void warn(String format, Object... args) { LOG.warn(format, args); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/MediaTypeUtils.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.rest.util; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; import ai.houyi.dorado.rest.MediaType; import io.netty.util.CharsetUtil; /** * * @author wangwp */ public final class MediaTypeUtils { public static MediaType forType(Class<?> type) { if (TypeUtils.isPrimitiveOrWrapper(type) || String.class == type || BigDecimal.class == type || BigInteger.class == type) { return MediaType.TEXT_HTML_TYPE.withCharset(CharsetUtil.UTF_8.name()); } if (byte[].class == type || InputStream.class.isAssignableFrom(type)) { return MediaType.APPLICATION_OCTET_STREAM_TYPE; } if (TypeUtils.isProtobufMessage(type)) { return MediaType.APPLICATION_PROTOBUF_TYPE; } return MediaType.APPLICATION_JSON_TYPE.withCharset(CharsetUtil.UTF_8.name()); } public static MediaType defaultForType(Class<?> type, String defaultType) { if (MediaType.WILDCARD.equals(defaultType) || StringUtils.isBlank(defaultType)) { return forType(type); } return MediaType.valueOf(defaultType); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/MethodDescriptor.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.rest.util; import static ai.houyi.dorado.rest.util.ProtobufMessageDescriptors.registerMessageDescriptorForType; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Type; import com.google.protobuf.Message; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.rest.DefaultParameterNameResolver; import ai.houyi.dorado.rest.MediaType; import ai.houyi.dorado.rest.ParameterNameResolver; import ai.houyi.dorado.rest.annotation.Consume; import ai.houyi.dorado.rest.annotation.Produce; import ai.houyi.dorado.rest.http.HttpRequest; import ai.houyi.dorado.rest.http.HttpResponse; import ai.houyi.dorado.rest.http.MultipartFile; /** * * @author wangwp */ public class MethodDescriptor { private final Class<?> clazz; private final Method method; private Annotation[] annotations; private Object invokeTarget; private Class<?> returnType; private MethodParameter[] methodParameters; private String consume; private String produce; private MethodDescriptor(Class<?> clazz, Method method) { this(clazz, method, new DefaultParameterNameResolver()); } private MethodDescriptor(Class<?> clazz, Method method, ParameterNameResolver parameterNameResolver) { this.clazz = clazz; this.method = method; this.returnType = method.getReturnType(); if (!method.isAccessible()) { method.setAccessible(true); } Class<?>[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); String[] parameterNames = parameterNameResolver.getParameterNames(method); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); this.invokeTarget = Dorado.beanContainer.getBean(clazz); this.annotations = method.getAnnotations(); Consume consumeAnnotation = method.getAnnotation(Consume.class); Produce produceAnnotation = method.getAnnotation(Produce.class); methodParameters = new MethodParameter[method.getParameterCount()]; for (int i = 0; i < method.getParameterCount(); i++) { Annotation annotation = parameterAnnotations[i].length == 0 ? null : parameterAnnotations[i][0]; Class<?> type = parameterTypes[i]; String name = parameterNames[i]; Type genericParameterType = genericParameterTypes[i]; MethodParameter methodParameter = MethodParameter.create(name, type, genericParameterType, annotation); if (methodParameter.annotationType == MultipartFile.class) { } methodParameters[i] = methodParameter; methodParameters[i].setMethodParameterCount(method.getParameterCount()); registerMessageDescriptorForTypeIfNeed(type); } this.consume = consumeAnnotation == null ? guessConsume() : consumeAnnotation.value(); this.produce = produceAnnotation == null ? guessProduce() : produceAnnotation.value(); } private void registerMessageDescriptorForTypeIfNeed(Class<?> type) { try { if (Message.class.isAssignableFrom(type)) { registerMessageDescriptorForType(type); } } catch (Throwable ex) { // ignore this ex } } public static MethodDescriptor create(Class<?> clazz, Method method) { MethodDescriptor methodDescriptor = new MethodDescriptor(clazz, method); return methodDescriptor; } public Class<?> getClazz() { return clazz; } public Method getMethod() { return method; } public MethodParameter[] getParameters() { return this.methodParameters; } public Class<?> getReturnType() { return returnType; } public Object getInvokeTarget() { return invokeTarget; } public Annotation[] getAnnotations() { return annotations; } public String consume() { return this.consume; } public boolean hasAnnotation(Annotation annotation) { for (Annotation _anno : annotations) { if (_anno.equals(annotation)) { return true; } } return false; } private String guessConsume() { for (MethodParameter param : this.methodParameters) { if (param.annotationType == MultipartFile.class) { return MediaType.MULTIPART_FORM_DATA; } else if (TypeUtils.isProtobufMessage(param.getType())) { return MediaType.APPLICATION_PROTOBUF; }else if(TypeUtils.isSerializableType(param.getType())) { return MediaType.APPLICATION_JSON; } } return MediaType.WILDCARD; } public String produce() { return this.produce; } private String guessProduce() { MediaType mediaType = MediaTypeUtils.forType(returnType); return mediaType == null ? MediaType.WILDCARD : mediaType.toString(); } public static class MethodParameter { private String name; private Class<?> type; private Annotation annotation; private Class<?> annotationType; private int methodParameterCount; private Type parameterizedType; private MethodParameter(String name, Class<?> type, Type parameterizedType, Annotation annotation) { this.name = name; this.type = type; this.annotation = annotation; this.annotationType = annotation == null ? null : annotation.annotationType(); if (type == HttpRequest.class) this.annotationType = HttpRequest.class; if (type == HttpResponse.class) this.annotationType = HttpResponse.class; if (type == MultipartFile.class) this.annotationType = MultipartFile.class; if (type.isArray() && type.getComponentType() == MultipartFile.class) { this.annotationType = MultipartFile.class; } this.parameterizedType = parameterizedType; } public void setMethodParameterCount(int parameterCount) { this.methodParameterCount = parameterCount; } public static MethodParameter create(String name, Class<?> type, Type genericParameterType, Annotation annotation) { return new MethodParameter(name, type, genericParameterType, annotation); } public String getName() { return this.name; } public int getMethodParameterCount() { return methodParameterCount; } public Class<?> getType() { return this.type; } public Annotation getAnnotation() { return this.annotation; } public Class<?> getAnnotationType() { return this.annotationType; } public Type getParameterizedType() { return parameterizedType; } @Override public String toString() { return "MethodParameter [name=" + name + ", type=" + type + ", annotation=" + annotation + ", annotationType=" + annotationType + "]"; } } public static void main(String[] args) throws Exception { MultipartFile[] a = new MultipartFile[] {}; System.out.println(a.getClass().isArray()); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/NamedThreadFactory.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.rest.util; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * @author wangweiping * */ public class NamedThreadFactory implements ThreadFactory { private static final AtomicInteger POOL_SEQ = new AtomicInteger(1); private final AtomicInteger mThreadNum = new AtomicInteger(1); private final String mPrefix; private final boolean mDaemo; private final ThreadGroup mGroup; public NamedThreadFactory() { this("pool-" + POOL_SEQ.getAndIncrement(), false); } public NamedThreadFactory(String prefix) { this(prefix, false); } public NamedThreadFactory(String prefix, boolean daemo) { mPrefix = prefix + "-thread-"; mDaemo = daemo; SecurityManager s = System.getSecurityManager(); mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup(); } public Thread newThread(Runnable runnable) { String name = mPrefix + mThreadNum.getAndIncrement(); Thread ret = new Thread(mGroup, runnable, name, 0); ret.setDaemon(mDaemo); return ret; } public ThreadGroup getThreadGroup() { return mGroup; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/NetUtils.java
/** * */ package ai.houyi.dorado.rest.util; /** * @author wangweiping * */ public final class NetUtils { private final static int INADDR4SZ = 4; public static boolean isInternalIp(String ip) { if (ip == null) return true; if (ip.equals("127.0.0.1")) return true; byte[] addr = textToNumericFormatV4(ip); final byte b0 = addr[0]; final byte b1 = addr[1]; // 10.x.x.x/8 final byte SECTION_1 = 0x0A; // 172.16.x.x/12 final byte SECTION_2 = (byte) 0xAC; final byte SECTION_3 = (byte) 0x10; final byte SECTION_4 = (byte) 0x1F; // 192.168.x.x/16 final byte SECTION_5 = (byte) 0xC0; final byte SECTION_6 = (byte) 0xA8; switch (b0) { case SECTION_1: return true; case SECTION_2: if (b1 >= SECTION_3 && b1 <= SECTION_4) { return true; } case SECTION_5: switch (b1) { case SECTION_6: return true; } default: return false; } } public static byte[] textToNumericFormatV4(String src) { if (src.length() == 0) { return null; } byte[] res = new byte[INADDR4SZ]; String[] s = src.split("\\.", -1); long val; for (int i = 0; i < 4; i++) { val = Integer.parseInt(s[i]); if (val < 0 || val > 0xff) return null; res[i] = (byte) (val & 0xff); } return res; } public static void main(String[] args) throws Exception { System.out.println(NetUtils.isInternalIp("10.200.136.128")); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/PackageScanner.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.rest.util; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import ai.houyi.dorado.exception.DoradoException; /** * * @author wangwp */ public class PackageScanner { public static List<Class<?>> scan(String packageName) throws ClassNotFoundException { List<Class<?>> classes = new LinkedList<>(); try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> urls = loader.getResources(packageName.replace('.', '/')); while (urls.hasMoreElements()) { URI uri = urls.nextElement().toURI(); switch (uri.getScheme().toLowerCase()) { case "jar": scanFromJarProtocol(loader, classes, uri.getRawSchemeSpecificPart()); break; case "file": scanFromFileProtocol(loader, classes, new File(uri).getPath(), packageName); break; default: throw new URISyntaxException(uri.getScheme(), "unknown schema " + uri.getScheme()); } } } catch (URISyntaxException | IOException e) { e.printStackTrace(); } return classes; } private static Class<?> loadClass(ClassLoader loader, String classPath) throws ClassNotFoundException { try { classPath = classPath.substring(0, classPath.length() - 6); return loader.loadClass(classPath); } catch (Throwable cause) { LogUtils.error("", cause); } return null; } private static void scanFromFileProtocol(ClassLoader loader, List<Class<?>> classes, String dir, String packageName) throws ClassNotFoundException { try { List<String> classNames = listAllClassNames(dir); classNames.forEach(className -> { try { classes.add(loadClass(loader, String.format("%s.%s", packageName,className))); } catch (Throwable e) { LogUtils.error(e.getMessage()); } }); } catch (Exception ex) { throw new DoradoException(ex); } } private static void scanFromJarProtocol(ClassLoader loader, List<Class<?>> classes, String fullPath) throws ClassNotFoundException { final String jar = fullPath.substring(0, fullPath.lastIndexOf('!')); final String parent = fullPath.substring(fullPath.lastIndexOf('!') + 2); JarEntry e = null; JarInputStream jarReader = null; try { jarReader = new JarInputStream(new URL(jar).openStream()); while ((e = jarReader.getNextJarEntry()) != null) { String className = e.getName(); if (!e.isDirectory() && className.startsWith(parent) && className.endsWith(Constant.CLASS_SUFFIX) && !className.contains("$")) { className = className.replace('/', '.'); classes.add(loadClass(loader, className)); } jarReader.closeEntry(); } } catch (IOException error) { error.printStackTrace(); } finally { try { if (jarReader != null) jarReader.close(); } catch (IOException exp) { exp.printStackTrace(); } } } public static List<String> listAllClassNames(String classpath) { List<String> classNames = new ArrayList<>(); List<File> allClassFiles = FileUtils.listFiles(new File(classpath), Constant.CLASS_SUFFIX, true); int index = classpath.endsWith(File.separator) ? classpath.length() : classpath.length() + 1; for (File classFile : allClassFiles) { String className = classFile.getAbsolutePath().substring(index).replace(File.separatorChar, '.'); classNames.add(className); } return classNames; } public static void main(String[] args) throws Exception { String packageName = "mobi.f2time"; List<Class<?>> classes = PackageScanner.scan(packageName); classes.forEach(type -> System.out.println(type.getName())); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/PathMatcher.java
/* * Copyright 2002-2012 the original author or authors. * * Licensed 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.rest.util; import java.util.Comparator; import java.util.Map; /** * Strategy interface for {@code String}-based path matching. * * The default implementation is {@link AntPathMatcher}, supporting the * Ant-style pattern syntax. * * @author Juergen Hoeller * @since 1.2 * @see AntPathMatcher */ public interface PathMatcher { boolean isPattern(String path); boolean match(String pattern, String path); boolean matchStart(String pattern, String path); String extractPathWithinPattern(String pattern, String path); Map<String, String> extractUriTemplateVariables(String pattern, String path); Comparator<String> getPatternComparator(String path); String combine(String pattern1, String pattern2); }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/PathMatchers.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.rest.util; /** * @author weiping wang * */ public final class PathMatchers { private static final PathMatcher DEFAULT = new AntPathMatcher(); public static PathMatcher getPathMatcher() { return DEFAULT; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/ProtobufMessageDescriptors.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.rest.util; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import ai.houyi.dorado.exception.DoradoException; /** * * @author wangwp */ public class ProtobufMessageDescriptors { private static final Map<Class<?>, ProtobufMessageDescriptor> messageDescriptorHolder = new ConcurrentHashMap<>(); public static void registerMessageDescriptor(ProtobufMessageDescriptor messageDescriptor) { messageDescriptorHolder.put(messageDescriptor.messageType, messageDescriptor); } public static ProtobufMessageDescriptor messageDescriptorForType(Class<?> type) { return messageDescriptorHolder.get(type); } public static void registerMessageDescriptorForType(Class<?> type) { messageDescriptorHolder.put(type, new ProtobufMessageDescriptor(type)); } public static Message newMessageForType(byte[] data, Class<?> type) { ProtobufMessageDescriptor messageDescriptor = messageDescriptorHolder.get(type); if (messageDescriptor == null) { return null; } return messageDescriptor.mergeFrom(data); } public static Message newMessageForType(InputStream in, Class<?> type) { ProtobufMessageDescriptor messageDescriptor = messageDescriptorHolder.get(type); if (messageDescriptor == null) { return null; } return messageDescriptor.mergeFrom(in); } public static class ProtobufMessageDescriptor { private static final String METHOD_GET_DEFAULT_INSTANCE = "getDefaultInstance"; private Class<?> messageType; private Message defaultMessageInstance; public ProtobufMessageDescriptor(Class<?> messageType) throws DoradoException { this.messageType = messageType; try { Method method = messageType.getMethod(METHOD_GET_DEFAULT_INSTANCE, (Class[]) null); if (!method.isAccessible()) { method.setAccessible(true); } defaultMessageInstance = (Message) method.invoke(messageType, (Object[]) null); } catch (Throwable ex) { throw new DoradoException(ex); } } public Message mergeFrom(byte[] data) { try { return defaultMessageInstance.newBuilderForType().mergeFrom(data).build(); } catch (InvalidProtocolBufferException ex) { throw new DoradoException(ex); } } public Message mergeFrom(InputStream in) { try { return defaultMessageInstance.newBuilderForType().mergeFrom(in).build(); } catch (IOException ex) { throw new DoradoException(ex); } } public Class<?> getMessageType() { return this.messageType; } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/SerializeUtils.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.rest.util; import java.io.InputStream; import java.lang.reflect.Type; import ai.houyi.dorado.rest.ObjectSerializer; /** * * @author wangwp */ public class SerializeUtils { public static byte[] serialize(Object t) { return ObjectSerializer.DEFAULT.serialize(t); } public static Object deserialize(InputStream in, Type type) { return ObjectSerializer.DEFAULT.deserialize(in, type); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/SimpleLRUCache.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.rest.util; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * 一个简单的LRU cache实现,不支持过期操作 * * @author wangwp */ public final class SimpleLRUCache<K, V> { private final LinkedHashMap<K, V> cache; private final Lock r; private final Lock w; private SimpleLRUCache(int capacity) { this.cache = new LRUMap<K, V>(capacity); ReadWriteLock lock = new ReentrantReadWriteLock(); this.r = lock.readLock(); this.w = lock.writeLock(); } public static <K, V> SimpleLRUCache<K, V> create(int capacity) { return new SimpleLRUCache<K, V>(capacity); } public void put(K key, V value) { w.lock(); try { this.cache.put(key, value); } finally { w.unlock(); } } public V get(K key) { r.lock(); try { return this.cache.get(key); } finally { r.unlock(); } } public void remove(K key) { w.lock(); try { this.cache.remove(key); } finally { w.unlock(); } } public void clear() { w.lock(); try { this.cache.clear(); } finally { w.unlock(); } } static class LRUMap<K, V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = 1L; private final int capacity; public LRUMap(int capacity) { super((int) Math.ceil(capacity / 0.75) + 1, 0.75f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Entry<K, V> eldest) { return size() > capacity; } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/StringUtils.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.rest.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.StringTokenizer; /** * * @author wangwp */ public final class StringUtils { public static final String EMPTY = ""; public static String defaultString(String str, String defaultStr) { if (isBlank(str)) return defaultStr; return str; } public static boolean isBlank(String str) { if (str == null || str.trim().length() == 0) { return true; } return false; } public static int toInt(String str) { if (isBlank(str)) { return 0; } try { return Integer.parseInt(str); } catch (Exception ex) { // do nothing } return 0; } public static long toLong(String str) { if (isBlank(str)) { return 0L; } try { return Long.parseLong(str); } catch (Exception ex) { // do nothing } return 0L; } public static float toFloat(String str) { if (isBlank(str)) { return 0.0F; } try { return Float.parseFloat(str); } catch (Exception ex) { // do nothing } return 0.0F; } public static double toDouble(String str) { if (isBlank(str)) { return 0.0D; } try { return Double.parseDouble(str); } catch (Exception ex) { } return 0.0D; } public static boolean toBoolean(String str) { if (isBlank(str)) { return false; } try { return Boolean.valueOf(str); } catch (Exception ex) { } return false; } public static short toShort(String str) { if (isBlank(str)) { return 0; } try { return Short.parseShort(str); } catch (Exception ex) { } return 0; } public static char toChar(String str) { if (isBlank(str)) { return (char) 0; } char[] chars = str.toCharArray(); if (chars.length > 1) { throw new IllegalArgumentException("invalid char"); } return chars[0]; } public static String[] tokenizeToStringArray(String str, String delimiters) { return tokenizeToStringArray(str, delimiters, true, true); } public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return null; } StringTokenizer st = new StringTokenizer(str, delimiters); List<String> tokens = new ArrayList<String>(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (trimTokens) { token = token.trim(); } if (!ignoreEmptyTokens || token.length() > 0) { tokens.add(token); } } return toStringArray(tokens); } public static String[] toStringArray(Collection<String> collection) { if (collection == null) { return null; } return collection.toArray(new String[collection.size()]); } public static boolean hasText(String str) { return (hasLength(str) && containsText(str)); } private static boolean containsText(CharSequence str) { int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } public static boolean hasLength(String str) { return (str != null && !str.isEmpty()); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/TracingThreadPoolExecutor.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.rest.util; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import ai.houyi.dorado.rest.controller.DoradoStatus; /** * @author weiping wang * */ public class TracingThreadPoolExecutor extends ThreadPoolExecutor { private final AtomicInteger pendingTasks = new AtomicInteger(); private final DoradoStatus serverStatus = DoradoStatus.get(); public TracingThreadPoolExecutor(int corePoolSize, int maximumPoolSize, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, 0L, TimeUnit.MILLISECONDS, workQueue); serverStatus.workerPool(this); } @Override public void execute(Runnable command) { super.execute(command); } @Override protected void beforeExecute(Thread t, Runnable r) { serverStatus.pendingRequestsIncrement(); } @Override protected void afterExecute(Runnable r, Throwable t) { serverStatus.pendingRequestsDecrement(); } public int getPendingTasks() { return pendingTasks.get(); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/TypeConverter.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.rest.util; import java.io.InputStream; import io.netty.util.CharsetUtil; /** * * @author wangwp */ public interface TypeConverter<F, T> { T convert(F value); TypeConverter<String, Integer> STRING_INT = s -> s == null ? null : StringUtils.toInt(s); TypeConverter<String, Long> STRING_LONG = s -> s == null ? null : StringUtils.toLong(s); TypeConverter<String, Float> STRING_FLOAT = s -> s == null ? null : StringUtils.toFloat(s); TypeConverter<String, Double> STRING_DOUBLE = s -> s == null ? null : StringUtils.toDouble(s); TypeConverter<String, Short> STRING_SHORT = s -> s == null ? null : StringUtils.toShort(s); TypeConverter<String, Boolean> STRING_BOOL = s -> s == null ? null : StringUtils.toBoolean(s); TypeConverter<String, Character> STRING_CHAR = s -> { throw new UnsupportedOperationException("unsupport convert string to char"); }; TypeConverter<String, Byte> STRING_BYTE = s -> { throw new UnsupportedOperationException("unsupport convert string to byte"); }; TypeConverter<Object, Object> DUMMY = s -> s; TypeConverter<InputStream, InputStream> INPUTSTREAM = s -> s; TypeConverter<InputStream, String> STRING_UTF8 = s -> IOUtils.toString(s, CharsetUtil.UTF_8.name()); TypeConverter<String, Float> STRING_FLOAT_WRAPPER = s -> s == null ? null : Float.valueOf(s); TypeConverter<String, Integer> STRING_INT_WRAPPER = s -> s == null ? null : Integer.valueOf(s); TypeConverter<String, Long> STRING_LONG_WRAPPER = s -> s == null ? null : Long.valueOf(s); TypeConverter<String, Double> STRING_DOUBLE_WRAPPER = s -> s == null ? null : Double.valueOf(s); TypeConverter<String, Short> STRING_SHORT_WRAPPER = s -> s == null ? null : Short.valueOf(s); TypeConverter<String, Boolean> STRING_BOOL_WRAPPER = s -> s == null ? null : Boolean.valueOf(s); TypeConverter<String, Character> STRING_CHAR_WRAPPER = s -> { throw new UnsupportedOperationException("unsupport convert string to character"); }; TypeConverter<String, Byte> STRING_BYTE_WRAPPER = s -> { throw new UnsupportedOperationException("unsupport convert string to byte"); }; }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/TypeConverters.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.rest.util; import java.util.HashMap; import java.util.Map; /** * * @author wangwp */ public class TypeConverters { private static Map<Class<?>, TypeConverter<?, ?>> converters = new HashMap<>(); static { converters.put(int.class, TypeConverter.STRING_INT); converters.put(long.class, TypeConverter.STRING_LONG); converters.put(double.class, TypeConverter.STRING_DOUBLE); converters.put(float.class, TypeConverter.STRING_FLOAT); converters.put(short.class, TypeConverter.STRING_SHORT); converters.put(boolean.class, TypeConverter.STRING_BOOL); converters.put(char.class, TypeConverter.STRING_CHAR); converters.put(byte.class, TypeConverter.STRING_BYTE); converters.put(Float.class, TypeConverter.STRING_FLOAT_WRAPPER); converters.put(Integer.class, TypeConverter.STRING_INT_WRAPPER); converters.put(Long.class, TypeConverter.STRING_LONG_WRAPPER); converters.put(Double.class, TypeConverter.STRING_DOUBLE_WRAPPER); converters.put(Short.class, TypeConverter.STRING_SHORT_WRAPPER); converters.put(Boolean.class, TypeConverter.STRING_BOOL_WRAPPER); converters.put(Character.class, TypeConverter.STRING_CHAR_WRAPPER); converters.put(Byte.class, TypeConverter.STRING_BYTE_WRAPPER); } @SuppressWarnings("rawtypes") public static TypeConverter resolveConverter(Class<?> type) { TypeConverter converter = converters.get(type); return converter == null ? TypeConverter.DUMMY : converter; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/TypeUtils.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.rest.util; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import com.google.protobuf.Message; /** * * @author wangwp */ public final class TypeUtils { private static final Map<Class<?>, Object> primitiveDefaultHolder = new HashMap<>(); static { primitiveDefaultHolder.put(int.class, 0); primitiveDefaultHolder.put(long.class, 0L); primitiveDefaultHolder.put(short.class, 0); primitiveDefaultHolder.put(float.class, 0.0F); primitiveDefaultHolder.put(byte.class, (byte) 0); primitiveDefaultHolder.put(double.class, 0.0D); primitiveDefaultHolder.put(boolean.class, false); primitiveDefaultHolder.put(char.class, (char) 0); } public static boolean isPrimitive(Class<?> type) { return (type != void.class && type != Void.class) && type.isPrimitive(); } public static boolean isWrapper(Class<?> type) { return (type == Integer.class) || (type == Long.class) || (type == Short.class) || (type == Float.class) || (type == Double.class) || (type == Boolean.class) || (type == Character.class) || (type == Byte.class); } public static boolean isPrimitiveOrWrapper(Class<?> type) { return isPrimitive(type) || isWrapper(type); } public static boolean isSerializableType(Class<?> type) { return !isPrimitive(type) && !isWrapper(type) && type != String.class && type != byte[].class && type != Byte[].class && type != InputStream.class; } public static Object primitiveDefault(Class<?> parameterType) { return primitiveDefaultHolder.get(parameterType); } public static boolean isProtobufMessage(Type type) { try { if (!(type instanceof Class)) return false; return Message.class.isAssignableFrom((Class<?>) type); } catch (Throwable ex) { // do nothing } return false; } @SuppressWarnings("rawtypes") public static boolean hasAnnotationByName(Class type, String annotationName) { Annotation[] annotations = type.getAnnotations(); for (Annotation annotation : annotations) { if (annotation.annotationType().getName().equals(annotationName)) { return true; } Annotation[] _annotations = annotation.annotationType().getAnnotations(); if (_annotations != null) return hasAnnotationByName(annotation.annotationType(), annotationName); } return false; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/rest/util/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.rest.util;
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/spring/DoradoApplicationContext.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.spring; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * * @author wangwp */ public class DoradoApplicationContext extends AnnotationConfigApplicationContext { private final DoradoClassPathBeanDefinitionScanner scanner; public DoradoApplicationContext(String... basePackages) { scanner = new DoradoClassPathBeanDefinitionScanner(this); scanner.scan(basePackages); refresh(); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/spring/DoradoClassPathBeanDefinitionScanner.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.spring; import java.util.logging.Filter; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.AssignableTypeFilter; import ai.houyi.dorado.rest.annotation.Controller; /** * * @author wangwp */ public class DoradoClassPathBeanDefinitionScanner extends ClassPathBeanDefinitionScanner { public DoradoClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment, ResourceLoader resourceLoader) { super(registry, useDefaultFilters, environment, resourceLoader); } public DoradoClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment) { super(registry, useDefaultFilters, environment); } public DoradoClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) { super(registry, useDefaultFilters); } public DoradoClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { super(registry); } @Override protected void registerDefaultFilters() { super.registerDefaultFilters(); this.addIncludeFilter(new AnnotationTypeFilter(Controller.class)); this.addIncludeFilter(new AssignableTypeFilter(Filter.class)); } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/spring/SpringContainer.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.spring; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.core.type.filter.AnnotationTypeFilter; import ai.houyi.dorado.BeanContainer; import ai.houyi.dorado.Dorado; import ai.houyi.dorado.rest.annotation.Controller; import ai.houyi.dorado.rest.controller.RootController; import ai.houyi.dorado.rest.server.DoradoServerBuilder; /** * * @author wangwp */ public final class SpringContainer implements BeanContainer { private static SpringContainer instance; private final ApplicationContext applicationContext; private SpringContainer(ApplicationContext applicationContext) { this.applicationContext = applicationContext; Dorado.beanContainer = this; } public synchronized static void create(ApplicationContext applicationContext) { DoradoServerBuilder builder = Dorado.serverConfig; if (builder == null) { throw new IllegalStateException("Please init DoradoServer first!"); } if (!(applicationContext instanceof DoradoApplicationContext) && (applicationContext instanceof BeanDefinitionRegistry)) { ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner( (BeanDefinitionRegistry) applicationContext); scanner.resetFilters(false); scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class)); scanner.scan(builder.scanPackages()); } instance = new SpringContainer(applicationContext); Dorado.springInitialized = true; } public static SpringContainer get() { return instance; } @Override public <T> T getBean(Class<T> type) { if (type == RootController.class) { return BeanContainer.DEFAULT.getBean(type); } try { return applicationContext.getBean(type); } catch (Throwable ex) { if (!type.isInterface()) { return BeanContainer.DEFAULT.getBean(type); } } return null; } public static void create(String[] scanPackages) { if (instance != null) { throw new IllegalStateException("SpringContainer has been initialized"); } DoradoApplicationContext applicationContext = new DoradoApplicationContext(scanPackages); create(applicationContext); Runtime.getRuntime().addShutdownHook(new Thread(() -> applicationContext.close())); } @SuppressWarnings("unchecked") @Override public <T> T getBean(String name) { if (applicationContext.containsBean(name)) return (T) applicationContext.getBean(name); else return null; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/spring/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.spring;
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/springboot/DoradoAutoConfiguration.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.springboot; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.annotation.Order; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.ClassUtils; import ai.houyi.dorado.rest.server.DoradoServer; import ai.houyi.dorado.rest.server.DoradoServerBuilder; import ai.houyi.dorado.rest.util.LogUtils; import ai.houyi.dorado.spring.SpringContainer; /** * @author weiping wang * */ @Configuration @ConditionalOnBean(annotation = EnableDorado.class) @EnableConfigurationProperties(DoradoConfig.class) @Order(Ordered.LOWEST_PRECEDENCE) public class DoradoAutoConfiguration { @Autowired private DoradoConfig config; @Autowired private ApplicationContext applicationContext; @PostConstruct public void startDoradoServer() { boolean isSpringBootApp = applicationContext.containsBean("springApplicationArguments"); if (!isSpringBootApp) { LogUtils.info("Not SpringBoot Application launch, unstart dorado server!"); return; } DoradoServerBuilder builder = DoradoServerBuilder.forPort(config.getPort()).backlog(config.getBacklog()) .acceptors(config.getAcceptors()).ioWorkers(config.getIoWorkers()).minWorkers(config.getMinWorkers()) .maxWorkers(config.getMaxWorkers()).maxConnection(config.getMaxConnections()) .maxPendingRequest(config.getMaxPendingRequest()).maxIdleTime(config.getMaxIdleTime()) .sendBuffer(config.getSendBuffer()).recvBuffer(config.getRecvBuffer()) .maxPacketLength(config.getMaxPacketLength()).contextPath(config.getContextPath()); String[] scanPackages = config.getScanPackages(); if (config.getScanPackages() == null || config.getScanPackages().length == 0) { scanPackages = getSpringBootAppScanPackages(); } DoradoServer doradoServer = builder.scanPackages(scanPackages).build(); SpringContainer.create(applicationContext); new Thread(() -> doradoServer.start()).start(); } private String[] getSpringBootAppScanPackages() { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext; Set<String> packages = new HashSet<>(); String[] names = registry.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = registry.getBeanDefinition(name); if (definition instanceof AnnotatedBeanDefinition) { AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition; addComponentScanningPackages(packages, annotatedDefinition.getMetadata()); } } return packages.toArray(new String[] {}); } private void addComponentScanningPackages(Set<String> packages, AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true)); if (attributes != null) { addPackages(packages, attributes.getStringArray("value")); addPackages(packages, attributes.getStringArray("basePackages")); addClasses(packages, attributes.getStringArray("basePackageClasses")); if (packages.isEmpty()) { packages.add(ClassUtils.getPackageName(metadata.getClassName())); } } } private void addPackages(Set<String> packages, String[] values) { if (values != null) { Collections.addAll(packages, values); } } private void addClasses(Set<String> packages, String[] values) { if (values != null) { for (String value : values) { packages.add(ClassUtils.getPackageName(value)); } } } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/springboot/DoradoConfig.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.springboot; import org.springframework.boot.context.properties.ConfigurationProperties; import ai.houyi.dorado.rest.util.Constant; import ai.houyi.dorado.rest.util.StringUtils; /** * @author weiping wang * */ @ConfigurationProperties("dorado") public class DoradoConfig { private int port = 18888; private int backlog = Constant.DEFAULT_BACKLOG; private int acceptors = Constant.DEFAULT_ACCEPTOR_COUNT; private int ioWorkers = Constant.DEFAULT_IO_WORKER_COUNT; private int minWorkers = Constant.DEFAULT_MIN_WORKER_THREAD; private int maxWorkers = Constant.DEFAULT_MAX_WORKER_THREAD; private int maxConnections = 100000; private int maxPendingRequest = Constant.DEFAULT_MAX_PENDING_REQUEST; private int maxIdleTime = 8 * 3600; private int sendBuffer = Constant.DEFAULT_SEND_BUFFER_SIZE; private int recvBuffer = Constant.DEFAULT_RECV_BUFFER_SIZE; private int maxPacketLength = Constant.DEFAULT_MAX_PACKET_LENGTH; private String contextPath = StringUtils.EMPTY; private String[] scanPackages; public int getBacklog() { return backlog; } public void setBacklog(int backlog) { this.backlog = backlog; } public int getAcceptors() { return acceptors; } public String[] getScanPackages() { return scanPackages; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public void setScanPackages(String[] scanPackages) { this.scanPackages = scanPackages; } public void setAcceptors(int acceptors) { this.acceptors = acceptors; } public int getIoWorkers() { return ioWorkers; } public void setIoWorkers(int ioWorkers) { this.ioWorkers = ioWorkers; } public int getMinWorkers() { return minWorkers; } public void setMinWorkers(int minWorkers) { this.minWorkers = minWorkers; } public int getMaxWorkers() { return maxWorkers; } public void setMaxWorkers(int maxWorkers) { this.maxWorkers = maxWorkers; } public int getMaxConnections() { return maxConnections; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } public int getMaxPendingRequest() { return maxPendingRequest; } public void setMaxPendingRequest(int maxPendingRequest) { this.maxPendingRequest = maxPendingRequest; } public int getMaxIdleTime() { return maxIdleTime; } public void setMaxIdleTime(int maxIdleTime) { this.maxIdleTime = maxIdleTime; } public int getSendBuffer() { return sendBuffer; } public void setSendBuffer(int sendBuffer) { this.sendBuffer = sendBuffer; } public int getRecvBuffer() { return recvBuffer; } public void setRecvBuffer(int recvBuffer) { this.recvBuffer = recvBuffer; } public int getMaxPacketLength() { return maxPacketLength; } public void setMaxPacketLength(int maxPacketLength) { this.maxPacketLength = maxPacketLength; } @Override public String toString() { return "DoradoProperties [backlog=" + backlog + ", acceptors=" + acceptors + ", ioWorkers=" + ioWorkers + ", minWorkers=" + minWorkers + ", maxWorkers=" + maxWorkers + ", maxConnections=" + maxConnections + ", maxPendingRequest=" + maxPendingRequest + ", maxIdleTime=" + maxIdleTime + ", sendBuffer=" + sendBuffer + ", recvBuffer=" + recvBuffer + ", maxPacketLength=" + maxPacketLength + "]"; } }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/springboot/DoradoSpringBootApplication.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.springboot; 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; import org.springframework.boot.autoconfigure.SpringBootApplication; @Documented @Retention(RUNTIME) @Target(TYPE) @EnableDorado @SpringBootApplication public @interface DoradoSpringBootApplication { }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/springboot/EnableDorado.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.springboot; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; /** * @author weiping wang * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Import(DoradoAutoConfiguration.class) public @interface EnableDorado { }
0
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-core/0.0.51/ai/houyi/dorado/springboot/package-info.java
/** * */ /** * @author marta * */ package ai.houyi.dorado.springboot;
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/Application.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ package ai.houyi.dorado.example; import ai.houyi.dorado.rest.server.DoradoServer; import ai.houyi.dorado.rest.server.DoradoServerBuilder; import ai.houyi.dorado.swagger.EnableSwagger; /** * @author wangweiping * */ @EnableSwagger public class Application { public static void main(String[] args) throws Exception { DoradoServer server = DoradoServerBuilder.forPort(18889).build(); //Webapp.get().getMethodReturnValueHandlerConfig().addExcludePath("/file/upload/*"); server.start(); } }
0
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado
java-sources/ai/houyi/dorado-examples/0.0.51/ai/houyi/dorado/example/package-info.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ /** * @author wangweiping * */ package ai.houyi.dorado.example;
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/controller/AuthController.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ package ai.houyi.dorado.example.controller; import ai.houyi.dorado.rest.annotation.Controller; import ai.houyi.dorado.rest.annotation.GET; import ai.houyi.dorado.rest.annotation.Path; /** * @author weiping wang * */ @Controller @Path("/auth") public class AuthController { @Path("/signin") @GET public String signin(String name,String pwd) { System.out.println("signin name: "+name); System.out.println("signin pwd: "+pwd); return "signin success"; } }
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/controller/ExampleController.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ package ai.houyi.dorado.example.controller; import ai.houyi.dorado.example.controller.helper.MyException; import ai.houyi.dorado.example.model.Campaign; import ai.houyi.dorado.rest.annotation.Controller; import ai.houyi.dorado.rest.annotation.DELETE; import ai.houyi.dorado.rest.annotation.GET; import ai.houyi.dorado.rest.annotation.POST; import ai.houyi.dorado.rest.annotation.Path; import ai.houyi.dorado.rest.annotation.RequestParam; import io.swagger.annotations.Api; /** * @author wangweiping * */ @Controller @Path("/campaign") @Api(tags="推广活动管理") public class ExampleController { @Path("/{id:[0-9]+}") @GET public Campaign newCampaign(int id) { Campaign campaign = new Campaign(); campaign.setId(id); campaign.setName("test campaign"); return campaign; } @GET @Path("/qtest") public String queryTest(@RequestParam("q") String query) { return "QQ"; } @Path("/name/{name}") public String campaignName(String name) { return String.format("hello_campaign, %s", name); } @POST public Campaign save(Campaign campaign) { System.out.println(campaign); return campaign; } @Path("/{id}") @DELETE public void deleteCampaign(int id) { System.out.println("delete campaign, id: " + id); } @GET @Path("/{id}") public Campaign getCampaign(int id) { return Campaign.builder().withId(12).withName("网易考拉推广计划").build(); } @GET @Path("/exception/my") public Campaign testMyException(int id) throws MyException { throw new MyException("my exception"); } @GET @Path("/exception/default") public Campaign testDefaultException(int id) throws Exception { throw new Exception("default exception"); } }
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/controller/FileUploadController.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.controller; import ai.houyi.dorado.rest.annotation.Controller; import ai.houyi.dorado.rest.annotation.POST; import ai.houyi.dorado.rest.annotation.Path; import ai.houyi.dorado.rest.annotation.Produce; import ai.houyi.dorado.rest.http.MultipartFile; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; /** * @author weiping wang * */ @Controller @Path("/file/upload") @Api(tags = { "文件上传" }) public class FileUploadController { @Produce("image/jpeg") @POST @Path("/single") @ApiOperation("文件上传测试") public byte[] upload(MultipartFile file) { System.out.println(file); System.out.println(file.getContent().length); // saveFile(file); return file.getContent(); } @POST @Path("/multi") @ApiOperation("多文件上传") @Produce("application/json") public String multiUpload(MultipartFile[] files) { for (MultipartFile mf : files) { System.out.println(mf.getName() + "," + mf.getContentType()); } return "OK"; } }
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/controller/package-info.java
/* * Copyright 2014-2018 f2time.com All right reserved. */ /** * @author wangweiping * */ package ai.houyi.dorado.example.controller;
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/ApiContextBuilderImpl.java
/** * */ package ai.houyi.dorado.example.controller.helper; 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.Contact; import io.swagger.models.Info; import io.swagger.models.License; /** * @author marta * */ public class ApiContextBuilderImpl implements ApiContextBuilder{ @Override // 这里定制Api全局信息,如文档描述、license,contact等信息 public ApiContext buildApiContext() { Info info = new Info() .contact(new Contact().email("javagossip@gmail.com").name("weiping wang") .url("http://github.com/javagossip/dorado")) .license(new License().name("apache v2.0").url("http://www.apache.org")) .termsOfService("http://swagger.io/terms/").description("Dorado服务框架api接口文档") .title("dorado demo api接口文档").version("1.0.0"); //构造api访问授权的apiKey ApiKey apiKey = ApiKey.builder().withName("Authorization").withIn("header").build(); ApiContext apiContext = ApiContext.builder().withApiKey(apiKey) .withInfo(info).build(); return apiContext; } }
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/MyException.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.controller.helper; /** * * @author wangwp */ @SuppressWarnings("serial") public class MyException extends Exception { public MyException() { super(); } public MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(String message) { super(message); } public MyException(Throwable cause) { super(cause); } }
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/TestExceptionAdvice.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.controller.helper; import ai.houyi.dorado.rest.annotation.ExceptionAdvice; import ai.houyi.dorado.rest.annotation.ExceptionType; import ai.houyi.dorado.rest.annotation.Status; /** * * @author wangwp */ @ExceptionAdvice public class TestExceptionAdvice { @ExceptionType(MyException.class) @Status(400) public String handleException(MyException ex) { return "cause: " + ex.getClass().getName() + "," + ex.getMessage(); } @ExceptionType(Exception.class) public String handleException(Exception ex) { return "use default exception handler,cause: " + ex.getClass().getName() + "," + ex.getMessage(); } @ExceptionType(Throwable.class) public String handleException(Throwable ex) { return "use default exception handler,cause: " + ex.getClass().getName() + "," + ex.getMessage(); } }
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/TestMethodReturnValueHandler.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.controller.helper; import ai.houyi.dorado.example.model.TestResp; import ai.houyi.dorado.rest.http.MethodReturnValueHandler; import ai.houyi.dorado.rest.util.MethodDescriptor; /** * * @author wangwp */ public class TestMethodReturnValueHandler implements MethodReturnValueHandler { @Override public Object handleMethodReturnValue(Object value, MethodDescriptor methodDescriptor) { if (value.getClass() == byte[].class) return value; return TestResp.builder().withCode(0).withMsg("OK").withData(value).build(); } @Override public boolean supportsReturnType(MethodDescriptor returnType) { return returnType.getReturnType()!=byte[].class; } }