index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Service.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Service annotation * * @see DubboService * @since 2.7.0 * @deprecated Recommend {@link DubboService} as the substitute */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) @Inherited @Deprecated public @interface Service { /** * Interface class, default value is void.class */ Class<?> interfaceClass() default void.class; /** * Interface class name, default value is empty string */ String interfaceName() default ""; /** * Service version, default value is empty string */ String version() default ""; /** * Service group, default value is empty string */ String group() default ""; /** * Service path, default value is empty string */ String path() default ""; /** * Whether to export service, default value is true */ boolean export() default true; /** * Service token, default value is false */ String token() default ""; /** * Whether the service is deprecated, default value is false */ boolean deprecated() default false; /** * Whether the service is dynamic, default value is true */ boolean dynamic() default true; /** * Access log for the service, default value is "" */ String accesslog() default ""; /** * Maximum concurrent executes for the service, default value is 0 - no limits */ int executes() default -1; /** * Whether to register the service to register center, default value is true */ boolean register() default true; /** * Service weight value, default value is 0 */ int weight() default -1; /** * Service doc, default value is "" */ String document() default ""; /** * Delay time for service registration, default value is 0 */ int delay() default -1; /** * @see Service#stub() * @deprecated */ String local() default ""; /** * Service stub name, use interface name + Local if not set */ String stub() default ""; /** * Cluster strategy, legal values include: failover, failfast, failsafe, failback, forking */ String cluster() default ""; /** * How the proxy is generated, legal values include: jdk, javassist */ String proxy() default ""; /** * Maximum connections service provider can accept, default value is 0 - connection is shared */ int connections() default -1; /** * The callback instance limit peer connection * <p> * see org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CALLBACK_INSTANCES */ int callbacks() default -1; /** * Callback method name when connected, default value is empty string */ String onconnect() default ""; /** * Callback method name when disconnected, default value is empty string */ String ondisconnect() default ""; /** * Service owner, default value is empty string */ String owner() default ""; /** * Service layer, default value is empty string */ String layer() default ""; /** * Service invocation retry times * * @see org.apache.dubbo.common.constants.CommonConstants#DEFAULT_RETRIES */ int retries() default -1; /** * Load balance strategy, legal values include: random, roundrobin, leastactive * * @see org.apache.dubbo.common.constants.CommonConstants#DEFAULT_LOADBALANCE */ String loadbalance() default ""; /** * Whether to enable async invocation, default value is false */ boolean async() default false; /** * Maximum active requests allowed, default value is 0 */ int actives() default -1; /** * Whether the async request has already been sent, the default value is false */ boolean sent() default false; /** * Service mock name, use interface name + Mock if not set */ String mock() default ""; /** * Whether to use JSR303 validation, legal values are: true, false */ String validation() default ""; /** * Timeout value for service invocation, default value is 0 */ int timeout() default -1; /** * Specify cache implementation for service invocation, legal values include: lru, threadlocal, jcache */ String cache() default ""; /** * Filters for service invocation * * @see Filter */ String[] filter() default {}; /** * Listeners for service exporting and unexporting * * @see ExporterListener */ String[] listener() default {}; /** * Customized parameter key-value pair, for example: {key1, value1, key2, value2} */ String[] parameters() default {}; /** * Application spring bean name * @deprecated Do not set it and use the global Application Config */ @Deprecated String application() default ""; /** * Module spring bean name */ String module() default ""; /** * Provider spring bean name */ String provider() default ""; /** * Protocol spring bean names */ String[] protocol() default {}; /** * Monitor spring bean name */ String monitor() default ""; /** * Registry spring bean name */ String[] registry() default {}; /** * Service tag name */ String tag() default ""; /** * methods support * * @return */ Method[] methods() default {}; }
6,700
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/DubboReference.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.annotation; import org.apache.dubbo.common.constants.ClusterRules; import org.apache.dubbo.common.constants.LoadbalanceRules; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.config.AbstractReferenceConfig; import org.apache.dubbo.config.ReferenceConfigBase; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation used for referencing a Dubbo service. * <p> * <b>It is recommended to use @DubboReference on the @Bean method in the Java-config class, but not on the fields or setter methods to be injected.</b> * </p> * <p> * Step 1: Register ReferenceBean in Java-config class: * <pre class="code"> * &#64;Configuration * public class ReferenceConfiguration { * &#64;Bean * &#64;DubboReference(group = "demo") * public ReferenceBean&lt;HelloService&gt; helloService() { * return new ReferenceBean(); * } * * &#64;Bean * &#64;DubboReference(group = "demo", interfaceClass = HelloService.class) * public ReferenceBean&lt;GenericService&gt; genericHelloService() { * return new ReferenceBean(); * } * } * </pre> * <p> * Step 2: Inject ReferenceBean by @Autowired * <pre class="code"> * public class FooController { * &#64;Autowired * private HelloService helloService; * * &#64;Autowired * private GenericService genericHelloService; * } * </pre> * * @see org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder * @see org.apache.dubbo.config.spring.ReferenceBean * @since 2.7.7 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface DubboReference { /** * Interface class, default value is void.class */ Class<?> interfaceClass() default void.class; /** * Interface class name, default value is empty string */ String interfaceName() default ""; /** * Service version, default value is empty string */ String version() default ""; /** * Service group, default value is empty string */ String group() default ""; /** * Service target URL for direct invocation, if this is specified, then registry center takes no effect. */ String url() default ""; /** * Client transport type, default value is "netty" */ String client() default ""; /** * Whether to enable generic invocation, default value is false * * @deprecated Do not need specify generic value, judge by injection type and interface class */ @Deprecated boolean generic() default false; /** * When enable, prefer to call local service in the same JVM if it's present, default value is true * * @deprecated using scope="local" or scope="remote" instead */ @Deprecated boolean injvm() default true; /** * Check if service provider is available during boot up, default value is true */ boolean check() default true; /** * Whether eager initialize the reference bean when all properties are set, default value is true ( null as true) * * @see ReferenceConfigBase#shouldInit() */ boolean init() default true; /** * Whether to make connection when the client is created, the default value is false */ boolean lazy() default false; /** * Export an stub service for event dispatch, default value is false. * <p> * see org.apache.dubbo.rpc.Constants#STUB_EVENT_METHODS_KEY */ boolean stubevent() default false; /** * Whether to reconnect if connection is lost, if not specify, reconnect is enabled by default, and the interval * for retry connecting is 2000 ms * <p> * see org.apache.dubbo.remoting.Constants#DEFAULT_RECONNECT_PERIOD */ String reconnect() default ""; /** * Whether to stick to the same node in the cluster, the default value is false * <p> * see Constants#DEFAULT_CLUSTER_STICKY */ boolean sticky() default false; /** * How the proxy is generated, legal values include: jdk, javassist */ String proxy() default ""; /** * Service stub name, use interface name + Stub if not set */ String stub() default ""; /** * Cluster strategy, legal values include: failover, failfast, failsafe, failback, forking * you can use {@link org.apache.dubbo.common.constants.ClusterRules#FAIL_FAST} …… */ String cluster() default ClusterRules.EMPTY; /** * Maximum connections service provider can accept, default value is 0 - connection is shared */ int connections() default -1; /** * The callback instance limit peer connection * <p> * see org.apache.dubbo.rpc.Constants#DEFAULT_CALLBACK_INSTANCES */ int callbacks() default -1; /** * Callback method name when connected, default value is empty string */ String onconnect() default ""; /** * Callback method name when disconnected, default value is empty string */ String ondisconnect() default ""; /** * Service owner, default value is empty string */ String owner() default ""; /** * Service layer, default value is empty string */ String layer() default ""; /** * Service invocation retry times * <p> * see Constants#DEFAULT_RETRIES */ int retries() default -1; /** * Load balance strategy, legal values include: random, roundrobin, leastactive * you can use {@link org.apache.dubbo.common.constants.LoadbalanceRules#RANDOM} …… */ String loadbalance() default LoadbalanceRules.EMPTY; /** * Whether to enable async invocation, default value is false */ boolean async() default false; /** * Maximum active requests allowed, default value is 0 */ int actives() default -1; /** * Whether the async request has already been sent, the default value is false */ boolean sent() default false; /** * Service mock name, use interface name + Mock if not set */ String mock() default ""; /** * Whether to use JSR303 validation, legal values are: true, false */ String validation() default ""; /** * Timeout value for service invocation, default value is 0 */ int timeout() default -1; /** * Specify cache implementation for service invocation, legal values include: lru, threadlocal, jcache */ String cache() default ""; /** * Filters for service invocation * <p> * see Filter */ String[] filter() default {}; /** * Listeners for service exporting and unexporting * <p> * see ExporterListener */ String[] listener() default {}; /** * Customized parameter key-value pair, for example: {key1, value1, key2, value2} or {"key1=value1", "key2=value2"} */ String[] parameters() default {}; /** * Application name * * @deprecated This attribute was deprecated, use bind application/module of spring ApplicationContext */ @Deprecated String application() default ""; /** * Module associated name */ String module() default ""; /** * Consumer associated name */ String consumer() default ""; /** * Monitor associated name */ String monitor() default ""; /** * Registry associated name */ String[] registry() default {}; /** * The communication protocol of Dubbo Service * * @return the default value is "" * @since 2.6.6 */ String protocol() default ""; /** * Service tag name */ String tag() default ""; /** * Service merger */ String merger() default ""; /** * methods support */ Method[] methods() default {}; /** * The id * NOTE: The id attribute is ignored when using @DubboReference on @Bean method * * @return default value is empty * @since 2.7.3 */ String id() default ""; /** * @return The service names that the Dubbo interface subscribed * @see RegistryConstants#SUBSCRIBED_SERVICE_NAMES_KEY * @since 2.7.8 * @deprecated using {@link DubboReference#providedBy()} */ @Deprecated String[] services() default {}; /** * declares which app or service this interface belongs to * * @see RegistryConstants#PROVIDED_BY */ String[] providedBy() default {}; /** * The service port of the provider * * @see AbstractReferenceConfig#providerPort * @since 3.1.0 */ int providerPort() default -1; /** * assign the namespace that provider belong to * @see AbstractReferenceConfig#providerNamespace * @since 3.1.1 */ String providerNamespace() default ""; /** * the scope for referring/exporting a service, if it's local, it means searching in current JVM only. * * @see org.apache.dubbo.rpc.Constants#SCOPE_LOCAL * @see org.apache.dubbo.rpc.Constants#SCOPE_REMOTE */ String scope() default ""; /** * Weather the reference is refer asynchronously */ boolean referAsync() default false; /** * unload Cluster related in mesh mode * * @see ReferenceConfigBase#unloadClusterRelated * @since 3.1.0 */ boolean unloadClusterRelated() default false; }
6,701
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/ProvidedBy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Class-level annotation used for declaring Dubbo interface. * Example: * @ProvidedBy("dubbo-samples-xds-provider") * public interface GreetingService { * String sayHello(String name); * } * * @Component("annotatedConsumer") * public class GreetingServiceConsumer { * @DubboReference(version = "1.0.0") * private GreetingService greetingService; * } */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Inherited public @interface ProvidedBy { /** * Interface app name, default value is empty string */ String[] name() default {}; }
6,702
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/support/Parameter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.support; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Parameter */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Parameter { /** * Specify the parameter key when append parameters to url */ String key() default ""; /** * If required=true, the value must not be empty when append to url */ boolean required() default false; /** * If excluded=true, ignore it when append parameters to url */ boolean excluded() default false; /** * if escaped=true, escape it when append parameters to url */ boolean escaped() default false; /** * If attribute=false, ignore it when processing refresh()/getMetadata()/equals()/toString() */ boolean attribute() default true; /** * If append=true, append new value to exist value instead of overriding it. */ boolean append() default false; }
6,703
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/support/Nested.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.support; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Nested Class Parameter */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface Nested {}
6,704
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/nested/ExporterConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.nested; import org.apache.dubbo.config.support.Nested; import java.io.Serializable; import java.time.Duration; import java.util.HashMap; import java.util.Map; public class ExporterConfig implements Serializable { @Nested private ZipkinConfig zipkinConfig; @Nested private OtlpConfig otlpConfig; public ZipkinConfig getZipkinConfig() { return zipkinConfig; } public void setZipkinConfig(ZipkinConfig zipkinConfig) { this.zipkinConfig = zipkinConfig; } public OtlpConfig getOtlpConfig() { return otlpConfig; } public void setOtlpConfig(OtlpConfig otlpConfig) { this.otlpConfig = otlpConfig; } public static class ZipkinConfig implements Serializable { /** * URL to the Zipkin API. */ private String endpoint; /** * Connection timeout for requests to Zipkin. */ private Duration connectTimeout = Duration.ofSeconds(1); /** * Read timeout for requests to Zipkin. */ private Duration readTimeout = Duration.ofSeconds(10); public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public Duration getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; } public Duration getReadTimeout() { return readTimeout; } public void setReadTimeout(Duration readTimeout) { this.readTimeout = readTimeout; } } public static class OtlpConfig implements Serializable { /** * URL to the Otlp API. */ private String endpoint; /** * The maximum time to wait for the collector to process an exported batch of spans. */ private Duration timeout = Duration.ofSeconds(10); /** * The method used to compress payloads. If unset, compression is disabled. Currently * supported compression methods include "gzip" and "none". */ private String compressionMethod = "none"; private Map<String, String> headers = new HashMap<>(); public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public Duration getTimeout() { return timeout; } public void setTimeout(Duration timeout) { this.timeout = timeout; } public String getCompressionMethod() { return compressionMethod; } public void setCompressionMethod(String compressionMethod) { this.compressionMethod = compressionMethod; } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } } }
6,705
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/nested/BaggageConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.nested; import org.apache.dubbo.config.support.Nested; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class BaggageConfig implements Serializable { private Boolean enabled = true; /** * Correlation configuration. */ @Nested private Correlation correlation = new Correlation(); /** * List of fields that are referenced the same in-process as it is on the wire. * For example, the field "x-vcap-request-id" would be set as-is including the * prefix. */ private List<String> remoteFields = new ArrayList<>(); public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public Correlation getCorrelation() { return correlation; } public void setCorrelation(Correlation correlation) { this.correlation = correlation; } public List<String> getRemoteFields() { return remoteFields; } public void setRemoteFields(List<String> remoteFields) { this.remoteFields = remoteFields; } public static class Correlation implements Serializable { /** * Whether to enable correlation of the baggage context with logging contexts. */ private boolean enabled = true; /** * List of fields that should be correlated with the logging context. That * means that these fields would end up as key-value pairs in e.g. MDC. */ private List<String> fields = new ArrayList<>(); public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public List<String> getFields() { return this.fields; } public void setFields(List<String> fields) { this.fields = fields; } } }
6,706
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/nested/AggregationConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.nested; import java.io.Serializable; public class AggregationConfig implements Serializable { /** * Enable local aggregation or not */ private Boolean enabled; private Boolean enableQps; private Boolean enableRtPxx; private Boolean enableRt; private Boolean enableRequest; /** * Bucket num for time window quantile */ private Integer bucketNum; /** * Time window seconds for time window quantile */ private Integer timeWindowSeconds; /** * Time window mill seconds for qps */ private Integer qpsTimeWindowMillSeconds; public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public Integer getBucketNum() { return bucketNum; } public void setBucketNum(Integer bucketNum) { this.bucketNum = bucketNum; } public Integer getTimeWindowSeconds() { return timeWindowSeconds; } public void setTimeWindowSeconds(Integer timeWindowSeconds) { this.timeWindowSeconds = timeWindowSeconds; } public Boolean getEnableQps() { return enableQps; } public void setEnableQps(Boolean enableQps) { this.enableQps = enableQps; } public Boolean getEnableRtPxx() { return enableRtPxx; } public void setEnableRtPxx(Boolean enableRtPxx) { this.enableRtPxx = enableRtPxx; } public Boolean getEnableRt() { return enableRt; } public void setEnableRt(Boolean enableRt) { this.enableRt = enableRt; } public Boolean getEnableRequest() { return enableRequest; } public void setEnableRequest(Boolean enableRequest) { this.enableRequest = enableRequest; } public Integer getQpsTimeWindowMillSeconds() { return qpsTimeWindowMillSeconds; } public void setQpsTimeWindowMillSeconds(Integer qpsTimeWindowMillSeconds) { this.qpsTimeWindowMillSeconds = qpsTimeWindowMillSeconds; } }
6,707
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/nested/PropagationConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.nested; import java.io.Serializable; public class PropagationConfig implements Serializable { public static final String B3 = "B3"; public static final String W3C = "W3C"; /** * Tracing context propagation type. */ private String type = W3C; public String getType() { return type; } public void setType(String type) { this.type = type; } }
6,708
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.nested; import java.io.Serializable; public class HistogramConfig implements Serializable { private Boolean enabled; private Integer[] bucketsMs; private Integer minExpectedMs; private Integer maxExpectedMs; private Boolean enabledPercentiles; private double[] percentiles; private Integer distributionStatisticExpiryMin; public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public Integer[] getBucketsMs() { return bucketsMs; } public void setBucketsMs(Integer[] bucketsMs) { this.bucketsMs = bucketsMs; } public Integer getMinExpectedMs() { return minExpectedMs; } public void setMinExpectedMs(Integer minExpectedMs) { this.minExpectedMs = minExpectedMs; } public Integer getMaxExpectedMs() { return maxExpectedMs; } public void setMaxExpectedMs(Integer maxExpectedMs) { this.maxExpectedMs = maxExpectedMs; } public Boolean getEnabledPercentiles() { return enabledPercentiles; } public void setEnabledPercentiles(Boolean enabledPercentiles) { this.enabledPercentiles = enabledPercentiles; } public double[] getPercentiles() { return percentiles; } public void setPercentiles(double[] percentiles) { this.percentiles = percentiles; } public Integer getDistributionStatisticExpiryMin() { return distributionStatisticExpiryMin; } public void setDistributionStatisticExpiryMin(Integer distributionStatisticExpiryMin) { this.distributionStatisticExpiryMin = distributionStatisticExpiryMin; } }
6,709
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/nested/SamplingConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.nested; import java.io.Serializable; public class SamplingConfig implements Serializable { /** * Probability in the range from 0.0 to 1.0 that a trace will be sampled. */ private float probability = 0.10f; public float getProbability() { return this.probability; } public void setProbability(float probability) { this.probability = probability; } }
6,710
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/config/nested/PrometheusConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.config.nested; import org.apache.dubbo.config.support.Nested; import java.io.Serializable; public class PrometheusConfig implements Serializable { /** * Prometheus exporter configuration */ @Nested private Exporter exporter; /** * Prometheus Pushgateway configuration */ @Nested private Pushgateway pushgateway; public Exporter getExporter() { return exporter; } public void setExporter(Exporter exporter) { this.exporter = exporter; } public Pushgateway getPushgateway() { return pushgateway; } public void setPushgateway(Pushgateway pushgateway) { this.pushgateway = pushgateway; } public static class Exporter implements Serializable { /** * Enable prometheus exporter */ private Boolean enabled; /** * Enable http service discovery for prometheus */ private Boolean enableHttpServiceDiscovery; /** * Http service discovery url */ private String httpServiceDiscoveryUrl; public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public Boolean getEnableHttpServiceDiscovery() { return enableHttpServiceDiscovery; } public void setEnableHttpServiceDiscovery(Boolean enableHttpServiceDiscovery) { this.enableHttpServiceDiscovery = enableHttpServiceDiscovery; } public String getHttpServiceDiscoveryUrl() { return httpServiceDiscoveryUrl; } public void setHttpServiceDiscoveryUrl(String httpServiceDiscoveryUrl) { this.httpServiceDiscoveryUrl = httpServiceDiscoveryUrl; } } public static class Pushgateway implements Serializable { /** * Enable publishing via a Prometheus Pushgateway */ private Boolean enabled; /** * Base URL for the Pushgateway */ private String baseUrl; /** * Login user of the Prometheus Pushgateway */ private String username; /** * Login password of the Prometheus Pushgateway */ private String password; /** * Frequency with which to push metrics */ private Integer pushInterval; /** * Job identifier for this application instance */ private String job; public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public String getBaseUrl() { return baseUrl; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getPushInterval() { return pushInterval; } public void setPushInterval(Integer pushInterval) { this.pushInterval = pushInterval; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } } }
6,711
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/Extension.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker for extension interface * <p/> * Changes on extension configuration file <br/> * Use <code>Protocol</code> as an example, its configuration file 'META-INF/dubbo/com.xxx.Protocol' is changes from: <br/> * <pre> * com.foo.XxxProtocol * com.foo.YyyProtocol * </pre> * <p> * to key-value pair <br/> * <pre> * xxx=com.foo.XxxProtocol * yyy=com.foo.YyyProtocol * </pre> * <br/> * The reason for this change is: * <p> * If there's third party library referenced by static field or by method in extension implementation, its class will * fail to initialize if the third party library doesn't exist. In this case, dubbo cannot figure out extension's id * therefore cannot be able to map the exception information with the extension, if the previous format is used. * <p/> * For example: * <p> * Fails to load Extension("mina"). When user configure to use mina, dubbo will complain the extension cannot be loaded, * instead of reporting which extract extension implementation fails and the extract reason. * </p> * * @deprecated because it's too general, switch to use {@link org.apache.dubbo.common.extension.SPI} */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Extension { /** * @deprecated */ @Deprecated String value() default ""; }
6,712
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/Node.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; /** * Node. (API/SPI, Prototype, ThreadSafe) */ public interface Node { /** * get url. * * @return url. */ URL getUrl(); /** * is available. * * @return available. */ boolean isAvailable(); /** * destroy. */ void destroy(); }
6,713
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/ServiceKey.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import java.util.Objects; public class ServiceKey { private final String interfaceName; private final String group; private final String version; public ServiceKey(String interfaceName, String version, String group) { this.interfaceName = interfaceName; this.group = group; this.version = version; } public String getInterfaceName() { return interfaceName; } public String getGroup() { return group; } public String getVersion() { return version; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServiceKey that = (ServiceKey) o; return Objects.equals(interfaceName, that.interfaceName) && Objects.equals(group, that.group) && Objects.equals(version, that.version); } @Override public int hashCode() { return Objects.hash(interfaceName, group, version); } @Override public String toString() { return BaseServiceMetadata.buildServiceKey(interfaceName, group, version); } public static class Matcher { public static boolean isMatch(ServiceKey rule, ServiceKey target) { // 1. match interface (accurate match) if (!Objects.equals(rule.getInterfaceName(), target.getInterfaceName())) { return false; } // 2. match version (accurate match) // 2.1. if rule version is *, match all if (!CommonConstants.ANY_VALUE.equals(rule.getVersion())) { // 2.2. if rule version is null, target version should be null if (StringUtils.isEmpty(rule.getVersion()) && !StringUtils.isEmpty(target.getVersion())) { return false; } if (!StringUtils.isEmpty(rule.getVersion())) { // 2.3. if rule version contains ',', split and match each if (rule.getVersion().contains(CommonConstants.COMMA_SEPARATOR)) { String[] versions = rule.getVersion().split("\\" + CommonConstants.COMMA_SEPARATOR, -1); boolean match = false; for (String version : versions) { version = version.trim(); if (StringUtils.isEmpty(version) && StringUtils.isEmpty(target.getVersion())) { match = true; break; } else if (version.equals(target.getVersion())) { match = true; break; } } if (!match) { return false; } } // 2.4. if rule version is not contains ',', match directly else if (!Objects.equals(rule.getVersion(), target.getVersion())) { return false; } } } // 3. match group (wildcard match) // 3.1. if rule group is *, match all if (!CommonConstants.ANY_VALUE.equals(rule.getGroup())) { // 3.2. if rule group is null, target group should be null if (StringUtils.isEmpty(rule.getGroup()) && !StringUtils.isEmpty(target.getGroup())) { return false; } if (!StringUtils.isEmpty(rule.getGroup())) { // 3.3. if rule group contains ',', split and match each if (rule.getGroup().contains(CommonConstants.COMMA_SEPARATOR)) { String[] groups = rule.getGroup().split("\\" + CommonConstants.COMMA_SEPARATOR, -1); boolean match = false; for (String group : groups) { group = group.trim(); if (StringUtils.isEmpty(group) && StringUtils.isEmpty(target.getGroup())) { match = true; break; } else if (group.equals(target.getGroup())) { match = true; break; } } if (!match) { return false; } } // 3.4. if rule group is not contains ',', match directly else if (!Objects.equals(rule.getGroup(), target.getGroup())) { return false; } } } return true; } } }
6,714
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/BaseServiceMetadata.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ServiceModel; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_VERSION; /** * 2019-10-10 */ public class BaseServiceMetadata { public static final char COLON_SEPARATOR = ':'; protected String serviceKey; protected String serviceInterfaceName; protected String version; protected volatile String group; private ServiceModel serviceModel; public static String buildServiceKey(String path, String group, String version) { int length = path == null ? 0 : path.length(); length += group == null ? 0 : group.length(); length += version == null ? 0 : version.length(); length += 2; StringBuilder buf = new StringBuilder(length); if (StringUtils.isNotEmpty(group)) { buf.append(group).append('/'); } buf.append(path); if (StringUtils.isNotEmpty(version)) { buf.append(':').append(version); } return buf.toString().intern(); } public static String versionFromServiceKey(String serviceKey) { int index = serviceKey.indexOf(":"); if (index == -1) { return DEFAULT_VERSION; } return serviceKey.substring(index + 1); } public static String groupFromServiceKey(String serviceKey) { int index = serviceKey.indexOf("/"); if (index == -1) { return null; } return serviceKey.substring(0, index); } public static String interfaceFromServiceKey(String serviceKey) { int groupIndex = serviceKey.indexOf("/"); int versionIndex = serviceKey.indexOf(":"); groupIndex = (groupIndex == -1) ? 0 : groupIndex + 1; versionIndex = (versionIndex == -1) ? serviceKey.length() : versionIndex; return serviceKey.substring(groupIndex, versionIndex); } /** * Format : interface:version * * @return */ public String getDisplayServiceKey() { StringBuilder serviceNameBuilder = new StringBuilder(); serviceNameBuilder.append(serviceInterfaceName); serviceNameBuilder.append(COLON_SEPARATOR).append(version); return serviceNameBuilder.toString(); } /** * revert of org.apache.dubbo.common.ServiceDescriptor#getDisplayServiceKey() * * @param displayKey * @return */ public static BaseServiceMetadata revertDisplayServiceKey(String displayKey) { String[] eles = StringUtils.split(displayKey, COLON_SEPARATOR); if (eles == null || eles.length < 1 || eles.length > 2) { return new BaseServiceMetadata(); } BaseServiceMetadata serviceDescriptor = new BaseServiceMetadata(); serviceDescriptor.setServiceInterfaceName(eles[0]); if (eles.length == 2) { serviceDescriptor.setVersion(eles[1]); } return serviceDescriptor; } public static String keyWithoutGroup(String interfaceName, String version) { if (StringUtils.isEmpty(version)) { return interfaceName + ":" + DEFAULT_VERSION; } return interfaceName + ":" + version; } public String getServiceKey() { return serviceKey; } public void generateServiceKey() { this.serviceKey = buildServiceKey(serviceInterfaceName, group, version); } public void setServiceKey(String serviceKey) { this.serviceKey = serviceKey; } public String getServiceInterfaceName() { return serviceInterfaceName; } public void setServiceInterfaceName(String serviceInterfaceName) { this.serviceInterfaceName = serviceInterfaceName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public ServiceModel getServiceModel() { return serviceModel; } public void setServiceModel(ServiceModel serviceModel) { this.serviceModel = serviceModel; } }
6,715
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; public class BatchExecutorQueue<T> { static final int DEFAULT_QUEUE_SIZE = 128; private final Queue<T> queue; private final AtomicBoolean scheduled; private final int chunkSize; public BatchExecutorQueue() { this(DEFAULT_QUEUE_SIZE); } public BatchExecutorQueue(int chunkSize) { this.queue = new ConcurrentLinkedQueue<>(); this.scheduled = new AtomicBoolean(false); this.chunkSize = chunkSize; } public void enqueue(T message, Executor executor) { queue.add(message); scheduleFlush(executor); } protected void scheduleFlush(Executor executor) { if (scheduled.compareAndSet(false, true)) { executor.execute(() -> this.run(executor)); } } private void run(Executor executor) { try { Queue<T> snapshot = new LinkedList<>(); T item; while ((item = queue.poll()) != null) { snapshot.add(item); } int i = 0; boolean flushedOnce = false; while ((item = snapshot.poll()) != null) { if (snapshot.size() == 0) { flushedOnce = false; break; } if (i == chunkSize) { i = 0; flush(item); flushedOnce = true; } else { prepare(item); i++; } } if (!flushedOnce && item != null) { flush(item); } } finally { scheduled.set(false); if (!queue.isEmpty()) { scheduleFlush(executor); } } } protected void prepare(T item) {} protected void flush(T item) {} }
6,716
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/URLStrParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.url.component.URLItemCache; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING; import static org.apache.dubbo.common.utils.StringUtils.decodeHexByte; import static org.apache.dubbo.common.utils.Utf8Utils.decodeUtf8; public final class URLStrParser { public static final String ENCODED_QUESTION_MARK = "%3F"; public static final String ENCODED_TIMESTAMP_KEY = "timestamp%3D"; public static final String ENCODED_PID_KEY = "pid%3D"; public static final String ENCODED_AND_MARK = "%26"; private static final char SPACE = 0x20; private static final ThreadLocal<TempBuf> DECODE_TEMP_BUF = ThreadLocal.withInitial(() -> new TempBuf(1024)); private URLStrParser() { // empty } /** * @param decodedURLStr : after {@link URL#decode} string * decodedURLStr format: protocol://username:password@host:port/path?k1=v1&k2=v2 * [protocol://][username:password@][host:port]/[path][?k1=v1&k2=v2] */ public static URL parseDecodedStr(String decodedURLStr) { Map<String, String> parameters = null; int pathEndIdx = decodedURLStr.indexOf('?'); if (pathEndIdx >= 0) { parameters = parseDecodedParams(decodedURLStr, pathEndIdx + 1); } else { pathEndIdx = decodedURLStr.length(); } String decodedBody = decodedURLStr.substring(0, pathEndIdx); return parseURLBody(decodedURLStr, decodedBody, parameters); } private static Map<String, String> parseDecodedParams(String str, int from) { int len = str.length(); if (from >= len) { return Collections.emptyMap(); } TempBuf tempBuf = DECODE_TEMP_BUF.get(); Map<String, String> params = new HashMap<>(); int nameStart = from; int valueStart = -1; int i; for (i = from; i < len; i++) { char ch = str.charAt(i); switch (ch) { case '=': if (nameStart == i) { nameStart = i + 1; } else if (valueStart < nameStart) { valueStart = i + 1; } break; case ';': case '&': addParam(str, false, nameStart, valueStart, i, params, tempBuf); nameStart = i + 1; break; default: // continue } } addParam(str, false, nameStart, valueStart, i, params, tempBuf); return params; } /** * @param fullURLStr : fullURLString * @param decodedBody : format: [protocol://][username:password@][host:port]/[path] * @param parameters : * @return URL */ private static URL parseURLBody(String fullURLStr, String decodedBody, Map<String, String> parameters) { int starIdx = 0, endIdx = decodedBody.length(); // ignore the url content following '#' int poundIndex = decodedBody.indexOf('#'); if (poundIndex != -1) { endIdx = poundIndex; } String protocol = null; int protoEndIdx = decodedBody.indexOf("://"); if (protoEndIdx >= 0) { if (protoEndIdx == 0) { throw new IllegalStateException("url missing protocol: \"" + fullURLStr + "\""); } protocol = decodedBody.substring(0, protoEndIdx); starIdx = protoEndIdx + 3; } else { // case: file:/path/to/file.txt protoEndIdx = decodedBody.indexOf(":/"); if (protoEndIdx >= 0) { if (protoEndIdx == 0) { throw new IllegalStateException("url missing protocol: \"" + fullURLStr + "\""); } protocol = decodedBody.substring(0, protoEndIdx); starIdx = protoEndIdx + 1; } } String path = null; int pathStartIdx = indexOf(decodedBody, '/', starIdx, endIdx); if (pathStartIdx >= 0) { path = decodedBody.substring(pathStartIdx + 1, endIdx); endIdx = pathStartIdx; } String username = null; String password = null; int pwdEndIdx = lastIndexOf(decodedBody, '@', starIdx, endIdx); if (pwdEndIdx > 0) { int passwordStartIdx = indexOf(decodedBody, ':', starIdx, pwdEndIdx); if (passwordStartIdx != -1) { // tolerate incomplete user pwd input, like '1234@' username = decodedBody.substring(starIdx, passwordStartIdx); password = decodedBody.substring(passwordStartIdx + 1, pwdEndIdx); } else { username = decodedBody.substring(starIdx, pwdEndIdx); } starIdx = pwdEndIdx + 1; } String host = null; int port = 0; int hostEndIdx = lastIndexOf(decodedBody, ':', starIdx, endIdx); if (hostEndIdx > 0 && hostEndIdx < decodedBody.length() - 1) { if (lastIndexOf(decodedBody, '%', starIdx, endIdx) > hostEndIdx) { // ipv6 address with scope id // e.g. fe80:0:0:0:894:aeec:f37d:23e1%en0 // see https://howdoesinternetwork.com/2013/ipv6-zone-id // ignore } else { port = Integer.parseInt(decodedBody.substring(hostEndIdx + 1, endIdx)); endIdx = hostEndIdx; } } if (endIdx > starIdx) { host = decodedBody.substring(starIdx, endIdx); } // check cache protocol = URLItemCache.intern(protocol); path = URLItemCache.checkPath(path); return new ServiceConfigURL(protocol, username, password, host, port, path, parameters); } public static String[] parseRawURLToArrays(String rawURLStr, int pathEndIdx) { String[] parts = new String[2]; int paramStartIdx = pathEndIdx + 3; // skip ENCODED_QUESTION_MARK if (pathEndIdx == -1) { pathEndIdx = rawURLStr.indexOf('?'); if (pathEndIdx == -1) { // url with no params, decode anyway rawURLStr = URL.decode(rawURLStr); } else { paramStartIdx = pathEndIdx + 1; } } if (pathEndIdx >= 0) { parts[0] = rawURLStr.substring(0, pathEndIdx); parts[1] = rawURLStr.substring(paramStartIdx); } else { parts = new String[] {rawURLStr}; } return parts; } public static Map<String, String> parseParams(String rawParams, boolean encoded) { if (encoded) { return parseEncodedParams(rawParams, 0); } return parseDecodedParams(rawParams, 0); } /** * @param encodedURLStr : after {@link URL#encode(String)} string * encodedURLStr after decode format: protocol://username:password@host:port/path?k1=v1&k2=v2 * [protocol://][username:password@][host:port]/[path][?k1=v1&k2=v2] */ public static URL parseEncodedStr(String encodedURLStr) { Map<String, String> parameters = null; int pathEndIdx = encodedURLStr.toUpperCase().indexOf("%3F"); // '?' if (pathEndIdx >= 0) { parameters = parseEncodedParams(encodedURLStr, pathEndIdx + 3); } else { pathEndIdx = encodedURLStr.length(); } // decodedBody format: [protocol://][username:password@][host:port]/[path] String decodedBody = decodeComponent(encodedURLStr, 0, pathEndIdx, false, DECODE_TEMP_BUF.get()); return parseURLBody(encodedURLStr, decodedBody, parameters); } private static Map<String, String> parseEncodedParams(String str, int from) { int len = str.length(); if (from >= len) { return Collections.emptyMap(); } TempBuf tempBuf = DECODE_TEMP_BUF.get(); Map<String, String> params = new HashMap<>(); int nameStart = from; int valueStart = -1; int i; for (i = from; i < len; i++) { char ch = str.charAt(i); if (ch == '%') { if (i + 3 > len) { throw new IllegalArgumentException("unterminated escape sequence at index " + i + " of: " + str); } ch = (char) decodeHexByte(str, i + 1); i += 2; } switch (ch) { case '=': if (nameStart == i) { nameStart = i + 1; } else if (valueStart < nameStart) { valueStart = i + 1; } break; case ';': case '&': addParam(str, true, nameStart, valueStart, i - 2, params, tempBuf); nameStart = i + 1; break; default: // continue } } addParam(str, true, nameStart, valueStart, i, params, tempBuf); return params; } private static boolean addParam( String str, boolean isEncoded, int nameStart, int valueStart, int valueEnd, Map<String, String> params, TempBuf tempBuf) { if (nameStart >= valueEnd) { return false; } if (valueStart <= nameStart) { valueStart = valueEnd + 1; } if (isEncoded) { String name = decodeComponent(str, nameStart, valueStart - 3, false, tempBuf); String value; if (valueStart >= valueEnd) { value = ""; } else { value = decodeComponent(str, valueStart, valueEnd, false, tempBuf); } URLItemCache.putParams(params, name, value); // compatible with lower versions registering "default." keys if (name.startsWith(DEFAULT_KEY_PREFIX)) { params.putIfAbsent(name.substring(DEFAULT_KEY_PREFIX.length()), value); } } else { String name = str.substring(nameStart, valueStart - 1); String value; if (valueStart >= valueEnd) { value = ""; } else { value = str.substring(valueStart, valueEnd); } URLItemCache.putParams(params, name, value); // compatible with lower versions registering "default." keys if (name.startsWith(DEFAULT_KEY_PREFIX)) { params.putIfAbsent(name.substring(DEFAULT_KEY_PREFIX.length()), value); } } return true; } private static String decodeComponent(String s, int from, int toExcluded, boolean isPath, TempBuf tempBuf) { int len = toExcluded - from; if (len <= 0) { return EMPTY_STRING; } int firstEscaped = -1; for (int i = from; i < toExcluded; i++) { char c = s.charAt(i); if (c == '%' || c == '+' && !isPath) { firstEscaped = i; break; } } if (firstEscaped == -1) { return s.substring(from, toExcluded); } // Each encoded byte takes 3 characters (e.g. "%20") int decodedCapacity = (toExcluded - firstEscaped) / 3; byte[] buf = tempBuf.byteBuf(decodedCapacity); char[] charBuf = tempBuf.charBuf(len); s.getChars(from, firstEscaped, charBuf, 0); int charBufIdx = firstEscaped - from; return decodeUtf8Component(s, firstEscaped, toExcluded, isPath, buf, charBuf, charBufIdx); } private static String decodeUtf8Component( String str, int firstEscaped, int toExcluded, boolean isPath, byte[] buf, char[] charBuf, int charBufIdx) { int bufIdx; for (int i = firstEscaped; i < toExcluded; i++) { char c = str.charAt(i); if (c != '%') { charBuf[charBufIdx++] = c != '+' || isPath ? c : SPACE; continue; } bufIdx = 0; do { if (i + 3 > toExcluded) { throw new IllegalArgumentException("unterminated escape sequence at index " + i + " of: " + str); } buf[bufIdx++] = decodeHexByte(str, i + 1); i += 3; } while (i < toExcluded && str.charAt(i) == '%'); i--; charBufIdx += decodeUtf8(buf, 0, bufIdx, charBuf, charBufIdx); } return new String(charBuf, 0, charBufIdx); } private static int indexOf(String str, char ch, int from, int toExclude) { from = Math.max(from, 0); toExclude = Math.min(toExclude, str.length()); if (from > toExclude) { return -1; } for (int i = from; i < toExclude; i++) { if (str.charAt(i) == ch) { return i; } } return -1; } private static int lastIndexOf(String str, char ch, int from, int toExclude) { from = Math.max(from, 0); toExclude = Math.min(toExclude, str.length() - 1); if (from > toExclude) { return -1; } for (int i = toExclude; i >= from; i--) { if (str.charAt(i) == ch) { return i; } } return -1; } private static final class TempBuf { private final char[] chars; private final byte[] bytes; TempBuf(int bufSize) { this.chars = new char[bufSize]; this.bytes = new byte[bufSize]; } public char[] charBuf(int size) { char[] chars = this.chars; if (size <= chars.length) { return chars; } return new char[size]; } public byte[] byteBuf(int size) { byte[] bytes = this.bytes; if (size <= bytes.length) { return bytes; } return new byte[size]; } } }
6,717
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.InmemoryConfiguration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.convert.ConverterUtil; import org.apache.dubbo.common.url.component.PathURLAddress; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.url.component.URLAddress; import org.apache.dubbo.common.url.component.URLParam; import org.apache.dubbo.common.url.component.URLPlainParam; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.LRUCache; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import org.apache.dubbo.rpc.model.ServiceModel; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import java.util.function.Predicate; import static org.apache.dubbo.common.BaseServiceMetadata.COLON_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.ADDRESS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PASSWORD_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.USERNAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.utils.StringUtils.isBlank; /** * URL - Uniform Resource Locator (Immutable, ThreadSafe) * <p> * url example: * <ul> * <li>http://www.facebook.com/friends?param1=value1&amp;param2=value2 * <li>http://username:password@10.20.130.230:8080/list?version=1.0.0 * <li>ftp://username:password@192.168.1.7:21/1/read.txt * <li>registry://192.168.1.7:9090/org.apache.dubbo.service1?param1=value1&amp;param2=value2 * </ul> * <p> * Some strange example below: * <ul> * <li>192.168.1.3:20880<br> * for this case, url protocol = null, url host = 192.168.1.3, port = 20880, url path = null * <li>file:///home/user1/router.js?type=script<br> * for this case, url protocol = file, url host = null, url path = home/user1/router.js * <li>file://home/user1/router.js?type=script<br> * for this case, url protocol = file, url host = home, url path = user1/router.js * <li>file:///D:/1/router.js?type=script<br> * for this case, url protocol = file, url host = null, url path = D:/1/router.js * <li>file:/D:/1/router.js?type=script<br> * same as above file:///D:/1/router.js?type=script * <li>/home/user1/router.js?type=script <br> * for this case, url protocol = null, url host = null, url path = home/user1/router.js * <li>home/user1/router.js?type=script <br> * for this case, url protocol = null, url host = home, url path = user1/router.js * </ul> * * @see java.net.URL * @see java.net.URI */ public /*final**/ class URL implements Serializable { private static final long serialVersionUID = -1985165475234910535L; private static final Map<String, URL> cachedURLs = new LRUCache<>(); private final URLAddress urlAddress; private final URLParam urlParam; // ==== cache ==== private transient String serviceKey; private transient String protocolServiceKey; protected volatile Map<String, Object> attributes; protected URL() { this.urlAddress = null; this.urlParam = URLParam.parse(new HashMap<>()); this.attributes = null; } public URL(URLAddress urlAddress, URLParam urlParam) { this(urlAddress, urlParam, null); } public URL(URLAddress urlAddress, URLParam urlParam, Map<String, Object> attributes) { this.urlAddress = urlAddress; this.urlParam = null == urlParam ? URLParam.parse(new HashMap<>()) : urlParam; if (attributes != null && !attributes.isEmpty()) { this.attributes = attributes; } else { this.attributes = null; } } public URL(String protocol, String host, int port) { this(protocol, null, null, host, port, null, (Map<String, String>) null); } public URL( String protocol, String host, int port, String[] pairs) { // varargs ... conflict with the following path argument, use array instead. this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } public URL(String protocol, String host, int port, Map<String, String> parameters) { this(protocol, null, null, host, port, null, parameters); } public URL(String protocol, String host, int port, String path) { this(protocol, null, null, host, port, path, (Map<String, String>) null); } public URL(String protocol, String host, int port, String path, String... pairs) { this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs)); } public URL(String protocol, String host, int port, String path, Map<String, String> parameters) { this(protocol, null, null, host, port, path, parameters); } public URL(String protocol, String username, String password, String host, int port, String path) { this(protocol, username, password, host, port, path, (Map<String, String>) null); } public URL(String protocol, String username, String password, String host, int port, String path, String... pairs) { this(protocol, username, password, host, port, path, CollectionUtils.toStringMap(pairs)); } public URL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) { if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) { throw new IllegalArgumentException("Invalid url, password without username!"); } this.urlAddress = new PathURLAddress(protocol, username, password, path, host, port); this.urlParam = URLParam.parse(parameters); this.attributes = null; } protected URL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters, boolean modifiable) { if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) { throw new IllegalArgumentException("Invalid url, password without username!"); } this.urlAddress = new PathURLAddress(protocol, username, password, path, host, port); this.urlParam = URLParam.parse(parameters); this.attributes = null; } public static URL cacheableValueOf(String url) { URL cachedURL = cachedURLs.get(url); if (cachedURL != null) { return cachedURL; } cachedURL = valueOf(url, false); cachedURLs.put(url, cachedURL); return cachedURL; } /** * parse decoded url string, formatted dubbo://host:port/path?param=value, into strutted URL. * * @param url, decoded url string * @return */ public static URL valueOf(String url) { return valueOf(url, false); } public static URL valueOf(String url, ScopeModel scopeModel) { return valueOf(url).setScopeModel(scopeModel); } /** * parse normal or encoded url string into strutted URL: * - dubbo://host:port/path?param=value * - URL.encode("dubbo://host:port/path?param=value") * * @param url, url string * @param encoded, encoded or decoded * @return */ public static URL valueOf(String url, boolean encoded) { if (encoded) { return URLStrParser.parseEncodedStr(url); } return URLStrParser.parseDecodedStr(url); } public static URL valueOf(String url, String... reserveParams) { URL result = valueOf(url); if (reserveParams == null || reserveParams.length == 0) { return result; } Map<String, String> newMap = new HashMap<>(reserveParams.length); Map<String, String> oldMap = result.getParameters(); for (String reserveParam : reserveParams) { String tmp = oldMap.get(reserveParam); if (StringUtils.isNotEmpty(tmp)) { newMap.put(reserveParam, tmp); } } return result.clearParameters().addParameters(newMap); } public static URL valueOf(URL url, String[] reserveParams, String[] reserveParamPrefixes) { Map<String, String> newMap = new HashMap<>(); Map<String, String> oldMap = url.getParameters(); if (reserveParamPrefixes != null && reserveParamPrefixes.length != 0) { for (Map.Entry<String, String> entry : oldMap.entrySet()) { for (String reserveParamPrefix : reserveParamPrefixes) { if (entry.getKey().startsWith(reserveParamPrefix) && StringUtils.isNotEmpty(entry.getValue())) { newMap.put(entry.getKey(), entry.getValue()); } } } } if (reserveParams != null) { for (String reserveParam : reserveParams) { String tmp = oldMap.get(reserveParam); if (StringUtils.isNotEmpty(tmp)) { newMap.put(reserveParam, tmp); } } } return newMap.isEmpty() ? new ServiceConfigURL( url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), (Map<String, String>) null, url.getAttributes()) : new ServiceConfigURL( url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), newMap, url.getAttributes()); } public static String encode(String value) { if (StringUtils.isEmpty(value)) { return ""; } try { return URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } public static String decode(String value) { if (StringUtils.isEmpty(value)) { return ""; } try { return URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } static String appendDefaultPort(String address, int defaultPort) { if (address != null && address.length() > 0 && defaultPort > 0) { int i = address.indexOf(':'); if (i < 0) { return address + ":" + defaultPort; } else if (Integer.parseInt(address.substring(i + 1)) == 0) { return address.substring(0, i + 1) + defaultPort; } } return address; } public URLAddress getUrlAddress() { return urlAddress; } public URLParam getUrlParam() { return urlParam; } public String getProtocol() { return urlAddress == null ? null : urlAddress.getProtocol(); } public URL setProtocol(String protocol) { if (urlAddress == null) { return new ServiceConfigURL(protocol, getHost(), getPort(), getPath(), getParameters()); } else { URLAddress newURLAddress = urlAddress.setProtocol(protocol); return returnURL(newURLAddress); } } public String getUsername() { return urlAddress == null ? null : urlAddress.getUsername(); } public URL setUsername(String username) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), getHost(), getPort(), getPath(), getParameters()) .setUsername(username); } else { URLAddress newURLAddress = urlAddress.setUsername(username); return returnURL(newURLAddress); } } public String getPassword() { return urlAddress == null ? null : urlAddress.getPassword(); } public URL setPassword(String password) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), getHost(), getPort(), getPath(), getParameters()) .setPassword(password); } else { URLAddress newURLAddress = urlAddress.setPassword(password); return returnURL(newURLAddress); } } /** * refer to https://datatracker.ietf.org/doc/html/rfc3986 * * @return authority */ public String getAuthority() { StringBuilder ret = new StringBuilder(); ret.append(getUserInformation()); if (StringUtils.isNotEmpty(getHost())) { if (StringUtils.isNotEmpty(getUsername()) || StringUtils.isNotEmpty(getPassword())) { ret.append('@'); } ret.append(getHost()); if (getPort() != 0) { ret.append(':'); ret.append(getPort()); } } return ret.length() == 0 ? null : ret.toString(); } /** * refer to https://datatracker.ietf.org/doc/html/rfc3986 * * @return user information */ public String getUserInformation() { StringBuilder ret = new StringBuilder(); if (StringUtils.isEmpty(getUsername()) && StringUtils.isEmpty(getPassword())) { return ret.toString(); } if (StringUtils.isNotEmpty(getUsername())) { ret.append(getUsername()); } ret.append(':'); if (StringUtils.isNotEmpty(getPassword())) { ret.append(getPassword()); } return ret.length() == 0 ? null : ret.toString(); } public String getHost() { return urlAddress == null ? null : urlAddress.getHost(); } public URL setHost(String host) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), host, getPort(), getPath(), getParameters()); } else { URLAddress newURLAddress = urlAddress.setHost(host); return returnURL(newURLAddress); } } public int getPort() { return urlAddress == null ? 0 : urlAddress.getPort(); } public URL setPort(int port) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), getHost(), port, getPath(), getParameters()); } else { URLAddress newURLAddress = urlAddress.setPort(port); return returnURL(newURLAddress); } } public int getPort(int defaultPort) { int port = getPort(); return port <= 0 ? defaultPort : port; } public String getAddress() { return urlAddress == null ? null : urlAddress.getAddress(); } public URL setAddress(String address) { int i = address.lastIndexOf(':'); String host; int port = this.getPort(); if (i >= 0) { host = address.substring(0, i); port = Integer.parseInt(address.substring(i + 1)); } else { host = address; } if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), host, port, getPath(), getParameters()); } else { URLAddress newURLAddress = urlAddress.setAddress(host, port); return returnURL(newURLAddress); } } public String getIp() { return urlAddress == null ? null : urlAddress.getIp(); } public String getBackupAddress() { return getBackupAddress(0); } public String getBackupAddress(int defaultPort) { StringBuilder address = new StringBuilder(appendDefaultPort(getAddress(), defaultPort)); String[] backups = getParameter(RemotingConstants.BACKUP_KEY, new String[0]); if (ArrayUtils.isNotEmpty(backups)) { for (String backup : backups) { address.append(','); address.append(appendDefaultPort(backup, defaultPort)); } } return address.toString(); } public List<URL> getBackupUrls() { List<URL> urls = new ArrayList<>(); urls.add(this); String[] backups = getParameter(RemotingConstants.BACKUP_KEY, new String[0]); if (backups != null && backups.length > 0) { for (String backup : backups) { urls.add(this.setAddress(backup)); } } return urls; } public String getPath() { return urlAddress == null ? null : urlAddress.getPath(); } public URL setPath(String path) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), getHost(), getPort(), path, getParameters()); } else { URLAddress newURLAddress = urlAddress.setPath(path); return returnURL(newURLAddress); } } public String getAbsolutePath() { String path = getPath(); if (path != null && !path.startsWith("/")) { return "/" + path; } return path; } public Map<String, String> getOriginalParameters() { return this.getParameters(); } public Map<String, String> getParameters() { return urlParam.getParameters(); } public Map<String, String> getAllParameters() { return this.getParameters(); } /** * Get the parameters to be selected(filtered) * * @param nameToSelect the {@link Predicate} to select the parameter name * @return non-null {@link Map} * @since 2.7.8 */ public Map<String, String> getParameters(Predicate<String> nameToSelect) { Map<String, String> selectedParameters = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : getParameters().entrySet()) { String name = entry.getKey(); if (nameToSelect.test(name)) { selectedParameters.put(name, entry.getValue()); } } return Collections.unmodifiableMap(selectedParameters); } public String getParameterAndDecoded(String key) { return getParameterAndDecoded(key, null); } public String getParameterAndDecoded(String key, String defaultValue) { return decode(getParameter(key, defaultValue)); } public String getOriginalParameter(String key) { return getParameter(key); } public String getParameter(String key) { return urlParam.getParameter(key); } public String getParameter(String key, String defaultValue) { String value = getParameter(key); return StringUtils.isEmpty(value) ? defaultValue : value; } public String[] getParameter(String key, String[] defaultValue) { String value = getParameter(key); return StringUtils.isEmpty(value) ? defaultValue : COMMA_SPLIT_PATTERN.split(value); } public List<String> getParameter(String key, List<String> defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } String[] strArray = COMMA_SPLIT_PATTERN.split(value); return Arrays.asList(strArray); } /** * Get parameter * * @param key the key of parameter * @param valueType the type of parameter value * @param <T> the type of parameter value * @return get the parameter if present, or <code>null</code> * @since 2.7.8 */ public <T> T getParameter(String key, Class<T> valueType) { return getParameter(key, valueType, null); } /** * Get parameter * * @param key the key of parameter * @param valueType the type of parameter value * @param defaultValue the default value if parameter is absent * @param <T> the type of parameter value * @return get the parameter if present, or <code>defaultValue</code> will be used. * @since 2.7.8 */ public <T> T getParameter(String key, Class<T> valueType, T defaultValue) { String value = getParameter(key); T result = null; if (!isBlank(value)) { result = getOrDefaultFrameworkModel() .getBeanFactory() .getBean(ConverterUtil.class) .convertIfPossible(value, valueType); } if (result == null) { result = defaultValue; } return result; } public URL setScopeModel(ScopeModel scopeModel) { return putAttribute(CommonConstants.SCOPE_MODEL, scopeModel); } public ScopeModel getScopeModel() { return (ScopeModel) getAttribute(CommonConstants.SCOPE_MODEL); } public FrameworkModel getOrDefaultFrameworkModel() { return ScopeModelUtil.getFrameworkModel(getScopeModel()); } public ApplicationModel getOrDefaultApplicationModel() { return ScopeModelUtil.getApplicationModel(getScopeModel()); } public ApplicationModel getApplicationModel() { return ScopeModelUtil.getOrNullApplicationModel(getScopeModel()); } public ModuleModel getOrDefaultModuleModel() { return ScopeModelUtil.getModuleModel(getScopeModel()); } public URL setServiceModel(ServiceModel serviceModel) { return putAttribute(CommonConstants.SERVICE_MODEL, serviceModel); } public ServiceModel getServiceModel() { return (ServiceModel) getAttribute(CommonConstants.SERVICE_MODEL); } public URL getUrlParameter(String key) { String value = getParameterAndDecoded(key); if (StringUtils.isEmpty(value)) { return null; } return URL.valueOf(value); } public double getParameter(String key, double defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Double.parseDouble(value); } public float getParameter(String key, float defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Float.parseFloat(value); } public long getParameter(String key, long defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Long.parseLong(value); } public int getParameter(String key, int defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Integer.parseInt(value); } public short getParameter(String key, short defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Short.parseShort(value); } public byte getParameter(String key, byte defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Byte.parseByte(value); } public float getPositiveParameter(String key, float defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } float value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public double getPositiveParameter(String key, double defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } double value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public long getPositiveParameter(String key, long defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } long value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public int getPositiveParameter(String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } int value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public short getPositiveParameter(String key, short defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } short value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public byte getPositiveParameter(String key, byte defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } byte value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public char getParameter(String key, char defaultValue) { String value = getParameter(key); return StringUtils.isEmpty(value) ? defaultValue : value.charAt(0); } public boolean getParameter(String key, boolean defaultValue) { String value = getParameter(key); return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value); } public boolean hasParameter(String key) { String value = getParameter(key); return value != null && value.length() > 0; } public String getMethodParameterAndDecoded(String method, String key) { return URL.decode(getMethodParameter(method, key)); } public String getMethodParameterAndDecoded(String method, String key, String defaultValue) { return URL.decode(getMethodParameter(method, key, defaultValue)); } public String getMethodParameter(String method, String key) { return urlParam.getMethodParameter(method, key); } public String getMethodParameterStrict(String method, String key) { return urlParam.getMethodParameterStrict(method, key); } public String getMethodParameter(String method, String key, String defaultValue) { String value = getMethodParameter(method, key); return StringUtils.isEmpty(value) ? defaultValue : value; } public double getMethodParameter(String method, String key, double defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Double.parseDouble(value); } public float getMethodParameter(String method, String key, float defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Float.parseFloat(value); } public long getMethodParameter(String method, String key, long defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Long.parseLong(value); } public int getMethodParameter(String method, String key, int defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Integer.parseInt(value); } public short getMethodParameter(String method, String key, short defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Short.parseShort(value); } public byte getMethodParameter(String method, String key, byte defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Byte.parseByte(value); } public double getMethodPositiveParameter(String method, String key, double defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } double value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public float getMethodPositiveParameter(String method, String key, float defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } float value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public long getMethodPositiveParameter(String method, String key, long defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } long value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public int getMethodPositiveParameter(String method, String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } int value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public short getMethodPositiveParameter(String method, String key, short defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } short value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public byte getMethodPositiveParameter(String method, String key, byte defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } byte value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public char getMethodParameter(String method, String key, char defaultValue) { String value = getMethodParameter(method, key); return StringUtils.isEmpty(value) ? defaultValue : value.charAt(0); } public boolean getMethodParameter(String method, String key, boolean defaultValue) { String value = getMethodParameter(method, key); return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value); } public boolean hasMethodParameter(String method, String key) { if (method == null) { String suffix = "." + key; for (String fullKey : getParameters().keySet()) { if (fullKey.endsWith(suffix)) { return true; } } return false; } if (key == null) { String prefix = method + "."; for (String fullKey : getParameters().keySet()) { if (fullKey.startsWith(prefix)) { return true; } } return false; } String value = getMethodParameterStrict(method, key); return StringUtils.isNotEmpty(value); } public String getAnyMethodParameter(String key) { return urlParam.getAnyMethodParameter(key); } public boolean hasMethodParameter(String method) { return urlParam.hasMethodParameter(method); } public boolean isLocalHost() { return NetUtils.isLocalHost(getHost()) || getParameter(LOCALHOST_KEY, false); } public boolean isAnyHost() { return ANYHOST_VALUE.equals(getHost()) || getParameter(ANYHOST_KEY, false); } public URL addParameterAndEncoded(String key, String value) { if (StringUtils.isEmpty(value)) { return this; } return addParameter(key, encode(value)); } public URL addParameter(String key, boolean value) { return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, char value) { return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, byte value) { return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, short value) { return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, int value) { return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, long value) { return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, float value) { return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, double value) { return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, Enum<?> value) { if (value == null) { return this; } return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, Number value) { if (value == null) { return this; } return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, CharSequence value) { if (value == null || value.length() == 0) { return this; } return addParameter(key, String.valueOf(value)); } public URL addParameter(String key, String value) { URLParam newParam = urlParam.addParameter(key, value); return returnURL(newParam); } public URL addParameterIfAbsent(String key, String value) { URLParam newParam = urlParam.addParameterIfAbsent(key, value); return returnURL(newParam); } /** * Add parameters to a new url. * * @param parameters parameters in key-value pairs * @return A new URL */ public URL addParameters(Map<String, String> parameters) { URLParam newParam = urlParam.addParameters(parameters); return returnURL(newParam); } public URL addParametersIfAbsent(Map<String, String> parameters) { URLParam newURLParam = urlParam.addParametersIfAbsent(parameters); return returnURL(newURLParam); } public URL addParameters(String... pairs) { if (pairs == null || pairs.length == 0) { return this; } if (pairs.length % 2 != 0) { throw new IllegalArgumentException("Map pairs can not be odd number."); } Map<String, String> map = new HashMap<>(); int len = pairs.length / 2; for (int i = 0; i < len; i++) { map.put(pairs[2 * i], pairs[2 * i + 1]); } return addParameters(map); } public URL addParameterString(String query) { if (StringUtils.isEmpty(query)) { return this; } return addParameters(StringUtils.parseQueryString(query)); } public URL removeParameter(String key) { if (StringUtils.isEmpty(key)) { return this; } return removeParameters(key); } public URL removeParameters(Collection<String> keys) { if (CollectionUtils.isEmpty(keys)) { return this; } return removeParameters(keys.toArray(new String[0])); } public URL removeParameters(String... keys) { URLParam newURLParam = urlParam.removeParameters(keys); return returnURL(newURLParam); } public URL clearParameters() { URLParam newURLParam = urlParam.clearParameters(); return returnURL(newURLParam); } public String getRawParameter(String key) { if (PROTOCOL_KEY.equals(key)) { return urlAddress.getProtocol(); } if (USERNAME_KEY.equals(key)) { return urlAddress.getUsername(); } if (PASSWORD_KEY.equals(key)) { return urlAddress.getPassword(); } if (HOST_KEY.equals(key)) { return urlAddress.getHost(); } if (PORT_KEY.equals(key)) { return String.valueOf(urlAddress.getPort()); } if (PATH_KEY.equals(key)) { return urlAddress.getPath(); } return urlParam.getParameter(key); } public Map<String, String> toOriginalMap() { Map<String, String> map = new HashMap<>(getOriginalParameters()); return addSpecialKeys(map); } public Map<String, String> toMap() { Map<String, String> map = new HashMap<>(getParameters()); return addSpecialKeys(map); } private Map<String, String> addSpecialKeys(Map<String, String> map) { if (getProtocol() != null) { map.put(PROTOCOL_KEY, getProtocol()); } if (getUsername() != null) { map.put(USERNAME_KEY, getUsername()); } if (getPassword() != null) { map.put(PASSWORD_KEY, getPassword()); } if (getHost() != null) { map.put(HOST_KEY, getHost()); } if (getPort() > 0) { map.put(PORT_KEY, String.valueOf(getPort())); } if (getPath() != null) { map.put(PATH_KEY, getPath()); } if (getAddress() != null) { map.put(ADDRESS_KEY, getAddress()); } return map; } @Override public String toString() { return buildString(false, true); // no show username and password } public String toString(String... parameters) { return buildString(false, true, parameters); // no show username and password } public String toIdentityString() { return buildString(true, false); // only return identity message, see the method "equals" and "hashCode" } public String toIdentityString(String... parameters) { return buildString( true, false, parameters); // only return identity message, see the method "equals" and "hashCode" } public String toFullString() { return buildString(true, true); } public String toFullString(String... parameters) { return buildString(true, true, parameters); } public String toParameterString() { return toParameterString(new String[0]); } public String toParameterString(String... parameters) { StringBuilder buf = new StringBuilder(); buildParameters(buf, false, parameters); return buf.toString(); } protected void buildParameters(StringBuilder buf, boolean concat, String[] parameters) { if (CollectionUtils.isNotEmptyMap(getParameters())) { List<String> includes = (ArrayUtils.isEmpty(parameters) ? null : Arrays.asList(parameters)); boolean first = true; for (Map.Entry<String, String> entry : new TreeMap<>(getParameters()).entrySet()) { if (StringUtils.isNotEmpty(entry.getKey()) && (includes == null || includes.contains(entry.getKey()))) { if (first) { if (concat) { buf.append('?'); } first = false; } else { buf.append('&'); } buf.append(entry.getKey()); buf.append('='); buf.append(entry.getValue() == null ? "" : entry.getValue().trim()); } } } } private String buildString(boolean appendUser, boolean appendParameter, String... parameters) { return buildString(appendUser, appendParameter, false, false, parameters); } private String buildString( boolean appendUser, boolean appendParameter, boolean useIP, boolean useService, String... parameters) { StringBuilder buf = new StringBuilder(); if (StringUtils.isNotEmpty(getProtocol())) { buf.append(getProtocol()); buf.append("://"); } if (appendUser && StringUtils.isNotEmpty(getUsername())) { buf.append(getUsername()); if (StringUtils.isNotEmpty(getPassword())) { buf.append(':'); buf.append(getPassword()); } buf.append('@'); } String host; if (useIP) { host = urlAddress.getIp(); } else { host = getHost(); } if (StringUtils.isNotEmpty(host)) { buf.append(host); if (getPort() > 0) { buf.append(':'); buf.append(getPort()); } } String path; if (useService) { path = getServiceKey(); } else { path = getPath(); } if (StringUtils.isNotEmpty(path)) { buf.append('/'); buf.append(path); } if (appendParameter) { buildParameters(buf, true, parameters); } return buf.toString(); } public java.net.URL toJavaURL() { try { return new java.net.URL(toString()); } catch (MalformedURLException e) { throw new IllegalStateException(e.getMessage(), e); } } public InetSocketAddress toInetSocketAddress() { return new InetSocketAddress(getHost(), getPort()); } /** * The format is "{interface}:[version]:[group]" * * @return */ public String getColonSeparatedKey() { StringBuilder serviceNameBuilder = new StringBuilder(); serviceNameBuilder.append(this.getServiceInterface()); append(serviceNameBuilder, VERSION_KEY, false); append(serviceNameBuilder, GROUP_KEY, false); return serviceNameBuilder.toString(); } private void append(StringBuilder target, String parameterName, boolean first) { String parameterValue = this.getParameter(parameterName); if (!isBlank(parameterValue)) { if (!first) { target.append(':'); } target.append(parameterValue); } else { target.append(':'); } } /** * The format of return value is '{group}/{interfaceName}:{version}' * * @return */ public String getServiceKey() { if (serviceKey != null) { return serviceKey; } String inf = getServiceInterface(); if (inf == null) { return null; } serviceKey = buildKey(inf, getGroup(), getVersion()); return serviceKey; } /** * Format : interface:version * * @return */ public String getDisplayServiceKey() { if (StringUtils.isEmpty(getVersion())) { return getServiceInterface(); } return getServiceInterface() + COLON_SEPARATOR + getVersion(); } /** * The format of return value is '{group}/{path/interfaceName}:{version}' * * @return */ public String getPathKey() { String inf = StringUtils.isNotEmpty(getPath()) ? getPath() : getServiceInterface(); if (inf == null) { return null; } return buildKey(inf, getGroup(), getVersion()); } public static String buildKey(String path, String group, String version) { return BaseServiceMetadata.buildServiceKey(path, group, version); } public String getProtocolServiceKey() { if (protocolServiceKey != null) { return protocolServiceKey; } this.protocolServiceKey = getServiceKey(); /* Special treatment for urls begins with 'consumer://', that is, a consumer subscription url instance with no protocol specified. If protocol is specified on the consumer side, then this method will return as normal. */ if (!CONSUMER.equals(getProtocol())) { this.protocolServiceKey += (GROUP_CHAR_SEPARATOR + getProtocol()); } return protocolServiceKey; } public String toServiceStringWithoutResolving() { return buildString(true, false, false, true); } public String toServiceString() { return buildString(true, false, true, true); } @Deprecated public String getServiceName() { return getServiceInterface(); } public String getServiceInterface() { return getParameter(INTERFACE_KEY, getPath()); } public URL setServiceInterface(String service) { return addParameter(INTERFACE_KEY, service); } /** * @see #getParameter(String, int) * @deprecated Replace to <code>getParameter(String, int)</code> */ @Deprecated public int getIntParameter(String key) { return getParameter(key, 0); } /** * @see #getParameter(String, int) * @deprecated Replace to <code>getParameter(String, int)</code> */ @Deprecated public int getIntParameter(String key, int defaultValue) { return getParameter(key, defaultValue); } /** * @see #getPositiveParameter(String, int) * @deprecated Replace to <code>getPositiveParameter(String, int)</code> */ @Deprecated public int getPositiveIntParameter(String key, int defaultValue) { return getPositiveParameter(key, defaultValue); } /** * @see #getParameter(String, boolean) * @deprecated Replace to <code>getParameter(String, boolean)</code> */ @Deprecated public boolean getBooleanParameter(String key) { return getParameter(key, false); } /** * @see #getParameter(String, boolean) * @deprecated Replace to <code>getParameter(String, boolean)</code> */ @Deprecated public boolean getBooleanParameter(String key, boolean defaultValue) { return getParameter(key, defaultValue); } /** * @see #getMethodParameter(String, String, int) * @deprecated Replace to <code>getMethodParameter(String, String, int)</code> */ @Deprecated public int getMethodIntParameter(String method, String key) { return getMethodParameter(method, key, 0); } /** * @see #getMethodParameter(String, String, int) * @deprecated Replace to <code>getMethodParameter(String, String, int)</code> */ @Deprecated public int getMethodIntParameter(String method, String key, int defaultValue) { return getMethodParameter(method, key, defaultValue); } /** * @see #getMethodPositiveParameter(String, String, int) * @deprecated Replace to <code>getMethodPositiveParameter(String, String, int)</code> */ @Deprecated public int getMethodPositiveIntParameter(String method, String key, int defaultValue) { return getMethodPositiveParameter(method, key, defaultValue); } /** * @see #getMethodParameter(String, String, boolean) * @deprecated Replace to <code>getMethodParameter(String, String, boolean)</code> */ @Deprecated public boolean getMethodBooleanParameter(String method, String key) { return getMethodParameter(method, key, false); } /** * @see #getMethodParameter(String, String, boolean) * @deprecated Replace to <code>getMethodParameter(String, String, boolean)</code> */ @Deprecated public boolean getMethodBooleanParameter(String method, String key, boolean defaultValue) { return getMethodParameter(method, key, defaultValue); } public Configuration toConfiguration() { InmemoryConfiguration configuration = new InmemoryConfiguration(); configuration.addProperties(getParameters()); return configuration; } private volatile int hashCodeCache = -1; @Override public int hashCode() { if (hashCodeCache == -1) { hashCodeCache = Objects.hash(urlAddress, urlParam); } return hashCodeCache; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof URL)) { return false; } URL other = (URL) obj; return Objects.equals(this.getUrlAddress(), other.getUrlAddress()) && Objects.equals(this.getUrlParam(), other.getUrlParam()); } public static void putMethodParameter( String method, String key, String value, Map<String, Map<String, String>> methodParameters) { Map<String, String> subParameter = methodParameters.computeIfAbsent(method, k -> new HashMap<>()); subParameter.put(key, value); } protected <T extends URL> T newURL(URLAddress urlAddress, URLParam urlParam) { return (T) new ServiceConfigURL(urlAddress, urlParam, attributes); } /* methods introduced for CompositeURL, CompositeURL must override to make the implementations meaningful */ public String getApplication(String defaultValue) { String value = getApplication(); return StringUtils.isEmpty(value) ? defaultValue : value; } public String getApplication() { return getParameter(APPLICATION_KEY); } public String getRemoteApplication() { return getParameter(REMOTE_APPLICATION_KEY); } public String getGroup() { return getParameter(GROUP_KEY); } public String getGroup(String defaultValue) { String value = getGroup(); return StringUtils.isEmpty(value) ? defaultValue : value; } public String getVersion() { return getParameter(VERSION_KEY); } public String getVersion(String defaultValue) { String value = getVersion(); return StringUtils.isEmpty(value) ? defaultValue : value; } public String getConcatenatedParameter(String key) { return getParameter(key); } public String getCategory(String defaultValue) { String value = getCategory(); if (StringUtils.isEmpty(value)) { value = defaultValue; } return value; } public String[] getCategory(String[] defaultValue) { String value = getCategory(); return StringUtils.isEmpty(value) ? defaultValue : COMMA_SPLIT_PATTERN.split(value); } public String getCategory() { return getParameter(CATEGORY_KEY); } public String getSide(String defaultValue) { String value = getSide(); return StringUtils.isEmpty(value) ? defaultValue : value; } public String getSide() { return getParameter(SIDE_KEY); } /* Service Config URL, START*/ public Map<String, Object> getAttributes() { return attributes == null ? Collections.emptyMap() : attributes; } public URL addAttributes(Map<String, Object> attributes) { if (attributes != null) { attributes.putAll(attributes); } return this; } public Object getAttribute(String key) { return attributes == null ? null : attributes.get(key); } public Object getAttribute(String key, Object defaultValue) { Object val = attributes == null ? null : attributes.get(key); return val != null ? val : defaultValue; } public URL putAttribute(String key, Object obj) { if (attributes == null) { this.attributes = new HashMap<>(); } attributes.put(key, obj); return this; } public URL removeAttribute(String key) { if (attributes != null) { attributes.remove(key); } return this; } public boolean hasAttribute(String key) { return attributes != null && attributes.containsKey(key); } /* Service Config URL, END*/ private URL returnURL(URLAddress newURLAddress) { if (urlAddress == newURLAddress) { return this; } return newURL(newURLAddress, urlParam); } private URL returnURL(URLParam newURLParam) { if (urlParam == newURLParam) { return this; } return newURL(urlAddress, newURLParam); } /* add service scope operations, see InstanceAddressURL */ public Map<String, String> getOriginalServiceParameters(String service) { return getServiceParameters(service); } public Map<String, String> getServiceParameters(String service) { return getParameters(); } public String getOriginalServiceParameter(String service, String key) { return this.getServiceParameter(service, key); } public String getServiceParameter(String service, String key) { return getParameter(key); } public String getServiceParameter(String service, String key, String defaultValue) { String value = getServiceParameter(service, key); return StringUtils.isEmpty(value) ? defaultValue : value; } public int getServiceParameter(String service, String key, int defaultValue) { return getParameter(key, defaultValue); } public double getServiceParameter(String service, String key, double defaultValue) { String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Double.parseDouble(value); } public float getServiceParameter(String service, String key, float defaultValue) { String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Float.parseFloat(value); } public long getServiceParameter(String service, String key, long defaultValue) { String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Long.parseLong(value); } public short getServiceParameter(String service, String key, short defaultValue) { String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Short.parseShort(value); } public byte getServiceParameter(String service, String key, byte defaultValue) { String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Byte.parseByte(value); } public char getServiceParameter(String service, String key, char defaultValue) { String value = getServiceParameter(service, key); return StringUtils.isEmpty(value) ? defaultValue : value.charAt(0); } public boolean getServiceParameter(String service, String key, boolean defaultValue) { String value = getServiceParameter(service, key); return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value); } public boolean hasServiceParameter(String service, String key) { String value = getServiceParameter(service, key); return value != null && value.length() > 0; } public float getPositiveServiceParameter(String service, String key, float defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } float value = getServiceParameter(service, key, defaultValue); return value <= 0 ? defaultValue : value; } public double getPositiveServiceParameter(String service, String key, double defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } double value = getServiceParameter(service, key, defaultValue); return value <= 0 ? defaultValue : value; } public long getPositiveServiceParameter(String service, String key, long defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } long value = getServiceParameter(service, key, defaultValue); return value <= 0 ? defaultValue : value; } public int getPositiveServiceParameter(String service, String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } int value = getServiceParameter(service, key, defaultValue); return value <= 0 ? defaultValue : value; } public short getPositiveServiceParameter(String service, String key, short defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } short value = getServiceParameter(service, key, defaultValue); return value <= 0 ? defaultValue : value; } public byte getPositiveServiceParameter(String service, String key, byte defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } byte value = getServiceParameter(service, key, defaultValue); return value <= 0 ? defaultValue : value; } public String getServiceMethodParameterAndDecoded(String service, String method, String key) { return URL.decode(getServiceMethodParameter(service, method, key)); } public String getServiceMethodParameterAndDecoded(String service, String method, String key, String defaultValue) { return URL.decode(getServiceMethodParameter(service, method, key, defaultValue)); } public String getServiceMethodParameterStrict(String service, String method, String key) { return getMethodParameterStrict(method, key); } public String getServiceMethodParameter(String service, String method, String key) { return getMethodParameter(method, key); } public String getServiceMethodParameter(String service, String method, String key, String defaultValue) { String value = getServiceMethodParameter(service, method, key); return StringUtils.isEmpty(value) ? defaultValue : value; } public double getServiceMethodParameter(String service, String method, String key, double defaultValue) { String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Double.parseDouble(value); } public float getServiceMethodParameter(String service, String method, String key, float defaultValue) { String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Float.parseFloat(value); } public long getServiceMethodParameter(String service, String method, String key, long defaultValue) { String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Long.parseLong(value); } public int getServiceMethodParameter(String service, String method, String key, int defaultValue) { String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Integer.parseInt(value); } public short getServiceMethodParameter(String service, String method, String key, short defaultValue) { String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Short.parseShort(value); } public byte getServiceMethodParameter(String service, String method, String key, byte defaultValue) { String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Byte.parseByte(value); } public boolean hasServiceMethodParameter(String service, String method, String key) { return hasMethodParameter(method, key); } public boolean hasServiceMethodParameter(String service, String method) { return hasMethodParameter(method); } public URL toSerializableURL() { return returnURL(URLPlainParam.toURLPlainParam(urlParam)); } }
6,718
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/ProtocolServiceKey.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import java.util.Objects; public class ProtocolServiceKey extends ServiceKey { private final String protocol; public ProtocolServiceKey(String interfaceName, String version, String group, String protocol) { super(interfaceName, version, group); this.protocol = protocol; } public String getProtocol() { return protocol; } public String getServiceKeyString() { return super.toString(); } public boolean isSameWith(ProtocolServiceKey protocolServiceKey) { // interface version group should be the same if (!super.equals(protocolServiceKey)) { return false; } // origin protocol is *, can not match any protocol if (CommonConstants.ANY_VALUE.equals(protocol)) { return false; } // origin protocol is null, can match any protocol if (StringUtils.isEmpty(protocol) || StringUtils.isEmpty(protocolServiceKey.getProtocol())) { return true; } // origin protocol is not *, match itself return Objects.equals(protocol, protocolServiceKey.getProtocol()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ProtocolServiceKey that = (ProtocolServiceKey) o; return Objects.equals(protocol, that.protocol); } @Override public int hashCode() { return Objects.hash(super.hashCode(), protocol); } @Override public String toString() { return super.toString() + CommonConstants.GROUP_CHAR_SEPARATOR + protocol; } public static class Matcher { public static boolean isMatch(ProtocolServiceKey rule, ProtocolServiceKey target) { // 1. 2. 3. match interface / version / group if (!ServiceKey.Matcher.isMatch(rule, target)) { return false; } // 4.match protocol // 4.1. if rule group is *, match all if (!CommonConstants.ANY_VALUE.equals(rule.getProtocol())) { // 4.2. if rule protocol is null, match all if (StringUtils.isNotEmpty(rule.getProtocol())) { // 4.3. if rule protocol contains ',', split and match each if (rule.getProtocol().contains(CommonConstants.COMMA_SEPARATOR)) { String[] protocols = rule.getProtocol().split("\\" + CommonConstants.COMMA_SEPARATOR, -1); boolean match = false; for (String protocol : protocols) { protocol = protocol.trim(); if (StringUtils.isEmpty(protocol) && StringUtils.isEmpty(target.getProtocol())) { match = true; break; } else if (protocol.equals(target.getProtocol())) { match = true; break; } } if (!match) { return false; } } // 4.3. if rule protocol is not contains ',', match directly else if (!Objects.equals(rule.getProtocol(), target.getProtocol())) { return false; } } } return true; } } }
6,719
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/CommonScopeModelInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.config.ConfigurationCache; import org.apache.dubbo.common.convert.ConverterUtil; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.DefaultSerializeClassChecker; import org.apache.dubbo.common.utils.SerializeSecurityConfigurator; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class CommonScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) { ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory(); beanFactory.registerBean(FrameworkExecutorRepository.class); beanFactory.registerBean(ConverterUtil.class); beanFactory.registerBean(SerializeSecurityManager.class); beanFactory.registerBean(DefaultSerializeClassChecker.class); beanFactory.registerBean(CertManager.class); } @Override public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); beanFactory.registerBean(ShutdownHookCallbacks.class); beanFactory.registerBean(FrameworkStatusReportService.class); beanFactory.registerBean(new ConfigurationCache()); } @Override public void initializeModuleModel(ModuleModel moduleModel) { ScopeBeanFactory beanFactory = moduleModel.getBeanFactory(); beanFactory.registerBean(new ConfigurationCache()); beanFactory.registerBean(SerializeSecurityConfigurator.class); } }
6,720
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/Experimental.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicating unstable API, may get removed or changed in future releases. */ @Retention(RetentionPolicy.CLASS) @Target({ ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE }) public @interface Experimental { String value(); }
6,721
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/Resetable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; /** * Resetable. */ public interface Resetable { /** * reset. * * @param url */ void reset(URL url); }
6,722
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static org.apache.dubbo.common.constants.CommonConstants.SCOPE_MODEL; public final class URLBuilder extends ServiceConfigURL { private String protocol; private String username; private String password; // by default, host to registry private String host; // by default, port to registry private int port; private String path; private final Map<String, String> parameters; private final Map<String, Object> attributes; private Map<String, Map<String, String>> methodParameters; public URLBuilder() { protocol = null; username = null; password = null; host = null; port = 0; path = null; parameters = new HashMap<>(); attributes = new HashMap<>(); methodParameters = new HashMap<>(); } public URLBuilder(String protocol, String host, int port) { this(protocol, null, null, host, port, null, null); } public URLBuilder(String protocol, String host, int port, String[] pairs) { this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } public URLBuilder(String protocol, String host, int port, Map<String, String> parameters) { this(protocol, null, null, host, port, null, parameters); } public URLBuilder(String protocol, String host, int port, String path) { this(protocol, null, null, host, port, path, null); } public URLBuilder(String protocol, String host, int port, String path, String... pairs) { this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs)); } public URLBuilder(String protocol, String host, int port, String path, Map<String, String> parameters) { this(protocol, null, null, host, port, path, parameters); } public URLBuilder( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) { this(protocol, username, password, host, port, path, parameters, null); } public URLBuilder( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters, Map<String, Object> attributes) { this.protocol = protocol; this.username = username; this.password = password; this.host = host; this.port = port; this.path = path; this.parameters = parameters != null ? parameters : new HashMap<>(); this.attributes = attributes != null ? attributes : new HashMap<>(); } public static URLBuilder from(URL url) { String protocol = url.getProtocol(); String username = url.getUsername(); String password = url.getPassword(); String host = url.getHost(); int port = url.getPort(); String path = url.getPath(); Map<String, String> parameters = new HashMap<>(url.getParameters()); Map<String, Object> attributes = new HashMap<>(url.getAttributes()); return new URLBuilder(protocol, username, password, host, port, path, parameters, attributes); } public ServiceConfigURL build() { if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) { throw new IllegalArgumentException("Invalid url, password without username!"); } port = Math.max(port, 0); // trim the leading "/" int firstNonSlash = 0; if (path != null) { while (firstNonSlash < path.length() && path.charAt(firstNonSlash) == '/') { firstNonSlash++; } if (firstNonSlash >= path.length()) { path = ""; } else if (firstNonSlash > 0) { path = path.substring(firstNonSlash); } } return new ServiceConfigURL(protocol, username, password, host, port, path, parameters, attributes); } @Override public URLBuilder putAttribute(String key, Object obj) { attributes.put(key, obj); return this; } @Override public URLBuilder removeAttribute(String key) { attributes.remove(key); return this; } @Override public URLBuilder setProtocol(String protocol) { this.protocol = protocol; return this; } @Override public URLBuilder setUsername(String username) { this.username = username; return this; } @Override public URLBuilder setPassword(String password) { this.password = password; return this; } @Override public URLBuilder setHost(String host) { this.host = host; return this; } @Override public URLBuilder setPort(int port) { this.port = port; return this; } @Override public URLBuilder setAddress(String address) { int i = address.lastIndexOf(':'); String host; int port = this.port; if (i >= 0) { host = address.substring(0, i); port = Integer.parseInt(address.substring(i + 1)); } else { host = address; } this.host = host; this.port = port; return this; } @Override public URLBuilder setPath(String path) { this.path = path; return this; } @Override public URLBuilder setScopeModel(ScopeModel scopeModel) { this.attributes.put(SCOPE_MODEL, scopeModel); return this; } @Override public URLBuilder addParameterAndEncoded(String key, String value) { if (StringUtils.isEmpty(value)) { return this; } return addParameter(key, URL.encode(value)); } @Override public URLBuilder addParameter(String key, boolean value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, char value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, byte value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, short value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, int value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, long value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, float value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, double value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, Enum<?> value) { if (value == null) { return this; } return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, Number value) { if (value == null) { return this; } return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, CharSequence value) { if (value == null || value.length() == 0) { return this; } return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, String value) { if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } parameters.put(key, value); return this; } public URLBuilder addMethodParameter(String method, String key, String value) { if (StringUtils.isEmpty(method) || StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } URL.putMethodParameter(method, key, value, methodParameters); return this; } @Override public URLBuilder addParameterIfAbsent(String key, String value) { if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } if (hasParameter(key)) { return this; } parameters.put(key, value); return this; } public URLBuilder addMethodParameterIfAbsent(String method, String key, String value) { if (StringUtils.isEmpty(method) || StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } if (hasMethodParameter(method, key)) { return this; } URL.putMethodParameter(method, key, value, methodParameters); return this; } @Override public URLBuilder addParameters(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } boolean hasAndEqual = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { String oldValue = this.parameters.get(entry.getKey()); String newValue = entry.getValue(); if (!Objects.equals(oldValue, newValue)) { hasAndEqual = false; break; } } // return immediately if there's no change if (hasAndEqual) { return this; } this.parameters.putAll(parameters); return this; } public URLBuilder addMethodParameters(Map<String, Map<String, String>> methodParameters) { if (CollectionUtils.isEmptyMap(methodParameters)) { return this; } this.methodParameters.putAll(methodParameters); return this; } @Override public URLBuilder addParametersIfAbsent(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } for (Map.Entry<String, String> entry : parameters.entrySet()) { this.parameters.putIfAbsent(entry.getKey(), entry.getValue()); } return this; } @Override public URLBuilder addParameters(String... pairs) { if (pairs == null || pairs.length == 0) { return this; } if (pairs.length % 2 != 0) { throw new IllegalArgumentException("Map pairs can not be odd number."); } Map<String, String> map = new HashMap<>(); int len = pairs.length / 2; for (int i = 0; i < len; i++) { map.put(pairs[2 * i], pairs[2 * i + 1]); } return addParameters(map); } @Override public URLBuilder addParameterString(String query) { if (StringUtils.isEmpty(query)) { return this; } return addParameters(StringUtils.parseQueryString(query)); } @Override public URLBuilder removeParameter(String key) { if (StringUtils.isEmpty(key)) { return this; } return removeParameters(key); } @Override public URLBuilder removeParameters(Collection<String> keys) { if (CollectionUtils.isEmpty(keys)) { return this; } return removeParameters(keys.toArray(new String[0])); } @Override public URLBuilder removeParameters(String... keys) { if (keys == null || keys.length == 0) { return this; } for (String key : keys) { parameters.remove(key); } return this; } @Override public URLBuilder clearParameters() { parameters.clear(); return this; } @Override public boolean hasParameter(String key) { String value = getParameter(key); return StringUtils.isNotEmpty(value); } @Override public boolean hasMethodParameter(String method, String key) { if (method == null) { String suffix = "." + key; for (String fullKey : parameters.keySet()) { if (fullKey.endsWith(suffix)) { return true; } } return false; } if (key == null) { String prefix = method + "."; for (String fullKey : parameters.keySet()) { if (fullKey.startsWith(prefix)) { return true; } } return false; } String value = getMethodParameter(method, key); return value != null && value.length() > 0; } @Override public String getParameter(String key) { return parameters.get(key); } @Override public String getMethodParameter(String method, String key) { Map<String, String> keyMap = methodParameters.get(method); String value = null; if (keyMap != null) { value = keyMap.get(key); } return value; } }
6,723
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * Parameters for backward compatibility for version prior to 2.0.5 * * @deprecated */ @Deprecated public class Parameters { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Parameters.class); private final Map<String, String> parameters; public Parameters(String... pairs) { this(toMap(pairs)); } public Parameters(Map<String, String> parameters) { this.parameters = Collections.unmodifiableMap(parameters != null ? new HashMap<>(parameters) : new HashMap<>(0)); } private static Map<String, String> toMap(String... pairs) { return CollectionUtils.toStringMap(pairs); } public static Parameters parseParameters(String query) { return new Parameters(StringUtils.parseQueryString(query)); } public Map<String, String> getParameters() { return parameters; } /** * @deprecated will be removed in 3.3.0 */ @Deprecated public <T> T getExtension(Class<T> type, String key) { String name = getParameter(key); return ExtensionLoader.getExtensionLoader(type).getExtension(name); } /** * @deprecated will be removed in 3.3.0 */ @Deprecated public <T> T getExtension(Class<T> type, String key, String defaultValue) { String name = getParameter(key, defaultValue); return ExtensionLoader.getExtensionLoader(type).getExtension(name); } /** * @deprecated will be removed in 3.3.0 */ @Deprecated public <T> T getMethodExtension(Class<T> type, String method, String key) { String name = getMethodParameter(method, key); return ExtensionLoader.getExtensionLoader(type).getExtension(name); } /** * @deprecated will be removed in 3.3.0 */ @Deprecated public <T> T getMethodExtension(Class<T> type, String method, String key, String defaultValue) { String name = getMethodParameter(method, key, defaultValue); return ExtensionLoader.getExtensionLoader(type).getExtension(name); } public String getDecodedParameter(String key) { return getDecodedParameter(key, null); } public String getDecodedParameter(String key, String defaultValue) { String value = getParameter(key, defaultValue); if (value != null && value.length() > 0) { try { value = URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } return value; } public String getParameter(String key) { String value = parameters.get(key); if (StringUtils.isEmpty(value)) { value = parameters.get(HIDE_KEY_PREFIX + key); } if (StringUtils.isEmpty(value)) { value = parameters.get(DEFAULT_KEY_PREFIX + key); } if (StringUtils.isEmpty(value)) { value = parameters.get(HIDE_KEY_PREFIX + DEFAULT_KEY_PREFIX + key); } return value; } public String getParameter(String key, String defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return value; } public int getIntParameter(String key) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return 0; } return Integer.parseInt(value); } public int getIntParameter(String key, int defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Integer.parseInt(value); } public int getPositiveIntParameter(String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); if (i > 0) { return i; } return defaultValue; } public boolean getBooleanParameter(String key) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return false; } return Boolean.parseBoolean(value); } public boolean getBooleanParameter(String key, boolean defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Boolean.parseBoolean(value); } public boolean hasParameter(String key) { String value = getParameter(key); return value != null && value.length() > 0; } public String getMethodParameter(String method, String key) { String value = parameters.get(method + "." + key); if (StringUtils.isEmpty(value)) { value = parameters.get(HIDE_KEY_PREFIX + method + "." + key); } if (StringUtils.isEmpty(value)) { return getParameter(key); } return value; } public String getMethodParameter(String method, String key, String defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return value; } public int getMethodIntParameter(String method, String key) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return 0; } return Integer.parseInt(value); } public int getMethodIntParameter(String method, String key, int defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Integer.parseInt(value); } public int getMethodPositiveIntParameter(String method, String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); if (i > 0) { return i; } return defaultValue; } public boolean getMethodBooleanParameter(String method, String key) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return false; } return Boolean.parseBoolean(value); } public boolean getMethodBooleanParameter(String method, String key, boolean defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Boolean.parseBoolean(value); } public boolean hasMethodParameter(String method, String key) { String value = getMethodParameter(method, key); return value != null && value.length() > 0; } @Override public boolean equals(Object o) { if (this == o) { return true; } return parameters.equals(o); } @Override public int hashCode() { return parameters.hashCode(); } @Override public String toString() { return StringUtils.toQueryString(getParameters()); } }
6,724
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.CodeSource; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * Version */ public final class Version { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Version.class); private static final Pattern PREFIX_DIGITS_PATTERN = Pattern.compile("^([0-9]*).*"); // Dubbo RPC protocol version, for compatibility, it must not be between 2.0.10 ~ 2.6.2 public static final String DEFAULT_DUBBO_PROTOCOL_VERSION = "2.0.2"; // version 1.0.0 represents Dubbo rpc protocol before v2.6.2 public static final int LEGACY_DUBBO_PROTOCOL_VERSION = 10000; // 1.0.0 // Dubbo implementation version. private static String VERSION; private static String LATEST_COMMIT_ID; /** * For protocol compatibility purpose. * Because {@link #isSupportResponseAttachment} is checked for every call, int compare expect to has higher * performance than string. */ public static final int LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT = 2000200; // 2.0.2 public static final int HIGHEST_PROTOCOL_VERSION = 2009900; // 2.0.99 private static final Map<String, Integer> VERSION2INT = new HashMap<String, Integer>(); static { // get dubbo version and last commit id try { tryLoadVersionFromResource(); checkDuplicate(); } catch (Throwable e) { logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "continue the old logic, ignore exception " + e.getMessage(), e); } if (StringUtils.isEmpty(VERSION)) { VERSION = getVersion(Version.class, ""); } if (StringUtils.isEmpty(LATEST_COMMIT_ID)) { LATEST_COMMIT_ID = ""; } } private static void tryLoadVersionFromResource() throws IOException { Enumeration<URL> configLoader = Version.class.getClassLoader().getResources("META-INF/versions/dubbo-common"); if (configLoader.hasMoreElements()) { URL url = configLoader.nextElement(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("revision=")) { VERSION = line.substring("revision=".length()); } else if (line.startsWith("git.commit.id=")) { LATEST_COMMIT_ID = line.substring("git.commit.id=".length()); } } } } } private Version() {} public static String getProtocolVersion() { return DEFAULT_DUBBO_PROTOCOL_VERSION; } public static String getVersion() { return VERSION; } public static String getLastCommitId() { return LATEST_COMMIT_ID; } /** * Compare versions * * @return the value {@code 0} if {@code version1 == version2}; * a value less than {@code 0} if {@code version1 < version2}; and * a value greater than {@code 0} if {@code version1 > version2} */ public static int compare(String version1, String version2) { return Integer.compare(getIntVersion(version1), getIntVersion(version2)); } /** * Check the framework release version number to decide if it's 2.7.0 or higher */ public static boolean isRelease270OrHigher(String version) { if (StringUtils.isEmpty(version)) { return false; } return getIntVersion(version) >= 2070000; } /** * Check the framework release version number to decide if it's 2.6.3 or higher * * @param version, the sdk version */ public static boolean isRelease263OrHigher(String version) { return getIntVersion(version) >= 2060300; } /** * Dubbo 2.x protocol version numbers are limited to 2.0.2/2000200 ~ 2.0.99/2009900, other versions are consider as * invalid or not from official release. * * @param version, the protocol version. * @return */ public static boolean isSupportResponseAttachment(String version) { if (StringUtils.isEmpty(version)) { return false; } int iVersion = getIntVersion(version); if (iVersion >= LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT && iVersion <= HIGHEST_PROTOCOL_VERSION) { return true; } return false; } public static int getIntVersion(String version) { Integer v = VERSION2INT.get(version); if (v == null) { try { v = parseInt(version); // e.g., version number 2.6.3 will convert to 2060300 if (version.split("\\.").length == 3) { v = v * 100; } } catch (Exception e) { logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "Please make sure your version value has the right format: " + "\n 1. only contains digital number: 2.0.0; \n 2. with string suffix: 2.6.7-stable. " + "\nIf you are using Dubbo before v2.6.2, the version value is the same with the jar version."); v = LEGACY_DUBBO_PROTOCOL_VERSION; } VERSION2INT.put(version, v); } return v; } private static int parseInt(String version) { int v = 0; String[] vArr = version.split("\\."); int len = vArr.length; for (int i = 0; i < len; i++) { String subV = getPrefixDigits(vArr[i]); if (StringUtils.isNotEmpty(subV)) { v += Integer.parseInt(subV) * Math.pow(10, (len - i - 1) * 2); } } return v; } /** * get prefix digits from given version string */ private static String getPrefixDigits(String v) { Matcher matcher = PREFIX_DIGITS_PATTERN.matcher(v); if (matcher.find()) { return matcher.group(1); } return ""; } public static String getVersion(Class<?> cls, String defaultVersion) { try { // find version info from MANIFEST.MF first Package pkg = cls.getPackage(); String version = null; if (pkg != null) { version = pkg.getImplementationVersion(); if (StringUtils.isNotEmpty(version)) { return version; } version = pkg.getSpecificationVersion(); if (StringUtils.isNotEmpty(version)) { return version; } } // guess version from jar file name if nothing's found from MANIFEST.MF CodeSource codeSource = cls.getProtectionDomain().getCodeSource(); if (codeSource == null) { logger.info("No codeSource for class " + cls.getName() + " when getVersion, use default version " + defaultVersion); return defaultVersion; } URL location = codeSource.getLocation(); if (location == null) { logger.info("No location for class " + cls.getName() + " when getVersion, use default version " + defaultVersion); return defaultVersion; } String file = location.getFile(); if (!StringUtils.isEmpty(file) && file.endsWith(".jar")) { version = getFromFile(file); } // return default version if no version info is found return StringUtils.isEmpty(version) ? defaultVersion : version; } catch (Throwable e) { // return default version when any exception is thrown logger.error( COMMON_UNEXPECTED_EXCEPTION, "", "", "return default version, ignore exception " + e.getMessage(), e); return defaultVersion; } } /** * get version from file: path/to/group-module-x.y.z.jar, returns x.y.z */ private static String getFromFile(String file) { // remove suffix ".jar": "path/to/group-module-x.y.z" file = file.substring(0, file.length() - 4); // remove path: "group-module-x.y.z" int i = file.lastIndexOf('/'); if (i >= 0) { file = file.substring(i + 1); } // remove group: "module-x.y.z" i = file.indexOf("-"); if (i >= 0) { file = file.substring(i + 1); } // remove module: "x.y.z" while (file.length() > 0 && !Character.isDigit(file.charAt(0))) { i = file.indexOf("-"); if (i >= 0) { file = file.substring(i + 1); } else { break; } } return file; } private static void checkDuplicate() { try { checkArtifacts(loadArtifactIds()); } catch (Throwable e) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } private static void checkArtifacts(Set<String> artifactIds) throws IOException { if (!artifactIds.isEmpty()) { for (String artifactId : artifactIds) { checkArtifact(artifactId); } } } private static void checkArtifact(String artifactId) throws IOException { Enumeration<URL> artifactEnumeration = Version.class.getClassLoader().getResources("META-INF/versions/" + artifactId); while (artifactEnumeration.hasMoreElements()) { URL url = artifactEnumeration.nextElement(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { continue; } String[] artifactInfo = line.split("="); if (artifactInfo.length == 2) { String key = artifactInfo[0]; String value = artifactInfo[1]; checkVersion(artifactId, url, key, value); } } } } } private static void checkVersion(String artifactId, URL url, String key, String value) { if ("revision".equals(key) && !value.equals(VERSION)) { String error = "Inconsistent version " + value + " found in " + artifactId + " from " + url.getPath() + ", " + "expected dubbo-common version is " + VERSION; logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", error); } if ("git.commit.id".equals(key) && !value.equals(LATEST_COMMIT_ID)) { String error = "Inconsistent git build commit id " + value + " found in " + artifactId + " from " + url.getPath() + ", " + "expected dubbo-common version is " + LATEST_COMMIT_ID; logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", error); } } private static Set<String> loadArtifactIds() throws IOException { Enumeration<URL> artifactsEnumeration = Version.class.getClassLoader().getResources("META-INF/versions/.artifacts"); Set<String> artifactIds = new HashSet<>(); while (artifactsEnumeration.hasMoreElements()) { URL url = artifactsEnumeration.nextElement(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { continue; } if (StringUtils.isEmpty(line)) { continue; } artifactIds.add(line); } } } return artifactIds; } }
6,725
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/Cert.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.ssl; import java.io.ByteArrayInputStream; import java.io.InputStream; public class Cert { private final byte[] keyCertChain; private final byte[] privateKey; private final byte[] trustCert; private final String password; public Cert(byte[] keyCertChain, byte[] privateKey, byte[] trustCert) { this(keyCertChain, privateKey, trustCert, null); } public Cert(byte[] keyCertChain, byte[] privateKey, byte[] trustCert, String password) { this.keyCertChain = keyCertChain; this.privateKey = privateKey; this.trustCert = trustCert; this.password = password; } public byte[] getKeyCertChain() { return keyCertChain; } public InputStream getKeyCertChainInputStream() { return keyCertChain != null ? new ByteArrayInputStream(keyCertChain) : null; } public byte[] getPrivateKey() { return privateKey; } public InputStream getPrivateKeyInputStream() { return privateKey != null ? new ByteArrayInputStream(privateKey) : null; } public byte[] getTrustCert() { return trustCert; } public InputStream getTrustCertInputStream() { return trustCert != null ? new ByteArrayInputStream(trustCert) : null; } public String getPassword() { return password; } }
6,726
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.FrameworkModel; import java.net.SocketAddress; import java.util.List; public class CertManager { private final List<CertProvider> certProviders; public CertManager(FrameworkModel frameworkModel) { this.certProviders = frameworkModel.getExtensionLoader(CertProvider.class).getActivateExtensions(); } public ProviderCert getProviderConnectionConfig(URL localAddress, SocketAddress remoteAddress) { for (CertProvider certProvider : certProviders) { if (certProvider.isSupport(localAddress)) { ProviderCert cert = certProvider.getProviderConnectionConfig(localAddress); if (cert != null) { return cert; } } } return null; } public Cert getConsumerConnectionConfig(URL remoteAddress) { for (CertProvider certProvider : certProviders) { if (certProvider.isSupport(remoteAddress)) { Cert cert = certProvider.getConsumerConnectionConfig(remoteAddress); if (cert != null) { return cert; } } } return null; } }
6,727
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/AuthPolicy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.ssl; public enum AuthPolicy { NONE, SERVER_AUTH, CLIENT_AUTH }
6,728
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.FRAMEWORK) public interface CertProvider { boolean isSupport(URL address); ProviderCert getProviderConnectionConfig(URL localAddress); Cert getConsumerConnectionConfig(URL remoteAddress); }
6,729
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/ProviderCert.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.ssl; public class ProviderCert extends Cert { private final AuthPolicy authPolicy; public ProviderCert(byte[] keyCertChain, byte[] privateKey, byte[] trustCert, AuthPolicy authPolicy) { super(keyCertChain, privateKey, trustCert); this.authPolicy = authPolicy; } public ProviderCert( byte[] keyCertChain, byte[] privateKey, byte[] trustCert, String password, AuthPolicy authPolicy) { super(keyCertChain, privateKey, trustCert, password); this.authPolicy = authPolicy; } public AuthPolicy getAuthPolicy() { return authPolicy; } }
6,730
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/ssl
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/impl/SSLConfigCertProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.ssl.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.ssl.AuthPolicy; import org.apache.dubbo.common.ssl.Cert; import org.apache.dubbo.common.ssl.CertProvider; import org.apache.dubbo.common.ssl.ProviderCert; import org.apache.dubbo.common.utils.IOUtils; import java.io.IOException; import java.util.Objects; @Activate(order = Integer.MAX_VALUE - 10000) public class SSLConfigCertProvider implements CertProvider { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SSLConfigCertProvider.class); @Override public boolean isSupport(URL address) { return address.getOrDefaultApplicationModel() .getApplicationConfigManager() .getSsl() .isPresent(); } @Override public ProviderCert getProviderConnectionConfig(URL localAddress) { return localAddress .getOrDefaultApplicationModel() .getApplicationConfigManager() .getSsl() .filter(sslConfig -> Objects.nonNull(sslConfig.getServerKeyCertChainPath())) .filter(sslConfig -> Objects.nonNull(sslConfig.getServerPrivateKeyPath())) .map(sslConfig -> { try { return new ProviderCert( IOUtils.toByteArray(sslConfig.getServerKeyCertChainPathStream()), IOUtils.toByteArray(sslConfig.getServerPrivateKeyPathStream()), sslConfig.getServerTrustCertCollectionPath() != null ? IOUtils.toByteArray(sslConfig.getServerTrustCertCollectionPathStream()) : null, sslConfig.getServerKeyPassword(), AuthPolicy.CLIENT_AUTH); } catch (IOException e) { logger.warn( LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, "", "", "Failed to load ssl config.", e); return null; } }) .orElse(null); } @Override public Cert getConsumerConnectionConfig(URL remoteAddress) { return remoteAddress .getOrDefaultApplicationModel() .getApplicationConfigManager() .getSsl() .filter(sslConfig -> Objects.nonNull(sslConfig.getClientKeyCertChainPath())) .filter(sslConfig -> Objects.nonNull(sslConfig.getClientPrivateKeyPath())) .map(sslConfig -> { try { return new Cert( IOUtils.toByteArray(sslConfig.getClientKeyCertChainPathStream()), IOUtils.toByteArray(sslConfig.getClientPrivateKeyPathStream()), sslConfig.getClientTrustCertCollectionPath() != null ? IOUtils.toByteArray(sslConfig.getClientTrustCertCollectionPathStream()) : null, sslConfig.getClientKeyPassword()); } catch (IOException e) { logger.warn( LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, "", "", "Failed to load ssl config.", e); return null; } }) .orElse(null); } }
6,731
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/infra/InfraAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.infra; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.util.Map; /** * Used to interact with other systems. Typical use cases are: * 1. get extra attributes from underlying infrastructures related to the instance on which Dubbo is currently deploying. * 2. get configurations from third-party systems which maybe useful for a specific component. */ @SPI(scope = ExtensionScope.APPLICATION) public interface InfraAdapter { /** * get extra attributes * * @param params application name or hostname are most likely to be used as input params. * @return */ Map<String, String> getExtraAttributes(Map<String, String> params); /** * @param key * @return */ String getAttribute(String key); }
6,732
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/infra
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/infra/support/EnvironmentAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.infra.support; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.infra.InfraAdapter; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_ENV_KEYS; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_LABELS; import static org.apache.dubbo.common.constants.CommonConstants.EQUAL_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; @Activate public class EnvironmentAdapter implements InfraAdapter, ScopeModelAware { private ApplicationModel applicationModel; @Override public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } /** * 1. OS Environment: DUBBO_LABELS=tag=pre;key=value * 2. JVM Options: -Denv_keys = DUBBO_KEY1, DUBBO_KEY2 * * @param params information of this Dubbo process, currently includes application name and host address. */ @Override public Map<String, String> getExtraAttributes(Map<String, String> params) { Map<String, String> parameters = new HashMap<>(); String rawLabels = ConfigurationUtils.getProperty(applicationModel, DUBBO_LABELS); if (StringUtils.isNotEmpty(rawLabels)) { String[] labelPairs = SEMICOLON_SPLIT_PATTERN.split(rawLabels); for (String pair : labelPairs) { String[] label = EQUAL_SPLIT_PATTERN.split(pair); if (label.length == 2) { parameters.put(label[0], label[1]); } } } String rawKeys = ConfigurationUtils.getProperty(applicationModel, DUBBO_ENV_KEYS); if (StringUtils.isNotEmpty(rawKeys)) { String[] keys = COMMA_SPLIT_PATTERN.split(rawKeys); for (String key : keys) { String value = ConfigurationUtils.getProperty(applicationModel, key); if (value != null) { // since 3.2 parameters.put(key.toLowerCase(), value); // upper-case key kept for compatibility parameters.put(key, value); } } } return parameters; } @Override public String getAttribute(String key) { return ConfigurationUtils.getProperty(applicationModel, key); } }
6,733
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2ActivateUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.compact; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class Dubbo2ActivateUtils { private static final Class<? extends Annotation> ACTIVATE_CLASS; private static final Method GROUP_METHOD; private static final Method VALUE_METHOD; private static final Method BEFORE_METHOD; private static final Method AFTER_METHOD; private static final Method ORDER_METHOD; private static final Method ON_CLASS_METHOD; static { ACTIVATE_CLASS = loadClass(); GROUP_METHOD = loadMethod("group"); VALUE_METHOD = loadMethod("value"); BEFORE_METHOD = loadMethod("before"); AFTER_METHOD = loadMethod("after"); ORDER_METHOD = loadMethod("order"); ON_CLASS_METHOD = loadMethod("onClass"); } @SuppressWarnings("unchecked") private static Class<? extends Annotation> loadClass() { try { Class<?> clazz = Class.forName("com.alibaba.dubbo.common.extension.Activate"); if (clazz.isAnnotation()) { return (Class<? extends Annotation>) clazz; } else { return null; } } catch (Throwable e) { return null; } } public static boolean isActivateLoaded() { return ACTIVATE_CLASS != null; } public static Class<? extends Annotation> getActivateClass() { return ACTIVATE_CLASS; } private static Method loadMethod(String name) { if (ACTIVATE_CLASS == null) { return null; } try { return ACTIVATE_CLASS.getMethod(name); } catch (Throwable e) { return null; } } public static String[] getGroup(Annotation annotation) { if (GROUP_METHOD == null) { return null; } try { Object result = GROUP_METHOD.invoke(annotation); if (result instanceof String[]) { return (String[]) result; } else { return null; } } catch (Throwable e) { return null; } } public static String[] getValue(Annotation annotation) { if (VALUE_METHOD == null) { return null; } try { Object result = VALUE_METHOD.invoke(annotation); if (result instanceof String[]) { return (String[]) result; } else { return null; } } catch (Throwable e) { return null; } } public static String[] getBefore(Annotation annotation) { if (BEFORE_METHOD == null) { return null; } try { Object result = BEFORE_METHOD.invoke(annotation); if (result instanceof String[]) { return (String[]) result; } else { return null; } } catch (Throwable e) { return null; } } public static String[] getAfter(Annotation annotation) { if (AFTER_METHOD == null) { return null; } try { Object result = AFTER_METHOD.invoke(annotation); if (result instanceof String[]) { return (String[]) result; } else { return null; } } catch (Throwable e) { return null; } } public static int getOrder(Annotation annotation) { if (ORDER_METHOD == null) { return 0; } try { Object result = ORDER_METHOD.invoke(annotation); if (result instanceof Integer) { return (Integer) result; } else { return 0; } } catch (Throwable e) { return 0; } } public static String[] getOnClass(Annotation annotation) { if (ON_CLASS_METHOD == null) { return null; } try { Object result = ON_CLASS_METHOD.invoke(annotation); if (result instanceof String[]) { return (String[]) result; } else { return null; } } catch (Throwable e) { return null; } } }
6,734
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.compact; import org.apache.dubbo.rpc.service.GenericException; import java.lang.reflect.Constructor; public class Dubbo2GenericExceptionUtils { private static final Class<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CLASS; private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CONSTRUCTOR; private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CONSTRUCTOR_S; private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CONSTRUCTOR_S_S; private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CONSTRUCTOR_T; private static final Constructor<? extends org.apache.dubbo.rpc.service.GenericException> GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S; static { GENERIC_EXCEPTION_CLASS = loadClass(); GENERIC_EXCEPTION_CONSTRUCTOR = loadConstructor(); GENERIC_EXCEPTION_CONSTRUCTOR_S = loadConstructor(String.class); GENERIC_EXCEPTION_CONSTRUCTOR_S_S = loadConstructor(String.class, String.class); GENERIC_EXCEPTION_CONSTRUCTOR_T = loadConstructor(Throwable.class); GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S = loadConstructor(String.class, Throwable.class, String.class, String.class); } @SuppressWarnings("unchecked") private static Class<? extends org.apache.dubbo.rpc.service.GenericException> loadClass() { try { Class<?> clazz = Class.forName("com.alibaba.dubbo.rpc.service.GenericException"); if (GenericException.class.isAssignableFrom(clazz)) { return (Class<? extends org.apache.dubbo.rpc.service.GenericException>) clazz; } else { return null; } } catch (Throwable e) { return null; } } private static Constructor<? extends org.apache.dubbo.rpc.service.GenericException> loadConstructor( Class<?>... parameterTypes) { if (GENERIC_EXCEPTION_CLASS == null) { return null; } try { return GENERIC_EXCEPTION_CLASS.getConstructor(parameterTypes); } catch (Throwable e) { return null; } } public static boolean isGenericExceptionClassLoaded() { return GENERIC_EXCEPTION_CLASS != null && GENERIC_EXCEPTION_CONSTRUCTOR != null && GENERIC_EXCEPTION_CONSTRUCTOR_S != null && GENERIC_EXCEPTION_CONSTRUCTOR_S_S != null && GENERIC_EXCEPTION_CONSTRUCTOR_T != null && GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S != null; } public static Class<? extends org.apache.dubbo.rpc.service.GenericException> getGenericExceptionClass() { return GENERIC_EXCEPTION_CLASS; } public static org.apache.dubbo.rpc.service.GenericException newGenericException() { if (GENERIC_EXCEPTION_CONSTRUCTOR == null) { return null; } try { return GENERIC_EXCEPTION_CONSTRUCTOR.newInstance(); } catch (Throwable e) { return null; } } public static org.apache.dubbo.rpc.service.GenericException newGenericException(String exceptionMessage) { if (GENERIC_EXCEPTION_CONSTRUCTOR_S == null) { return null; } try { return GENERIC_EXCEPTION_CONSTRUCTOR_S.newInstance(exceptionMessage); } catch (Throwable e) { return null; } } public static org.apache.dubbo.rpc.service.GenericException newGenericException( String exceptionClass, String exceptionMessage) { if (GENERIC_EXCEPTION_CONSTRUCTOR_S_S == null) { return null; } try { return GENERIC_EXCEPTION_CONSTRUCTOR_S_S.newInstance(exceptionClass, exceptionMessage); } catch (Throwable e) { return null; } } public static org.apache.dubbo.rpc.service.GenericException newGenericException(Throwable cause) { if (GENERIC_EXCEPTION_CONSTRUCTOR_T == null) { return null; } try { return GENERIC_EXCEPTION_CONSTRUCTOR_T.newInstance(cause); } catch (Throwable e) { return null; } } public static org.apache.dubbo.rpc.service.GenericException newGenericException( String message, Throwable cause, String exceptionClass, String exceptionMessage) { if (GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S == null) { return null; } try { return GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S.newInstance(message, cause, exceptionClass, exceptionMessage); } catch (Throwable e) { return null; } } }
6,735
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.compact; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import java.lang.annotation.Annotation; public class Dubbo2CompactUtils { private static volatile boolean enabled = true; private static final Class<? extends Annotation> REFERENCE_CLASS; private static final Class<? extends Annotation> SERVICE_CLASS; private static final Class<?> ECHO_SERVICE_CLASS; private static final Class<?> GENERIC_SERVICE_CLASS; static { initEnabled(); REFERENCE_CLASS = loadAnnotation("com.alibaba.dubbo.config.annotation.Reference"); SERVICE_CLASS = loadAnnotation("com.alibaba.dubbo.config.annotation.Service"); ECHO_SERVICE_CLASS = loadClass("com.alibaba.dubbo.rpc.service.EchoService"); GENERIC_SERVICE_CLASS = loadClass("com.alibaba.dubbo.rpc.service.GenericService"); } private static void initEnabled() { try { String fromProp = System.getProperty(CommonConstants.DUBBO2_COMPACT_ENABLE); if (StringUtils.isNotEmpty(fromProp)) { enabled = Boolean.parseBoolean(fromProp); return; } String fromEnv = System.getenv(CommonConstants.DUBBO2_COMPACT_ENABLE); if (StringUtils.isNotEmpty(fromEnv)) { enabled = Boolean.parseBoolean(fromEnv); return; } fromEnv = System.getenv(StringUtils.toOSStyleKey(CommonConstants.DUBBO2_COMPACT_ENABLE)); enabled = !StringUtils.isNotEmpty(fromEnv) || Boolean.parseBoolean(fromEnv); } catch (Throwable t) { enabled = true; } } public static boolean isEnabled() { return enabled; } public static void setEnabled(boolean enabled) { Dubbo2CompactUtils.enabled = enabled; } private static Class<?> loadClass(String name) { try { return Class.forName(name); } catch (Throwable e) { return null; } } @SuppressWarnings("unchecked") private static Class<? extends Annotation> loadAnnotation(String name) { try { Class<?> clazz = Class.forName(name); if (clazz.isAnnotation()) { return (Class<? extends Annotation>) clazz; } else { return null; } } catch (Throwable e) { return null; } } public static boolean isReferenceClassLoaded() { return REFERENCE_CLASS != null; } public static Class<? extends Annotation> getReferenceClass() { return REFERENCE_CLASS; } public static boolean isServiceClassLoaded() { return SERVICE_CLASS != null; } public static Class<? extends Annotation> getServiceClass() { return SERVICE_CLASS; } public static boolean isEchoServiceClassLoaded() { return ECHO_SERVICE_CLASS != null; } public static Class<?> getEchoServiceClass() { return ECHO_SERVICE_CLASS; } public static boolean isGenericServiceClassLoaded() { return GENERIC_SERVICE_CLASS != null; } public static Class<?> getGenericServiceClass() { return GENERIC_SERVICE_CLASS; } }
6,736
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/context/ApplicationExt.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.context; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.APPLICATION) public interface ApplicationExt extends Lifecycle {}
6,737
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/context/Lifecycle.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.context; import org.apache.dubbo.common.resource.Disposable; /** * The Lifecycle of Dubbo component * * @since 2.7.5 */ public interface Lifecycle extends Disposable { /** * Initialize the component before {@link #start() start} * * @return current {@link Lifecycle} * @throws IllegalStateException */ void initialize() throws IllegalStateException; /** * Start the component * * @return current {@link Lifecycle} * @throws IllegalStateException */ void start() throws IllegalStateException; /** * Destroy the component * * @throws IllegalStateException */ void destroy() throws IllegalStateException; }
6,738
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/context/ModuleExt.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.context; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.MODULE) public interface ModuleExt extends Lifecycle {}
6,739
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/context/LifecycleAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.context; public abstract class LifecycleAdapter implements Lifecycle { @Override public void initialize() throws IllegalStateException {} @Override public void start() throws IllegalStateException {} @Override public void destroy() throws IllegalStateException {} }
6,740
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Code generator for Adaptive class */ public class AdaptiveClassCodeGenerator { private static final Logger logger = LoggerFactory.getLogger(AdaptiveClassCodeGenerator.class); private static final String CLASS_NAME_INVOCATION = "org.apache.dubbo.rpc.Invocation"; private static final String CODE_PACKAGE = "package %s;\n"; private static final String CODE_IMPORTS = "import %s;\n"; private static final String CODE_CLASS_DECLARATION = "public class %s$Adaptive implements %s {\n"; private static final String CODE_METHOD_DECLARATION = "public %s %s(%s) %s {\n%s}\n"; private static final String CODE_METHOD_ARGUMENT = "%s arg%d"; private static final String CODE_METHOD_THROWS = "throws %s"; private static final String CODE_UNSUPPORTED = "throw new UnsupportedOperationException(\"The method %s of interface %s is not adaptive method!\");\n"; private static final String CODE_URL_NULL_CHECK = "if (arg%d == null) throw new IllegalArgumentException(\"url == null\");\n%s url = arg%d;\n"; private static final String CODE_EXT_NAME_ASSIGNMENT = "String extName = %s;\n"; private static final String CODE_EXT_NAME_NULL_CHECK = "if(extName == null) " + "throw new IllegalStateException(\"Failed to get extension (%s) name from url (\" + url.toString() + \") use keys(%s)\");\n"; private static final String CODE_INVOCATION_ARGUMENT_NULL_CHECK = "if (arg%d == null) throw new IllegalArgumentException(\"invocation == null\"); " + "String methodName = arg%d.getMethodName();\n"; private static final String CODE_SCOPE_MODEL_ASSIGNMENT = "ScopeModel scopeModel = ScopeModelUtil.getOrDefault(url.getScopeModel(), %s.class);\n"; private static final String CODE_EXTENSION_ASSIGNMENT = "%s extension = (%<s)scopeModel.getExtensionLoader(%s.class).getExtension(extName);\n"; private static final String CODE_EXTENSION_METHOD_INVOKE_ARGUMENT = "arg%d"; private final Class<?> type; private final String defaultExtName; public AdaptiveClassCodeGenerator(Class<?> type, String defaultExtName) { this.type = type; this.defaultExtName = defaultExtName; } /** * test if given type has at least one method annotated with <code>Adaptive</code> */ private boolean hasAdaptiveMethod() { return Arrays.stream(type.getMethods()).anyMatch(m -> m.isAnnotationPresent(Adaptive.class)); } /** * generate and return class code */ public String generate() { return this.generate(false); } /** * generate and return class code * @param sort - whether sort methods */ public String generate(boolean sort) { // no need to generate adaptive class since there's no adaptive method found. if (!hasAdaptiveMethod()) { throw new IllegalStateException("No adaptive method exist on extension " + type.getName() + ", refuse to create the adaptive class!"); } StringBuilder code = new StringBuilder(); code.append(generatePackageInfo()); code.append(generateImports()); code.append(generateClassDeclaration()); Method[] methods = type.getMethods(); if (sort) { Arrays.sort(methods, Comparator.comparing(Method::toString)); } for (Method method : methods) { code.append(generateMethod(method)); } code.append('}'); if (logger.isDebugEnabled()) { logger.debug(code.toString()); } return code.toString(); } /** * generate package info */ private String generatePackageInfo() { return String.format(CODE_PACKAGE, type.getPackage().getName()); } /** * generate imports */ private String generateImports() { StringBuilder builder = new StringBuilder(); builder.append(String.format(CODE_IMPORTS, ScopeModel.class.getName())); builder.append(String.format(CODE_IMPORTS, ScopeModelUtil.class.getName())); return builder.toString(); } /** * generate class declaration */ private String generateClassDeclaration() { return String.format(CODE_CLASS_DECLARATION, type.getSimpleName(), type.getCanonicalName()); } /** * generate method not annotated with Adaptive with throwing unsupported exception */ private String generateUnsupported(Method method) { return String.format(CODE_UNSUPPORTED, method, type.getName()); } /** * get index of parameter with type URL */ private int getUrlTypeIndex(Method method) { int urlTypeIndex = -1; Class<?>[] pts = method.getParameterTypes(); for (int i = 0; i < pts.length; ++i) { if (pts[i].equals(URL.class)) { urlTypeIndex = i; break; } } return urlTypeIndex; } /** * generate method declaration */ private String generateMethod(Method method) { String methodReturnType = method.getReturnType().getCanonicalName(); String methodName = method.getName(); String methodContent = generateMethodContent(method); String methodArgs = generateMethodArguments(method); String methodThrows = generateMethodThrows(method); return String.format( CODE_METHOD_DECLARATION, methodReturnType, methodName, methodArgs, methodThrows, methodContent); } /** * generate method arguments */ private String generateMethodArguments(Method method) { Class<?>[] pts = method.getParameterTypes(); return IntStream.range(0, pts.length) .mapToObj(i -> String.format(CODE_METHOD_ARGUMENT, pts[i].getCanonicalName(), i)) .collect(Collectors.joining(", ")); } /** * generate method throws */ private String generateMethodThrows(Method method) { Class<?>[] ets = method.getExceptionTypes(); if (ets.length > 0) { String list = Arrays.stream(ets).map(Class::getCanonicalName).collect(Collectors.joining(", ")); return String.format(CODE_METHOD_THROWS, list); } else { return ""; } } /** * generate method URL argument null check */ private String generateUrlNullCheck(int index) { return String.format(CODE_URL_NULL_CHECK, index, URL.class.getName(), index); } /** * generate method content */ private String generateMethodContent(Method method) { Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class); StringBuilder code = new StringBuilder(512); if (adaptiveAnnotation == null) { return generateUnsupported(method); } else { int urlTypeIndex = getUrlTypeIndex(method); // found parameter in URL type if (urlTypeIndex != -1) { // Null Point check code.append(generateUrlNullCheck(urlTypeIndex)); } else { // did not find parameter in URL type code.append(generateUrlAssignmentIndirectly(method)); } String[] value = getMethodAdaptiveValue(adaptiveAnnotation); boolean hasInvocation = hasInvocationArgument(method); code.append(generateInvocationArgumentNullCheck(method)); code.append(generateExtNameAssignment(value, hasInvocation)); // check extName == null? code.append(generateExtNameNullCheck(value)); code.append(generateScopeModelAssignment()); code.append(generateExtensionAssignment()); // return statement code.append(generateReturnAndInvocation(method)); } return code.toString(); } /** * generate code for variable extName null check */ private String generateExtNameNullCheck(String[] value) { return String.format(CODE_EXT_NAME_NULL_CHECK, type.getName(), Arrays.toString(value)); } /** * generate extName assignment code */ private String generateExtNameAssignment(String[] value, boolean hasInvocation) { // TODO: refactor it String getNameCode = null; for (int i = value.length - 1; i >= 0; --i) { if (i == value.length - 1) { if (null != defaultExtName) { if (!CommonConstants.PROTOCOL_KEY.equals(value[i])) { if (hasInvocation) { getNameCode = String.format( "url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName); } } else { getNameCode = String.format( "( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName); } } else { if (!CommonConstants.PROTOCOL_KEY.equals(value[i])) { if (hasInvocation) { getNameCode = String.format( "url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\")", value[i]); } } else { getNameCode = "url.getProtocol()"; } } } else { if (!CommonConstants.PROTOCOL_KEY.equals(value[i])) { if (hasInvocation) { getNameCode = String.format( "url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode); } } else { getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode); } } } return String.format(CODE_EXT_NAME_ASSIGNMENT, getNameCode); } /** * @return */ private String generateScopeModelAssignment() { return String.format(CODE_SCOPE_MODEL_ASSIGNMENT, type.getName()); } private String generateExtensionAssignment() { return String.format(CODE_EXTENSION_ASSIGNMENT, type.getName(), type.getName()); } /** * generate method invocation statement and return it if necessary */ private String generateReturnAndInvocation(Method method) { String returnStatement = method.getReturnType().equals(void.class) ? "" : "return "; String args = IntStream.range(0, method.getParameters().length) .mapToObj(i -> String.format(CODE_EXTENSION_METHOD_INVOKE_ARGUMENT, i)) .collect(Collectors.joining(", ")); return returnStatement + String.format("extension.%s(%s);\n", method.getName(), args); } /** * test if method has argument of type <code>Invocation</code> */ private boolean hasInvocationArgument(Method method) { Class<?>[] pts = method.getParameterTypes(); return Arrays.stream(pts).anyMatch(p -> CLASS_NAME_INVOCATION.equals(p.getName())); } /** * generate code to test argument of type <code>Invocation</code> is null */ private String generateInvocationArgumentNullCheck(Method method) { Class<?>[] pts = method.getParameterTypes(); return IntStream.range(0, pts.length) .filter(i -> CLASS_NAME_INVOCATION.equals(pts[i].getName())) .mapToObj(i -> String.format(CODE_INVOCATION_ARGUMENT_NULL_CHECK, i, i)) .findFirst() .orElse(""); } /** * get value of adaptive annotation or if empty return splitted simple name */ private String[] getMethodAdaptiveValue(Adaptive adaptiveAnnotation) { String[] value = adaptiveAnnotation.value(); // value is not set, use the value generated from class name as the key if (value.length == 0) { String splitName = StringUtils.camelToSplitName(type.getSimpleName(), "."); value = new String[] {splitName}; } return value; } /** * get parameter with type <code>URL</code> from method parameter: * <p> * test if parameter has method which returns type <code>URL</code> * <p> * if not found, throws IllegalStateException */ private String generateUrlAssignmentIndirectly(Method method) { Class<?>[] pts = method.getParameterTypes(); Map<String, Integer> getterReturnUrl = new HashMap<>(); // find URL getter method for (int i = 0; i < pts.length; ++i) { for (Method m : pts[i].getMethods()) { String name = m.getName(); if ((name.startsWith("get") || name.length() > 3) && Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && m.getReturnType() == URL.class) { getterReturnUrl.put(name, i); } } } if (getterReturnUrl.size() <= 0) { // getter method not found, throw throw new IllegalStateException("Failed to create adaptive class for interface " + type.getName() + ": not found url parameter or url attribute in parameters of method " + method.getName()); } Integer index = getterReturnUrl.get("getUrl"); if (index != null) { return generateGetUrlNullCheck(index, pts[index], "getUrl"); } else { Map.Entry<String, Integer> entry = getterReturnUrl.entrySet().iterator().next(); return generateGetUrlNullCheck(entry.getValue(), pts[entry.getValue()], entry.getKey()); } } /** * 1, test if argi is null * 2, test if argi.getXX() returns null * 3, assign url with argi.getXX() */ private String generateGetUrlNullCheck(int index, Class<?> type, String method) { // Null point check StringBuilder code = new StringBuilder(); code.append(String.format( "if (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");\n", index, type.getName())); code.append(String.format( "if (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");\n", index, method, type.getName(), method)); code.append(String.format("%s url = arg%d.%s();\n", URL.class.getName(), index, method)); return code.toString(); } }
6,741
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/DisableInject.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface DisableInject {}
6,742
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/LoadingStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import org.apache.dubbo.common.lang.Prioritized; public interface LoadingStrategy extends Prioritized { String directory(); default boolean preferExtensionClassLoader() { return false; } default String[] excludedPackages() { return null; } /** * To restrict some class that should not be loaded from `org.apache.dubbo` package type SPI class. * For example, we can restrict the implementation class which package is `org.xxx.xxx` * can be loaded as SPI implementation. * * @return packages can be loaded in `org.apache.dubbo`'s SPI */ default String[] includedPackages() { // default match all return null; } /** * To restrict some class that should not be loaded from `org.alibaba.dubbo`(for compatible purpose) * package type SPI class. * For example, we can restrict the implementation class which package is `org.xxx.xxx` * can be loaded as SPI implementation * * @return packages can be loaded in `org.alibaba.dubbo`'s SPI */ default String[] includedPackagesInCompatibleType() { // default match all return null; } /** * To restrict some class that should load from Dubbo's ClassLoader. * For example, we can restrict the class declaration in `org.apache.dubbo` package should * be loaded from Dubbo's ClassLoader and users cannot declare these classes. * * @return class packages should load * @since 3.0.4 */ default String[] onlyExtensionClassLoaderPackages() { return new String[] {}; } /** * Indicates current {@link LoadingStrategy} supports overriding other lower prioritized instances or not. * * @return if supports, return <code>true</code>, or <code>false</code> * @since 2.7.7 */ default boolean overridden() { return false; } default String getName() { return this.getClass().getSimpleName(); } /** * when spi is loaded by dubbo framework classloader only, it indicates all LoadingStrategy should load this spi */ String ALL = "ALL"; }
6,743
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; /** * ExtensionFactory * @deprecated use {@link ExtensionInjector} instead */ @Deprecated @SPI(scope = ExtensionScope.FRAMEWORK) public interface ExtensionFactory extends ExtensionInjector { @Override default <T> T getInstance(Class<T> type, String name) { return getExtension(type, name); } /** * Get extension. * * @param type object type. * @param name object name. * @return object instance. */ <T> T getExtension(Class<T> type, String name); }
6,744
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Wrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * The annotated class will only work as a wrapper when the condition matches. */ @Retention(RetentionPolicy.RUNTIME) public @interface Wrapper { /** * the extension names that need to be wrapped. * default is matching when this array is empty. */ String[] matches() default {}; /** * the extension names that need to be excluded. */ String[] mismatches() default {}; /** * absolute ordering, optional * ascending order, smaller values will be in the front of the list. * @return */ int order() default 0; }
6,745
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionScope.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; /** * Extension SPI Scope * @see SPI * @see ExtensionDirector */ public enum ExtensionScope { /** * The extension instance is used within framework, shared with all applications and modules. * * <p>Framework scope SPI extension can only obtain {@link FrameworkModel}, * cannot get the {@link ApplicationModel} and {@link ModuleModel}.</p> * * <p></p> * Consideration: * <ol> * <li>Some SPI need share data between applications inside framework</li> * <li>Stateless SPI is safe shared inside framework</li> * </ol> */ FRAMEWORK, /** * The extension instance is used within one application, shared with all modules of the application, * and different applications create different extension instances. * * <p>Application scope SPI extension can obtain {@link FrameworkModel} and {@link ApplicationModel}, * cannot get the {@link ModuleModel}.</p> * * <p></p> * Consideration: * <ol> * <li>Isolate extension data in different applications inside framework</li> * <li>Share extension data between all modules inside application</li> * </ol> */ APPLICATION, /** * The extension instance is used within one module, and different modules create different extension instances. * * <p>Module scope SPI extension can obtain {@link FrameworkModel}, {@link ApplicationModel} and {@link ModuleModel}.</p> * * <p></p> * Consideration: * <ol> * <li>Isolate extension data in different modules inside application</li> * </ol> */ MODULE, /** * self-sufficient, creates an instance for per scope, for special SPI extension, like {@link ExtensionInjector} */ SELF }
6,746
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; /** * Uniform accessor for extension */ public interface ExtensionAccessor { ExtensionDirector getExtensionDirector(); default <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) { return this.getExtensionDirector().getExtensionLoader(type); } default <T> T getExtension(Class<T> type, String name) { ExtensionLoader<T> extensionLoader = getExtensionLoader(type); return extensionLoader != null ? extensionLoader.getExtension(name) : null; } default <T> T getAdaptiveExtension(Class<T> type) { ExtensionLoader<T> extensionLoader = getExtensionLoader(type); return extensionLoader != null ? extensionLoader.getAdaptiveExtension() : null; } default <T> T getDefaultExtension(Class<T> type) { ExtensionLoader<T> extensionLoader = getExtensionLoader(type); return extensionLoader != null ? extensionLoader.getDefaultExtension() : null; } }
6,747
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; /** * A Post-processor called before or after extension initialization. */ public interface ExtensionPostProcessor { default Object postProcessBeforeInitialization(Object instance, String name) throws Exception { return instance; } default Object postProcessAfterInitialization(Object instance, String name) throws Exception { return instance; } }
6,748
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessorAware.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; /** * SPI extension can implement this aware interface to obtain appropriate {@link ExtensionAccessor} instance. */ public interface ExtensionAccessorAware { void setExtensionAccessor(final ExtensionAccessor extensionAccessor); }
6,749
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionInjector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; /** * An injector to provide resources for SPI extension. */ @SPI(scope = ExtensionScope.SELF) public interface ExtensionInjector extends ExtensionAccessorAware { /** * Get instance of specify type and name. * * @param type object type. * @param name object name. * @return object instance. */ <T> T getInstance(final Class<T> type, final String name); @Override default void setExtensionAccessor(final ExtensionAccessor extensionAccessor) {} }
6,750
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/DubboInternalLoadingStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; /** * Dubbo internal {@link LoadingStrategy} * * @since 2.7.7 */ public class DubboInternalLoadingStrategy implements LoadingStrategy { @Override public String directory() { return "META-INF/dubbo/internal/"; } @Override public int getPriority() { return MAX_PRIORITY; } @Override public String getName() { return "DUBBO_INTERNAL"; } }
6,751
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/SPI.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker for extension interface * <p/> * Changes on extension configuration file <br/> * Use <code>Protocol</code> as an example, its configuration file 'META-INF/dubbo/com.xxx.Protocol' is changed from: <br/> * <pre> * com.foo.XxxProtocol * com.foo.YyyProtocol * </pre> * <p> * to key-value pair <br/> * <pre> * xxx=com.foo.XxxProtocol * yyy=com.foo.YyyProtocol * </pre> * <br/> * The reason for this change is: * <p> * If there's third party library referenced by static field or by method in extension implementation, its class will * fail to initialize if the third party library doesn't exist. In this case, dubbo cannot figure out extension's id * therefore cannot be able to map the exception information with the extension, if the previous format is used. * <p/> * For example: * <p> * Fails to load Extension("mina"). When user configure to use mina, dubbo will complain the extension cannot be loaded, * instead of reporting which extract extension implementation fails and the extract reason. * </p> */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface SPI { /** * default extension name */ String value() default ""; /** * scope of SPI, default value is application scope. */ ExtensionScope scope() default ExtensionScope.APPLICATION; }
6,752
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ServicesLoadingStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; /** * Services {@link LoadingStrategy} * * @since 2.7.7 */ public class ServicesLoadingStrategy implements LoadingStrategy { @Override public String directory() { return "META-INF/services/"; } @Override public boolean overridden() { return true; } @Override public int getPriority() { return MIN_PRIORITY; } @Override public String getName() { return "SERVICES"; } }
6,753
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/DubboLoadingStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; /** * Dubbo {@link LoadingStrategy} * * @since 2.7.7 */ public class DubboLoadingStrategy implements LoadingStrategy { @Override public String directory() { return "META-INF/dubbo/"; } @Override public boolean overridden() { return true; } @Override public int getPriority() { return NORMAL_PRIORITY; } @Override public String getName() { return "DUBBO"; } }
6,754
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import org.apache.dubbo.common.Extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.support.InstantiationStrategy; import org.apache.dubbo.common.compact.Dubbo2ActivateUtils; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.context.Lifecycle; import org.apache.dubbo.common.extension.support.ActivateComparator; import org.apache.dubbo.common.extension.support.WrapperComparator; import org.apache.dubbo.common.lang.Prioritized; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ClassLoaderResourceLoader; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.NativeUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelAccessor; import org.apache.dubbo.rpc.model.ScopeModelAware; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.lang.ref.SoftReference; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.ServiceLoader.load; import static java.util.stream.StreamSupport.stream; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_LOAD_EXTENSION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_LOAD_ENV_VARIABLE; /** * {@link org.apache.dubbo.rpc.model.ApplicationModel}, {@code DubboBootstrap} and this class are * at present designed to be singleton or static (by itself totally static or uses some static fields). * So the instances returned from them are of process or classloader scope. If you want to support * multiple dubbo servers in a single process, you may need to refactor these three classes. * <p> * Load dubbo extensions * <ul> * <li>auto inject dependency extension </li> * <li>auto wrap extension in wrapper </li> * <li>default extension is an adaptive instance</li> * </ul> * * @see <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service%20Provider">Service Provider in Java 5</a> * @see org.apache.dubbo.common.extension.SPI * @see org.apache.dubbo.common.extension.Adaptive * @see org.apache.dubbo.common.extension.Activate */ public class ExtensionLoader<T> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExtensionLoader.class); private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*"); private static final String SPECIAL_SPI_PROPERTIES = "special_spi.properties"; private final ConcurrentMap<Class<?>, Object> extensionInstances = new ConcurrentHashMap<>(64); private final Class<?> type; private final ExtensionInjector injector; private final ConcurrentMap<Class<?>, String> cachedNames = new ConcurrentHashMap<>(); private final Holder<Map<String, Class<?>>> cachedClasses = new Holder<>(); private final Map<String, Object> cachedActivates = Collections.synchronizedMap(new LinkedHashMap<>()); private final Map<String, Set<String>> cachedActivateGroups = Collections.synchronizedMap(new LinkedHashMap<>()); private final Map<String, String[][]> cachedActivateValues = Collections.synchronizedMap(new LinkedHashMap<>()); private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap<>(); private final Holder<Object> cachedAdaptiveInstance = new Holder<>(); private volatile Class<?> cachedAdaptiveClass = null; private String cachedDefaultName; private volatile Throwable createAdaptiveInstanceError; private Set<Class<?>> cachedWrapperClasses; private final Map<String, IllegalStateException> exceptions = new ConcurrentHashMap<>(); private static volatile LoadingStrategy[] strategies = loadLoadingStrategies(); private static final Map<String, String> specialSPILoadingStrategyMap = getSpecialSPILoadingStrategyMap(); private static SoftReference<Map<java.net.URL, List<String>>> urlListMapCache = new SoftReference<>(new ConcurrentHashMap<>()); private static final List<String> ignoredInjectMethodsDesc = getIgnoredInjectMethodsDesc(); /** * Record all unacceptable exceptions when using SPI */ private final Set<String> unacceptableExceptions = new ConcurrentHashSet<>(); private final ExtensionDirector extensionDirector; private final List<ExtensionPostProcessor> extensionPostProcessors; private InstantiationStrategy instantiationStrategy; private final ActivateComparator activateComparator; private final ScopeModel scopeModel; private final AtomicBoolean destroyed = new AtomicBoolean(); public static void setLoadingStrategies(LoadingStrategy... strategies) { if (ArrayUtils.isNotEmpty(strategies)) { ExtensionLoader.strategies = strategies; } } /** * Load all {@link Prioritized prioritized} {@link LoadingStrategy Loading Strategies} via {@link ServiceLoader} * * @return non-null * @since 2.7.7 */ private static LoadingStrategy[] loadLoadingStrategies() { return stream(load(LoadingStrategy.class).spliterator(), false).sorted().toArray(LoadingStrategy[]::new); } /** * some spi are implements by dubbo framework only and scan multi classloaders resources may cause * application startup very slow * * @return */ private static Map<String, String> getSpecialSPILoadingStrategyMap() { Map map = new ConcurrentHashMap<>(); Properties properties = loadProperties(ExtensionLoader.class.getClassLoader(), SPECIAL_SPI_PROPERTIES); map.putAll(properties); return map; } /** * Get all {@link LoadingStrategy Loading Strategies} * * @return non-null * @see LoadingStrategy * @see Prioritized * @since 2.7.7 */ public static List<LoadingStrategy> getLoadingStrategies() { return asList(strategies); } private static List<String> getIgnoredInjectMethodsDesc() { List<String> ignoreInjectMethodsDesc = new ArrayList<>(); Arrays.stream(ScopeModelAware.class.getMethods()) .map(ReflectUtils::getDesc) .forEach(ignoreInjectMethodsDesc::add); Arrays.stream(ExtensionAccessorAware.class.getMethods()) .map(ReflectUtils::getDesc) .forEach(ignoreInjectMethodsDesc::add); return ignoreInjectMethodsDesc; } ExtensionLoader(Class<?> type, ExtensionDirector extensionDirector, ScopeModel scopeModel) { this.type = type; this.extensionDirector = extensionDirector; this.extensionPostProcessors = extensionDirector.getExtensionPostProcessors(); initInstantiationStrategy(); this.injector = (type == ExtensionInjector.class ? null : extensionDirector.getExtensionLoader(ExtensionInjector.class).getAdaptiveExtension()); this.activateComparator = new ActivateComparator(extensionDirector); this.scopeModel = scopeModel; } private void initInstantiationStrategy() { instantiationStrategy = extensionPostProcessors.stream() .filter(extensionPostProcessor -> extensionPostProcessor instanceof ScopeModelAccessor) .map(extensionPostProcessor -> new InstantiationStrategy((ScopeModelAccessor) extensionPostProcessor)) .findFirst() .orElse(new InstantiationStrategy()); } /** * @see ApplicationModel#getExtensionDirector() * @see FrameworkModel#getExtensionDirector() * @see ModuleModel#getExtensionDirector() * @see ExtensionDirector#getExtensionLoader(java.lang.Class) * @deprecated get extension loader from extension director of some module. */ @Deprecated public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) { return ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(type); } @Deprecated public static void resetExtensionLoader(Class type) {} public void destroy() { if (!destroyed.compareAndSet(false, true)) { return; } // destroy raw extension instance extensionInstances.forEach((type, instance) -> { if (instance instanceof Disposable) { Disposable disposable = (Disposable) instance; try { disposable.destroy(); } catch (Exception e) { logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Error destroying extension " + disposable, e); } } }); extensionInstances.clear(); // destroy wrapped extension instance for (Holder<Object> holder : cachedInstances.values()) { Object wrappedInstance = holder.get(); if (wrappedInstance instanceof Disposable) { Disposable disposable = (Disposable) wrappedInstance; try { disposable.destroy(); } catch (Exception e) { logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Error destroying extension " + disposable, e); } } } cachedInstances.clear(); } private void checkDestroyed() { if (destroyed.get()) { throw new IllegalStateException("ExtensionLoader is destroyed: " + type); } } public String getExtensionName(T extensionInstance) { return getExtensionName(extensionInstance.getClass()); } public String getExtensionName(Class<?> extensionClass) { getExtensionClasses(); // load class return cachedNames.get(extensionClass); } /** * This is equivalent to {@code getActivateExtension(url, key, null)} * * @param url url * @param key url parameter key which used to get extension point names * @return extension list which are activated. * @see #getActivateExtension(org.apache.dubbo.common.URL, String, String) */ public List<T> getActivateExtension(URL url, String key) { return getActivateExtension(url, key, null); } /** * This is equivalent to {@code getActivateExtension(url, values, null)} * * @param url url * @param values extension point names * @return extension list which are activated * @see #getActivateExtension(org.apache.dubbo.common.URL, String[], String) */ public List<T> getActivateExtension(URL url, String[] values) { return getActivateExtension(url, values, null); } /** * This is equivalent to {@code getActivateExtension(url, url.getParameter(key).split(","), null)} * * @param url url * @param key url parameter key which used to get extension point names * @param group group * @return extension list which are activated. * @see #getActivateExtension(org.apache.dubbo.common.URL, String[], String) */ public List<T> getActivateExtension(URL url, String key, String group) { String value = url.getParameter(key); return getActivateExtension(url, StringUtils.isEmpty(value) ? null : COMMA_SPLIT_PATTERN.split(value), group); } /** * Get activate extensions. * * @param url url * @param values extension point names * @param group group * @return extension list which are activated * @see org.apache.dubbo.common.extension.Activate */ @SuppressWarnings("deprecation") public List<T> getActivateExtension(URL url, String[] values, String group) { checkDestroyed(); // solve the bug of using @SPI's wrapper method to report a null pointer exception. Map<Class<?>, T> activateExtensionsMap = new TreeMap<>(activateComparator); List<String> names = values == null ? new ArrayList<>(0) : Arrays.stream(values).map(StringUtils::trim).collect(Collectors.toList()); Set<String> namesSet = new HashSet<>(names); if (!namesSet.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) { if (cachedActivateGroups.size() == 0) { synchronized (cachedActivateGroups) { // cache all extensions if (cachedActivateGroups.size() == 0) { getExtensionClasses(); for (Map.Entry<String, Object> entry : cachedActivates.entrySet()) { String name = entry.getKey(); Object activate = entry.getValue(); String[] activateGroup, activateValue; if (activate instanceof Activate) { activateGroup = ((Activate) activate).group(); activateValue = ((Activate) activate).value(); } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && Dubbo2ActivateUtils.getActivateClass().isAssignableFrom(activate.getClass())) { activateGroup = Dubbo2ActivateUtils.getGroup((Annotation) activate); activateValue = Dubbo2ActivateUtils.getValue((Annotation) activate); } else { continue; } cachedActivateGroups.put(name, new HashSet<>(Arrays.asList(activateGroup))); String[][] keyPairs = new String[activateValue.length][]; for (int i = 0; i < activateValue.length; i++) { if (activateValue[i].contains(":")) { keyPairs[i] = new String[2]; String[] arr = activateValue[i].split(":"); keyPairs[i][0] = arr[0]; keyPairs[i][1] = arr[1]; } else { keyPairs[i] = new String[1]; keyPairs[i][0] = activateValue[i]; } } cachedActivateValues.put(name, keyPairs); } } } } // traverse all cached extensions cachedActivateGroups.forEach((name, activateGroup) -> { if (isMatchGroup(group, activateGroup) && !namesSet.contains(name) && !namesSet.contains(REMOVE_VALUE_PREFIX + name) && isActive(cachedActivateValues.get(name), url)) { activateExtensionsMap.put(getExtensionClass(name), getExtension(name)); } }); } if (namesSet.contains(DEFAULT_KEY)) { // will affect order // `ext1,default,ext2` means ext1 will happens before all of the default extensions while ext2 will after // them ArrayList<T> extensionsResult = new ArrayList<>(activateExtensionsMap.size() + names.size()); for (String name : names) { if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains(REMOVE_VALUE_PREFIX + name)) { continue; } if (DEFAULT_KEY.equals(name)) { extensionsResult.addAll(activateExtensionsMap.values()); continue; } if (containsExtension(name)) { extensionsResult.add(getExtension(name)); } } return extensionsResult; } else { // add extensions, will be sorted by its order for (String name : names) { if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains(REMOVE_VALUE_PREFIX + name)) { continue; } if (DEFAULT_KEY.equals(name)) { continue; } if (containsExtension(name)) { activateExtensionsMap.put(getExtensionClass(name), getExtension(name)); } } return new ArrayList<>(activateExtensionsMap.values()); } } public List<T> getActivateExtensions() { checkDestroyed(); List<T> activateExtensions = new ArrayList<>(); TreeMap<Class<?>, T> activateExtensionsMap = new TreeMap<>(activateComparator); getExtensionClasses(); for (Map.Entry<String, Object> entry : cachedActivates.entrySet()) { String name = entry.getKey(); Object activate = entry.getValue(); if (!(activate instanceof Activate)) { continue; } activateExtensionsMap.put(getExtensionClass(name), getExtension(name)); } if (!activateExtensionsMap.isEmpty()) { activateExtensions.addAll(activateExtensionsMap.values()); } return activateExtensions; } private boolean isMatchGroup(String group, Set<String> groups) { if (StringUtils.isEmpty(group)) { return true; } if (CollectionUtils.isNotEmpty(groups)) { return groups.contains(group); } return false; } private boolean isActive(String[][] keyPairs, URL url) { if (keyPairs.length == 0) { return true; } for (String[] keyPair : keyPairs) { // @Active(value="key1:value1, key2:value2") String key; String keyValue = null; if (keyPair.length > 1) { key = keyPair[0]; keyValue = keyPair[1]; } else { key = keyPair[0]; } String realValue = url.getParameter(key); if (StringUtils.isEmpty(realValue)) { realValue = url.getAnyMethodParameter(key); } if ((keyValue != null && keyValue.equals(realValue)) || (keyValue == null && ConfigUtils.isNotEmpty(realValue))) { return true; } } return false; } /** * Get extension's instance. Return <code>null</code> if extension is not found or is not initialized. Pls. note * that this method will not trigger extension load. * <p> * In order to trigger extension load, call {@link #getExtension(String)} instead. * * @see #getExtension(String) */ @SuppressWarnings("unchecked") public T getLoadedExtension(String name) { checkDestroyed(); if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("Extension name == null"); } Holder<Object> holder = getOrCreateHolder(name); return (T) holder.get(); } private Holder<Object> getOrCreateHolder(String name) { Holder<Object> holder = cachedInstances.get(name); if (holder == null) { cachedInstances.putIfAbsent(name, new Holder<>()); holder = cachedInstances.get(name); } return holder; } /** * Return the list of extensions which are already loaded. * <p> * Usually {@link #getSupportedExtensions()} should be called in order to get all extensions. * * @see #getSupportedExtensions() */ public Set<String> getLoadedExtensions() { return Collections.unmodifiableSet(new TreeSet<>(cachedInstances.keySet())); } @SuppressWarnings("unchecked") public List<T> getLoadedExtensionInstances() { checkDestroyed(); List<T> instances = new ArrayList<>(); cachedInstances.values().forEach(holder -> instances.add((T) holder.get())); return instances; } /** * Find the extension with the given name. * * @throws IllegalStateException If the specified extension is not found. */ public T getExtension(String name) { T extension = getExtension(name, true); if (extension == null) { throw new IllegalArgumentException("Not find extension: " + name); } return extension; } @SuppressWarnings("unchecked") public T getExtension(String name, boolean wrap) { checkDestroyed(); if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("Extension name == null"); } if ("true".equals(name)) { return getDefaultExtension(); } String cacheKey = name; if (!wrap) { cacheKey += "_origin"; } final Holder<Object> holder = getOrCreateHolder(cacheKey); Object instance = holder.get(); if (instance == null) { synchronized (holder) { instance = holder.get(); if (instance == null) { instance = createExtension(name, wrap); holder.set(instance); } } } return (T) instance; } /** * Get the extension by specified name if found, or {@link #getDefaultExtension() returns the default one} * * @param name the name of extension * @return non-null */ public T getOrDefaultExtension(String name) { return containsExtension(name) ? getExtension(name) : getDefaultExtension(); } /** * Return default extension, return <code>null</code> if it's not configured. */ public T getDefaultExtension() { getExtensionClasses(); if (StringUtils.isBlank(cachedDefaultName) || "true".equals(cachedDefaultName)) { return null; } return getExtension(cachedDefaultName); } public boolean hasExtension(String name) { checkDestroyed(); if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("Extension name == null"); } Class<?> c = this.getExtensionClass(name); return c != null; } public Set<String> getSupportedExtensions() { checkDestroyed(); Map<String, Class<?>> classes = getExtensionClasses(); return Collections.unmodifiableSet(new TreeSet<>(classes.keySet())); } public Set<T> getSupportedExtensionInstances() { checkDestroyed(); List<T> instances = new LinkedList<>(); Set<String> supportedExtensions = getSupportedExtensions(); if (CollectionUtils.isNotEmpty(supportedExtensions)) { for (String name : supportedExtensions) { instances.add(getExtension(name)); } } // sort the Prioritized instances instances.sort(Prioritized.COMPARATOR); return new LinkedHashSet<>(instances); } /** * Return default extension name, return <code>null</code> if not configured. */ public String getDefaultExtensionName() { getExtensionClasses(); return cachedDefaultName; } /** * Register new extension via API * * @param name extension name * @param clazz extension class * @throws IllegalStateException when extension with the same name has already been registered. */ public void addExtension(String name, Class<?> clazz) { checkDestroyed(); getExtensionClasses(); // load classes if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Input type " + clazz + " doesn't implement the Extension " + type); } if (clazz.isInterface()) { throw new IllegalStateException("Input type " + clazz + " can't be interface!"); } if (!clazz.isAnnotationPresent(Adaptive.class)) { if (StringUtils.isBlank(name)) { throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); } if (cachedClasses.get().containsKey(name)) { throw new IllegalStateException("Extension name " + name + " already exists (Extension " + type + ")!"); } cachedNames.put(clazz, name); cachedClasses.get().put(name, clazz); } else { if (cachedAdaptiveClass != null) { throw new IllegalStateException("Adaptive Extension already exists (Extension " + type + ")!"); } cachedAdaptiveClass = clazz; } } /** * Replace the existing extension via API * * @param name extension name * @param clazz extension class * @throws IllegalStateException when extension to be placed doesn't exist * @deprecated not recommended any longer, and use only when test */ @Deprecated public void replaceExtension(String name, Class<?> clazz) { checkDestroyed(); getExtensionClasses(); // load classes if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Input type " + clazz + " doesn't implement Extension " + type); } if (clazz.isInterface()) { throw new IllegalStateException("Input type " + clazz + " can't be interface!"); } if (!clazz.isAnnotationPresent(Adaptive.class)) { if (StringUtils.isBlank(name)) { throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); } if (!cachedClasses.get().containsKey(name)) { throw new IllegalStateException("Extension name " + name + " doesn't exist (Extension " + type + ")!"); } cachedNames.put(clazz, name); cachedClasses.get().put(name, clazz); cachedInstances.remove(name); } else { if (cachedAdaptiveClass == null) { throw new IllegalStateException("Adaptive Extension doesn't exist (Extension " + type + ")!"); } cachedAdaptiveClass = clazz; cachedAdaptiveInstance.set(null); } } @SuppressWarnings("unchecked") public T getAdaptiveExtension() { checkDestroyed(); Object instance = cachedAdaptiveInstance.get(); if (instance == null) { if (createAdaptiveInstanceError != null) { throw new IllegalStateException( "Failed to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError); } synchronized (cachedAdaptiveInstance) { instance = cachedAdaptiveInstance.get(); if (instance == null) { try { instance = createAdaptiveExtension(); cachedAdaptiveInstance.set(instance); } catch (Throwable t) { createAdaptiveInstanceError = t; throw new IllegalStateException("Failed to create adaptive instance: " + t.toString(), t); } } } } return (T) instance; } private IllegalStateException findException(String name) { StringBuilder buf = new StringBuilder("No such extension " + type.getName() + " by name " + name); int i = 1; for (Map.Entry<String, IllegalStateException> entry : exceptions.entrySet()) { if (entry.getKey().toLowerCase().startsWith(name.toLowerCase())) { if (i == 1) { buf.append(", possible causes: "); } buf.append("\r\n("); buf.append(i++); buf.append(") "); buf.append(entry.getKey()); buf.append(":\r\n"); buf.append(StringUtils.toString(entry.getValue())); } } if (i == 1) { buf.append(", no related exception was found, please check whether related SPI module is missing."); } return new IllegalStateException(buf.toString()); } @SuppressWarnings("unchecked") private T createExtension(String name, boolean wrap) { Class<?> clazz = getExtensionClasses().get(name); if (clazz == null || unacceptableExceptions.contains(name)) { throw findException(name); } try { T instance = (T) extensionInstances.get(clazz); if (instance == null) { extensionInstances.putIfAbsent(clazz, createExtensionInstance(clazz)); instance = (T) extensionInstances.get(clazz); instance = postProcessBeforeInitialization(instance, name); injectExtension(instance); instance = postProcessAfterInitialization(instance, name); } if (wrap) { List<Class<?>> wrapperClassesList = new ArrayList<>(); if (cachedWrapperClasses != null) { wrapperClassesList.addAll(cachedWrapperClasses); wrapperClassesList.sort(WrapperComparator.COMPARATOR); Collections.reverse(wrapperClassesList); } if (CollectionUtils.isNotEmpty(wrapperClassesList)) { for (Class<?> wrapperClass : wrapperClassesList) { Wrapper wrapper = wrapperClass.getAnnotation(Wrapper.class); boolean match = (wrapper == null) || ((ArrayUtils.isEmpty(wrapper.matches()) || ArrayUtils.contains(wrapper.matches(), name)) && !ArrayUtils.contains(wrapper.mismatches(), name)); if (match) { instance = injectExtension( (T) wrapperClass.getConstructor(type).newInstance(instance)); instance = postProcessAfterInitialization(instance, name); } } } } // Warning: After an instance of Lifecycle is wrapped by cachedWrapperClasses, it may not still be Lifecycle // instance, this application may not invoke the lifecycle.initialize hook. initExtension(instance); return instance; } catch (Throwable t) { throw new IllegalStateException( "Extension instance (name: " + name + ", class: " + type + ") couldn't be instantiated: " + t.getMessage(), t); } } private Object createExtensionInstance(Class<?> type) throws ReflectiveOperationException { return instantiationStrategy.instantiate(type); } @SuppressWarnings("unchecked") private T postProcessBeforeInitialization(T instance, String name) throws Exception { if (extensionPostProcessors != null) { for (ExtensionPostProcessor processor : extensionPostProcessors) { instance = (T) processor.postProcessBeforeInitialization(instance, name); } } return instance; } @SuppressWarnings("unchecked") private T postProcessAfterInitialization(T instance, String name) throws Exception { if (instance instanceof ExtensionAccessorAware) { ((ExtensionAccessorAware) instance).setExtensionAccessor(extensionDirector); } if (extensionPostProcessors != null) { for (ExtensionPostProcessor processor : extensionPostProcessors) { instance = (T) processor.postProcessAfterInitialization(instance, name); } } return instance; } private boolean containsExtension(String name) { return getExtensionClasses().containsKey(name); } private T injectExtension(T instance) { if (injector == null) { return instance; } try { for (Method method : instance.getClass().getMethods()) { if (!isSetter(method)) { continue; } /** * Check {@link DisableInject} to see if we need auto-injection for this property */ if (method.isAnnotationPresent(DisableInject.class)) { continue; } // When spiXXX implements ScopeModelAware, ExtensionAccessorAware, // the setXXX of ScopeModelAware and ExtensionAccessorAware does not need to be injected if (method.getDeclaringClass() == ScopeModelAware.class) { continue; } if (instance instanceof ScopeModelAware || instance instanceof ExtensionAccessorAware) { if (ignoredInjectMethodsDesc.contains(ReflectUtils.getDesc(method))) { continue; } } Class<?> pt = method.getParameterTypes()[0]; if (ReflectUtils.isPrimitives(pt)) { continue; } try { String property = getSetterProperty(method); Object object = injector.getInstance(pt, property); if (object != null) { method.invoke(instance, object); } } catch (Exception e) { logger.error( COMMON_ERROR_LOAD_EXTENSION, "", "", "Failed to inject via method " + method.getName() + " of interface " + type.getName() + ": " + e.getMessage(), e); } } } catch (Exception e) { logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", e.getMessage(), e); } return instance; } private void initExtension(T instance) { if (instance instanceof Lifecycle) { Lifecycle lifecycle = (Lifecycle) instance; lifecycle.initialize(); } } /** * get properties name for setter, for instance: setVersion, return "version" * <p> * return "", if setter name with length less than 3 */ private String getSetterProperty(Method method) { return method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : ""; } /** * return true if and only if: * <p> * 1, public * <p> * 2, name starts with "set" * <p> * 3, only has one parameter */ private boolean isSetter(Method method) { return method.getName().startsWith("set") && method.getParameterTypes().length == 1 && Modifier.isPublic(method.getModifiers()); } private Class<?> getExtensionClass(String name) { if (type == null) { throw new IllegalArgumentException("Extension type == null"); } if (name == null) { throw new IllegalArgumentException("Extension name == null"); } return getExtensionClasses().get(name); } private Map<String, Class<?>> getExtensionClasses() { Map<String, Class<?>> classes = cachedClasses.get(); if (classes == null) { synchronized (cachedClasses) { classes = cachedClasses.get(); if (classes == null) { try { classes = loadExtensionClasses(); } catch (InterruptedException e) { logger.error( COMMON_ERROR_LOAD_EXTENSION, "", "", "Exception occurred when loading extension class (interface: " + type + ")", e); throw new IllegalStateException( "Exception occurred when loading extension class (interface: " + type + ")", e); } cachedClasses.set(classes); } } } return classes; } /** * synchronized in getExtensionClasses */ @SuppressWarnings("deprecation") private Map<String, Class<?>> loadExtensionClasses() throws InterruptedException { checkDestroyed(); cacheDefaultExtensionName(); Map<String, Class<?>> extensionClasses = new HashMap<>(); for (LoadingStrategy strategy : strategies) { loadDirectory(extensionClasses, strategy, type.getName()); // compatible with old ExtensionFactory if (this.type == ExtensionInjector.class) { loadDirectory(extensionClasses, strategy, ExtensionFactory.class.getName()); } } return extensionClasses; } private void loadDirectory(Map<String, Class<?>> extensionClasses, LoadingStrategy strategy, String type) throws InterruptedException { loadDirectoryInternal(extensionClasses, strategy, type); if (Dubbo2CompactUtils.isEnabled()) { try { String oldType = type.replace("org.apache", "com.alibaba"); if (oldType.equals(type)) { return; } // if class not found,skip try to load resources ClassUtils.forName(oldType); loadDirectoryInternal(extensionClasses, strategy, oldType); } catch (ClassNotFoundException classNotFoundException) { } } } /** * extract and cache default extension name if exists */ private void cacheDefaultExtensionName() { final SPI defaultAnnotation = type.getAnnotation(SPI.class); if (defaultAnnotation == null) { return; } String value = defaultAnnotation.value(); if ((value = value.trim()).length() > 0) { String[] names = NAME_SEPARATOR.split(value); if (names.length > 1) { throw new IllegalStateException("More than 1 default extension name on extension " + type.getName() + ": " + Arrays.toString(names)); } if (names.length == 1) { cachedDefaultName = names[0]; } } } private void loadDirectoryInternal( Map<String, Class<?>> extensionClasses, LoadingStrategy loadingStrategy, String type) throws InterruptedException { String fileName = loadingStrategy.directory() + type; try { List<ClassLoader> classLoadersToLoad = new LinkedList<>(); // try to load from ExtensionLoader's ClassLoader first if (loadingStrategy.preferExtensionClassLoader()) { ClassLoader extensionLoaderClassLoader = ExtensionLoader.class.getClassLoader(); if (ClassLoader.getSystemClassLoader() != extensionLoaderClassLoader) { classLoadersToLoad.add(extensionLoaderClassLoader); } } if (specialSPILoadingStrategyMap.containsKey(type)) { String internalDirectoryType = specialSPILoadingStrategyMap.get(type); // skip to load spi when name don't match if (!LoadingStrategy.ALL.equals(internalDirectoryType) && !internalDirectoryType.equals(loadingStrategy.getName())) { return; } classLoadersToLoad.clear(); classLoadersToLoad.add(ExtensionLoader.class.getClassLoader()); } else { // load from scope model Set<ClassLoader> classLoaders = scopeModel.getClassLoaders(); if (CollectionUtils.isEmpty(classLoaders)) { Enumeration<java.net.URL> resources = ClassLoader.getSystemResources(fileName); if (resources != null) { while (resources.hasMoreElements()) { loadResource( extensionClasses, null, resources.nextElement(), loadingStrategy.overridden(), loadingStrategy.includedPackages(), loadingStrategy.excludedPackages(), loadingStrategy.onlyExtensionClassLoaderPackages()); } } } else { classLoadersToLoad.addAll(classLoaders); } } Map<ClassLoader, Set<java.net.URL>> resources = ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad); resources.forEach(((classLoader, urls) -> { loadFromClass( extensionClasses, loadingStrategy.overridden(), urls, classLoader, loadingStrategy.includedPackages(), loadingStrategy.excludedPackages(), loadingStrategy.onlyExtensionClassLoaderPackages()); })); } catch (InterruptedException e) { throw e; } catch (Throwable t) { logger.error( COMMON_ERROR_LOAD_EXTENSION, "", "", "Exception occurred when loading extension class (interface: " + type + ", description file: " + fileName + ").", t); } } private void loadFromClass( Map<String, Class<?>> extensionClasses, boolean overridden, Set<java.net.URL> urls, ClassLoader classLoader, String[] includedPackages, String[] excludedPackages, String[] onlyExtensionClassLoaderPackages) { if (CollectionUtils.isNotEmpty(urls)) { for (java.net.URL url : urls) { loadResource( extensionClasses, classLoader, url, overridden, includedPackages, excludedPackages, onlyExtensionClassLoaderPackages); } } } private void loadResource( Map<String, Class<?>> extensionClasses, ClassLoader classLoader, java.net.URL resourceURL, boolean overridden, String[] includedPackages, String[] excludedPackages, String[] onlyExtensionClassLoaderPackages) { try { List<String> newContentList = getResourceContent(resourceURL); String clazz; for (String line : newContentList) { try { String name = null; int i = line.indexOf('='); if (i > 0) { name = line.substring(0, i).trim(); clazz = line.substring(i + 1).trim(); } else { clazz = line; } if (StringUtils.isNotEmpty(clazz) && !isExcluded(clazz, excludedPackages) && isIncluded(clazz, includedPackages) && !isExcludedByClassLoader(clazz, classLoader, onlyExtensionClassLoaderPackages)) { loadClass( classLoader, extensionClasses, resourceURL, Class.forName(clazz, true, classLoader), name, overridden); } } catch (Throwable t) { IllegalStateException e = new IllegalStateException( "Failed to load extension class (interface: " + type + ", class line: " + line + ") in " + resourceURL + ", cause: " + t.getMessage(), t); exceptions.put(line, e); } } } catch (Throwable t) { logger.error( COMMON_ERROR_LOAD_EXTENSION, "", "", "Exception occurred when loading extension class (interface: " + type + ", class file: " + resourceURL + ") in " + resourceURL, t); } } private List<String> getResourceContent(java.net.URL resourceURL) throws IOException { Map<java.net.URL, List<String>> urlListMap = urlListMapCache.get(); if (urlListMap == null) { synchronized (ExtensionLoader.class) { if ((urlListMap = urlListMapCache.get()) == null) { urlListMap = new ConcurrentHashMap<>(); urlListMapCache = new SoftReference<>(urlListMap); } } } List<String> contentList = urlListMap.computeIfAbsent(resourceURL, key -> { List<String> newContentList = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { final int ci = line.indexOf('#'); if (ci >= 0) { line = line.substring(0, ci); } line = line.trim(); if (line.length() > 0) { newContentList.add(line); } } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } return newContentList; }); return contentList; } private boolean isIncluded(String className, String... includedPackages) { if (includedPackages != null && includedPackages.length > 0) { for (String includedPackage : includedPackages) { if (className.startsWith(includedPackage + ".")) { // one match, return true return true; } } // none matcher match, return false return false; } // matcher is empty, return true return true; } private boolean isExcluded(String className, String... excludedPackages) { if (excludedPackages != null) { for (String excludePackage : excludedPackages) { if (className.startsWith(excludePackage + ".")) { return true; } } } return false; } private boolean isExcludedByClassLoader( String className, ClassLoader classLoader, String... onlyExtensionClassLoaderPackages) { if (onlyExtensionClassLoaderPackages != null) { for (String excludePackage : onlyExtensionClassLoaderPackages) { if (className.startsWith(excludePackage + ".")) { // if target classLoader is not ExtensionLoader's classLoader should be excluded return !Objects.equals(ExtensionLoader.class.getClassLoader(), classLoader); } } } return false; } private void loadClass( ClassLoader classLoader, Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name, boolean overridden) { if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException( "Error occurred when loading extension class (interface: " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + " is not subtype of interface."); } boolean isActive = loadClassIfActive(classLoader, clazz); if (!isActive) { return; } if (clazz.isAnnotationPresent(Adaptive.class)) { cacheAdaptiveClass(clazz, overridden); } else if (isWrapperClass(clazz)) { cacheWrapperClass(clazz); } else { if (StringUtils.isEmpty(name)) { name = findAnnotationName(clazz); if (name.length() == 0) { throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + resourceURL); } } String[] names = NAME_SEPARATOR.split(name); if (ArrayUtils.isNotEmpty(names)) { cacheActivateClass(clazz, names[0]); for (String n : names) { cacheName(clazz, n); saveInExtensionClass(extensionClasses, clazz, n, overridden); } } } } private boolean loadClassIfActive(ClassLoader classLoader, Class<?> clazz) { Activate activate = clazz.getAnnotation(Activate.class); if (activate == null) { return true; } String[] onClass = null; if (activate instanceof Activate) { onClass = ((Activate) activate).onClass(); } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && Dubbo2ActivateUtils.getActivateClass().isAssignableFrom(activate.getClass())) { onClass = Dubbo2ActivateUtils.getOnClass(activate); } boolean isActive = true; if (null != onClass && onClass.length > 0) { isActive = Arrays.stream(onClass) .filter(StringUtils::isNotBlank) .allMatch(className -> ClassUtils.isPresent(className, classLoader)); } return isActive; } /** * cache name */ private void cacheName(Class<?> clazz, String name) { if (!cachedNames.containsKey(clazz)) { cachedNames.put(clazz, name); } } /** * put clazz in extensionClasses */ private void saveInExtensionClass( Map<String, Class<?>> extensionClasses, Class<?> clazz, String name, boolean overridden) { Class<?> c = extensionClasses.get(name); if (c == null || overridden) { extensionClasses.put(name, clazz); } else if (c != clazz) { // duplicate implementation is unacceptable unacceptableExceptions.add(name); String duplicateMsg = "Duplicate extension " + type.getName() + " name " + name + " on " + c.getName() + " and " + clazz.getName(); logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", duplicateMsg); throw new IllegalStateException(duplicateMsg); } } /** * cache Activate class which is annotated with <code>Activate</code> * <p> * for compatibility, also cache class with old alibaba Activate annotation */ @SuppressWarnings("deprecation") private void cacheActivateClass(Class<?> clazz, String name) { Activate activate = clazz.getAnnotation(Activate.class); if (activate != null) { cachedActivates.put(name, activate); } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded()) { // support com.alibaba.dubbo.common.extension.Activate Annotation oldActivate = clazz.getAnnotation(Dubbo2ActivateUtils.getActivateClass()); if (oldActivate != null) { cachedActivates.put(name, oldActivate); } } } /** * cache Adaptive class which is annotated with <code>Adaptive</code> */ private void cacheAdaptiveClass(Class<?> clazz, boolean overridden) { if (cachedAdaptiveClass == null || overridden) { cachedAdaptiveClass = clazz; } else if (!cachedAdaptiveClass.equals(clazz)) { throw new IllegalStateException( "More than 1 adaptive class found: " + cachedAdaptiveClass.getName() + ", " + clazz.getName()); } } /** * cache wrapper class * <p> * like: ProtocolFilterWrapper, ProtocolListenerWrapper */ private void cacheWrapperClass(Class<?> clazz) { if (cachedWrapperClasses == null) { cachedWrapperClasses = new ConcurrentHashSet<>(); } cachedWrapperClasses.add(clazz); } /** * test if clazz is a wrapper class * <p> * which has Constructor with given class type as its only argument */ protected boolean isWrapperClass(Class<?> clazz) { Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0] == type) { return true; } } return false; } @SuppressWarnings("deprecation") private String findAnnotationName(Class<?> clazz) { Extension extension = clazz.getAnnotation(Extension.class); if (extension != null) { return extension.value(); } String name = clazz.getSimpleName(); if (name.endsWith(type.getSimpleName())) { name = name.substring(0, name.length() - type.getSimpleName().length()); } return name.toLowerCase(); } @SuppressWarnings("unchecked") private T createAdaptiveExtension() { try { T instance = (T) getAdaptiveExtensionClass().newInstance(); instance = postProcessBeforeInitialization(instance, null); injectExtension(instance); instance = postProcessAfterInitialization(instance, null); initExtension(instance); return instance; } catch (Exception e) { throw new IllegalStateException( "Can't create adaptive extension " + type + ", cause: " + e.getMessage(), e); } } private Class<?> getAdaptiveExtensionClass() { getExtensionClasses(); if (cachedAdaptiveClass != null) { return cachedAdaptiveClass; } return cachedAdaptiveClass = createAdaptiveExtensionClass(); } private Class<?> createAdaptiveExtensionClass() { // Adaptive Classes' ClassLoader should be the same with Real SPI interface classes' ClassLoader ClassLoader classLoader = type.getClassLoader(); try { if (NativeUtils.isNative()) { return classLoader.loadClass(type.getName() + "$Adaptive"); } } catch (Throwable ignore) { } String code = new AdaptiveClassCodeGenerator(type, cachedDefaultName).generate(); org.apache.dubbo.common.compiler.Compiler compiler = extensionDirector .getExtensionLoader(org.apache.dubbo.common.compiler.Compiler.class) .getAdaptiveExtension(); return compiler.compile(type, code, classLoader); } @Override public String toString() { return this.getClass().getName() + "[" + type.getName() + "]"; } private static Properties loadProperties(ClassLoader classLoader, String resourceName) { Properties properties = new Properties(); if (classLoader != null) { try { Enumeration<java.net.URL> resources = classLoader.getResources(resourceName); while (resources.hasMoreElements()) { java.net.URL url = resources.nextElement(); Properties props = loadFromUrl(url); for (Map.Entry<Object, Object> entry : props.entrySet()) { String key = entry.getKey().toString(); if (properties.containsKey(key)) { continue; } properties.put(key, entry.getValue().toString()); } } } catch (IOException ex) { logger.error(CONFIG_FAILED_LOAD_ENV_VARIABLE, "", "", "load properties failed.", ex); } } return properties; } private static Properties loadFromUrl(java.net.URL url) { Properties properties = new Properties(); InputStream is = null; try { is = url.openStream(); properties.load(is); } catch (IOException e) { // ignore } finally { if (is != null) { try { is.close(); } catch (IOException e) { // ignore } } } return properties; } }
6,755
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionDirector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; /** * ExtensionDirector is a scoped extension loader manager. * * <p></p> * <p>ExtensionDirector supports multiple levels, and the child can inherit the parent's extension instances. </p> * <p>The way to find and create an extension instance is similar to Java classloader.</p> */ public class ExtensionDirector implements ExtensionAccessor { private final ConcurrentMap<Class<?>, ExtensionLoader<?>> extensionLoadersMap = new ConcurrentHashMap<>(64); private final ConcurrentMap<Class<?>, ExtensionScope> extensionScopeMap = new ConcurrentHashMap<>(64); private final ExtensionDirector parent; private final ExtensionScope scope; private final List<ExtensionPostProcessor> extensionPostProcessors = new ArrayList<>(); private final ScopeModel scopeModel; private final AtomicBoolean destroyed = new AtomicBoolean(); public ExtensionDirector(ExtensionDirector parent, ExtensionScope scope, ScopeModel scopeModel) { this.parent = parent; this.scope = scope; this.scopeModel = scopeModel; } public void addExtensionPostProcessor(ExtensionPostProcessor processor) { if (!this.extensionPostProcessors.contains(processor)) { this.extensionPostProcessors.add(processor); } } public List<ExtensionPostProcessor> getExtensionPostProcessors() { return extensionPostProcessors; } @Override public ExtensionDirector getExtensionDirector() { return this; } @Override @SuppressWarnings("unchecked") public <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) { checkDestroyed(); if (type == null) { throw new IllegalArgumentException("Extension type == null"); } if (!type.isInterface()) { throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!"); } if (!withExtensionAnnotation(type)) { throw new IllegalArgumentException("Extension type (" + type + ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!"); } // 1. find in local cache ExtensionLoader<T> loader = (ExtensionLoader<T>) extensionLoadersMap.get(type); ExtensionScope scope = extensionScopeMap.get(type); if (scope == null) { SPI annotation = type.getAnnotation(SPI.class); scope = annotation.scope(); extensionScopeMap.put(type, scope); } if (loader == null && scope == ExtensionScope.SELF) { // create an instance in self scope loader = createExtensionLoader0(type); } // 2. find in parent if (loader == null) { if (this.parent != null) { loader = this.parent.getExtensionLoader(type); } } // 3. create it if (loader == null) { loader = createExtensionLoader(type); } return loader; } private <T> ExtensionLoader<T> createExtensionLoader(Class<T> type) { ExtensionLoader<T> loader = null; if (isScopeMatched(type)) { // if scope is matched, just create it loader = createExtensionLoader0(type); } return loader; } @SuppressWarnings("unchecked") private <T> ExtensionLoader<T> createExtensionLoader0(Class<T> type) { checkDestroyed(); ExtensionLoader<T> loader; extensionLoadersMap.putIfAbsent(type, new ExtensionLoader<T>(type, this, scopeModel)); loader = (ExtensionLoader<T>) extensionLoadersMap.get(type); return loader; } private boolean isScopeMatched(Class<?> type) { final SPI defaultAnnotation = type.getAnnotation(SPI.class); return defaultAnnotation.scope().equals(scope); } private static boolean withExtensionAnnotation(Class<?> type) { return type.isAnnotationPresent(SPI.class); } public ExtensionDirector getParent() { return parent; } public void removeAllCachedLoader() {} public void destroy() { if (destroyed.compareAndSet(false, true)) { for (ExtensionLoader<?> extensionLoader : extensionLoadersMap.values()) { extensionLoader.destroy(); } extensionLoadersMap.clear(); extensionScopeMap.clear(); extensionPostProcessors.clear(); } } private void checkDestroyed() { if (destroyed.get()) { throw new IllegalStateException("ExtensionDirector is destroyed"); } } }
6,756
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Activate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import org.apache.dubbo.common.URL; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Activate. This annotation is useful for automatically activate certain extensions with the given criteria, * for examples: <code>@Activate</code> can be used to load certain <code>Filter</code> extension when there are * multiple implementations. * <ol> * <li>{@link Activate#group()} specifies group criteria. Framework SPI defines the valid group values. * <li>{@link Activate#value()} specifies parameter key in {@link URL} criteria. * </ol> * SPI provider can call {@link ExtensionLoader#getActivateExtension(URL, String, String)} to find out all activated * extensions with the given criteria. * * @see SPI * @see URL * @see ExtensionLoader */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Activate { /** * Activate the current extension when one of the groups matches. The group passed into * {@link ExtensionLoader#getActivateExtension(URL, String, String)} will be used for matching. * * @return group names to match * @see ExtensionLoader#getActivateExtension(URL, String, String) */ String[] group() default {}; /** * Activate the current extension when the specified keys appear in the URL's parameters. * <p> * For example, given <code>@Activate("cache, validation")</code>, the current extension will be return only when * there's either <code>cache</code> or <code>validation</code> key appeared in the URL's parameters. * </p> * * @return URL parameter keys * @see ExtensionLoader#getActivateExtension(URL, String) * @see ExtensionLoader#getActivateExtension(URL, String, String) */ String[] value() default {}; /** * Relative ordering info, optional * Deprecated since 2.7.0 * * @return extension list which should be put before the current one */ @Deprecated String[] before() default {}; /** * Relative ordering info, optional * Deprecated since 2.7.0 * * @return extension list which should be put after the current one */ @Deprecated String[] after() default {}; /** * Absolute ordering info, optional * * Ascending order, smaller values will be in the front o the list. * * @return absolute ordering info */ int order() default 0; /** * Activate loadClass when the current extension when the specified className all match * @return className names to all match */ String[] onClass() default {}; }
6,757
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Adaptive.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension; import org.apache.dubbo.common.URL; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Provide helpful information for {@link ExtensionLoader} to inject dependency extension instance. * * @see ExtensionLoader * @see URL */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Adaptive { /** * Decide which target extension to be injected. The name of the target extension is decided by the parameter passed * in the URL, and the parameter names are given by this method. * <p> * If the specified parameters are not found from {@link URL}, then the default extension will be used for * dependency injection (specified in its interface's {@link SPI}). * <p> * For example, given <code>String[] {"key1", "key2"}</code>: * <ol> * <li>find parameter 'key1' in URL, use its value as the extension's name</li> * <li>try 'key2' for extension's name if 'key1' is not found (or its value is empty) in URL</li> * <li>use default extension if 'key2' doesn't exist either</li> * <li>otherwise, throw {@link IllegalStateException}</li> * </ol> * If the parameter names are empty, then a default parameter name is generated from interface's * class name with the rule: divide classname from capital char into several parts, and separate the parts with * dot '.', for example, for {@code org.apache.dubbo.xxx.YyyInvokerWrapper}, the generated name is * <code>String[] {"yyy.invoker.wrapper"}</code>. * * @return parameter names in URL */ String[] value() default {}; }
6,758
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension.inject; import org.apache.dubbo.common.context.Lifecycle; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionInjector; import org.apache.dubbo.common.extension.ExtensionLoader; import java.util.Collection; import java.util.Collections; import java.util.Objects; import java.util.stream.Collectors; /** * AdaptiveExtensionInjector */ @Adaptive public class AdaptiveExtensionInjector implements ExtensionInjector, Lifecycle { private Collection<ExtensionInjector> injectors = Collections.emptyList(); private ExtensionAccessor extensionAccessor; public AdaptiveExtensionInjector() {} @Override public void setExtensionAccessor(final ExtensionAccessor extensionAccessor) { this.extensionAccessor = extensionAccessor; } @Override public void initialize() throws IllegalStateException { ExtensionLoader<ExtensionInjector> loader = extensionAccessor.getExtensionLoader(ExtensionInjector.class); injectors = loader.getSupportedExtensions().stream() .map(loader::getExtension) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @Override public <T> T getInstance(final Class<T> type, final String name) { return injectors.stream() .map(injector -> injector.getInstance(type, name)) .filter(Objects::nonNull) .findFirst() .orElse(null); } @Override public void start() throws IllegalStateException {} @Override public void destroy() throws IllegalStateException {} }
6,759
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/SpiExtensionInjector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension.inject; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionInjector; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.SPI; /** * SpiExtensionInjector */ public class SpiExtensionInjector implements ExtensionInjector { private ExtensionAccessor extensionAccessor; @Override public void setExtensionAccessor(final ExtensionAccessor extensionAccessor) { this.extensionAccessor = extensionAccessor; } @Override public <T> T getInstance(final Class<T> type, final String name) { if (!type.isInterface() || !type.isAnnotationPresent(SPI.class)) { return null; } ExtensionLoader<T> loader = extensionAccessor.getExtensionLoader(type); if (loader == null) { return null; } if (!loader.getSupportedExtensions().isEmpty()) { return loader.getAdaptiveExtension(); } return null; } }
6,760
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.compact.Dubbo2ActivateUtils; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.Wrapper; import java.lang.annotation.Annotation; import java.util.Comparator; /** * OrderComparator * Derived from {@link ActivateComparator} */ public class WrapperComparator implements Comparator<Object> { public static final Comparator<Object> COMPARATOR = new WrapperComparator(); @Override public int compare(Object o1, Object o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } if (o1.equals(o2)) { return 0; } Class clazz1 = (Class) o1; Class clazz2 = (Class) o2; OrderInfo a1 = parseOrder(clazz1); OrderInfo a2 = parseOrder(clazz2); int n1 = a1.order; int n2 = a2.order; // never return 0 even if n1 equals n2, otherwise, o1 and o2 will override each other in collection like HashSet return n1 > n2 ? 1 : -1; } @SuppressWarnings("deprecation") private OrderInfo parseOrder(Class<?> clazz) { OrderInfo info = new OrderInfo(); if (clazz.isAnnotationPresent(Activate.class)) { // TODO: backward compatibility Activate activate = clazz.getAnnotation(Activate.class); info.order = activate.order(); } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { // TODO: backward compatibility Annotation activate = clazz.getAnnotation(Dubbo2ActivateUtils.getActivateClass()); info.order = Dubbo2ActivateUtils.getOrder(activate); } else if (clazz.isAnnotationPresent(Wrapper.class)) { Wrapper wrapper = clazz.getAnnotation(Wrapper.class); info.order = wrapper.order(); } return info; } private static class OrderInfo { private int order; } }
6,761
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.compact.Dubbo2ActivateUtils; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.ExtensionDirector; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.ArrayUtils; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * OrderComparator */ public class ActivateComparator implements Comparator<Class<?>> { private final List<ExtensionDirector> extensionDirectors; private final Map<Class<?>, ActivateInfo> activateInfoMap = new ConcurrentHashMap<>(); public ActivateComparator(ExtensionDirector extensionDirector) { extensionDirectors = new ArrayList<>(); extensionDirectors.add(extensionDirector); } public ActivateComparator(List<ExtensionDirector> extensionDirectors) { this.extensionDirectors = extensionDirectors; } @Override public int compare(Class o1, Class o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } if (o1.equals(o2)) { return 0; } Class<?> inf = findSpi(o1); ActivateInfo a1 = parseActivate(o1); ActivateInfo a2 = parseActivate(o2); if ((a1.applicableToCompare() || a2.applicableToCompare()) && inf != null) { if (a1.applicableToCompare()) { String n2 = null; for (ExtensionDirector director : extensionDirectors) { ExtensionLoader<?> extensionLoader = director.getExtensionLoader(inf); n2 = extensionLoader.getExtensionName(o2); if (n2 != null) { break; } } if (a1.isLess(n2)) { return -1; } if (a1.isMore(n2)) { return 1; } } if (a2.applicableToCompare()) { String n1 = null; for (ExtensionDirector director : extensionDirectors) { ExtensionLoader<?> extensionLoader = director.getExtensionLoader(inf); n1 = extensionLoader.getExtensionName(o1); if (n1 != null) { break; } } if (a2.isLess(n1)) { return 1; } if (a2.isMore(n1)) { return -1; } } return a1.order > a2.order ? 1 : -1; } // In order to avoid the problem of inconsistency between the loading order of two filters // in different loading scenarios without specifying the order attribute of the filter, // when the order is the same, compare its filterName if (a1.order > a2.order) { return 1; } else if (a1.order == a2.order) { return o1.getSimpleName().compareTo(o2.getSimpleName()) > 0 ? 1 : -1; } else { return -1; } } private Class<?> findSpi(Class<?> clazz) { if (clazz.getInterfaces().length == 0) { return null; } for (Class<?> intf : clazz.getInterfaces()) { if (intf.isAnnotationPresent(SPI.class)) { return intf; } Class<?> result = findSpi(intf); if (result != null) { return result; } } return null; } @SuppressWarnings("deprecation") private ActivateInfo parseActivate(Class<?> clazz) { ActivateInfo info = activateInfoMap.get(clazz); if (info != null) { return info; } info = new ActivateInfo(); if (clazz.isAnnotationPresent(Activate.class)) { Activate activate = clazz.getAnnotation(Activate.class); info.before = activate.before(); info.after = activate.after(); info.order = activate.order(); } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { Annotation activate = clazz.getAnnotation(Dubbo2ActivateUtils.getActivateClass()); info.before = Dubbo2ActivateUtils.getBefore(activate); info.after = Dubbo2ActivateUtils.getAfter(activate); info.order = Dubbo2ActivateUtils.getOrder(activate); } else { info.order = 0; } activateInfoMap.put(clazz, info); return info; } private static class ActivateInfo { private String[] before; private String[] after; private int order; private boolean applicableToCompare() { return ArrayUtils.isNotEmpty(before) || ArrayUtils.isNotEmpty(after); } private boolean isLess(String name) { return Arrays.asList(before).contains(name); } private boolean isMore(String name) { return Arrays.asList(after).contains(name); } } }
6,762
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/ErrorTypeAwareLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger; import org.apache.dubbo.common.constants.LoggerCodeConstants; /** * Logger interface with the ability of displaying solution of different types of error. * * <p> * This logger will log a message like this: * * <blockquote><pre> * ... (original logging message) This may be caused by (... cause), * go to https://dubbo.apache.org/faq/[Cat]/[X] to find instructions. (... extendedInformation) * </pre></blockquote> * * Where "[Cat]/[X]" is the error code ("code" in arguments). The link is clickable, leading user to * the "Error code and its corresponding solutions" page. * * @see LoggerCodeConstants Detailed Format of Error Code and Error Code Constants */ public interface ErrorTypeAwareLogger extends Logger { /** * Logs a message with warn log level. * * @param code error code * @param cause error cause * @param extendedInformation extended information * @param msg log this message */ void warn(String code, String cause, String extendedInformation, String msg); /** * Logs a message with warn log level. * * @param code error code * @param cause error cause * @param extendedInformation extended information * @param msg log this message * @param e log this cause */ void warn(String code, String cause, String extendedInformation, String msg, Throwable e); /** * Logs a message with error log level. * * @param code error code * @param cause error cause * @param extendedInformation extended information * @param msg log this message */ void error(String code, String cause, String extendedInformation, String msg); /** * Logs a message with error log level. * * @param code error code * @param cause error cause * @param extendedInformation extended information * @param msg log this message * @param e log this cause */ void error(String code, String cause, String extendedInformation, String msg, Throwable e); }
6,763
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger; /** * Logger interface * <p> * This interface is referred from commons-logging */ public interface Logger { /** * Logs a message with trace log level. * * @param msg log this message */ void trace(String msg); /** * Logs an error with trace log level. * * @param e log this cause */ void trace(Throwable e); /** * Logs an error with trace log level. * * @param msg log this message * @param e log this cause */ void trace(String msg, Throwable e); /** * Logs a message with debug log level. * * @param msg log this message */ void debug(String msg); /** * Logs an error with debug log level. * * @param e log this cause */ void debug(Throwable e); /** * Logs an error with debug log level. * * @param msg log this message * @param e log this cause */ void debug(String msg, Throwable e); /** * Logs a message with info log level. * * @param msg log this message */ void info(String msg); /** * Logs an error with info log level. * * @param e log this cause */ void info(Throwable e); /** * Logs an error with info log level. * * @param msg log this message * @param e log this cause */ void info(String msg, Throwable e); /** * Logs a message with warn log level. * * @param msg log this message */ void warn(String msg); /** * Logs a message with warn log level. * * @param e log this message */ void warn(Throwable e); /** * Logs a message with warn log level. * * @param msg log this message * @param e log this cause */ void warn(String msg, Throwable e); /** * Logs a message with error log level. * * @param msg log this message */ void error(String msg); /** * Logs an error with error log level. * * @param e log this cause */ void error(Throwable e); /** * Logs an error with error log level. * * @param msg log this message * @param e log this cause */ void error(String msg, Throwable e); /** * Is trace logging currently enabled? * * @return true if trace is enabled */ boolean isTraceEnabled(); /** * Is debug logging currently enabled? * * @return true if debug is enabled */ boolean isDebugEnabled(); /** * Is info logging currently enabled? * * @return true if info is enabled */ boolean isInfoEnabled(); /** * Is warn logging currently enabled? * * @return true if warn is enabled */ boolean isWarnEnabled(); /** * Is error logging currently enabled? * * @return true if error is enabled */ boolean isErrorEnabled(); }
6,764
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.io.File; /** * Logger provider */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface LoggerAdapter { /** * Get a logger * * @param key the returned logger will be named after clazz * @return logger */ Logger getLogger(Class<?> key); /** * Get a logger * * @param key the returned logger will be named after key * @return logger */ Logger getLogger(String key); /** * Get the current logging level * * @return current logging level */ Level getLevel(); /** * Set the current logging level * * @param level logging level */ void setLevel(Level level); /** * Get the current logging file * * @return current logging file */ File getFile(); /** * Set the current logging file * * @param file logging file */ void setFile(File file); /** * Return is the current logger has been configured. * Used to check if logger is available to use. * * @return true if the current logger has been configured */ default boolean isConfigured() { return true; } }
6,765
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LoggerFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger; import org.apache.dubbo.common.logger.jcl.JclLoggerAdapter; import org.apache.dubbo.common.logger.jdk.JdkLoggerAdapter; import org.apache.dubbo.common.logger.log4j.Log4jLoggerAdapter; import org.apache.dubbo.common.logger.log4j2.Log4j2LoggerAdapter; import org.apache.dubbo.common.logger.slf4j.Slf4jLoggerAdapter; import org.apache.dubbo.common.logger.support.FailsafeErrorTypeAwareLogger; import org.apache.dubbo.common.logger.support.FailsafeLogger; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Logger factory */ public class LoggerFactory { private static final ConcurrentMap<String, FailsafeLogger> LOGGERS = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, FailsafeErrorTypeAwareLogger> ERROR_TYPE_AWARE_LOGGERS = new ConcurrentHashMap<>(); private static volatile LoggerAdapter loggerAdapter; // search common-used logging frameworks static { String logger = System.getProperty("dubbo.application.logger", ""); switch (logger) { case Slf4jLoggerAdapter.NAME: setLoggerAdapter(new Slf4jLoggerAdapter()); break; case JclLoggerAdapter.NAME: setLoggerAdapter(new JclLoggerAdapter()); break; case Log4jLoggerAdapter.NAME: setLoggerAdapter(new Log4jLoggerAdapter()); break; case JdkLoggerAdapter.NAME: setLoggerAdapter(new JdkLoggerAdapter()); break; case Log4j2LoggerAdapter.NAME: setLoggerAdapter(new Log4j2LoggerAdapter()); break; default: List<Class<? extends LoggerAdapter>> candidates = Arrays.asList( Log4jLoggerAdapter.class, Slf4jLoggerAdapter.class, Log4j2LoggerAdapter.class, JclLoggerAdapter.class, JdkLoggerAdapter.class); boolean found = false; // try to use the first available adapter for (Class<? extends LoggerAdapter> clazz : candidates) { try { LoggerAdapter loggerAdapter = clazz.getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); if (loggerAdapter.isConfigured()) { setLoggerAdapter(loggerAdapter); found = true; break; } } catch (Exception | LinkageError ignored) { // ignore } } if (found) { break; } System.err.println("Dubbo: Unable to find a proper configured logger to log out."); for (Class<? extends LoggerAdapter> clazz : candidates) { try { LoggerAdapter loggerAdapter = clazz.getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); setLoggerAdapter(loggerAdapter); found = true; break; } catch (Throwable ignored) { // ignore } } if (found) { System.err.println( "Dubbo: Using default logger: " + loggerAdapter.getClass().getName() + ". " + "If you cannot see any log, please configure -Ddubbo.application.logger property to your preferred logging framework."); } else { System.err.println( "Dubbo: Unable to find any available logger adapter to log out. Dubbo logs will be ignored. " + "Please configure -Ddubbo.application.logger property and add corresponding logging library to classpath."); } } } private LoggerFactory() {} public static void setLoggerAdapter(FrameworkModel frameworkModel, String loggerAdapter) { if (loggerAdapter != null && loggerAdapter.length() > 0) { setLoggerAdapter( frameworkModel.getExtensionLoader(LoggerAdapter.class).getExtension(loggerAdapter)); } } /** * Set logger provider * * @param loggerAdapter logger provider */ public static void setLoggerAdapter(LoggerAdapter loggerAdapter) { if (loggerAdapter != null) { if (loggerAdapter == LoggerFactory.loggerAdapter) { return; } loggerAdapter.getLogger(LoggerFactory.class.getName()); LoggerFactory.loggerAdapter = loggerAdapter; for (Map.Entry<String, FailsafeLogger> entry : LOGGERS.entrySet()) { entry.getValue().setLogger(LoggerFactory.loggerAdapter.getLogger(entry.getKey())); } } } /** * Get logger provider * * @param key the returned logger will be named after clazz * @return logger */ public static Logger getLogger(Class<?> key) { return ConcurrentHashMapUtils.computeIfAbsent( LOGGERS, key.getName(), name -> new FailsafeLogger(loggerAdapter.getLogger(name))); } /** * Get logger provider * * @param key the returned logger will be named after key * @return logger provider */ public static Logger getLogger(String key) { return ConcurrentHashMapUtils.computeIfAbsent( LOGGERS, key, k -> new FailsafeLogger(loggerAdapter.getLogger(k))); } /** * Get error type aware logger by Class object. * * @param key the returned logger will be named after clazz * @return error type aware logger */ public static ErrorTypeAwareLogger getErrorTypeAwareLogger(Class<?> key) { return ConcurrentHashMapUtils.computeIfAbsent( ERROR_TYPE_AWARE_LOGGERS, key.getName(), name -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(name))); } /** * Get error type aware logger by a String key. * * @param key the returned logger will be named after key * @return error type aware logger */ public static ErrorTypeAwareLogger getErrorTypeAwareLogger(String key) { return ConcurrentHashMapUtils.computeIfAbsent( ERROR_TYPE_AWARE_LOGGERS, key, k -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(k))); } /** * Get logging level * * @return logging level */ public static Level getLevel() { return loggerAdapter.getLevel(); } /** * Set the current logging level * * @param level logging level */ public static void setLevel(Level level) { loggerAdapter.setLevel(level); } /** * Get the current logging file * * @return current logging file */ public static File getFile() { return loggerAdapter.getFile(); } /** * Get the available adapter names * * @return available adapter names */ public static List<String> getAvailableAdapter() { Map<Class<? extends LoggerAdapter>, String> candidates = new HashMap<>(); candidates.put(Log4jLoggerAdapter.class, "log4j"); candidates.put(Slf4jLoggerAdapter.class, "slf4j"); candidates.put(Log4j2LoggerAdapter.class, "log4j2"); candidates.put(JclLoggerAdapter.class, "jcl"); candidates.put(JdkLoggerAdapter.class, "jdk"); List<String> result = new LinkedList<>(); for (Map.Entry<Class<? extends LoggerAdapter>, String> entry : candidates.entrySet()) { try { LoggerAdapter loggerAdapter = entry.getKey().getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); result.add(entry.getValue()); } catch (Exception ignored) { // ignored } } return result; } /** * Get the current adapter name * * @return current adapter name */ public static String getCurrentAdapter() { Map<Class<? extends LoggerAdapter>, String> candidates = new HashMap<>(); candidates.put(Log4jLoggerAdapter.class, "log4j"); candidates.put(Slf4jLoggerAdapter.class, "slf4j"); candidates.put(Log4j2LoggerAdapter.class, "log4j2"); candidates.put(JclLoggerAdapter.class, "jcl"); candidates.put(JdkLoggerAdapter.class, "jdk"); String name = candidates.get(loggerAdapter.getClass()); if (name == null) { name = loggerAdapter.getClass().getSimpleName(); } return name; } }
6,766
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Level.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger; /** * Level */ public enum Level { /** * ALL */ ALL, /** * TRACE */ TRACE, /** * DEBUG */ DEBUG, /** * INFO */ INFO, /** * WARN */ WARN, /** * ERROR */ ERROR, /** * OFF */ OFF }
6,767
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.jcl; import org.apache.dubbo.common.logger.Logger; import org.apache.commons.logging.Log; /** * Adaptor to commons logging, depends on commons-logging.jar. For more information about commons logging, pls. refer to * <a target="_blank" href="http://www.apache.org/">http://www.apache.org/</a> */ public class JclLogger implements Logger { private final Log logger; public JclLogger(Log logger) { this.logger = logger; } @Override public void trace(String msg) { logger.trace(msg); } @Override public void trace(Throwable e) { logger.trace(e); } @Override public void trace(String msg, Throwable e) { logger.trace(msg, e); } @Override public void debug(String msg) { logger.debug(msg); } @Override public void debug(Throwable e) { logger.debug(e); } @Override public void debug(String msg, Throwable e) { logger.debug(msg, e); } @Override public void info(String msg) { logger.info(msg); } @Override public void info(Throwable e) { logger.info(e); } @Override public void info(String msg, Throwable e) { logger.info(msg, e); } @Override public void warn(String msg) { logger.warn(msg); } @Override public void warn(Throwable e) { logger.warn(e); } @Override public void warn(String msg, Throwable e) { logger.warn(msg, e); } @Override public void error(String msg) { logger.error(msg); } @Override public void error(Throwable e) { logger.error(e); } @Override public void error(String msg, Throwable e) { logger.error(msg, e); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public boolean isErrorEnabled() { return logger.isErrorEnabled(); } }
6,768
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.jcl; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import java.io.File; import org.apache.commons.logging.LogFactory; public class JclLoggerAdapter implements LoggerAdapter { public static final String NAME = "jcl"; private Level level; private File file; @Override public Logger getLogger(String key) { return new JclLogger(LogFactory.getLog(key)); } @Override public Logger getLogger(Class<?> key) { return new JclLogger(LogFactory.getLog(key)); } @Override public Level getLevel() { return level; } @Override public void setLevel(Level level) { this.level = level; } @Override public File getFile() { return file; } @Override public void setFile(File file) { this.file = file; } }
6,769
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.slf4j; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.support.FailsafeLogger; import org.slf4j.spi.LocationAwareLogger; public class Slf4jLogger implements Logger { private static final String FQCN = FailsafeLogger.class.getName(); private final org.slf4j.Logger logger; private final LocationAwareLogger locationAwareLogger; public Slf4jLogger(org.slf4j.Logger logger) { if (logger instanceof LocationAwareLogger) { locationAwareLogger = (LocationAwareLogger) logger; } else { locationAwareLogger = null; } this.logger = logger; } @Override public void trace(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, null); return; } logger.trace(msg); } @Override public void trace(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.TRACE_INT, e.getMessage(), null, e); return; } logger.trace(e.getMessage(), e); } @Override public void trace(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, e); return; } logger.trace(msg, e); } @Override public void debug(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, null); return; } logger.debug(msg); } @Override public void debug(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, e.getMessage(), null, e); return; } logger.debug(e.getMessage(), e); } @Override public void debug(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, e); return; } logger.debug(msg, e); } @Override public void info(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, null); return; } logger.info(msg); } @Override public void info(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.INFO_INT, e.getMessage(), null, e); return; } logger.info(e.getMessage(), e); } @Override public void info(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, e); return; } logger.info(msg, e); } @Override public void warn(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, null); return; } logger.warn(msg); } @Override public void warn(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.WARN_INT, e.getMessage(), null, e); return; } logger.warn(e.getMessage(), e); } @Override public void warn(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, e); return; } logger.warn(msg, e); } @Override public void error(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, null); return; } logger.error(msg); } @Override public void error(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.ERROR_INT, e.getMessage(), null, e); return; } logger.error(e.getMessage(), e); } @Override public void error(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, e); return; } logger.error(msg, e); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public boolean isErrorEnabled() { return logger.isErrorEnabled(); } public static Level getLevel(org.slf4j.Logger logger) { if (logger.isTraceEnabled()) { return Level.TRACE; } if (logger.isDebugEnabled()) { return Level.DEBUG; } if (logger.isInfoEnabled()) { return Level.INFO; } if (logger.isWarnEnabled()) { return Level.WARN; } if (logger.isErrorEnabled()) { return Level.ERROR; } return Level.OFF; } public Level getLevel() { return getLevel(logger); } }
6,770
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.slf4j; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import org.apache.dubbo.common.utils.ClassUtils; import java.io.File; import org.slf4j.LoggerFactory; public class Slf4jLoggerAdapter implements LoggerAdapter { public static final String NAME = "slf4j"; private Level level; private File file; private static final org.slf4j.Logger ROOT_LOGGER = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); public Slf4jLoggerAdapter() { this.level = Slf4jLogger.getLevel(ROOT_LOGGER); } @Override public Logger getLogger(String key) { return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(key)); } @Override public Logger getLogger(Class<?> key) { return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(key)); } @Override public Level getLevel() { return level; } @Override public void setLevel(Level level) { System.err.printf( "The level of slf4j logger current can not be set, using the default level: %s \n", Slf4jLogger.getLevel(ROOT_LOGGER)); this.level = level; } @Override public File getFile() { return file; } @Override public void setFile(File file) { this.file = file; } @Override public boolean isConfigured() { try { ClassUtils.forName("org.slf4j.impl.StaticLoggerBinder"); return true; } catch (ClassNotFoundException ignore) { // ignore } return false; } }
6,771
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j2/Log4j2LoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.log4j2; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.config.Configurator; public class Log4j2LoggerAdapter implements LoggerAdapter { public static final String NAME = "log4j2"; private Level level; public Log4j2LoggerAdapter() { try { org.apache.logging.log4j.Logger logger = LogManager.getRootLogger(); this.level = fromLog4j2Level(logger.getLevel()); } catch (Exception t) { // ignore } } private static org.apache.logging.log4j.Level toLog4j2Level(Level level) { if (level == Level.ALL) { return org.apache.logging.log4j.Level.ALL; } if (level == Level.TRACE) { return org.apache.logging.log4j.Level.TRACE; } if (level == Level.DEBUG) { return org.apache.logging.log4j.Level.DEBUG; } if (level == Level.INFO) { return org.apache.logging.log4j.Level.INFO; } if (level == Level.WARN) { return org.apache.logging.log4j.Level.WARN; } if (level == Level.ERROR) { return org.apache.logging.log4j.Level.ERROR; } return org.apache.logging.log4j.Level.OFF; } private static Level fromLog4j2Level(org.apache.logging.log4j.Level level) { if (level == org.apache.logging.log4j.Level.ALL) { return Level.ALL; } if (level == org.apache.logging.log4j.Level.TRACE) { return Level.TRACE; } if (level == org.apache.logging.log4j.Level.DEBUG) { return Level.DEBUG; } if (level == org.apache.logging.log4j.Level.INFO) { return Level.INFO; } if (level == org.apache.logging.log4j.Level.WARN) { return Level.WARN; } if (level == org.apache.logging.log4j.Level.ERROR) { return Level.ERROR; } return Level.OFF; } @Override public Logger getLogger(Class<?> key) { return new Log4j2Logger(LogManager.getLogger(key)); } @Override public Logger getLogger(String key) { return new Log4j2Logger(LogManager.getLogger(key)); } @Override public Level getLevel() { return level; } @Override public void setLevel(Level level) { this.level = level; Configurator.setLevel(LogManager.getRootLogger(), toLog4j2Level(level)); } @Override public File getFile() { return null; } @Override public void setFile(File file) { // ignore } @Override public boolean isConfigured() { return true; } }
6,772
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j2/Log4j2Logger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.log4j2; import org.apache.dubbo.common.logger.Logger; public class Log4j2Logger implements Logger { private final org.apache.logging.log4j.Logger logger; public Log4j2Logger(org.apache.logging.log4j.Logger logger) { this.logger = logger; } @Override public void trace(String msg) { logger.trace(msg); } @Override public void trace(Throwable e) { logger.trace(e == null ? null : e.getMessage(), e); } @Override public void trace(String msg, Throwable e) { logger.trace(msg, e); } @Override public void debug(String msg) { logger.debug(msg); } @Override public void debug(Throwable e) { logger.debug(e == null ? null : e.getMessage(), e); } @Override public void debug(String msg, Throwable e) { logger.debug(msg, e); } @Override public void info(String msg) { logger.info(msg); } @Override public void info(Throwable e) { logger.info(e == null ? null : e.getMessage(), e); } @Override public void info(String msg, Throwable e) { logger.info(msg, e); } @Override public void warn(String msg) { logger.warn(msg); } @Override public void warn(Throwable e) { logger.warn(e == null ? null : e.getMessage(), e); } @Override public void warn(String msg, Throwable e) { logger.warn(msg, e); } @Override public void error(String msg) { logger.error(msg); } @Override public void error(Throwable e) { logger.error(e == null ? null : e.getMessage(), e); } @Override public void error(String msg, Throwable e) { logger.error(msg, e); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public boolean isErrorEnabled() { return logger.isErrorEnabled(); } }
6,773
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.jdk; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import java.io.File; import java.io.InputStream; import java.lang.reflect.Field; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.LogManager; public class JdkLoggerAdapter implements LoggerAdapter { public static final String NAME = "jdk"; private static final String GLOBAL_LOGGER_NAME = "global"; private File file; private boolean propertiesLoaded = false; public JdkLoggerAdapter() { try { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("logging.properties"); if (in != null) { LogManager.getLogManager().readConfiguration(in); propertiesLoaded = true; } else { System.err.println("No such logging.properties in classpath for jdk logging config!"); } } catch (Exception t) { System.err.println( "Failed to load logging.properties in classpath for jdk logging config, cause: " + t.getMessage()); } try { Handler[] handlers = java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getHandlers(); for (Handler handler : handlers) { if (handler instanceof FileHandler) { FileHandler fileHandler = (FileHandler) handler; Field field = fileHandler.getClass().getField("files"); File[] files = (File[]) field.get(fileHandler); if (files != null && files.length > 0) { file = files[0]; } } } } catch (Exception ignored) { // ignore } } private static java.util.logging.Level toJdkLevel(Level level) { if (level == Level.ALL) { return java.util.logging.Level.ALL; } if (level == Level.TRACE) { return java.util.logging.Level.FINER; } if (level == Level.DEBUG) { return java.util.logging.Level.FINE; } if (level == Level.INFO) { return java.util.logging.Level.INFO; } if (level == Level.WARN) { return java.util.logging.Level.WARNING; } if (level == Level.ERROR) { return java.util.logging.Level.SEVERE; } // if (level == Level.OFF) return java.util.logging.Level.OFF; } private static Level fromJdkLevel(java.util.logging.Level level) { if (level == java.util.logging.Level.ALL) { return Level.ALL; } if (level == java.util.logging.Level.FINER) { return Level.TRACE; } if (level == java.util.logging.Level.FINE) { return Level.DEBUG; } if (level == java.util.logging.Level.INFO) { return Level.INFO; } if (level == java.util.logging.Level.WARNING) { return Level.WARN; } if (level == java.util.logging.Level.SEVERE) { return Level.ERROR; } // if (level == java.util.logging.Level.OFF) return Level.OFF; } @Override public Logger getLogger(Class<?> key) { return new JdkLogger(java.util.logging.Logger.getLogger(key == null ? "" : key.getName())); } @Override public Logger getLogger(String key) { return new JdkLogger(java.util.logging.Logger.getLogger(key)); } @Override public Level getLevel() { return fromJdkLevel( java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getLevel()); } @Override public void setLevel(Level level) { java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).setLevel(toJdkLevel(level)); } @Override public File getFile() { return file; } @Override public void setFile(File file) { // ignore } @Override public boolean isConfigured() { return propertiesLoaded; } }
6,774
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.jdk; import org.apache.dubbo.common.logger.Logger; import java.util.logging.Level; public class JdkLogger implements Logger { private final java.util.logging.Logger logger; public JdkLogger(java.util.logging.Logger logger) { this.logger = logger; } @Override public void trace(String msg) { logger.log(Level.FINER, msg); } @Override public void trace(Throwable e) { logger.log(Level.FINER, e.getMessage(), e); } @Override public void trace(String msg, Throwable e) { logger.log(Level.FINER, msg, e); } @Override public void debug(String msg) { logger.log(Level.FINE, msg); } @Override public void debug(Throwable e) { logger.log(Level.FINE, e.getMessage(), e); } @Override public void debug(String msg, Throwable e) { logger.log(Level.FINE, msg, e); } @Override public void info(String msg) { logger.log(Level.INFO, msg); } @Override public void info(String msg, Throwable e) { logger.log(Level.INFO, msg, e); } @Override public void warn(String msg) { logger.log(Level.WARNING, msg); } @Override public void warn(String msg, Throwable e) { logger.log(Level.WARNING, msg, e); } @Override public void error(String msg) { logger.log(Level.SEVERE, msg); } @Override public void error(String msg, Throwable e) { logger.log(Level.SEVERE, msg, e); } @Override public void error(Throwable e) { logger.log(Level.SEVERE, e.getMessage(), e); } @Override public void info(Throwable e) { logger.log(Level.INFO, e.getMessage(), e); } @Override public void warn(Throwable e) { logger.log(Level.WARNING, e.getMessage(), e); } @Override public boolean isTraceEnabled() { return logger.isLoggable(Level.FINER); } @Override public boolean isDebugEnabled() { return logger.isLoggable(Level.FINE); } @Override public boolean isInfoEnabled() { return logger.isLoggable(Level.INFO); } @Override public boolean isWarnEnabled() { return logger.isLoggable(Level.WARNING); } @Override public boolean isErrorEnabled() { return logger.isLoggable(Level.SEVERE); } }
6,775
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.support; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.utils.NetUtils; public class FailsafeLogger implements Logger { private Logger logger; private static boolean disabled = false; public FailsafeLogger(Logger logger) { this.logger = logger; } public static void setDisabled(boolean disabled) { FailsafeLogger.disabled = disabled; } static boolean getDisabled() { return disabled; } public Logger getLogger() { return logger; } public void setLogger(Logger logger) { this.logger = logger; } private String appendContextMessage(String msg) { return " [DUBBO] " + msg + ", dubbo version: " + Version.getVersion() + ", current host: " + NetUtils.getLocalHost(); } @Override public void trace(String msg, Throwable e) { if (disabled) { return; } try { logger.trace(appendContextMessage(msg), e); } catch (Throwable t) { } } @Override public void trace(Throwable e) { if (disabled) { return; } try { logger.trace(e); } catch (Throwable t) { } } @Override public void trace(String msg) { if (disabled) { return; } try { logger.trace(appendContextMessage(msg)); } catch (Throwable t) { } } @Override public void debug(String msg, Throwable e) { if (disabled) { return; } try { logger.debug(appendContextMessage(msg), e); } catch (Throwable t) { } } @Override public void debug(Throwable e) { if (disabled) { return; } try { logger.debug(e); } catch (Throwable t) { } } @Override public void debug(String msg) { if (disabled) { return; } try { logger.debug(appendContextMessage(msg)); } catch (Throwable t) { } } @Override public void info(String msg, Throwable e) { if (disabled) { return; } try { logger.info(appendContextMessage(msg), e); } catch (Throwable t) { } } @Override public void info(String msg) { if (disabled) { return; } try { logger.info(appendContextMessage(msg)); } catch (Throwable t) { } } @Override public void warn(String msg, Throwable e) { if (disabled) { return; } try { logger.warn(appendContextMessage(msg), e); } catch (Throwable t) { } } @Override public void warn(String msg) { if (disabled) { return; } try { logger.warn(appendContextMessage(msg)); } catch (Throwable t) { } } @Override public void error(String msg, Throwable e) { if (disabled) { return; } try { logger.error(appendContextMessage(msg), e); } catch (Throwable t) { } } @Override public void error(String msg) { if (disabled) { return; } try { logger.error(appendContextMessage(msg)); } catch (Throwable t) { } } @Override public void error(Throwable e) { if (disabled) { return; } try { logger.error(e); } catch (Throwable t) { } } @Override public void info(Throwable e) { if (disabled) { return; } try { logger.info(e); } catch (Throwable t) { } } @Override public void warn(Throwable e) { if (disabled) { return; } try { logger.warn(e); } catch (Throwable t) { } } @Override public boolean isTraceEnabled() { if (disabled) { return false; } try { return logger.isTraceEnabled(); } catch (Throwable t) { return false; } } @Override public boolean isDebugEnabled() { if (disabled) { return false; } try { return logger.isDebugEnabled(); } catch (Throwable t) { return false; } } @Override public boolean isInfoEnabled() { if (disabled) { return false; } try { return logger.isInfoEnabled(); } catch (Throwable t) { return false; } } @Override public boolean isWarnEnabled() { if (disabled) { return false; } try { return logger.isWarnEnabled(); } catch (Throwable t) { return false; } } @Override public boolean isErrorEnabled() { if (disabled) { return false; } try { return logger.isErrorEnabled(); } catch (Throwable t) { return false; } } }
6,776
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.support; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.utils.NetUtils; import java.util.regex.Pattern; /** * A fail-safe (ignoring exception thrown by logger) wrapper of error type aware logger. */ public class FailsafeErrorTypeAwareLogger extends FailsafeLogger implements ErrorTypeAwareLogger { /** * Template address for formatting. */ private static final String INSTRUCTIONS_URL = "https://dubbo.apache.org/faq/%d/%d"; private static final Pattern ERROR_CODE_PATTERN = Pattern.compile("\\d+-\\d+"); public FailsafeErrorTypeAwareLogger(Logger logger) { super(logger); } private String appendContextMessageWithInstructions( String code, String cause, String extendedInformation, String msg) { return " [DUBBO] " + msg + ", dubbo version: " + Version.getVersion() + ", current host: " + NetUtils.getLocalHost() + ", error code: " + code + ". This may be caused by " + cause + ", " + "go to " + getErrorUrl(code) + " to find instructions. " + extendedInformation; } private String getErrorUrl(String code) { String trimmedString = code.trim(); if (!ERROR_CODE_PATTERN.matcher(trimmedString).matches()) { error("Invalid error code: " + code + ", the format of error code is: X-X (where X is a number)."); return ""; } String[] segments = trimmedString.split("[-]"); int[] errorCodeSegments = new int[2]; try { errorCodeSegments[0] = Integer.parseInt(segments[0]); errorCodeSegments[1] = Integer.parseInt(segments[1]); } catch (NumberFormatException numberFormatException) { error( "Invalid error code: " + code + ", the format of error code is: X-X (where X is a number).", numberFormatException); return ""; } return String.format(INSTRUCTIONS_URL, errorCodeSegments[0], errorCodeSegments[1]); } @Override public void warn(String code, String cause, String extendedInformation, String msg) { if (getDisabled()) { return; } try { getLogger().warn(appendContextMessageWithInstructions(code, cause, extendedInformation, msg)); } catch (Throwable t) { // ignored. } } @Override public void warn(String code, String cause, String extendedInformation, String msg, Throwable e) { if (getDisabled()) { return; } try { getLogger().warn(appendContextMessageWithInstructions(code, cause, extendedInformation, msg), e); } catch (Throwable t) { // ignored. } } @Override public void error(String code, String cause, String extendedInformation, String msg) { if (getDisabled()) { return; } try { getLogger().error(appendContextMessageWithInstructions(code, cause, extendedInformation, msg)); } catch (Throwable t) { // ignored. } } @Override public void error(String code, String cause, String extendedInformation, String msg, Throwable e) { if (getDisabled()) { return; } try { getLogger().error(appendContextMessageWithInstructions(code, cause, extendedInformation, msg), e); } catch (Throwable t) { // ignored. } } }
6,777
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.log4j; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import java.io.File; import java.util.Enumeration; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.LogManager; public class Log4jLoggerAdapter implements LoggerAdapter { public static final String NAME = "log4j"; private File file; @SuppressWarnings("unchecked") public Log4jLoggerAdapter() { try { org.apache.log4j.Logger logger = LogManager.getRootLogger(); if (logger != null) { Enumeration<Appender> appenders = logger.getAllAppenders(); if (appenders != null) { while (appenders.hasMoreElements()) { Appender appender = appenders.nextElement(); if (appender instanceof FileAppender) { FileAppender fileAppender = (FileAppender) appender; String filename = fileAppender.getFile(); file = new File(filename); break; } } } } } catch (Exception t) { // ignore } } private static org.apache.log4j.Level toLog4jLevel(Level level) { if (level == Level.ALL) { return org.apache.log4j.Level.ALL; } if (level == Level.TRACE) { return org.apache.log4j.Level.TRACE; } if (level == Level.DEBUG) { return org.apache.log4j.Level.DEBUG; } if (level == Level.INFO) { return org.apache.log4j.Level.INFO; } if (level == Level.WARN) { return org.apache.log4j.Level.WARN; } if (level == Level.ERROR) { return org.apache.log4j.Level.ERROR; } // if (level == Level.OFF) return org.apache.log4j.Level.OFF; } private static Level fromLog4jLevel(org.apache.log4j.Level level) { if (level == org.apache.log4j.Level.ALL) { return Level.ALL; } if (level == org.apache.log4j.Level.TRACE) { return Level.TRACE; } if (level == org.apache.log4j.Level.DEBUG) { return Level.DEBUG; } if (level == org.apache.log4j.Level.INFO) { return Level.INFO; } if (level == org.apache.log4j.Level.WARN) { return Level.WARN; } if (level == org.apache.log4j.Level.ERROR) { return Level.ERROR; } // if (level == org.apache.log4j.Level.OFF) return Level.OFF; } @Override public Logger getLogger(Class<?> key) { return new Log4jLogger(LogManager.getLogger(key)); } @Override public Logger getLogger(String key) { return new Log4jLogger(LogManager.getLogger(key)); } @Override public Level getLevel() { return fromLog4jLevel(LogManager.getRootLogger().getLevel()); } @Override public void setLevel(Level level) { LogManager.getRootLogger().setLevel(toLog4jLevel(level)); } @Override public File getFile() { return file; } @Override public void setFile(File file) { // ignore } @Override public boolean isConfigured() { boolean hasAppender = false; try { org.apache.log4j.Logger logger = LogManager.getRootLogger(); if (logger != null) { Enumeration<Appender> appenders = logger.getAllAppenders(); if (appenders != null) { while (appenders.hasMoreElements()) { hasAppender = true; Appender appender = appenders.nextElement(); if (appender instanceof FileAppender) { FileAppender fileAppender = (FileAppender) appender; String filename = fileAppender.getFile(); file = new File(filename); break; } } } } } catch (Exception t) { // ignore } return hasAppender; } }
6,778
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.logger.log4j; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.support.FailsafeLogger; import org.apache.log4j.Level; public class Log4jLogger implements Logger { private static final String FQCN = FailsafeLogger.class.getName(); private final org.apache.log4j.Logger logger; public Log4jLogger(org.apache.log4j.Logger logger) { this.logger = logger; } @Override public void trace(String msg) { logger.log(FQCN, Level.TRACE, msg, null); } @Override public void trace(Throwable e) { logger.log(FQCN, Level.TRACE, e == null ? null : e.getMessage(), e); } @Override public void trace(String msg, Throwable e) { logger.log(FQCN, Level.TRACE, msg, e); } @Override public void debug(String msg) { logger.log(FQCN, Level.DEBUG, msg, null); } @Override public void debug(Throwable e) { logger.log(FQCN, Level.DEBUG, e == null ? null : e.getMessage(), e); } @Override public void debug(String msg, Throwable e) { logger.log(FQCN, Level.DEBUG, msg, e); } @Override public void info(String msg) { logger.log(FQCN, Level.INFO, msg, null); } @Override public void info(Throwable e) { logger.log(FQCN, Level.INFO, e == null ? null : e.getMessage(), e); } @Override public void info(String msg, Throwable e) { logger.log(FQCN, Level.INFO, msg, e); } @Override public void warn(String msg) { logger.log(FQCN, Level.WARN, msg, null); } @Override public void warn(Throwable e) { logger.log(FQCN, Level.WARN, e == null ? null : e.getMessage(), e); } @Override public void warn(String msg, Throwable e) { logger.log(FQCN, Level.WARN, msg, e); } @Override public void error(String msg) { logger.log(FQCN, Level.ERROR, msg, null); } @Override public void error(Throwable e) { logger.log(FQCN, Level.ERROR, e == null ? null : e.getMessage(), e); } @Override public void error(String msg, Throwable e) { logger.log(FQCN, Level.ERROR, msg, e); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public boolean isWarnEnabled() { return logger.isEnabledFor(Level.WARN); } @Override public boolean isErrorEnabled() { return logger.isEnabledFor(Level.ERROR); } // test purpose only public org.apache.log4j.Logger getLogger() { return logger; } }
6,779
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.cache; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.channels.FileLock; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CACHE_MAX_ENTRY_COUNT_LIMIT_EXCEED; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CACHE_MAX_FILE_SIZE_LIMIT_EXCEED; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CACHE_PATH_INACCESSIBLE; /** * Local file interaction class that can back different caches. * <p> * All items in local file are of human friendly format. */ public class FileCacheStore { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FileCacheStore.class); private final String cacheFilePath; private final File cacheFile; private final File lockFile; private final FileLock directoryLock; private FileCacheStore(String cacheFilePath, File cacheFile, File lockFile, FileLock directoryLock) { this.cacheFilePath = cacheFilePath; this.cacheFile = cacheFile; this.lockFile = lockFile; this.directoryLock = directoryLock; } public synchronized Map<String, String> loadCache(int entrySize) throws IOException { Map<String, String> properties = new HashMap<>(); try (BufferedReader reader = new BufferedReader(new FileReader(cacheFile))) { int count = 1; String line = reader.readLine(); while (line != null && count <= entrySize) { // content has '=' need to be encoded before write if (!line.startsWith("#") && line.contains("=")) { String[] pairs = line.split("="); properties.put(pairs[0], pairs[1]); count++; } line = reader.readLine(); } if (count > entrySize) { logger.warn( COMMON_CACHE_MAX_FILE_SIZE_LIMIT_EXCEED, "mis-configuration of system properties", "Check Java system property 'dubbo.mapping.cache.entrySize' and 'dubbo.meta.cache.entrySize'.", "Cache file was truncated for exceeding the maximum entry size: " + entrySize); } } catch (IOException e) { logger.warn(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Load cache failed ", e); throw e; } return properties; } private void unlock() { if (directoryLock != null && directoryLock.isValid()) { try { directoryLock.release(); directoryLock.channel().close(); deleteFile(lockFile); } catch (IOException e) { logger.error( COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Failed to release cache path's lock file:" + lockFile, e); throw new RuntimeException("Failed to release cache path's lock file:" + lockFile, e); } } } public synchronized void refreshCache(Map<String, String> properties, String comment, long maxFileSize) { if (CollectionUtils.isEmptyMap(properties)) { return; } try (LimitedLengthBufferedWriter bw = new LimitedLengthBufferedWriter( new OutputStreamWriter(new FileOutputStream(cacheFile, false), StandardCharsets.UTF_8), maxFileSize)) { bw.write("#" + comment); bw.newLine(); bw.write("#" + new Date()); bw.newLine(); for (Map.Entry<String, String> e : properties.entrySet()) { String key = e.getKey(); String val = e.getValue(); bw.write(key + "=" + val); bw.newLine(); } bw.flush(); long remainSize = bw.getRemainSize(); if (remainSize < 0) { logger.warn( COMMON_CACHE_MAX_ENTRY_COUNT_LIMIT_EXCEED, "mis-configuration of system properties", "Check Java system property 'dubbo.mapping.cache.maxFileSize' and 'dubbo.meta.cache.maxFileSize'.", "Cache file was truncated for exceeding the maximum file size " + maxFileSize + " byte. Exceeded by " + (-remainSize) + " byte."); } } catch (IOException e) { logger.warn(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Update cache error.", e); } } private static void deleteFile(File f) { Path pathOfFile = f.toPath(); try { Files.delete(pathOfFile); } catch (IOException ioException) { logger.debug("Failed to delete file " + f.getAbsolutePath(), ioException); } } public synchronized void destroy() { unlock(); FileCacheStoreFactory.removeCache(cacheFilePath); } /** * for unit test only */ @Deprecated protected String getCacheFilePath() { return cacheFilePath; } public static Builder newBuilder() { return new Builder(); } public static class Builder { private String cacheFilePath; private File cacheFile; private File lockFile; private FileLock directoryLock; private Builder() {} public Builder cacheFilePath(String cacheFilePath) { this.cacheFilePath = cacheFilePath; return this; } public Builder cacheFile(File cacheFile) { this.cacheFile = cacheFile; return this; } public Builder lockFile(File lockFile) { this.lockFile = lockFile; return this; } public Builder directoryLock(FileLock directoryLock) { this.directoryLock = directoryLock; return this; } public FileCacheStore build() { return new FileCacheStore(cacheFilePath, cacheFile, lockFile, directoryLock); } } /** * An empty (or fallback) implementation of FileCacheStore. Used when cache file creation failed. */ protected static class Empty extends FileCacheStore { private Empty(String cacheFilePath) { super(cacheFilePath, null, null, null); } public static Empty getInstance(String cacheFilePath) { return new Empty(cacheFilePath); } @Override public synchronized Map<String, String> loadCache(int entrySize) throws IOException { return Collections.emptyMap(); } @Override public synchronized void refreshCache(Map<String, String> properties, String comment, long maxFileSize) { // No-op. } } /** * A BufferedWriter which limits the length (in bytes). When limit exceed, this writer stops writing. */ private static class LimitedLengthBufferedWriter extends BufferedWriter { private long remainSize; public LimitedLengthBufferedWriter(Writer out, long maxSize) { super(out); this.remainSize = maxSize == 0 ? Long.MAX_VALUE : maxSize; } @Override public void write(String str) throws IOException { remainSize -= str.getBytes(StandardCharsets.UTF_8).length; if (remainSize < 0) { return; } super.write(str); } public long getRemainSize() { return remainSize; } } }
6,780
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStoreFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.cache; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CACHE_PATH_INACCESSIBLE; /** * ClassLoader Level static share. * Prevent FileCacheStore being operated in multi-application */ public final class FileCacheStoreFactory { /** * Forbids instantiation. */ private FileCacheStoreFactory() { throw new UnsupportedOperationException("No instance of 'FileCacheStoreFactory' for you! "); } private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FileCacheStoreFactory.class); private static final ConcurrentMap<String, FileCacheStore> cacheMap = new ConcurrentHashMap<>(); private static final String SUFFIX = ".dubbo.cache"; private static final char ESCAPE_MARK = '%'; private static final Set<Character> LEGAL_CHARACTERS = Collections.unmodifiableSet(new HashSet<Character>() { { // - $ . _ 0-9 a-z A-Z add('-'); add('$'); add('.'); add('_'); for (char c = '0'; c <= '9'; c++) { add(c); } for (char c = 'a'; c <= 'z'; c++) { add(c); } for (char c = 'A'; c <= 'Z'; c++) { add(c); } } }); public static FileCacheStore getInstance(String basePath, String cacheName) { return getInstance(basePath, cacheName, true); } public static FileCacheStore getInstance(String basePath, String cacheName, boolean enableFileCache) { if (basePath == null) { // default case: ~/.dubbo basePath = System.getProperty("user.home") + File.separator + ".dubbo"; } if (basePath.endsWith(File.separator)) { basePath = basePath.substring(0, basePath.length() - 1); } File candidate = new File(basePath); Path path = candidate.toPath(); // ensure cache store path exists if (!candidate.isDirectory()) { try { Files.createDirectories(path); } catch (IOException e) { // 0-3 - cache path inaccessible logger.error( COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Cache store path can't be created: ", e); throw new RuntimeException("Cache store path can't be created: " + candidate, e); } } cacheName = safeName(cacheName); if (!cacheName.endsWith(SUFFIX)) { cacheName = cacheName + SUFFIX; } String cacheFilePath = basePath + File.separator + cacheName; return ConcurrentHashMapUtils.computeIfAbsent(cacheMap, cacheFilePath, k -> getFile(k, enableFileCache)); } /** * sanitize a name for valid file or directory name * * @param name origin file name * @return sanitized version of name */ private static String safeName(String name) { int len = name.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = name.charAt(i); if (LEGAL_CHARACTERS.contains(c)) { sb.append(c); } else { sb.append(ESCAPE_MARK); sb.append(String.format("%04x", (int) c)); } } return sb.toString(); } /** * Get a file object for the given name * * @param name the file name * @return a file object */ private static FileCacheStore getFile(String name, boolean enableFileCache) { if (!enableFileCache) { return FileCacheStore.Empty.getInstance(name); } try { FileCacheStore.Builder builder = FileCacheStore.newBuilder(); tryFileLock(builder, name); File file = new File(name); if (!file.exists()) { Path pathObjectOfFile = file.toPath(); Files.createFile(pathObjectOfFile); } builder.cacheFilePath(name).cacheFile(file); return builder.build(); } catch (Throwable t) { logger.warn( COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Failed to create file store cache. Local file cache will be disabled. Cache file name: " + name, t); return FileCacheStore.Empty.getInstance(name); } } private static void tryFileLock(FileCacheStore.Builder builder, String fileName) throws PathNotExclusiveException { File lockFile = new File(fileName + ".lock"); FileLock dirLock; try { lockFile.createNewFile(); if (!lockFile.exists()) { throw new AssertionError("Failed to create lock file " + lockFile); } FileChannel lockFileChannel = new RandomAccessFile(lockFile, "rw").getChannel(); dirLock = lockFileChannel.tryLock(); } catch (OverlappingFileLockException ofle) { dirLock = null; } catch (IOException ioe) { throw new RuntimeException(ioe); } if (dirLock == null) { throw new PathNotExclusiveException( fileName + " is not exclusive. Maybe multiple Dubbo instances are using the same folder."); } lockFile.deleteOnExit(); builder.directoryLock(dirLock).lockFile(lockFile); } static void removeCache(String cacheFileName) { cacheMap.remove(cacheFileName); } /** * for unit test only */ @Deprecated static Map<String, FileCacheStore> getCacheMap() { return cacheMap; } private static class PathNotExclusiveException extends Exception { public PathNotExclusiveException(String msg) { super(msg); } } }
6,781
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.context.ApplicationExt; import org.apache.dubbo.common.context.LifecycleAdapter; import org.apache.dubbo.common.extension.DisableInject; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.context.ConfigConfigurationAdapter; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; public class Environment extends LifecycleAdapter implements ApplicationExt { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Environment.class); public static final String NAME = "environment"; // dubbo properties in classpath private PropertiesConfiguration propertiesConfiguration; // java system props (-D) private SystemConfiguration systemConfiguration; // java system environment private EnvironmentConfiguration environmentConfiguration; // external config, such as config-center global/default config private InmemoryConfiguration externalConfiguration; // external app config, such as config-center app config private InmemoryConfiguration appExternalConfiguration; // local app config , such as Spring Environment/PropertySources/application.properties private InmemoryConfiguration appConfiguration; protected CompositeConfiguration globalConfiguration; protected List<Map<String, String>> globalConfigurationMaps; private CompositeConfiguration defaultDynamicGlobalConfiguration; private DynamicConfiguration defaultDynamicConfiguration; private String localMigrationRule; private final AtomicBoolean initialized = new AtomicBoolean(false); private final ScopeModel scopeModel; public Environment(ScopeModel scopeModel) { this.scopeModel = scopeModel; } @Override public void initialize() throws IllegalStateException { if (initialized.compareAndSet(false, true)) { this.propertiesConfiguration = new PropertiesConfiguration(scopeModel); this.systemConfiguration = new SystemConfiguration(); this.environmentConfiguration = new EnvironmentConfiguration(); this.externalConfiguration = new InmemoryConfiguration("ExternalConfig"); this.appExternalConfiguration = new InmemoryConfiguration("AppExternalConfig"); this.appConfiguration = new InmemoryConfiguration("AppConfig"); loadMigrationRule(); } } /** * @deprecated MigrationRule will be removed in 3.1 */ @Deprecated private void loadMigrationRule() { if (Boolean.parseBoolean(System.getProperty(CommonConstants.DUBBO_MIGRATION_FILE_ENABLE, "false"))) { String path = System.getProperty(CommonConstants.DUBBO_MIGRATION_KEY); if (StringUtils.isEmpty(path)) { path = System.getenv(CommonConstants.DUBBO_MIGRATION_KEY); if (StringUtils.isEmpty(path)) { path = CommonConstants.DEFAULT_DUBBO_MIGRATION_FILE; } } this.localMigrationRule = ConfigUtils.loadMigrationRule(scopeModel.getClassLoaders(), path); } else { this.localMigrationRule = null; } } /** * @deprecated only for ut */ @Deprecated @DisableInject public void setLocalMigrationRule(String localMigrationRule) { this.localMigrationRule = localMigrationRule; } @DisableInject public void setExternalConfigMap(Map<String, String> externalConfiguration) { if (externalConfiguration != null) { this.externalConfiguration.setProperties(externalConfiguration); } } @DisableInject public void setAppExternalConfigMap(Map<String, String> appExternalConfiguration) { if (appExternalConfiguration != null) { this.appExternalConfiguration.setProperties(appExternalConfiguration); } } @DisableInject public void setAppConfigMap(Map<String, String> appConfiguration) { if (appConfiguration != null) { this.appConfiguration.setProperties(appConfiguration); } } public Map<String, String> getExternalConfigMap() { return externalConfiguration.getProperties(); } public Map<String, String> getAppExternalConfigMap() { return appExternalConfiguration.getProperties(); } public Map<String, String> getAppConfigMap() { return appConfiguration.getProperties(); } public void updateExternalConfigMap(Map<String, String> externalMap) { this.externalConfiguration.addProperties(externalMap); } public void updateAppExternalConfigMap(Map<String, String> externalMap) { this.appExternalConfiguration.addProperties(externalMap); } /** * Merge target map properties into app configuration * * @param map */ public void updateAppConfigMap(Map<String, String> map) { this.appConfiguration.addProperties(map); } /** * At start-up, Dubbo is driven by various configuration, such as Application, Registry, Protocol, etc. * All configurations will be converged into a data bus - URL, and then drive the subsequent process. * <p> * At present, there are many configuration sources, including AbstractConfig (API, XML, annotation), - D, config center, etc. * This method helps us t filter out the most priority values from various configuration sources. * * @param config * @param prefix * @return */ public Configuration getPrefixedConfiguration(AbstractConfig config, String prefix) { // The sequence would be: SystemConfiguration -> EnvironmentConfiguration -> AppExternalConfiguration -> // ExternalConfiguration -> AppConfiguration -> AbstractConfig -> PropertiesConfiguration Configuration instanceConfiguration = new ConfigConfigurationAdapter(config, prefix); CompositeConfiguration compositeConfiguration = new CompositeConfiguration(); compositeConfiguration.addConfiguration(systemConfiguration); compositeConfiguration.addConfiguration(environmentConfiguration); compositeConfiguration.addConfiguration(appExternalConfiguration); compositeConfiguration.addConfiguration(externalConfiguration); compositeConfiguration.addConfiguration(appConfiguration); compositeConfiguration.addConfiguration(instanceConfiguration); compositeConfiguration.addConfiguration(propertiesConfiguration); return new PrefixedConfiguration(compositeConfiguration, prefix); } /** * There are two ways to get configuration during exposure / reference or at runtime: * 1. URL, The value in the URL is relatively fixed. we can get value directly. * 2. The configuration exposed in this method is convenient for us to query the latest values from multiple * prioritized sources, it also guarantees that configs changed dynamically can take effect on the fly. */ public CompositeConfiguration getConfiguration() { if (globalConfiguration == null) { CompositeConfiguration configuration = new CompositeConfiguration(); configuration.addConfiguration(systemConfiguration); configuration.addConfiguration(environmentConfiguration); configuration.addConfiguration(appExternalConfiguration); configuration.addConfiguration(externalConfiguration); configuration.addConfiguration(appConfiguration); configuration.addConfiguration(propertiesConfiguration); globalConfiguration = configuration; } return globalConfiguration; } /** * Get configuration map list for target instance * * @param config * @param prefix * @return */ public List<Map<String, String>> getConfigurationMaps(AbstractConfig config, String prefix) { // The sequence would be: SystemConfiguration -> EnvironmentConfiguration -> AppExternalConfiguration -> // ExternalConfiguration -> AppConfiguration -> AbstractConfig -> PropertiesConfiguration List<Map<String, String>> maps = new ArrayList<>(); maps.add(systemConfiguration.getProperties()); maps.add(environmentConfiguration.getProperties()); maps.add(appExternalConfiguration.getProperties()); maps.add(externalConfiguration.getProperties()); maps.add(appConfiguration.getProperties()); if (config != null) { ConfigConfigurationAdapter configurationAdapter = new ConfigConfigurationAdapter(config, prefix); maps.add(configurationAdapter.getProperties()); } maps.add(propertiesConfiguration.getProperties()); return maps; } /** * Get global configuration as map list * * @return */ public List<Map<String, String>> getConfigurationMaps() { if (globalConfigurationMaps == null) { globalConfigurationMaps = getConfigurationMaps(null, null); } return globalConfigurationMaps; } @Override public void destroy() throws IllegalStateException { initialized.set(false); systemConfiguration = null; propertiesConfiguration = null; environmentConfiguration = null; externalConfiguration = null; appExternalConfiguration = null; appConfiguration = null; globalConfiguration = null; globalConfigurationMaps = null; defaultDynamicGlobalConfiguration = null; if (defaultDynamicConfiguration != null) { try { defaultDynamicConfiguration.close(); } catch (Exception e) { logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "close dynamic configuration failed: " + e.getMessage(), e); } defaultDynamicConfiguration = null; } } /** * Reset environment. * For test only. */ public void reset() { destroy(); initialize(); } public String resolvePlaceholders(String str) { return ConfigUtils.replaceProperty(str, getConfiguration()); } public PropertiesConfiguration getPropertiesConfiguration() { return propertiesConfiguration; } public SystemConfiguration getSystemConfiguration() { return systemConfiguration; } public EnvironmentConfiguration getEnvironmentConfiguration() { return environmentConfiguration; } public InmemoryConfiguration getExternalConfiguration() { return externalConfiguration; } public InmemoryConfiguration getAppExternalConfiguration() { return appExternalConfiguration; } public InmemoryConfiguration getAppConfiguration() { return appConfiguration; } public String getLocalMigrationRule() { return localMigrationRule; } public synchronized void refreshClassLoaders() { propertiesConfiguration.refresh(); loadMigrationRule(); this.globalConfiguration = null; this.globalConfigurationMaps = null; this.defaultDynamicGlobalConfiguration = null; } public Configuration getDynamicGlobalConfiguration() { if (defaultDynamicGlobalConfiguration == null) { if (defaultDynamicConfiguration == null) { if (logger.isWarnEnabled()) { logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "dynamicConfiguration is null , return globalConfiguration."); } return getConfiguration(); } defaultDynamicGlobalConfiguration = new CompositeConfiguration(); defaultDynamicGlobalConfiguration.addConfiguration(defaultDynamicConfiguration); defaultDynamicGlobalConfiguration.addConfiguration(getConfiguration()); } return defaultDynamicGlobalConfiguration; } public Optional<DynamicConfiguration> getDynamicConfiguration() { return Optional.ofNullable(defaultDynamicConfiguration); } @DisableInject public void setDynamicConfiguration(DynamicConfiguration defaultDynamicConfiguration) { this.defaultDynamicConfiguration = defaultDynamicConfiguration; } }
6,782
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/ReferenceCache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.config.ReferenceConfigBase; import java.util.List; public interface ReferenceCache { @SuppressWarnings("unchecked") default <T> T get(ReferenceConfigBase<T> referenceConfig) { return get(referenceConfig, true); } @SuppressWarnings("unchecked") <T> T get(ReferenceConfigBase<T> referenceConfig, boolean check); @SuppressWarnings("unchecked") <T> T get(String key, Class<T> type); @SuppressWarnings("unchecked") <T> T get(String key); @SuppressWarnings("unchecked") <T> List<T> getAll(Class<T> type); @SuppressWarnings("unchecked") <T> T get(Class<T> type); @SuppressWarnings("unchecked") <T> void check(ReferenceConfigBase<T> referenceConfig, long timeout); void check(String key, Class<?> type, long timeout); void destroy(String key, Class<?> type); void destroy(Class<?> type); <T> void destroy(ReferenceConfigBase<T> referenceConfig); void destroyAll(); }
6,783
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/EnvironmentConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.utils.StringUtils; import java.util.Map; /** * Configuration from system environment */ public class EnvironmentConfiguration implements Configuration { @Override public Object getInternalProperty(String key) { String value = getenv(key); if (StringUtils.isEmpty(value)) { value = getenv(StringUtils.toOSStyleKey(key)); } return value; } public Map<String, String> getProperties() { return getenv(); } // Adapt to System api, design for unit test protected String getenv(String key) { return System.getenv(key); } protected Map<String, String> getenv() { return System.getenv(); } }
6,784
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.NoSuchElementException; import static org.apache.dubbo.common.config.ConfigurationUtils.isEmptyValue; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH; /** * Configuration interface, to fetch the value for the specified key. */ public interface Configuration { ErrorTypeAwareLogger interfaceLevelLogger = LoggerFactory.getErrorTypeAwareLogger(Configuration.class); /** * Get a string associated with the given configuration key. * * @param key The configuration key. * @return The associated string. */ default String getString(String key) { return convert(String.class, key, null); } /** * Get a string associated with the given configuration key. * If the key doesn't map to an existing object, the default value * is returned. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated string if key is found and has valid * format, default value otherwise. */ default String getString(String key, String defaultValue) { return convert(String.class, key, defaultValue); } default int getInt(String key) { Integer i = this.getInteger(key, null); if (i != null) { return i; } else { throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object"); } } default int getInt(String key, int defaultValue) { Integer i = this.getInteger(key, null); return i == null ? defaultValue : i; } default Integer getInteger(String key, Integer defaultValue) { try { return convert(Integer.class, key, defaultValue); } catch (NumberFormatException e) { // 0-2 Property type mismatch. interfaceLevelLogger.error( COMMON_PROPERTY_TYPE_MISMATCH, "typo in property value", "This property requires an integer value.", "Actual Class: " + getClass().getName(), e); throw new IllegalStateException('\'' + key + "' doesn't map to a Integer object", e); } } default boolean getBoolean(String key) { Boolean b = this.getBoolean(key, null); if (b != null) { return b; } else { throw new NoSuchElementException('\'' + key + "' doesn't map to an existing object"); } } default boolean getBoolean(String key, boolean defaultValue) { return this.getBoolean(key, toBooleanObject(defaultValue)); } default Boolean getBoolean(String key, Boolean defaultValue) { try { return convert(Boolean.class, key, defaultValue); } catch (Exception e) { throw new IllegalStateException( "Try to get " + '\'' + key + "' failed, maybe because this key doesn't map to a Boolean object", e); } } /** * Gets a property from the configuration. This is the most basic get * method for retrieving values of properties. In a typical implementation * of the {@code Configuration} interface the other get methods (that * return specific data types) will internally make use of this method. On * this level variable substitution is not yet performed. The returned * object is an internal representation of the property value for the passed * in key. It is owned by the {@code Configuration} object. So a caller * should not modify this object. It cannot be guaranteed that this object * will stay constant over time (i.e. further update operations on the * configuration may change its internal state). * * @param key property to retrieve * @return the value to which this configuration maps the specified key, or * null if the configuration contains no mapping for this key. */ default Object getProperty(String key) { return getProperty(key, null); } /** * Gets a property from the configuration. The default value will return if the configuration doesn't contain * the mapping for the specified key. * * @param key property to retrieve * @param defaultValue default value * @return the value to which this configuration maps the specified key, or default value if the configuration * contains no mapping for this key. */ default Object getProperty(String key, Object defaultValue) { Object value = getInternalProperty(key); return value != null ? value : defaultValue; } Object getInternalProperty(String key); /** * Check if the configuration contains the specified key. * * @param key the key whose presence in this configuration is to be tested * @return {@code true} if the configuration contains a value for this * key, {@code false} otherwise */ default boolean containsKey(String key) { return !isEmptyValue(getProperty(key)); } default <T> T convert(Class<T> cls, String key, T defaultValue) { // we only process String properties for now String value = (String) getProperty(key); if (value == null) { return defaultValue; } Object obj = value; if (cls.isInstance(value)) { return cls.cast(value); } if (Boolean.class.equals(cls) || Boolean.TYPE.equals(cls)) { obj = Boolean.valueOf(value); } else if (Number.class.isAssignableFrom(cls) || cls.isPrimitive()) { if (Integer.class.equals(cls) || Integer.TYPE.equals(cls)) { obj = Integer.valueOf(value); } else if (Long.class.equals(cls) || Long.TYPE.equals(cls)) { obj = Long.valueOf(value); } else if (Byte.class.equals(cls) || Byte.TYPE.equals(cls)) { obj = Byte.valueOf(value); } else if (Short.class.equals(cls) || Short.TYPE.equals(cls)) { obj = Short.valueOf(value); } else if (Float.class.equals(cls) || Float.TYPE.equals(cls)) { obj = Float.valueOf(value); } else if (Double.class.equals(cls) || Double.TYPE.equals(cls)) { obj = Double.valueOf(value); } } else if (cls.isEnum()) { obj = Enum.valueOf(cls.asSubclass(Enum.class), value); } return cls.cast(obj); } static Boolean toBooleanObject(boolean bool) { return bool ? Boolean.TRUE : Boolean.FALSE; } }
6,785
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.util.Properties; /** * * The smaller value, the higher priority * */ @SPI(scope = ExtensionScope.MODULE) public interface OrderedPropertiesProvider { /** * order * * @return */ int priority(); /** * load the properties * * @return */ Properties initProperties(); }
6,786
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/PropertiesConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.Map; import java.util.Properties; /** * Configuration from system properties and dubbo.properties */ public class PropertiesConfiguration implements Configuration { private Properties properties; private final ScopeModel scopeModel; public PropertiesConfiguration(ScopeModel scopeModel) { this.scopeModel = scopeModel; refresh(); } public void refresh() { properties = ConfigUtils.getProperties(scopeModel.getClassLoaders()); } @Override public String getProperty(String key) { return properties.getProperty(key); } @Override public Object getInternalProperty(String key) { return properties.getProperty(key); } public void setProperty(String key, String value) { properties.setProperty(key, value); } public String remove(String key) { return (String) properties.remove(key); } @Deprecated public void setProperties(Properties properties) { this.properties = properties; } public Map<String, String> getProperties() { return (Map) properties; } }
6,787
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.context.ModuleExt; import org.apache.dubbo.common.extension.DisableInject; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; public class ModuleEnvironment extends Environment implements ModuleExt { // delegate private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ModuleEnvironment.class); public static final String NAME = "moduleEnvironment"; private final AtomicBoolean initialized = new AtomicBoolean(false); private final ModuleModel moduleModel; private final Environment applicationDelegate; private OrderedPropertiesConfiguration orderedPropertiesConfiguration; private CompositeConfiguration dynamicGlobalConfiguration; private DynamicConfiguration dynamicConfiguration; public ModuleEnvironment(ModuleModel moduleModel) { super(moduleModel); this.moduleModel = moduleModel; this.applicationDelegate = moduleModel.getApplicationModel().modelEnvironment(); } @Override public void initialize() throws IllegalStateException { if (initialized.compareAndSet(false, true)) { this.orderedPropertiesConfiguration = new OrderedPropertiesConfiguration(moduleModel); } } @Override public Configuration getPrefixedConfiguration(AbstractConfig config, String prefix) { CompositeConfiguration compositeConfiguration = new CompositeConfiguration(); compositeConfiguration.addConfiguration(applicationDelegate.getPrefixedConfiguration(config, prefix)); compositeConfiguration.addConfiguration(orderedPropertiesConfiguration); return new PrefixedConfiguration(compositeConfiguration, prefix); } @Override public CompositeConfiguration getConfiguration() { if (globalConfiguration == null) { CompositeConfiguration configuration = new CompositeConfiguration(); configuration.addConfiguration(applicationDelegate.getConfiguration()); configuration.addConfiguration(orderedPropertiesConfiguration); globalConfiguration = configuration; } return globalConfiguration; } @Override public List<Map<String, String>> getConfigurationMaps(AbstractConfig config, String prefix) { List<Map<String, String>> maps = applicationDelegate.getConfigurationMaps(config, prefix); maps.add(orderedPropertiesConfiguration.getProperties()); return maps; } @Override public Configuration getDynamicGlobalConfiguration() { if (dynamicConfiguration == null) { return applicationDelegate.getDynamicGlobalConfiguration(); } if (dynamicGlobalConfiguration == null) { if (dynamicConfiguration == null) { if (logger.isWarnEnabled()) { logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "dynamicConfiguration is null , return globalConfiguration."); } return getConfiguration(); } dynamicGlobalConfiguration = new CompositeConfiguration(); dynamicGlobalConfiguration.addConfiguration(dynamicConfiguration); dynamicGlobalConfiguration.addConfiguration(getConfiguration()); } return dynamicGlobalConfiguration; } @Override public Optional<DynamicConfiguration> getDynamicConfiguration() { if (dynamicConfiguration == null) { return applicationDelegate.getDynamicConfiguration(); } return Optional.ofNullable(dynamicConfiguration); } @Override @DisableInject public void setDynamicConfiguration(DynamicConfiguration dynamicConfiguration) { this.dynamicConfiguration = dynamicConfiguration; } @Override public void destroy() throws IllegalStateException { super.destroy(); this.orderedPropertiesConfiguration = null; } @Override @DisableInject public void setLocalMigrationRule(String localMigrationRule) { applicationDelegate.setLocalMigrationRule(localMigrationRule); } @Override @DisableInject public void setExternalConfigMap(Map<String, String> externalConfiguration) { applicationDelegate.setExternalConfigMap(externalConfiguration); } @Override @DisableInject public void setAppExternalConfigMap(Map<String, String> appExternalConfiguration) { applicationDelegate.setAppExternalConfigMap(appExternalConfiguration); } @Override @DisableInject public void setAppConfigMap(Map<String, String> appConfiguration) { applicationDelegate.setAppConfigMap(appConfiguration); } @Override public Map<String, String> getExternalConfigMap() { return applicationDelegate.getExternalConfigMap(); } @Override public Map<String, String> getAppExternalConfigMap() { return applicationDelegate.getAppExternalConfigMap(); } @Override public Map<String, String> getAppConfigMap() { return applicationDelegate.getAppConfigMap(); } @Override public void updateExternalConfigMap(Map<String, String> externalMap) { applicationDelegate.updateExternalConfigMap(externalMap); } @Override public void updateAppExternalConfigMap(Map<String, String> externalMap) { applicationDelegate.updateAppExternalConfigMap(externalMap); } @Override public void updateAppConfigMap(Map<String, String> map) { applicationDelegate.updateAppConfigMap(map); } @Override public PropertiesConfiguration getPropertiesConfiguration() { return applicationDelegate.getPropertiesConfiguration(); } @Override public SystemConfiguration getSystemConfiguration() { return applicationDelegate.getSystemConfiguration(); } @Override public EnvironmentConfiguration getEnvironmentConfiguration() { return applicationDelegate.getEnvironmentConfiguration(); } @Override public InmemoryConfiguration getExternalConfiguration() { return applicationDelegate.getExternalConfiguration(); } @Override public InmemoryConfiguration getAppExternalConfiguration() { return applicationDelegate.getAppExternalConfiguration(); } @Override public InmemoryConfiguration getAppConfiguration() { return applicationDelegate.getAppConfiguration(); } @Override public String getLocalMigrationRule() { return applicationDelegate.getLocalMigrationRule(); } @Override public synchronized void refreshClassLoaders() { orderedPropertiesConfiguration.refresh(); applicationDelegate.refreshClassLoaders(); } }
6,788
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationCache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; /** * Properties Cache of Configuration {@link ConfigurationUtils#getCachedDynamicProperty(ScopeModel, String, String)} */ public class ConfigurationCache { private final Map<String, String> cache = new ConcurrentHashMap<>(); /** * Get Cached Value * * @param key key * @param function function to produce value, should not return `null` * @return value */ public String computeIfAbsent(String key, Function<String, String> function) { String value = cache.get(key); // value might be empty here! // empty value from config center will be cached here if (value == null) { // lock free, tolerate repeat apply, will return previous value cache.putIfAbsent(key, function.apply(key)); value = cache.get(key); } return value; } }
6,789
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModel; import java.io.IOException; import java.io.StringReader; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY; /** * Utilities for manipulating configurations from different sources */ public final class ConfigurationUtils { /** * Forbids instantiation. */ private ConfigurationUtils() { throw new UnsupportedOperationException("No instance of 'ConfigurationUtils' for you! "); } private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigurationUtils.class); private static final List<String> securityKey; private static volatile long expectedShutdownTime = Long.MAX_VALUE; static { List<String> keys = new LinkedList<>(); keys.add("accesslog"); keys.add("router"); keys.add("rule"); keys.add("runtime"); keys.add("type"); securityKey = Collections.unmodifiableList(keys); } /** * Used to get properties from the jvm * * @return */ public static Configuration getSystemConfiguration(ScopeModel scopeModel) { return getScopeModelOrDefaultApplicationModel(scopeModel) .modelEnvironment() .getSystemConfiguration(); } /** * Used to get properties from the os environment * * @return */ public static Configuration getEnvConfiguration(ScopeModel scopeModel) { return getScopeModelOrDefaultApplicationModel(scopeModel) .modelEnvironment() .getEnvironmentConfiguration(); } /** * Used to get a composite property value. * <p> * Also see {@link Environment#getConfiguration()} * * @return */ public static Configuration getGlobalConfiguration(ScopeModel scopeModel) { return getScopeModelOrDefaultApplicationModel(scopeModel) .modelEnvironment() .getConfiguration(); } public static Configuration getDynamicGlobalConfiguration(ScopeModel scopeModel) { return scopeModel.modelEnvironment().getDynamicGlobalConfiguration(); } // FIXME /** * Server shutdown wait timeout mills * * @return */ @SuppressWarnings("deprecation") public static int getServerShutdownTimeout(ScopeModel scopeModel) { if (expectedShutdownTime < System.currentTimeMillis()) { return 1; } int timeout = DEFAULT_SERVER_SHUTDOWN_TIMEOUT; Configuration configuration = getGlobalConfiguration(scopeModel); String value = StringUtils.trim(configuration.getString(SHUTDOWN_WAIT_KEY)); if (StringUtils.isNotEmpty(value)) { try { timeout = Integer.parseInt(value); } catch (Exception e) { // ignore } } else { value = StringUtils.trim(configuration.getString(SHUTDOWN_WAIT_SECONDS_KEY)); if (StringUtils.isNotEmpty(value)) { try { timeout = Integer.parseInt(value) * 1000; } catch (Exception e) { // ignore } } } if (expectedShutdownTime - System.currentTimeMillis() < timeout) { return (int) Math.max(1, expectedShutdownTime - System.currentTimeMillis()); } return timeout; } public static int reCalShutdownTime(int expected) { // already timeout if (expectedShutdownTime < System.currentTimeMillis()) { return 1; } if (expectedShutdownTime - System.currentTimeMillis() < expected) { // the shutdown time rest is less than expected return (int) Math.max(1, expectedShutdownTime - System.currentTimeMillis()); } // return the expected return expected; } public static void setExpectedShutdownTime(long expectedShutdownTime) { ConfigurationUtils.expectedShutdownTime = expectedShutdownTime; } public static String getCachedDynamicProperty(ScopeModel realScopeModel, String key, String defaultValue) { ScopeModel scopeModel = getScopeModelOrDefaultApplicationModel(realScopeModel); ConfigurationCache configurationCache = scopeModel.getBeanFactory().getBean(ConfigurationCache.class); String value = configurationCache.computeIfAbsent( key, _k -> ConfigurationUtils.getDynamicProperty(scopeModel, _k, "")); return StringUtils.isEmpty(value) ? defaultValue : value; } private static ScopeModel getScopeModelOrDefaultApplicationModel(ScopeModel realScopeModel) { if (realScopeModel == null) { return ApplicationModel.defaultModel(); } return realScopeModel; } public static String getDynamicProperty(ScopeModel scopeModel, String property) { return getDynamicProperty(scopeModel, property, null); } public static String getDynamicProperty(ScopeModel scopeModel, String property, String defaultValue) { return StringUtils.trim(getDynamicGlobalConfiguration(scopeModel).getString(property, defaultValue)); } public static String getProperty(ScopeModel scopeModel, String property) { return getProperty(scopeModel, property, null); } public static String getProperty(ScopeModel scopeModel, String property, String defaultValue) { return StringUtils.trim(getGlobalConfiguration(scopeModel).getString(property, defaultValue)); } public static int get(ScopeModel scopeModel, String property, int defaultValue) { return getGlobalConfiguration(scopeModel).getInt(property, defaultValue); } public static Map<String, String> parseProperties(String content) throws IOException { Map<String, String> map = new HashMap<>(); if (StringUtils.isEmpty(content)) { logger.info("Config center was specified, but no config item found."); } else { Properties properties = new Properties(); properties.load(new StringReader(content)); properties.stringPropertyNames().forEach(k -> { boolean deny = false; for (String key : securityKey) { if (k.contains(key)) { deny = true; break; } } if (!deny) { map.put(k, properties.getProperty(k)); } }); } return map; } public static boolean isEmptyValue(Object value) { return value == null || value instanceof String && StringUtils.isBlank((String) value); } /** * Search props and extract sub properties. * <pre> * # properties * dubbo.protocol.name=dubbo * dubbo.protocol.port=1234 * * # extract protocol props * Map props = getSubProperties("dubbo.protocol."); * * # result * props: {"name": "dubbo", "port" : "1234"} * * </pre> * * @param configMaps * @param prefix * @param <V> * @return */ public static <V extends Object> Map<String, V> getSubProperties( Collection<Map<String, V>> configMaps, String prefix) { Map<String, V> map = new LinkedHashMap<>(); for (Map<String, V> configMap : configMaps) { getSubProperties(configMap, prefix, map); } return map; } public static <V extends Object> Map<String, V> getSubProperties(Map<String, V> configMap, String prefix) { return getSubProperties(configMap, prefix, null); } private static <V extends Object> Map<String, V> getSubProperties( Map<String, V> configMap, String prefix, Map<String, V> resultMap) { if (!prefix.endsWith(".")) { prefix += "."; } if (null == resultMap) { resultMap = new LinkedHashMap<>(); } if (CollectionUtils.isNotEmptyMap(configMap)) { Map<String, V> copy; synchronized (configMap) { copy = new HashMap<>(configMap); } for (Map.Entry<String, V> entry : copy.entrySet()) { String key = entry.getKey(); V val = entry.getValue(); if (StringUtils.startsWithIgnoreCase(key, prefix) && key.length() > prefix.length() && !ConfigurationUtils.isEmptyValue(val)) { String k = key.substring(prefix.length()); // convert camelCase/snake_case to kebab-case String newK = StringUtils.convertToSplitName(k, "-"); resultMap.putIfAbsent(newK, val); if (!Objects.equals(k, newK)) { resultMap.putIfAbsent(k, val); } } } } return resultMap; } public static <V extends Object> boolean hasSubProperties(Collection<Map<String, V>> configMaps, String prefix) { if (!prefix.endsWith(".")) { prefix += "."; } for (Map<String, V> configMap : configMaps) { if (hasSubProperties(configMap, prefix)) { return true; } } return false; } public static <V extends Object> boolean hasSubProperties(Map<String, V> configMap, String prefix) { if (!prefix.endsWith(".")) { prefix += "."; } Map<String, V> copy; synchronized (configMap) { copy = new HashMap<>(configMap); } for (Map.Entry<String, V> entry : copy.entrySet()) { String key = entry.getKey(); if (StringUtils.startsWithIgnoreCase(key, prefix) && key.length() > prefix.length() && !ConfigurationUtils.isEmptyValue(entry.getValue())) { return true; } } return false; } /** * Search props and extract config ids * <pre> * # properties * dubbo.registries.registry1.address=xxx * dubbo.registries.registry2.port=xxx * * # extract ids * Set configIds = getSubIds("dubbo.registries.") * * # result * configIds: ["registry1", "registry2"] * </pre> * * @param configMaps * @param prefix * @return */ public static <V extends Object> Set<String> getSubIds(Collection<Map<String, V>> configMaps, String prefix) { if (!prefix.endsWith(".")) { prefix += "."; } Set<String> ids = new LinkedHashSet<>(); for (Map<String, V> configMap : configMaps) { Map<String, V> copy; synchronized (configMap) { copy = new HashMap<>(configMap); } for (Map.Entry<String, V> entry : copy.entrySet()) { String key = entry.getKey(); V val = entry.getValue(); if (StringUtils.startsWithIgnoreCase(key, prefix) && key.length() > prefix.length() && !ConfigurationUtils.isEmptyValue(val)) { String k = key.substring(prefix.length()); int endIndex = k.indexOf("."); if (endIndex > 0) { String id = k.substring(0, endIndex); ids.add(id); } } } } return ids; } /** * Get an instance of {@link DynamicConfigurationFactory} by the specified name. If not found, take the default * extension of {@link DynamicConfigurationFactory} * * @param name the name of extension of {@link DynamicConfigurationFactory} * @return non-null * @see 2.7.4 */ public static DynamicConfigurationFactory getDynamicConfigurationFactory( ExtensionAccessor extensionAccessor, String name) { ExtensionLoader<DynamicConfigurationFactory> loader = extensionAccessor.getExtensionLoader(DynamicConfigurationFactory.class); return loader.getOrDefaultExtension(name); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#getSystemConfiguration(ScopeModel)} */ @Deprecated public static Configuration getSystemConfiguration() { return ApplicationModel.defaultModel().modelEnvironment().getSystemConfiguration(); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#getEnvConfiguration(ScopeModel)} */ @Deprecated public static Configuration getEnvConfiguration() { return ApplicationModel.defaultModel().modelEnvironment().getEnvironmentConfiguration(); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#getGlobalConfiguration(ScopeModel)} */ @Deprecated public static Configuration getGlobalConfiguration() { return ApplicationModel.defaultModel().modelEnvironment().getConfiguration(); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#getDynamicGlobalConfiguration(ScopeModel)} */ @Deprecated public static Configuration getDynamicGlobalConfiguration() { return ApplicationModel.defaultModel() .getDefaultModule() .modelEnvironment() .getDynamicGlobalConfiguration(); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#getCachedDynamicProperty(ScopeModel, String, String)} */ @Deprecated public static String getCachedDynamicProperty(String key, String defaultValue) { return getCachedDynamicProperty(ApplicationModel.defaultModel(), key, defaultValue); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#getDynamicProperty(ScopeModel, String)} */ @Deprecated public static String getDynamicProperty(String property) { return getDynamicProperty(ApplicationModel.defaultModel(), property); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#getDynamicProperty(ScopeModel, String, String)} */ @Deprecated public static String getDynamicProperty(String property, String defaultValue) { return getDynamicProperty(ApplicationModel.defaultModel(), property, defaultValue); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#getProperty(ScopeModel, String)} */ @Deprecated public static String getProperty(String property) { return getProperty(ApplicationModel.defaultModel(), property); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#getProperty(ScopeModel, String, String)} */ @Deprecated public static String getProperty(String property, String defaultValue) { return getProperty(ApplicationModel.defaultModel(), property, defaultValue); } /** * For compact single instance * * @deprecated Replaced to {@link ConfigurationUtils#get(ScopeModel, String, int)} */ @Deprecated public static int get(String property, int defaultValue) { return get(ApplicationModel.defaultModel(), property, defaultValue); } }
6,790
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/InmemoryConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import java.util.LinkedHashMap; import java.util.Map; /** * In-memory configuration */ public class InmemoryConfiguration implements Configuration { private String name; // stores the configuration key-value pairs private Map<String, String> store = new LinkedHashMap<>(); public InmemoryConfiguration() {} public InmemoryConfiguration(String name) { this.name = name; } public InmemoryConfiguration(Map<String, String> properties) { this.setProperties(properties); } @Override public Object getInternalProperty(String key) { return store.get(key); } /** * Add one property into the store, the previous value will be replaced if the key exists */ public void addProperty(String key, String value) { store.put(key, value); } /** * Add a set of properties into the store */ public void addProperties(Map<String, String> properties) { if (properties != null) { this.store.putAll(properties); } } /** * set store */ public void setProperties(Map<String, String> properties) { if (properties != null) { this.store = properties; } } public Map<String, String> getProperties() { return store; } }
6,791
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/PrefixedConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.utils.StringUtils; public class PrefixedConfiguration implements Configuration { private final String prefix; private final Configuration origin; public PrefixedConfiguration(Configuration origin, String prefix) { this.origin = origin; this.prefix = prefix; } @Override public Object getInternalProperty(String key) { if (StringUtils.isBlank(prefix)) { return origin.getInternalProperty(key); } Object value = origin.getInternalProperty(prefix + "." + key); if (!ConfigurationUtils.isEmptyValue(value)) { return value; } return null; } }
6,792
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class OrderedPropertiesConfiguration implements Configuration { private Properties properties; private final ModuleModel moduleModel; public OrderedPropertiesConfiguration(ModuleModel moduleModel) { this.moduleModel = moduleModel; refresh(); } public void refresh() { properties = new Properties(); ExtensionLoader<OrderedPropertiesProvider> propertiesProviderExtensionLoader = moduleModel.getExtensionLoader(OrderedPropertiesProvider.class); Set<String> propertiesProviderNames = propertiesProviderExtensionLoader.getSupportedExtensions(); if (CollectionUtils.isEmpty(propertiesProviderNames)) { return; } List<OrderedPropertiesProvider> orderedPropertiesProviders = new ArrayList<>(); for (String propertiesProviderName : propertiesProviderNames) { orderedPropertiesProviders.add(propertiesProviderExtensionLoader.getExtension(propertiesProviderName)); } // order the propertiesProvider according the priority descending orderedPropertiesProviders.sort((a, b) -> b.priority() - a.priority()); // override the properties. for (OrderedPropertiesProvider orderedPropertiesProvider : orderedPropertiesProviders) { properties.putAll(orderedPropertiesProvider.initProperties()); } } @Override public String getProperty(String key) { return properties.getProperty(key); } @Override public Object getInternalProperty(String key) { return properties.getProperty(key); } public void setProperty(String key, String value) { properties.setProperty(key, value); } public String remove(String key) { return (String) properties.remove(key); } /** * For ut only */ @Deprecated public void setProperties(Properties properties) { this.properties = properties; } public Map<String, String> getProperties() { return (Map) properties; } }
6,793
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/SystemConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import java.util.Map; /** * Configuration from system properties */ public class SystemConfiguration implements Configuration { @Override public Object getInternalProperty(String key) { return System.getProperty(key); } public Map<String, String> getProperties() { return (Map) System.getProperties(); } }
6,794
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_LOAD_ENV_VARIABLE; /** * This is an abstraction specially customized for the sequence Dubbo retrieves properties. */ public class CompositeConfiguration implements Configuration { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompositeConfiguration.class); /** * List holding all the configuration */ private final List<Configuration> configList = new CopyOnWriteArrayList<>(); // FIXME, consider change configList to SortedMap to replace this boolean status. private boolean dynamicIncluded; public CompositeConfiguration() {} public CompositeConfiguration(Configuration... configurations) { if (ArrayUtils.isNotEmpty(configurations)) { Arrays.stream(configurations) .filter(config -> !configList.contains(config)) .forEach(configList::add); } } // FIXME, consider changing configList to SortedMap to replace this boolean status. public boolean isDynamicIncluded() { return dynamicIncluded; } public void setDynamicIncluded(boolean dynamicIncluded) { this.dynamicIncluded = dynamicIncluded; } public void addConfiguration(Configuration configuration) { if (configList.contains(configuration)) { return; } this.configList.add(configuration); } public void addConfigurationFirst(Configuration configuration) { this.addConfiguration(0, configuration); } public void addConfiguration(int pos, Configuration configuration) { this.configList.add(pos, configuration); } @Override public Object getInternalProperty(String key) { for (Configuration config : configList) { try { Object value = config.getProperty(key); if (!ConfigurationUtils.isEmptyValue(value)) { return value; } } catch (Exception e) { logger.error( CONFIG_FAILED_LOAD_ENV_VARIABLE, "", "", "Error when trying to get value for key " + key + " from " + config + ", " + "will continue to try the next one."); } } return null; } }
6,795
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/TreePathDynamicConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config.configcenter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.file.FileSystemDynamicConfiguration; import org.apache.dubbo.common.utils.StringUtils; import java.util.Collection; import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.utils.PathUtils.buildPath; import static org.apache.dubbo.common.utils.PathUtils.normalize; /** * An abstract implementation of {@link DynamicConfiguration} is like "tree-structure" path : * <ul> * <li>{@link FileSystemDynamicConfiguration "file"}</li> * <li>{@link org.apache.dubbo.configcenter.support.zookeeper.ZookeeperDynamicConfiguration "zookeeper"}</li> * <li>{@link org.apache.dubbo.configcenter.consul.ConsulDynamicConfiguration "consul"}</li> * </ul> * * @see DynamicConfiguration * @see AbstractDynamicConfiguration * @since 2.7.8 */ public abstract class TreePathDynamicConfiguration extends AbstractDynamicConfiguration { /** * The parameter name of URL for the config root path */ public static final String CONFIG_ROOT_PATH_PARAM_NAME = PARAM_NAME_PREFIX + "root-path"; /** * The parameter name of URL for the config base path */ public static final String CONFIG_BASE_PATH_PARAM_NAME = PARAM_NAME_PREFIX + "base-path"; /** * The default value of parameter of URL for the config base path */ public static final String DEFAULT_CONFIG_BASE_PATH = "/config"; protected final String rootPath; public TreePathDynamicConfiguration(URL url) { super(url); this.rootPath = getRootPath(url); } public TreePathDynamicConfiguration( String rootPath, String threadPoolPrefixName, int threadPoolSize, long keepAliveTime, String group, long timeout) { super(threadPoolPrefixName, threadPoolSize, keepAliveTime, group, timeout); this.rootPath = rootPath; } @Override protected final String doGetConfig(String key, String group) throws Exception { String pathKey = buildPathKey(group, key); return doGetConfig(pathKey); } @Override public final boolean publishConfig(String key, String group, String content) { String pathKey = buildPathKey(group, key); return Boolean.TRUE.equals(execute(() -> doPublishConfig(pathKey, content), getDefaultTimeout())); } @Override protected final boolean doRemoveConfig(String key, String group) throws Exception { String pathKey = buildPathKey(group, key); return doRemoveConfig(pathKey); } @Override public final void addListener(String key, String group, ConfigurationListener listener) { String pathKey = buildPathKey(group, key); doAddListener(pathKey, listener, key, group); } @Override public final void removeListener(String key, String group, ConfigurationListener listener) { String pathKey = buildPathKey(group, key); doRemoveListener(pathKey, listener); } protected abstract boolean doPublishConfig(String pathKey, String content) throws Exception; protected abstract String doGetConfig(String pathKey) throws Exception; protected abstract boolean doRemoveConfig(String pathKey) throws Exception; protected abstract Collection<String> doGetConfigKeys(String groupPath); protected abstract void doAddListener(String pathKey, ConfigurationListener listener, String key, String group); protected abstract void doRemoveListener(String pathKey, ConfigurationListener listener); protected String buildGroupPath(String group) { return buildPath(rootPath, group); } protected String buildPathKey(String group, String key) { return buildPath(buildGroupPath(group), key); } /** * Get the root path from the specified {@link URL connection URl} * * @param url the specified {@link URL connection URl} * @return non-null */ protected String getRootPath(URL url) { String rootPath = url.getParameter(CONFIG_ROOT_PATH_PARAM_NAME, buildRootPath(url)); rootPath = normalize(rootPath); int rootPathLength = rootPath.length(); if (rootPathLength > 1 && rootPath.endsWith(PATH_SEPARATOR)) { rootPath = rootPath.substring(0, rootPathLength - 1); } return rootPath; } private String buildRootPath(URL url) { return PATH_SEPARATOR + getConfigNamespace(url) + getConfigBasePath(url); } /** * Get the namespace from the specified {@link URL connection URl} * * @param url the specified {@link URL connection URl} * @return non-null */ protected String getConfigNamespace(URL url) { return url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP); } /** * Get the config base path from the specified {@link URL connection URl} * * @param url the specified {@link URL connection URl} * @return non-null */ protected String getConfigBasePath(URL url) { String configBasePath = url.getParameter(CONFIG_BASE_PATH_PARAM_NAME, DEFAULT_CONFIG_BASE_PATH); if (StringUtils.isNotEmpty(configBasePath) && !configBasePath.startsWith(PATH_SEPARATOR)) { configBasePath = PATH_SEPARATOR + configBasePath; } return configBasePath; } }
6,796
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEvent.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config.configcenter; import java.util.EventObject; import java.util.Objects; /** * An event raised when the config changed, immutable. * * @see ConfigChangeType */ public class ConfigChangedEvent extends EventObject { private final String key; private final String group; private final String content; private final ConfigChangeType changeType; public ConfigChangedEvent(String key, String group, String content) { this(key, group, content, ConfigChangeType.MODIFIED); } public ConfigChangedEvent(String key, String group, String content, ConfigChangeType changeType) { super(key + "," + group); this.key = key; this.group = group; this.content = content; this.changeType = changeType; } public String getKey() { return key; } public String getGroup() { return group; } public String getContent() { return content; } public ConfigChangeType getChangeType() { return changeType; } @Override public String toString() { return "ConfigChangedEvent{" + "key='" + key + '\'' + ", group='" + group + '\'' + ", content='" + content + '\'' + ", changeType=" + changeType + "} " + super.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ConfigChangedEvent)) { return false; } ConfigChangedEvent that = (ConfigChangedEvent) o; return Objects.equals(getKey(), that.getKey()) && Objects.equals(getGroup(), that.getGroup()) && Objects.equals(getContent(), that.getContent()) && getChangeType() == that.getChangeType(); } @Override public int hashCode() { return Objects.hash(getKey(), getGroup(), getContent(), getChangeType()); } }
6,797
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigurationListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config.configcenter; import java.util.EventListener; /** * Config listener, will get notified when the config it listens on changes. */ public interface ConfigurationListener extends EventListener { /** * Listener call back method. Listener gets notified by this method once there's any change happens on the config * the listener listens on. * * @param event config change event */ void process(ConfigChangedEvent event); }
6,798
0
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config
Create_ds/dubbo/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.dubbo.common.config.configcenter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.Configuration; /** * Dynamic Configuration * <br/> * From the use scenario internally inside framework, there are mainly three kinds of methods: * <ol> * <li>{@link #getProperties(String, String, long)}, get configuration file from Config Center at start up.</li> * <li>{@link #addListener(String, String, ConfigurationListener)}/ {@link #removeListener(String, String, ConfigurationListener)} * , add or remove listeners for governance rules or config items that need to watch.</li> * <li>{@link #getProperty(String, Object)}, get a single config item.</li> * <li>{@link #getConfig(String, String, long)}, get the specified config</li> * </ol> * * @see AbstractDynamicConfiguration */ public interface DynamicConfiguration extends Configuration, AutoCloseable { String DEFAULT_GROUP = "dubbo"; /** * {@link #addListener(String, String, ConfigurationListener)} * * @param key the key to represent a configuration * @param listener configuration listener */ default void addListener(String key, ConfigurationListener listener) { addListener(key, getDefaultGroup(), listener); } /** * {@link #removeListener(String, String, ConfigurationListener)} * * @param key the key to represent a configuration * @param listener configuration listener */ default void removeListener(String key, ConfigurationListener listener) { removeListener(key, getDefaultGroup(), listener); } /** * Register a configuration listener for a specified key * The listener only works for service governance purpose, so the target group would always be the value user * specifies at startup or 'dubbo' by default. This method will only register listener, which means it will not * trigger a notification that contains the current value. * * @param key the key to represent a configuration * @param group the group where the key belongs to * @param listener configuration listener */ void addListener(String key, String group, ConfigurationListener listener); /** * Stops one listener from listening to value changes in the specified key. * * @param key the key to represent a configuration * @param group the group where the key belongs to * @param listener configuration listener */ void removeListener(String key, String group, ConfigurationListener listener); /** * Get the configuration mapped to the given key and the given group with {@link #getDefaultTimeout() the default * timeout} * * @param key the key to represent a configuration * @param group the group where the key belongs to * @return target configuration mapped to the given key and the given group */ default String getConfig(String key, String group) { return getConfig(key, group, getDefaultTimeout()); } /** * get configItem which contains content and stat info. * * @param key * @param group * @return */ default ConfigItem getConfigItem(String key, String group) { String content = getConfig(key, group); return new ConfigItem(content, null); } /** * Get the configuration mapped to the given key and the given group. If the * configuration fails to fetch after timeout exceeds, IllegalStateException will be thrown. * * @param key the key to represent a configuration * @param group the group where the key belongs to * @param timeout timeout value for fetching the target config * @return target configuration mapped to the given key and the given group, IllegalStateException will be thrown * if timeout exceeds. */ String getConfig(String key, String group, long timeout) throws IllegalStateException; /** * This method are mostly used to get a compound config file with {@link #getDefaultTimeout() the default timeout}, * such as a complete dubbo.properties file. */ default String getProperties(String key, String group) throws IllegalStateException { return getProperties(key, group, getDefaultTimeout()); } /** * This method are mostly used to get a compound config file, such as a complete dubbo.properties file. * * @revision 2.7.4 */ default String getProperties(String key, String group, long timeout) throws IllegalStateException { return getConfig(key, group, timeout); } /** * Publish Config mapped to the given key under the {@link #getDefaultGroup() default group} * * @param key the key to represent a configuration * @param content the content of configuration * @return <code>true</code> if success, or <code>false</code> * @throws UnsupportedOperationException If the under layer does not support * @since 2.7.5 */ default boolean publishConfig(String key, String content) throws UnsupportedOperationException { return publishConfig(key, getDefaultGroup(), content); } /** * Publish Config mapped to the given key and the given group. * * @param key the key to represent a configuration * @param group the group where the key belongs to * @param content the content of configuration * @return <code>true</code> if success, or <code>false</code> * @throws UnsupportedOperationException If the under layer does not support * @since 2.7.5 */ default boolean publishConfig(String key, String group, String content) throws UnsupportedOperationException { return false; } /** * publish config mapped to this given key and given group with stat. * * @param key * @param group * @param content * @param ticket * @return * @throws UnsupportedOperationException */ default boolean publishConfigCas(String key, String group, String content, Object ticket) throws UnsupportedOperationException { return false; } /** * Get the default group for the operations * * @return The default value is {@link #DEFAULT_GROUP "dubbo"} * @since 2.7.5 */ default String getDefaultGroup() { return DEFAULT_GROUP; } /** * Get the default timeout for the operations in milliseconds * * @return The default value is <code>-1L</code> * @since 2.7.5 */ default long getDefaultTimeout() { return -1L; } /** * Close the configuration * * @throws Exception * @since 2.7.5 */ @Override default void close() throws Exception { throw new UnsupportedOperationException(); } /** * The format is '{interfaceName}:[version]:[group]' * * @return */ static String getRuleKey(URL url) { return url.getColonSeparatedKey(); } /** * @param key the key to represent a configuration * @param group the group where the key belongs to * @return <code>true</code> if success, or <code>false</code> * @since 2.7.8 */ default boolean removeConfig(String key, String group) { return true; } }
6,799