repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployer.java
dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployer.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.deploy; import org.apache.dubbo.common.config.ReferenceCache; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.concurrent.Future; /** * Export/refer services of module */ public interface ModuleDeployer extends Deployer<ModuleModel> { void initialize() throws IllegalStateException; Future start() throws IllegalStateException; Future getStartFuture(); void stop() throws IllegalStateException; void preDestroy() throws IllegalStateException; void postDestroy() throws IllegalStateException; boolean isInitialized(); ReferenceCache getReferenceCache(); void registerServiceInstance(); void prepare(); void setPending(); /** * Whether start in background, do not await finish */ boolean isBackground(); boolean hasRegistryInteraction(); ApplicationDeployer getApplicationDeployer(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/Deployer.java
dubbo-common/src/main/java/org/apache/dubbo/common/deploy/Deployer.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.deploy; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.concurrent.Future; public interface Deployer<E extends ScopeModel> { /** * Initialize the component */ void initialize() throws IllegalStateException; /** * Starts the component. * @return */ Future start() throws IllegalStateException; /** * Stops the component. */ void stop() throws IllegalStateException; /** * @return true if the component is added and waiting to start */ boolean isPending(); /** * @return true if the component is starting or has been started. */ boolean isRunning(); /** * @return true if the component has been started. * @see #start() * @see #isStarting() */ boolean isStarted(); boolean isCompletion(); /** * @return true if the component is starting. * @see #isStarted() */ boolean isStarting(); /** * @return true if the component is stopping. * @see #isStopped() */ boolean isStopping(); /** * @return true if the component is stopping. * @see #isStopped() */ boolean isStopped(); /** * @return true if the component has failed to start or has failed to stop. */ boolean isFailed(); /** * @return current state */ DeployState getState(); void addDeployListener(DeployListener<E> listener); void removeDeployListener(DeployListener<E> listener); Throwable getError(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListener.java
dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListener.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.deploy; import org.apache.dubbo.rpc.model.ScopeModel; public interface DeployListener<E extends ScopeModel> { /** * Useful to inject some configuration like MetricsConfig, RegistryConfig, etc. */ void onInitialize(E scopeModel); /** * Triggered before starting module. */ void onStarting(E scopeModel); /** * Triggered before registering and exposing the service. */ void onStarted(E scopeModel); /** * Triggered after deployer startup is complete. */ default void onCompletion(E scopeModel) {} /** * Triggered before the app is destroyed, * can do some customized things before offline the service and destroy reference. */ void onStopping(E scopeModel); /** * Triggered after the application is destroyed, * can do some customized things after the service is offline and the reference is destroyed. */ void onStopped(E scopeModel); /** * Useful to do something when deployer was failed. */ void onFailure(E scopeModel, Throwable cause); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployListener.java
dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployListener.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.deploy; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.model.ApplicationModel; /** * Listen for Dubbo application deployment events */ @SPI(scope = ExtensionScope.APPLICATION) public interface ApplicationDeployListener extends DeployListener<ApplicationModel> { default void onModuleStarted(ApplicationModel applicationModel) {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java
dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.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.deploy; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION; import static org.apache.dubbo.common.deploy.DeployState.COMPLETION; import static org.apache.dubbo.common.deploy.DeployState.FAILED; import static org.apache.dubbo.common.deploy.DeployState.PENDING; import static org.apache.dubbo.common.deploy.DeployState.STARTED; import static org.apache.dubbo.common.deploy.DeployState.STARTING; import static org.apache.dubbo.common.deploy.DeployState.STOPPED; import static org.apache.dubbo.common.deploy.DeployState.STOPPING; public abstract class AbstractDeployer<E extends ScopeModel> implements Deployer<E> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractDeployer.class); private volatile DeployState state = PENDING; private volatile Throwable lastError; protected volatile boolean initialized = false; protected List<DeployListener<E>> listeners = new CopyOnWriteArrayList<>(); private E scopeModel; public AbstractDeployer(E scopeModel) { this.scopeModel = scopeModel; } @Override public boolean isPending() { return state == PENDING; } @Override public boolean isRunning() { return state == STARTING || state == STARTED || state == COMPLETION; } @Override public boolean isStarted() { return state == STARTED || state == COMPLETION; } @Override public boolean isCompletion() { return state == COMPLETION; } @Override public boolean isStarting() { return state == STARTING; } @Override public boolean isStopping() { return state == STOPPING; } @Override public boolean isStopped() { return state == STOPPED; } @Override public boolean isFailed() { return state == FAILED; } @Override public DeployState getState() { return state; } @Override public void addDeployListener(DeployListener<E> listener) { listeners.add(listener); } @Override public void removeDeployListener(DeployListener<E> listener) { listeners.remove(listener); } public void setPending() { this.state = PENDING; } protected void setStarting() { this.state = STARTING; for (DeployListener<E> listener : listeners) { try { listener.onStarting(scopeModel); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle starting event", e); } } } protected void setStarted() { this.state = STARTED; for (DeployListener<E> listener : listeners) { try { listener.onStarted(scopeModel); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle started event", e); } } } protected void setCompletion() { this.state = COMPLETION; for (DeployListener<E> listener : listeners) { try { listener.onCompletion(scopeModel); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle completion event", e); } } } protected void setStopping() { this.state = STOPPING; for (DeployListener<E> listener : listeners) { try { listener.onStopping(scopeModel); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle stopping event", e); } } } protected void setStopped() { this.state = STOPPED; for (DeployListener<E> listener : listeners) { try { listener.onStopped(scopeModel); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle stopped event", e); } } } protected void setFailed(Throwable error) { this.state = FAILED; this.lastError = error; for (DeployListener<E> listener : listeners) { try { listener.onFailure(scopeModel, error); } catch (Throwable e) { logger.error( COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle failed event", e); } } } @Override public Throwable getError() { return lastError; } public boolean isInitialized() { return initialized; } protected String getIdentifier() { return scopeModel.getDesc(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployer.java
dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployer.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.deploy; import org.apache.dubbo.common.config.ReferenceCache; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.concurrent.Future; /** * initialize and start application instance */ public interface ApplicationDeployer extends Deployer<ApplicationModel> { /** * Initialize the component */ void initialize() throws IllegalStateException; /** * Starts the component. * @return */ Future start() throws IllegalStateException; /** * Stops the component. */ void stop() throws IllegalStateException; Future getStartFuture(); /** * Register application instance and start internal services */ void prepareApplicationInstance(ModuleModel moduleModel); void exportMetadataService(); void registerServiceInstance(); /** * Register application instance and start internal services */ void prepareInternalModule(); /** * Pre-processing before destroy model */ void preDestroy(); /** * Post-processing after destroy model */ void postDestroy(); /** * Indicates that the Application is initialized or not. */ boolean isInitialized(); ApplicationModel getApplicationModel(); ReferenceCache getReferenceCache(); /** * Whether start in background, do not await finish */ boolean isBackground(); /** * check all module state and update application state */ void checkState(ModuleModel moduleModel, DeployState moduleState); /** * module state changed callbacks */ void notifyModuleChanged(ModuleModel moduleModel, DeployState state); /** * refresh service instance */ void refreshServiceInstance(); /** * Increase the count of service update threads. * NOTE: should call ${@link ApplicationDeployer#decreaseServiceRefreshCount()} after update finished */ void increaseServiceRefreshCount(); /** * Decrease the count of service update threads */ void decreaseServiceRefreshCount(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployListener.java
dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployListener.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.deploy; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.model.ModuleModel; /** * Module deploy listener */ @SPI(scope = ExtensionScope.MODULE) public interface ModuleDeployListener extends DeployListener<ModuleModel> {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListenerAdapter.java
dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListenerAdapter.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.deploy; import org.apache.dubbo.rpc.model.ScopeModel; public class DeployListenerAdapter<E extends ScopeModel> implements DeployListener<E> { @Override public void onInitialize(E scopeModel) {} @Override public void onStarting(E scopeModel) {} @Override public void onStarted(E scopeModel) {} @Override public void onCompletion(E scopeModel) {} @Override public void onStopping(E scopeModel) {} @Override public void onStopped(E scopeModel) {} @Override public void onFailure(E scopeModel, Throwable cause) {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/store/DataStore.java
dubbo-common/src/main/java/org/apache/dubbo/common/store/DataStore.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.store; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.util.Map; @SPI(value = "simple", scope = ExtensionScope.APPLICATION) public interface DataStore { /** * return a snapshot value of componentName */ Map<String, Object> get(String componentName); Object get(String componentName, String key); void put(String componentName, String key, Object value); void remove(String componentName, String key); default void addListener(DataStoreUpdateListener dataStoreUpdateListener) {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/store/DataStoreUpdateListener.java
dubbo-common/src/main/java/org/apache/dubbo/common/store/DataStoreUpdateListener.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.store; public interface DataStoreUpdateListener { void onUpdate(String componentName, String key, Object value); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.java
dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.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.store.support; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.common.store.DataStoreUpdateListener; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class SimpleDataStore implements DataStore { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SimpleDataStore.class); // <component name or id, <data-name, data-value>> private final ConcurrentMap<String, ConcurrentMap<String, Object>> data = new ConcurrentHashMap<>(); private final ConcurrentHashSet<DataStoreUpdateListener> listeners = new ConcurrentHashSet<>(); @Override public Map<String, Object> get(String componentName) { ConcurrentMap<String, Object> value = data.get(componentName); if (value == null) { return new HashMap<>(); } return new HashMap<>(value); } @Override public Object get(String componentName, String key) { if (!data.containsKey(componentName)) { return null; } return data.get(componentName).get(key); } @Override public void put(String componentName, String key, Object value) { Map<String, Object> componentData = ConcurrentHashMapUtils.computeIfAbsent(data, componentName, k -> new ConcurrentHashMap<>()); componentData.put(key, value); notifyListeners(componentName, key, value); } @Override public void remove(String componentName, String key) { if (!data.containsKey(componentName)) { return; } data.get(componentName).remove(key); notifyListeners(componentName, key, null); } @Override public void addListener(DataStoreUpdateListener dataStoreUpdateListener) { listeners.add(dataStoreUpdateListener); } private void notifyListeners(String componentName, String key, Object value) { for (DataStoreUpdateListener listener : listeners) { try { listener.onUpdate(componentName, key, value); } catch (Throwable t) { logger.warn( LoggerCodeConstants.INTERNAL_ERROR, "", "", "Failed to notify data store update listener. " + "ComponentName: " + componentName + " Key: " + key, t); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchMethodException.java
dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchMethodException.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.bytecode; /** * NoSuchMethodException. */ public class NoSuchMethodException extends RuntimeException { private static final long serialVersionUID = -2725364246023268766L; public NoSuchMethodException() { super(); } public NoSuchMethodException(String msg) { super(msg); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchPropertyException.java
dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchPropertyException.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.bytecode; /** * NoSuchPropertyException. */ public class NoSuchPropertyException extends RuntimeException { private static final long serialVersionUID = -2725364246023268766L; public NoSuchPropertyException() { super(); } public NoSuchPropertyException(String msg) { super(msg); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java
dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.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.bytecode; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; public abstract class Mixin { private static final String PACKAGE_NAME = Mixin.class.getPackage().getName(); private static final AtomicLong MIXIN_CLASS_COUNTER = new AtomicLong(0); protected Mixin() {} /** * mixin interface and delegates. * all class must be public. * * @param ics interface class array. * @param dc delegate class. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?> dc) { return mixin(ics, new Class[] {dc}); } /** * mixin interface and delegates. * all class must be public. * * @param ics interface class array. * @param dc delegate class. * @param cl class loader. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?> dc, ClassLoader cl) { return mixin(ics, new Class[] {dc}, cl); } /** * mixin interface and delegates. * all class must be public. * * @param ics interface class array. * @param dcs delegate class array. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?>[] dcs) { return mixin(ics, dcs, ClassUtils.getCallerClassLoader(Mixin.class)); } /** * mixin interface and delegates. * all class must be public. * * @param ics interface class array. * @param dcs delegate class array. * @param cl class loader. * @return Mixin instance. */ public static Mixin mixin(Class<?>[] ics, Class<?>[] dcs, ClassLoader cl) { assertInterfaceArray(ics); long id = MIXIN_CLASS_COUNTER.getAndIncrement(); String pkg = null; ClassGenerator ccp = null, ccm = null; try { ccp = ClassGenerator.newInstance(cl); // impl constructor StringBuilder code = new StringBuilder(); for (int i = 0; i < dcs.length; i++) { if (!Modifier.isPublic(dcs[i].getModifiers())) { String npkg = dcs[i].getPackage().getName(); if (pkg == null) { pkg = npkg; } else { if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public interfaces class from different packages"); } } } ccp.addField("private " + dcs[i].getName() + " d" + i + ";"); code.append('d') .append(i) .append(" = (") .append(dcs[i].getName()) .append(")$1[") .append(i) .append("];\n"); if (MixinAware.class.isAssignableFrom(dcs[i])) { code.append('d').append(i).append(".setMixinInstance(this);\n"); } } ccp.addConstructor(Modifier.PUBLIC, new Class<?>[] {Object[].class}, code.toString()); Class<?> neighbor = null; // impl methods. Set<String> worked = new HashSet<>(); for (int i = 0; i < ics.length; i++) { if (!Modifier.isPublic(ics[i].getModifiers())) { String npkg = ics[i].getPackage().getName(); if (pkg == null) { pkg = npkg; neighbor = ics[i]; } else { if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public delegate class from different packages"); } } } ccp.addInterface(ics[i]); for (Method method : ics[i].getMethods()) { if ("java.lang.Object".equals(method.getDeclaringClass().getName())) { continue; } String desc = ReflectUtils.getDesc(method); if (worked.contains(desc)) { continue; } worked.add(desc); int ix = findMethod(dcs, desc); if (ix < 0) { throw new RuntimeException("Missing method [" + desc + "] implement."); } Class<?> rt = method.getReturnType(); String mn = method.getName(); if (Void.TYPE.equals(rt)) { ccp.addMethod( mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), "d" + ix + "." + mn + "($$);"); } else { ccp.addMethod( mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), "return ($r)d" + ix + "." + mn + "($$);"); } } } if (pkg == null) { pkg = PACKAGE_NAME; neighbor = Mixin.class; } // create MixinInstance class. String micn = pkg + ".mixin" + id; ccp.setClassName(micn); ccp.toClass(neighbor); // create Mixin class. String fcn = Mixin.class.getName() + id; ccm = ClassGenerator.newInstance(cl); ccm.setClassName(fcn); ccm.addDefaultConstructor(); ccm.setSuperClass(Mixin.class.getName()); ccm.addMethod("public Object newInstance(Object[] delegates){ return new " + micn + "($1); }"); Class<?> mixin = ccm.toClass(Mixin.class); return (Mixin) mixin.getDeclaredConstructor().newInstance(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { // release ClassGenerator if (ccp != null) { ccp.release(); } if (ccm != null) { ccm.release(); } } } private static int findMethod(Class<?>[] dcs, String desc) { Class<?> cl; Method[] methods; for (int i = 0; i < dcs.length; i++) { cl = dcs[i]; methods = cl.getMethods(); for (Method method : methods) { if (desc.equals(ReflectUtils.getDesc(method))) { return i; } } } return -1; } private static void assertInterfaceArray(Class<?>[] ics) { for (int i = 0; i < ics.length; i++) { if (!ics[i].isInterface()) { throw new RuntimeException("Class " + ics[i].getName() + " is not a interface."); } } } /** * new Mixin instance. * * @param ds delegates instance. * @return instance. */ public abstract Object newInstance(Object[] ds); public static interface MixinAware { void setMixinInstance(Object instance); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java
dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.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.bytecode; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.common.constants.CommonConstants.MAX_PROXY_COUNT; /** * Proxy. */ public class Proxy { public static final InvocationHandler THROW_UNSUPPORTED_INVOKER = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) { throw new UnsupportedOperationException("Method [" + ReflectUtils.getName(method) + "] unimplemented."); } }; private static final AtomicLong PROXY_CLASS_COUNTER = new AtomicLong(0); private static final Map<ClassLoader, Map<String, Proxy>> PROXY_CACHE_MAP = new WeakHashMap<>(); private final Class<?> classToCreate; protected Proxy(Class<?> classToCreate) { this.classToCreate = classToCreate; } /** * Get proxy. * * @param ics interface class array. * @return Proxy instance. */ public static Proxy getProxy(Class<?>... ics) { if (ics.length > MAX_PROXY_COUNT) { throw new IllegalArgumentException("interface limit exceeded"); } // ClassLoader from App Interface should support load some class from Dubbo ClassLoader cl = ics[0].getClassLoader(); ProtectionDomain domain = ics[0].getProtectionDomain(); // use interface class name list as key. String key = buildInterfacesKey(cl, ics); // get cache by class loader. final Map<String, Proxy> cache; synchronized (PROXY_CACHE_MAP) { cache = PROXY_CACHE_MAP.computeIfAbsent(cl, k -> new ConcurrentHashMap<>()); } Proxy proxy = cache.get(key); if (proxy == null) { synchronized (ics[0]) { proxy = cache.get(key); if (proxy == null) { // create Proxy class. proxy = new Proxy(buildProxyClass(cl, ics, domain)); cache.put(key, proxy); } } } return proxy; } private static String buildInterfacesKey(ClassLoader cl, Class<?>[] ics) { StringBuilder sb = new StringBuilder(); for (Class<?> ic : ics) { String itf = ic.getName(); if (!ic.isInterface()) { throw new RuntimeException(itf + " is not a interface."); } Class<?> tmp = null; try { tmp = Class.forName(itf, false, cl); } catch (ClassNotFoundException ignore) { } if (tmp != ic) { throw new IllegalArgumentException(ic + " is not visible from class loader"); } sb.append(itf).append(';'); } return sb.toString(); } private static Class<?> buildProxyClass(ClassLoader cl, Class<?>[] ics, ProtectionDomain domain) { ClassGenerator ccp = null; try { ccp = ClassGenerator.newInstance(cl); Set<String> worked = new HashSet<>(); List<Method> methods = new ArrayList<>(); String pkg = ics[0].getPackage().getName(); Class<?> neighbor = ics[0]; for (Class<?> ic : ics) { String npkg = ic.getPackage().getName(); if (!Modifier.isPublic(ic.getModifiers())) { if (!pkg.equals(npkg)) { throw new IllegalArgumentException("non-public interfaces from different packages"); } } ccp.addInterface(ic); for (Method method : ic.getMethods()) { String desc = ReflectUtils.getDesc(method); if (worked.contains(desc) || Modifier.isStatic(method.getModifiers())) { continue; } worked.add(desc); int ix = methods.size(); Class<?> rt = method.getReturnType(); Class<?>[] pts = method.getParameterTypes(); StringBuilder code = new StringBuilder("Object[] args = new Object[") .append(pts.length) .append("];"); for (int j = 0; j < pts.length; j++) { code.append(" args[") .append(j) .append("] = ($w)$") .append(j + 1) .append(';'); } code.append(" Object ret = handler.invoke(this, methods[") .append(ix) .append("], args);"); if (!Void.TYPE.equals(rt)) { code.append(" return ").append(asArgument(rt, "ret")).append(';'); } methods.add(method); ccp.addMethod( method.getName(), method.getModifiers(), rt, pts, method.getExceptionTypes(), code.toString()); } } // create ProxyInstance class. String pcn = neighbor.getName() + "DubboProxy" + PROXY_CLASS_COUNTER.getAndIncrement(); ccp.setClassName(pcn); ccp.addField("public static java.lang.reflect.Method[] methods;"); ccp.addField("private " + InvocationHandler.class.getName() + " handler;"); ccp.addConstructor( Modifier.PUBLIC, new Class<?>[] {InvocationHandler.class}, new Class<?>[0], "handler=$1;"); ccp.addDefaultConstructor(); Class<?> clazz = ccp.toClass(neighbor, cl, domain); clazz.getField("methods").set(null, methods.toArray(new Method[0])); return clazz; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { // release ClassGenerator if (ccp != null) { ccp.release(); } } } private static String asArgument(Class<?> cl, String name) { if (cl.isPrimitive()) { if (Boolean.TYPE == cl) { return name + "==null?false:((Boolean)" + name + ").booleanValue()"; } if (Byte.TYPE == cl) { return name + "==null?(byte)0:((Byte)" + name + ").byteValue()"; } if (Character.TYPE == cl) { return name + "==null?(char)0:((Character)" + name + ").charValue()"; } if (Double.TYPE == cl) { return name + "==null?(double)0:((Double)" + name + ").doubleValue()"; } if (Float.TYPE == cl) { return name + "==null?(float)0:((Float)" + name + ").floatValue()"; } if (Integer.TYPE == cl) { return name + "==null?(int)0:((Integer)" + name + ").intValue()"; } if (Long.TYPE == cl) { return name + "==null?(long)0:((Long)" + name + ").longValue()"; } if (Short.TYPE == cl) { return name + "==null?(short)0:((Short)" + name + ").shortValue()"; } throw new RuntimeException(name + " is unknown primitive type."); } return "(" + ReflectUtils.getName(cl) + ")" + name; } /** * get instance with default handler. * * @return instance. */ public Object newInstance() { return newInstance(THROW_UNSUPPORTED_INVOKER); } /** * get instance with special handler. * * @return instance. */ public Object newInstance(InvocationHandler handler) { Constructor<?> constructor; try { constructor = classToCreate.getDeclaredConstructor(InvocationHandler.class); return constructor.newInstance(handler); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } public Class<?> getClassToCreate() { return classToCreate; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/DubboLoaderClassPath.java
dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/DubboLoaderClassPath.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.bytecode; import java.io.InputStream; import java.net.URL; import javassist.LoaderClassPath; import javassist.NotFoundException; /** * Ensure javassist will load Dubbo's class from Dubbo's classLoader */ public class DubboLoaderClassPath extends LoaderClassPath { public DubboLoaderClassPath() { super(DubboLoaderClassPath.class.getClassLoader()); } @Override public InputStream openClassfile(String classname) throws NotFoundException { if (!classname.startsWith("org.apache.dubbo") && !classname.startsWith("grpc.health") && !classname.startsWith("com.google")) { return null; } return super.openClassfile(classname); } @Override public URL find(String classname) { if (!classname.startsWith("org.apache.dubbo")) { return null; } return super.find(classname); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Wrapper.java
dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/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.bytecode; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ReflectUtils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.stream.Collectors; import javassist.ClassPool; import javassist.CtMethod; /** * Wrapper. */ public abstract class Wrapper { // class wrapper map private static final ConcurrentMap<Class<?>, Wrapper> WRAPPER_MAP = new ConcurrentHashMap<>(); private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String[] OBJECT_METHODS = new String[] {"getClass", "hashCode", "toString", "equals"}; private static final Wrapper OBJECT_WRAPPER = new Wrapper() { @Override public String[] getMethodNames() { return OBJECT_METHODS; } @Override public String[] getDeclaredMethodNames() { return OBJECT_METHODS; } @Override public String[] getPropertyNames() { return EMPTY_STRING_ARRAY; } @Override public Class<?> getPropertyType(String pn) { return null; } @Override public Object getPropertyValue(Object instance, String pn) throws NoSuchPropertyException { throw new NoSuchPropertyException("Property [" + pn + "] not found."); } @Override public void setPropertyValue(Object instance, String pn, Object pv) throws NoSuchPropertyException { throw new NoSuchPropertyException("Property [" + pn + "] not found."); } @Override public boolean hasProperty(String name) { return false; } @Override public Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args) throws NoSuchMethodException { if ("getClass".equals(mn)) { return instance.getClass(); } if ("hashCode".equals(mn)) { return instance.hashCode(); } if ("toString".equals(mn)) { return instance.toString(); } if ("equals".equals(mn)) { if (args.length == 1) { return instance.equals(args[0]); } throw new IllegalArgumentException("Invoke method [" + mn + "] argument number error."); } throw new NoSuchMethodException("Method [" + mn + "] not found."); } }; private static AtomicLong WRAPPER_CLASS_COUNTER = new AtomicLong(0); /** * get wrapper. * * @param c Class instance. * @return Wrapper instance(not null). */ public static Wrapper getWrapper(Class<?> c) { return ConcurrentHashMapUtils.computeIfAbsent(WRAPPER_MAP, c, (clazz) -> { while (ClassGenerator.isDynamicClass(clazz)) // can not wrapper on dynamic class. { clazz = clazz.getSuperclass(); } if (clazz == Object.class) { return OBJECT_WRAPPER; } return makeWrapper(clazz); }); } private static Wrapper makeWrapper(Class<?> c) { if (c.isPrimitive()) { throw new IllegalArgumentException("Can not create wrapper for primitive type: " + c); } String name = c.getName(); ClassLoader cl = ClassUtils.getClassLoader(c); StringBuilder c1 = new StringBuilder("public void setPropertyValue(Object o, String n, Object v){ "); StringBuilder c2 = new StringBuilder("public Object getPropertyValue(Object o, String n){ "); StringBuilder c3 = new StringBuilder("public Object invokeMethod(Object o, String n, Class[] p, Object[] v) throws " + InvocationTargetException.class.getName() + "{ "); c1.append(name) .append(" w; try{ w = ((") .append(name) .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); c2.append(name) .append(" w; try{ w = ((") .append(name) .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); c3.append(name) .append(" w; try{ w = ((") .append(name) .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); Map<String, Class<?>> pts = new HashMap<>(); // <property name, property types> Map<String, Method> ms = new LinkedHashMap<>(); // <method desc, Method instance> List<String> mns = new ArrayList<>(); // method names. List<String> dmns = new ArrayList<>(); // declaring method names. // get all public field. for (Field f : c.getFields()) { String fn = f.getName(); Class<?> ft = f.getType(); if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) { continue; } c1.append(" if( $2.equals(\"") .append(fn) .append("\") ){ ((") .append(f.getDeclaringClass().getName()) .append(")w).") .append(fn) .append('=') .append(arg(ft, "$3")) .append("; return; }"); c2.append(" if( $2.equals(\"") .append(fn) .append("\") ){ return ($w)((") .append(f.getDeclaringClass().getName()) .append(")w).") .append(fn) .append("; }"); pts.put(fn, ft); } final ClassPool classPool = ClassGenerator.getClassPool(cl); List<String> allMethod = new ArrayList<>(); try { final CtMethod[] ctMethods = classPool.get(c.getName()).getMethods(); for (CtMethod method : ctMethods) { allMethod.add(ReflectUtils.getDesc(method)); } } catch (Exception e) { throw new RuntimeException(e); } Method[] methods = Arrays.stream(c.getMethods()) .filter(method -> allMethod.contains(ReflectUtils.getDesc(method))) .collect(Collectors.toList()) .toArray(new Method[] {}); // get all public method. boolean hasMethod = ClassUtils.hasMethods(methods); if (hasMethod) { Map<String, Integer> sameNameMethodCount = new HashMap<>((int) (methods.length / 0.75f) + 1); for (Method m : methods) { sameNameMethodCount.compute(m.getName(), (key, oldValue) -> oldValue == null ? 1 : oldValue + 1); } c3.append(" try{"); for (Method m : methods) { // ignore Object's method. if (m.getDeclaringClass() == Object.class) { continue; } String mn = m.getName(); c3.append(" if( \"").append(mn).append("\".equals( $2 ) "); int len = m.getParameterTypes().length; c3.append(" && ").append(" $3.length == ").append(len); boolean overload = sameNameMethodCount.get(m.getName()) > 1; if (overload) { if (len > 0) { for (int l = 0; l < len; l++) { c3.append(" && ") .append(" $3[") .append(l) .append("].getName().equals(\"") .append(m.getParameterTypes()[l].getName()) .append("\")"); } } } c3.append(" ) { "); if (m.getReturnType() == Void.TYPE) { c3.append(" w.") .append(mn) .append('(') .append(args(m.getParameterTypes(), "$4")) .append(");") .append(" return null;"); } else { c3.append(" return ($w)w.") .append(mn) .append('(') .append(args(m.getParameterTypes(), "$4")) .append(");"); } c3.append(" }"); mns.add(mn); if (m.getDeclaringClass() == c) { dmns.add(mn); } ms.put(ReflectUtils.getDesc(m), m); } c3.append(" } catch(Throwable e) { "); c3.append(" throw new java.lang.reflect.InvocationTargetException(e); "); c3.append(" }"); } c3.append(" throw new ") .append(NoSuchMethodException.class.getName()) .append("(\"Not found method \\\"\"+$2+\"\\\" in class ") .append(c.getName()) .append(".\"); }"); // deal with get/set method. Matcher matcher; for (Map.Entry<String, Method> entry : ms.entrySet()) { String md = entry.getKey(); Method method = entry.getValue(); if ((matcher = ReflectUtils.GETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { String pn = propertyName(matcher.group(1)); c2.append(" if( $2.equals(\"") .append(pn) .append("\") ){ return ($w)w.") .append(method.getName()) .append("(); }"); pts.put(pn, method.getReturnType()); } else if ((matcher = ReflectUtils.IS_HAS_CAN_METHOD_DESC_PATTERN.matcher(md)).matches()) { String pn = propertyName(matcher.group(1)); c2.append(" if( $2.equals(\"") .append(pn) .append("\") ){ return ($w)w.") .append(method.getName()) .append("(); }"); pts.put(pn, method.getReturnType()); } else if ((matcher = ReflectUtils.SETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { Class<?> pt = method.getParameterTypes()[0]; String pn = propertyName(matcher.group(1)); c1.append(" if( $2.equals(\"") .append(pn) .append("\") ){ w.") .append(method.getName()) .append('(') .append(arg(pt, "$3")) .append("); return; }"); pts.put(pn, pt); } } c1.append(" throw new ") .append(NoSuchPropertyException.class.getName()) .append("(\"Not found property \\\"\"+$2+\"\\\" field or setter method in class ") .append(c.getName()) .append(".\"); }"); c2.append(" throw new ") .append(NoSuchPropertyException.class.getName()) .append("(\"Not found property \\\"\"+$2+\"\\\" field or getter method in class ") .append(c.getName()) .append(".\"); }"); // make class long id = WRAPPER_CLASS_COUNTER.getAndIncrement(); ClassGenerator cc = ClassGenerator.newInstance(cl); cc.setClassName(c.getName() + "DubboWrap" + id); cc.setSuperClass(Wrapper.class); cc.addDefaultConstructor(); cc.addField("public static String[] pns;"); // property name array. cc.addField("public static " + Map.class.getName() + " pts;"); // property type map. cc.addField("public static String[] mns;"); // all method name array. cc.addField("public static String[] dmns;"); // declared method name array. for (int i = 0, len = ms.size(); i < len; i++) { cc.addField("public static Class[] mts" + i + ";"); } cc.addMethod("public String[] getPropertyNames(){ return pns; }"); cc.addMethod("public boolean hasProperty(String n){ return pts.containsKey($1); }"); cc.addMethod("public Class getPropertyType(String n){ return (Class)pts.get($1); }"); cc.addMethod("public String[] getMethodNames(){ return mns; }"); cc.addMethod("public String[] getDeclaredMethodNames(){ return dmns; }"); cc.addMethod(c1.toString()); cc.addMethod(c2.toString()); cc.addMethod(c3.toString()); try { Class<?> wc = cc.toClass(c); // setup static field. wc.getField("pts").set(null, pts); wc.getField("pns").set(null, pts.keySet().toArray(new String[0])); wc.getField("mns").set(null, mns.toArray(new String[0])); wc.getField("dmns").set(null, dmns.toArray(new String[0])); int ix = 0; for (Method m : ms.values()) { wc.getField("mts" + ix++).set(null, m.getParameterTypes()); } return (Wrapper) wc.getDeclaredConstructor().newInstance(); } catch (RuntimeException e) { throw e; } catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } finally { cc.release(); pts.clear(); ms.clear(); mns.clear(); dmns.clear(); } } private static String arg(Class<?> cl, String name) { if (cl.isPrimitive()) { if (cl == Boolean.TYPE) { return "((Boolean)" + name + ").booleanValue()"; } if (cl == Byte.TYPE) { return "((Byte)" + name + ").byteValue()"; } if (cl == Character.TYPE) { return "((Character)" + name + ").charValue()"; } if (cl == Double.TYPE) { return "((Number)" + name + ").doubleValue()"; } if (cl == Float.TYPE) { return "((Number)" + name + ").floatValue()"; } if (cl == Integer.TYPE) { return "((Number)" + name + ").intValue()"; } if (cl == Long.TYPE) { return "((Number)" + name + ").longValue()"; } if (cl == Short.TYPE) { return "((Number)" + name + ").shortValue()"; } throw new RuntimeException("Unknown primitive type: " + cl.getName()); } return "(" + ReflectUtils.getName(cl) + ")" + name; } private static String args(Class<?>[] cs, String name) { int len = cs.length; if (len == 0) { return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { if (i > 0) { sb.append(','); } sb.append(arg(cs[i], name + "[" + i + "]")); } return sb.toString(); } private static String propertyName(String pn) { return pn.length() == 1 || Character.isLowerCase(pn.charAt(1)) ? Character.toLowerCase(pn.charAt(0)) + pn.substring(1) : pn; } /** * get property name array. * * @return property name array. */ public abstract String[] getPropertyNames(); /** * get property type. * * @param pn property name. * @return Property type or nul. */ public abstract Class<?> getPropertyType(String pn); /** * has property. * * @param name property name. * @return has or has not. */ public abstract boolean hasProperty(String name); /** * get property value. * * @param instance instance. * @param pn property name. * @return value. */ public abstract Object getPropertyValue(Object instance, String pn) throws NoSuchPropertyException, IllegalArgumentException; /** * set property value. * * @param instance instance. * @param pn property name. * @param pv property value. */ public abstract void setPropertyValue(Object instance, String pn, Object pv) throws NoSuchPropertyException, IllegalArgumentException; /** * get property value. * * @param instance instance. * @param pns property name array. * @return value array. */ public Object[] getPropertyValues(Object instance, String[] pns) throws NoSuchPropertyException, IllegalArgumentException { Object[] ret = new Object[pns.length]; for (int i = 0; i < ret.length; i++) { ret[i] = getPropertyValue(instance, pns[i]); } return ret; } /** * set property value. * * @param instance instance. * @param pns property name array. * @param pvs property value array. */ public void setPropertyValues(Object instance, String[] pns, Object[] pvs) throws NoSuchPropertyException, IllegalArgumentException { if (pns.length != pvs.length) { throw new IllegalArgumentException("pns.length != pvs.length"); } for (int i = 0; i < pns.length; i++) { setPropertyValue(instance, pns[i], pvs[i]); } } /** * get method name array. * * @return method name array. */ public abstract String[] getMethodNames(); /** * get method name array. * * @return method name array. */ public abstract String[] getDeclaredMethodNames(); /** * has method. * * @param name method name. * @return has or has not. */ public boolean hasMethod(String name) { for (String mn : getMethodNames()) { if (mn.equals(name)) { return true; } } return false; } /** * invoke method. * * @param instance instance. * @param mn method name. * @param types * @param args argument array. * @return return value. */ public abstract Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args) throws NoSuchMethodException, InvocationTargetException; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.java
dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.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.bytecode; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.NotFoundException; public final class ClassGenerator { private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0); private static final String SIMPLE_NAME_TAG = "<init>"; private static final Map<ClassLoader, ClassPool> POOL_MAP = new ConcurrentHashMap<>(); // ClassLoader - ClassPool private ClassPool mPool; private CtClass mCtc; private String mClassName; private String mSuperClass; private Set<String> mInterfaces; private List<String> mFields; private List<String> mConstructors; private List<String> mMethods; private ClassLoader mClassLoader; private Map<String, Method> mCopyMethods; // <method desc,method instance> private Map<String, Constructor<?>> mCopyConstructors; // <constructor desc,constructor instance> private boolean mDefaultConstructor = false; private ClassGenerator() {} private ClassGenerator(ClassLoader classLoader, ClassPool pool) { mClassLoader = classLoader; mPool = pool; } public static ClassGenerator newInstance() { return new ClassGenerator( Thread.currentThread().getContextClassLoader(), getClassPool(Thread.currentThread().getContextClassLoader())); } public static ClassGenerator newInstance(ClassLoader loader) { return new ClassGenerator(loader, getClassPool(loader)); } public static boolean isDynamicClass(Class<?> cl) { return ClassGenerator.DC.class.isAssignableFrom(cl); } public static ClassPool getClassPool(ClassLoader loader) { if (loader == null) { return ClassPool.getDefault(); } ClassPool pool = POOL_MAP.get(loader); if (pool == null) { synchronized (POOL_MAP) { pool = POOL_MAP.get(loader); if (pool == null) { pool = new ClassPool(true); pool.insertClassPath(new LoaderClassPath(loader)); pool.insertClassPath(new DubboLoaderClassPath()); POOL_MAP.put(loader, pool); } } } return pool; } private static String modifier(int mod) { StringBuilder modifier = new StringBuilder(); if (Modifier.isPublic(mod)) { modifier.append("public"); } else if (Modifier.isProtected(mod)) { modifier.append("protected"); } else if (Modifier.isPrivate(mod)) { modifier.append("private"); } if (Modifier.isStatic(mod)) { modifier.append(" static"); } if (Modifier.isVolatile(mod)) { modifier.append(" volatile"); } return modifier.toString(); } public String getClassName() { return mClassName; } public ClassGenerator setClassName(String name) { mClassName = name; return this; } public ClassGenerator addInterface(String cn) { if (mInterfaces == null) { mInterfaces = new HashSet<>(); } mInterfaces.add(cn); return this; } public ClassGenerator addInterface(Class<?> cl) { return addInterface(cl.getName()); } public ClassGenerator setSuperClass(String cn) { mSuperClass = cn; return this; } public ClassGenerator setSuperClass(Class<?> cl) { mSuperClass = cl.getName(); return this; } public ClassGenerator addField(String code) { if (mFields == null) { mFields = new ArrayList<>(); } mFields.add(code); return this; } public ClassGenerator addField(String name, int mod, Class<?> type) { return addField(name, mod, type, null); } public ClassGenerator addField(String name, int mod, Class<?> type, String def) { StringBuilder sb = new StringBuilder(); sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' '); sb.append(name); if (StringUtils.isNotEmpty(def)) { sb.append('='); sb.append(def); } sb.append(';'); return addField(sb.toString()); } public ClassGenerator addMethod(String code) { if (mMethods == null) { mMethods = new ArrayList<>(); } mMethods.add(code); return this; } public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, String body) { return addMethod(name, mod, rt, pts, null, body); } public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, Class<?>[] ets, String body) { StringBuilder sb = new StringBuilder(); sb.append(modifier(mod)) .append(' ') .append(ReflectUtils.getName(rt)) .append(' ') .append(name); sb.append('('); if (ArrayUtils.isNotEmpty(pts)) { for (int i = 0; i < pts.length; i++) { if (i > 0) { sb.append(','); } sb.append(ReflectUtils.getName(pts[i])); sb.append(" arg").append(i); } } sb.append(')'); if (ArrayUtils.isNotEmpty(ets)) { sb.append(" throws "); for (int i = 0; i < ets.length; i++) { if (i > 0) { sb.append(','); } sb.append(ReflectUtils.getName(ets[i])); } } sb.append('{').append(body).append('}'); return addMethod(sb.toString()); } public ClassGenerator addMethod(Method m) { addMethod(m.getName(), m); return this; } public ClassGenerator addMethod(String name, Method m) { String desc = name + ReflectUtils.getDescWithoutMethodName(m); addMethod(':' + desc); if (mCopyMethods == null) { mCopyMethods = new ConcurrentHashMap<>(8); } mCopyMethods.put(desc, m); return this; } public ClassGenerator addConstructor(String code) { if (mConstructors == null) { mConstructors = new LinkedList<>(); } mConstructors.add(code); return this; } public ClassGenerator addConstructor(int mod, Class<?>[] pts, String body) { return addConstructor(mod, pts, null, body); } public ClassGenerator addConstructor(int mod, Class<?>[] pts, Class<?>[] ets, String body) { StringBuilder sb = new StringBuilder(); sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG); sb.append('('); for (int i = 0; i < pts.length; i++) { if (i > 0) { sb.append(','); } sb.append(ReflectUtils.getName(pts[i])); sb.append(" arg").append(i); } sb.append(')'); if (ArrayUtils.isNotEmpty(ets)) { sb.append(" throws "); for (int i = 0; i < ets.length; i++) { if (i > 0) { sb.append(','); } sb.append(ReflectUtils.getName(ets[i])); } } sb.append('{').append(body).append('}'); return addConstructor(sb.toString()); } public ClassGenerator addConstructor(Constructor<?> c) { String desc = ReflectUtils.getDesc(c); addConstructor(":" + desc); if (mCopyConstructors == null) { mCopyConstructors = new ConcurrentHashMap<>(4); } mCopyConstructors.put(desc, c); return this; } public ClassGenerator addDefaultConstructor() { mDefaultConstructor = true; return this; } public ClassPool getClassPool() { return mPool; } /** * @param neighbor A class belonging to the same package that this * class belongs to. It is used to load the class. */ public Class<?> toClass(Class<?> neighbor) { return toClass(neighbor, mClassLoader, getClass().getProtectionDomain()); } public Class<?> toClass(Class<?> neighborClass, ClassLoader loader, ProtectionDomain pd) { if (mCtc != null) { mCtc.detach(); } long id = CLASS_NAME_COUNTER.getAndIncrement(); try { CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass); if (mClassName == null) { mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers()) ? ClassGenerator.class.getName() : mSuperClass + "$sc") + id; } mCtc = mPool.makeClass(mClassName); if (mSuperClass != null) { mCtc.setSuperclass(ctcs); } mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag. if (mInterfaces != null) { for (String cl : mInterfaces) { mCtc.addInterface(mPool.get(cl)); } } if (mFields != null) { for (String code : mFields) { mCtc.addField(CtField.make(code, mCtc)); } } if (mMethods != null) { for (String code : mMethods) { if (code.charAt(0) == ':') { mCtc.addMethod(CtNewMethod.copy( getCtMethod(mCopyMethods.get(code.substring(1))), code.substring(1, code.indexOf('(')), mCtc, null)); } else { mCtc.addMethod(CtNewMethod.make(code, mCtc)); } } } if (mDefaultConstructor) { mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc)); } if (mConstructors != null) { for (String code : mConstructors) { if (code.charAt(0) == ':') { mCtc.addConstructor(CtNewConstructor.copy( getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null)); } else { String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $. mCtc.addConstructor( CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length - 1]), mCtc)); } } } try { return mPool.toClass(mCtc, neighborClass, loader, pd); } catch (Throwable t) { if (!(t instanceof CannotCompileException)) { return mPool.toClass(mCtc, loader, pd); } throw t; } } catch (RuntimeException e) { throw e; } catch (NotFoundException | CannotCompileException e) { throw new RuntimeException(e.getMessage(), e); } } public void release() { if (mCtc != null) { mCtc.detach(); } if (mInterfaces != null) { mInterfaces.clear(); } if (mFields != null) { mFields.clear(); } if (mMethods != null) { mMethods.clear(); } if (mConstructors != null) { mConstructors.clear(); } if (mCopyMethods != null) { mCopyMethods.clear(); } if (mCopyConstructors != null) { mCopyConstructors.clear(); } } private CtClass getCtClass(Class<?> c) throws NotFoundException { return mPool.get(c.getName()); } private CtMethod getCtMethod(Method m) throws NotFoundException { return getCtClass(m.getDeclaringClass()).getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m)); } private CtConstructor getCtConstructor(Constructor<?> c) throws NotFoundException { return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c)); } public static interface DC {} // dynamic class tag interface. }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.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.json; import org.apache.dubbo.common.utils.ClassUtils; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_GSON; public class GsonUtils { // weak reference of com.google.gson.Gson, prevent throw exception when init private static volatile Object gsonCache = null; private static volatile Boolean supportGson; private static boolean isSupportGson() { if (supportGson == null) { synchronized (GsonUtils.class) { if (supportGson == null) { try { Class<?> aClass = ClassUtils.forName("com.google.gson.Gson"); supportGson = aClass != null; } catch (Throwable t) { supportGson = false; } } } } return supportGson; } public static Object fromJson(String json, Type originType) throws RuntimeException { if (!isSupportGson()) { throw new RuntimeException("Gson is not supported. Please import Gson in JVM env."); } Type type = TypeToken.get(originType).getType(); try { return getGson().fromJson(json, type); } catch (JsonSyntaxException ex) { throw new RuntimeException(String.format( "Generic serialization [%s] Json syntax exception thrown when parsing (message:%s type:%s) error:%s", GENERIC_SERIALIZATION_GSON, json, type.toString(), ex.getMessage())); } } public static String toJson(Object obj) throws RuntimeException { if (!isSupportGson()) { throw new RuntimeException("Gson is not supported. Please import Gson in JVM env."); } try { return getGson().toJson(obj); } catch (JsonSyntaxException ex) { throw new RuntimeException(String.format( "Generic serialization [%s] Json syntax exception thrown when parsing (object:%s ) error:%s", GENERIC_SERIALIZATION_GSON, obj, ex.getMessage())); } } private static Gson getGson() { if (gsonCache == null || !(gsonCache instanceof Gson)) { synchronized (GsonUtils.class) { if (gsonCache == null || !(gsonCache instanceof Gson)) { gsonCache = new Gson(); } } } return (Gson) gsonCache; } /** * @deprecated for uts only */ @Deprecated protected static void setSupportGson(Boolean supportGson) { GsonUtils.supportGson = supportGson; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/json/JsonUtil.java
dubbo-common/src/main/java/org/apache/dubbo/common/json/JsonUtil.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.json; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.lang.reflect.Type; import java.util.List; import java.util.Map; @SPI(scope = ExtensionScope.FRAMEWORK) public interface JsonUtil { String getName(); boolean isSupport(); boolean isJson(String json); <T> T toJavaObject(String json, Type type); <T> List<T> toJavaList(String json, Class<T> clazz); String toJson(Object obj); String toPrettyJson(Object obj); List<?> getList(Map<String, ?> obj, String key); List<Map<String, ?>> getListOfObjects(Map<String, ?> obj, String key); List<String> getListOfStrings(Map<String, ?> obj, String key); Map<String, ?> getObject(Map<String, ?> obj, String key); Object convertObject(Object obj, Type type); Object convertObject(Object obj, Class<?> clazz); Double getNumberAsDouble(Map<String, ?> obj, String key); Integer getNumberAsInteger(Map<String, ?> obj, String key); Long getNumberAsLong(Map<String, ?> obj, String key); String getString(Map<String, ?> obj, String key); List<Map<String, ?>> checkObjectList(List<?> rawList); List<String> checkStringList(List<?> rawList); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJsonUtilImpl.java
dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJsonUtilImpl.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.json.impl; import org.apache.dubbo.common.json.JsonUtil; import org.apache.dubbo.common.utils.CollectionUtils; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public abstract class AbstractJsonUtilImpl implements JsonUtil { @Override public boolean isSupport() { try { Map<String, String> map = new HashMap<>(); map.put("json", "test"); if (!CollectionUtils.mapEquals(map, toJavaObject(toJson(map), Map.class))) { return false; } List<String> list = new LinkedList<>(); list.add("json"); return CollectionUtils.equals(list, toJavaList(toJson(list), String.class)); } catch (Throwable t) { return false; } } @Override public List<?> getList(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (!(value instanceof List)) { throw new ClassCastException(String.format("value '%s' for key '%s' in '%s' is not List", value, key, obj)); } return (List<?>) value; } /** * Gets a list from an object for the given key, and verifies all entries are objects. If the key * is not present, this returns null. If the value is not a List or an entry is not an object, * throws an exception. */ @Override public List<Map<String, ?>> getListOfObjects(Map<String, ?> obj, String key) { assert obj != null; List<?> list = getList(obj, key); if (list == null) { return null; } return checkObjectList(list); } /** * Gets a list from an object for the given key, and verifies all entries are strings. If the key * is not present, this returns null. If the value is not a List or an entry is not a string, * throws an exception. */ @Override public List<String> getListOfStrings(Map<String, ?> obj, String key) { assert obj != null; List<?> list = getList(obj, key); if (list == null) { return null; } return checkStringList(list); } /** * Gets an object from an object for the given key. If the key is not present, this returns null. * If the value is not a Map, throws an exception. */ @SuppressWarnings("unchecked") @Override public Map<String, ?> getObject(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (!(value instanceof Map)) { throw new ClassCastException( String.format("value '%s' for key '%s' in '%s' is not object", value, key, obj)); } return (Map<String, ?>) value; } /** * Gets a number from an object for the given key. If the key is not present, this returns null. * If the value does not represent a double, throws an exception. */ @Override public Double getNumberAsDouble(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (value instanceof Double) { return (Double) value; } if (value instanceof String) { try { return Double.parseDouble((String) value); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("value '%s' for key '%s' is not a double", value, key)); } } throw new IllegalArgumentException( String.format("value '%s' for key '%s' in '%s' is not a number", value, key, obj)); } /** * Gets a number from an object for the given key, casted to an integer. If the key is not * present, this returns null. If the value does not represent an integer, throws an exception. */ @Override public Integer getNumberAsInteger(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (value instanceof Double) { Double d = (Double) value; int i = d.intValue(); if (i != d) { throw new ClassCastException("Number expected to be integer: " + d); } return i; } if (value instanceof String) { try { return Integer.parseInt((String) value); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("value '%s' for key '%s' is not an integer", value, key)); } } throw new IllegalArgumentException(String.format("value '%s' for key '%s' is not an integer", value, key)); } /** * Gets a number from an object for the given key, casted to an long. If the key is not * present, this returns null. If the value does not represent a long integer, throws an * exception. */ @Override public Long getNumberAsLong(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (value instanceof Double) { Double d = (Double) value; long l = d.longValue(); if (l != d) { throw new ClassCastException("Number expected to be long: " + d); } return l; } if (value instanceof String) { try { return Long.parseLong((String) value); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("value '%s' for key '%s' is not a long integer", value, key)); } } throw new IllegalArgumentException(String.format("value '%s' for key '%s' is not a long integer", value, key)); } /** * Gets a string from an object for the given key. If the key is not present, this returns null. * If the value is not a String, throws an exception. */ @Override public String getString(Map<String, ?> obj, String key) { assert obj != null; assert key != null; if (!obj.containsKey(key)) { return null; } Object value = obj.get(key); if (!(value instanceof String)) { throw new ClassCastException( String.format("value '%s' for key '%s' in '%s' is not String", value, key, obj)); } return (String) value; } /** * Casts a list of unchecked JSON values to a list of checked objects in Java type. * If the given list contains a value that is not a Map, throws an exception. */ @SuppressWarnings("unchecked") @Override public List<Map<String, ?>> checkObjectList(List<?> rawList) { assert rawList != null; for (int i = 0; i < rawList.size(); i++) { if (!(rawList.get(i) instanceof Map)) { throw new ClassCastException( String.format("value %s for idx %d in %s is not object", rawList.get(i), i, rawList)); } } return (List<Map<String, ?>>) rawList; } /** * Casts a list of unchecked JSON values to a list of String. If the given list * contains a value that is not a String, throws an exception. */ @SuppressWarnings("unchecked") @Override public List<String> checkStringList(List<?> rawList) { assert rawList != null; for (int i = 0; i < rawList.size(); i++) { if (!(rawList.get(i) instanceof String)) { throw new ClassCastException( String.format("value '%s' for idx %d in '%s' is not string", rawList.get(i), i, rawList)); } } return (List<String>) rawList; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/JacksonImpl.java
dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/JacksonImpl.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.json.impl; import org.apache.dubbo.common.extension.Activate; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.databind.json.JsonMapper.Builder; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @Activate(order = 400, onClass = "com.fasterxml.jackson.databind.json.JsonMapper") public class JacksonImpl extends AbstractJsonUtilImpl { private volatile JsonMapper mapper; private final List<Module> customModules = new ArrayList<>(); @Override public String getName() { return "jackson"; } @Override public boolean isJson(String json) { try { JsonNode node = getMapper().readTree(json); return node.isObject() || node.isArray(); } catch (JsonProcessingException e) { return false; } } @Override public <T> T toJavaObject(String json, Type type) { try { JsonMapper mapper = getMapper(); return mapper.readValue(json, mapper.getTypeFactory().constructType(type)); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalArgumentException(e); } } @Override public <T> List<T> toJavaList(String json, Class<T> clazz) { try { JsonMapper mapper = getMapper(); // Use ArrayList.class instead of List.class for JDK 21+ compatibility // JDK 21+ introduced SequencedCollection interface which causes type inference issues with List.class return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz)); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalArgumentException(e); } } @Override public String toJson(Object obj) { try { return getMapper().writeValueAsString(obj); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalArgumentException(e); } } @Override public String toPrettyJson(Object obj) { try { return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e); } } @Override public Object convertObject(Object obj, Type type) { JsonMapper mapper = getMapper(); return mapper.convertValue(obj, mapper.constructType(type)); } @Override public Object convertObject(Object obj, Class<?> clazz) { return getMapper().convertValue(obj, clazz); } protected JsonMapper getMapper() { JsonMapper mapper = this.mapper; if (mapper == null) { synchronized (this) { mapper = this.mapper; if (mapper == null) { this.mapper = mapper = createBuilder().build(); } } } return mapper; } protected Builder createBuilder() { Builder builder = JsonMapper.builder() .configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .serializationInclusion(Include.NON_NULL) .addModule(new JavaTimeModule()); for (Module module : customModules) { builder.addModule(module); } return builder; } public void addModule(Module module) { synchronized (this) { customModules.add(module); // Invalidate the mapper to rebuild it this.mapper = null; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJson2Impl.java
dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJson2Impl.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.json.impl; import org.apache.dubbo.common.extension.Activate; import java.lang.reflect.Type; import java.util.List; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONValidator; import com.alibaba.fastjson2.JSONWriter.Feature; import com.alibaba.fastjson2.util.TypeUtils; @Activate(order = 100, onClass = "com.alibaba.fastjson2.JSON") public class FastJson2Impl extends AbstractJsonUtilImpl { @Override public String getName() { return "fastjson2"; } @Override public boolean isJson(String json) { return JSONValidator.from(json).validate(); } @Override public <T> T toJavaObject(String json, Type type) { return JSON.parseObject(json, type); } @Override public <T> List<T> toJavaList(String json, Class<T> clazz) { return JSON.parseArray(json, clazz); } @Override public String toJson(Object obj) { return JSON.toJSONString(obj, Feature.WriteEnumsUsingName); } @Override public String toPrettyJson(Object obj) { return JSON.toJSONString(obj, Feature.WriteEnumsUsingName, Feature.PrettyFormat); } @Override public Object convertObject(Object obj, Type type) { return TypeUtils.cast(obj, type); } @Override public Object convertObject(Object obj, Class<?> clazz) { return TypeUtils.cast(obj, clazz); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJsonImpl.java
dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJsonImpl.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.json.impl; import org.apache.dubbo.common.extension.Activate; import java.lang.reflect.Type; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.util.TypeUtils; @Activate(order = 200, onClass = "com.alibaba.fastjson.JSON") public class FastJsonImpl extends AbstractJsonUtilImpl { @Override public String getName() { return "fastjson"; } @Override public boolean isJson(String json) { try { Object obj = JSON.parse(json); return obj instanceof JSONObject || obj instanceof JSONArray; } catch (JSONException e) { return false; } } @Override public <T> T toJavaObject(String json, Type type) { return JSON.parseObject(json, type); } @Override public <T> List<T> toJavaList(String json, Class<T> clazz) { return JSON.parseArray(json, clazz); } @Override public String toJson(Object obj) { return JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect); } @Override public String toPrettyJson(Object obj) { return JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.PrettyFormat); } @Override public Object convertObject(Object obj, Type type) { return TypeUtils.cast(obj, type, ParserConfig.getGlobalInstance()); } @Override public Object convertObject(Object obj, Class<?> clazz) { return TypeUtils.cast(obj, clazz, ParserConfig.getGlobalInstance()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/GsonImpl.java
dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/GsonImpl.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.json.impl; import org.apache.dubbo.common.extension.Activate; import java.lang.reflect.Type; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; @Activate(order = 300, onClass = "com.google.gson.Gson") public class GsonImpl extends AbstractJsonUtilImpl { private volatile Gson gson; @Override public String getName() { return "gson"; } @Override public boolean isJson(String json) { try { JsonElement jsonElement = JsonParser.parseString(json); return jsonElement.isJsonObject() || jsonElement.isJsonArray(); } catch (JsonSyntaxException e) { return false; } } @Override public <T> T toJavaObject(String json, Type type) { return getGson().fromJson(json, type); } @Override public <T> List<T> toJavaList(String json, Class<T> clazz) { Type type = TypeToken.getParameterized(List.class, clazz).getType(); return getGson().fromJson(json, type); } @Override public String toJson(Object obj) { return getGson().toJson(obj); } @Override public String toPrettyJson(Object obj) { return createBuilder().setPrettyPrinting().create().toJson(obj); } @Override public Object convertObject(Object obj, Type type) { Gson gson = getGson(); return gson.fromJson(gson.toJsonTree(obj), type); } @Override public Object convertObject(Object obj, Class<?> clazz) { Gson gson = getGson(); return gson.fromJson(gson.toJsonTree(obj), clazz); } protected Gson getGson() { Gson gson = this.gson; if (gson == null) { synchronized (this) { gson = this.gson; if (gson == null) { this.gson = gson = createBuilder().create(); } } } return gson; } protected GsonBuilder createBuilder() { return new GsonBuilder(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/infra/InfraAdapter.java
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); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/infra/support/EnvironmentAdapter.java
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); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceAddressURL.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceAddressURL.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.url.component; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_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.constants.RegistryConstants.PROVIDERS_CATEGORY; public abstract class ServiceAddressURL extends URL { protected final transient URL consumerURL; // cache private transient Map<String, String> concatenatedPrams; // private transient Map<String, String> allParameters; public ServiceAddressURL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters, URL consumerURL) { super(protocol, username, password, host, port, path, parameters); this.consumerURL = consumerURL; } public ServiceAddressURL(URLAddress urlAddress, URLParam urlParam, URL consumerURL) { super(urlAddress, urlParam); this.consumerURL = consumerURL; } @Override public String getPath() { String path = super.getPath(); if (StringUtils.isNotEmpty(path)) { return path; } return consumerURL.getPath(); } @Override public String getServiceInterface() { return consumerURL.getServiceInterface(); } @Override public String getApplication() { return consumerURL.getApplication(); } @Override public String getRemoteApplication() { return super.getParameter(APPLICATION_KEY); } @Override public String getGroup() { return super.getParameter(GROUP_KEY); } @Override public String getVersion() { return super.getParameter(VERSION_KEY); } @Override public String getOriginalParameter(String key) { // call corresponding methods directly, then we can remove the following if branches. if (GROUP_KEY.equals(key)) { return getGroup(); } else if (VERSION_KEY.equals(key)) { return getVersion(); } else if (APPLICATION_KEY.equals(key)) { return getRemoteApplication(); } else if (SIDE_KEY.equals(key)) { return getSide(); } else if (CATEGORY_KEY.equals(key)) { return getCategory(); } return super.getParameter(key); } @Override public String getParameter(String key) { // call corresponding methods directly, then we can remove the following if branches. if (GROUP_KEY.equals(key)) { return getGroup(); } else if (VERSION_KEY.equals(key)) { return getVersion(); } else if (APPLICATION_KEY.equals(key)) { return getRemoteApplication(); } else if (SIDE_KEY.equals(key)) { return getSide(); } else if (CATEGORY_KEY.equals(key)) { return getCategory(); } String value = null; if (consumerURL != null) { value = consumerURL.getParameter(key); } if (StringUtils.isEmpty(value)) { value = super.getParameter(key); } return value; } @Override public String getMethodParameter(String method, String key) { String value = null; if (consumerURL != null) { value = consumerURL.getMethodParameterStrict(method, key); } if (StringUtils.isEmpty(value)) { value = super.getMethodParameterStrict(method, key); } if (StringUtils.isEmpty(value)) { value = getParameter(key); } return value; } @Override public String getAnyMethodParameter(String key) { String value = null; if (consumerURL != null) { value = consumerURL.getAnyMethodParameter(key); } if (StringUtils.isEmpty(value)) { value = super.getAnyMethodParameter(key); } return value; } @Override public String getConcatenatedParameter(String key) { if (concatenatedPrams == null) { concatenatedPrams = new HashMap<>(1); } String value = concatenatedPrams.get(key); if (StringUtils.isNotEmpty(value)) { return value; } // Combine filters and listeners on Provider and Consumer String remoteValue = super.getParameter(key); String localValue = consumerURL.getParameter(key); if (remoteValue != null && remoteValue.length() > 0 && localValue != null && localValue.length() > 0) { value = remoteValue + "," + localValue; concatenatedPrams.put(key, value); return value; } if (localValue != null && localValue.length() > 0) { value = localValue; } else if (remoteValue != null && remoteValue.length() > 0) { value = remoteValue; } concatenatedPrams.put(key, value); return value; } @Override public String getCategory() { return PROVIDERS_CATEGORY; } @Override public String getSide() { return CONSUMER_SIDE; } public URL getConsumerURL() { return consumerURL; } @Override public int hashCode() { return super.hashCode(); } @Override public ScopeModel getScopeModel() { return consumerURL.getScopeModel(); } @Override public ServiceModel getServiceModel() { return consumerURL.getServiceModel(); } @Override public URL setScopeModel(ScopeModel scopeModel) { throw new UnsupportedOperationException("setScopeModel is forbidden for ServiceAddressURL"); } @Override public URL setServiceModel(ServiceModel serviceModel) { throw new UnsupportedOperationException("setServiceModel is forbidden for ServiceAddressURL"); } /** * ignore consumer url compare. * It's only meaningful for comparing two address urls related to the same consumerURL. * * @param obj * @return */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof ServiceAddressURL)) { return false; } return super.equals(obj); } @Override public String toString() { URLParam totalParam = getUrlParam().addParametersIfAbsent(consumerURL.getParameters()); return new ServiceConfigURL(getUrlAddress(), totalParam, null).toString(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/PathURLAddress.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/PathURLAddress.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.url.component; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import java.util.Objects; public class PathURLAddress extends URLAddress { private String protocol; private String username; private String password; private String path; private transient String address; private transient String ip; public PathURLAddress(String protocol, String username, String password, String path, String host, int port) { this(protocol, username, password, path, host, port, null); } public PathURLAddress( String protocol, String username, String password, String path, String host, int port, String rawAddress) { super(host, port, rawAddress); this.protocol = protocol; this.username = username; this.password = password; // trim the beginning "/" while (path != null && path.startsWith("/")) { path = path.substring(1); } if (path != null) { path = path.intern(); } this.path = path; } public String getProtocol() { return protocol; } public URLAddress setProtocol(String protocol) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } public String getUsername() { return username; } public URLAddress setUsername(String username) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } public String getPassword() { return password; } public PathURLAddress setPassword(String password) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } public String getPath() { return path; } public PathURLAddress setPath(String path) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } @Override public URLAddress setHost(String host) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } @Override public URLAddress setPort(int port) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } @Override public URLAddress setAddress(String host, int port) { return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } public String getAddress() { if (address == null) { address = getAddress(getHost(), getPort()); } return address; } /** * Fetch IP address for this URL. * <p> * Pls. note that IP should be used instead of Host when to compare with socket's address or to search in a map * which use address as its key. * * @return ip in string format */ public String getIp() { if (ip == null) { ip = NetUtils.getIpByHost(getHost()); } return ip; } @Override public int hashCode() { return Objects.hash(protocol, username, password, path, host, port); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof URLAddress)) return false; URLAddress that = (URLAddress) obj; return Objects.equals(this.getProtocol(), that.getProtocol()) && Objects.equals(this.getUsername(), that.getUsername()) && Objects.equals(this.getPassword(), that.getPassword()) && Objects.equals(this.getPath(), that.getPath()) && Objects.equals(this.getHost(), that.getHost()) && Objects.equals(this.getPort(), that.getPort()); } @Override public String toString() { if (rawAddress != null) { return rawAddress; } StringBuilder buf = new StringBuilder(); if (StringUtils.isNotEmpty(protocol)) { buf.append(protocol); buf.append("://"); } // // if (StringUtils.isNotEmpty(username)) { // buf.append(username); // if (StringUtils.isNotEmpty(password)) { // buf.append(":"); // buf.append(password); // } // buf.append("@"); // } if (StringUtils.isNotEmpty(host)) { buf.append(host); if (port > 0) { buf.append(':'); buf.append(port); } } if (StringUtils.isNotEmpty(path)) { buf.append('/'); buf.append(path); } return buf.toString(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLItemCache.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLItemCache.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.url.component; import org.apache.dubbo.common.utils.LRUCache; import org.apache.dubbo.common.utils.StringUtils; import java.util.Map; public class URLItemCache { // thread safe with limited size, by default 1000 private static final Map<String, String> PARAM_KEY_CACHE = new LRUCache<>(10000); private static final Map<String, String> PARAM_VALUE_CACHE = new LRUCache<>(50000); private static final Map<String, String> PATH_CACHE = new LRUCache<>(10000); private static final Map<String, String> REVISION_CACHE = new LRUCache<>(10000); public static void putParams(Map<String, String> params, String key, String value) { String cachedKey = PARAM_KEY_CACHE.get(key); if (StringUtils.isBlank(cachedKey)) { cachedKey = key; PARAM_KEY_CACHE.put(key, key); } String cachedValue = PARAM_VALUE_CACHE.get(value); if (StringUtils.isBlank(cachedValue)) { cachedValue = value; PARAM_VALUE_CACHE.put(value, value); } params.put(cachedKey, cachedValue); } public static String checkPath(String path) { if (StringUtils.isBlank(path)) { return path; } String cachedPath = PATH_CACHE.putIfAbsent(path, path); if (StringUtils.isNotBlank(cachedPath)) { return cachedPath; } return path; } public static String checkRevision(String revision) { if (StringUtils.isBlank(revision)) { return revision; } String cachedRevision = REVISION_CACHE.putIfAbsent(revision, revision); if (StringUtils.isNotBlank(cachedRevision)) { return cachedRevision; } return revision; } public static String intern(String protocol) { if (StringUtils.isBlank(protocol)) { return protocol; } return protocol.intern(); } public static void putParamsIntern(Map<String, String> params, String key, String value) { if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) { params.put(key, value); return; } key = key.intern(); value = value.intern(); params.put(key, value); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLParam.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLParam.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.url.component; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLStrParser; import org.apache.dubbo.common.url.component.param.DynamicParamTable; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import java.util.AbstractMap; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.StringJoiner; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; /** * A class which store parameters for {@link URL} * <br/> * Using {@link DynamicParamTable} to compress common keys (i.e. side, version) * <br/> * {@link DynamicParamTable} allow to use only two integer value named `key` and * `value-offset` to find a unique string to string key-pair. Also, `value-offset` * is not required if the real value is the default value. * <br/> * URLParam should operate as Copy-On-Write, each modify actions will return a new Object * <br/> * <p> * NOTE: URLParam is not support serialization! {@link DynamicParamTable} is related with * current running environment. If you want to make URL as a parameter, please call * {@link URL#toSerializableURL()} to create {@link URLPlainParam} instead. * * @since 3.0 */ public class URLParam { /** * Maximum size of key-pairs requested using array moving to add into URLParam. * If user request like addParameter for only one key-pair, adding value into a array * on moving is more efficient. However when add more than ADD_PARAMETER_ON_MOVE_THRESHOLD * size of key-pairs, recover compressed array back to map can reduce operation count * when putting objects. */ private static final int ADD_PARAMETER_ON_MOVE_THRESHOLD = 1; /** * the original parameters string, empty if parameters have been modified or init by {@link Map} */ private final String rawParam; /** * using bit to save if index exist even if value is default value */ private final BitSet KEY; /** * an array which contains value-offset */ private final int[] VALUE; /** * store extra parameters which key not match in {@link DynamicParamTable} */ private final Map<String, String> EXTRA_PARAMS; /** * store method related parameters * <p> * K - key * V - * K - method * V - value * <p> * e.g. method1.mock=true => ( mock, (method1, true) ) */ private final Map<String, Map<String, String>> METHOD_PARAMETERS; private transient long timestamp; /** * Whether to enable DynamicParamTable compression */ protected boolean enableCompressed; private static final URLParam EMPTY_PARAM = new URLParam(new BitSet(0), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), ""); protected URLParam() { this.rawParam = null; this.KEY = null; this.VALUE = null; this.EXTRA_PARAMS = null; this.METHOD_PARAMETERS = null; this.enableCompressed = true; } protected URLParam( BitSet key, Map<Integer, Integer> value, Map<String, String> extraParams, Map<String, Map<String, String>> methodParameters, String rawParam) { this.KEY = key; this.VALUE = new int[value.size()]; for (int i = key.nextSetBit(0), offset = 0; i >= 0; i = key.nextSetBit(i + 1)) { if (value.containsKey(i)) { VALUE[offset++] = value.get(i); } else { throw new IllegalArgumentException(); } } this.EXTRA_PARAMS = Collections.unmodifiableMap((extraParams == null ? new HashMap<>() : new HashMap<>(extraParams))); this.METHOD_PARAMETERS = Collections.unmodifiableMap( (methodParameters == null) ? Collections.emptyMap() : new LinkedHashMap<>(methodParameters)); this.rawParam = rawParam; this.timestamp = System.currentTimeMillis(); this.enableCompressed = true; } protected URLParam( BitSet key, int[] value, Map<String, String> extraParams, Map<String, Map<String, String>> methodParameters, String rawParam) { this.KEY = key; this.VALUE = value; this.EXTRA_PARAMS = Collections.unmodifiableMap((extraParams == null ? new HashMap<>() : new HashMap<>(extraParams))); this.METHOD_PARAMETERS = Collections.unmodifiableMap( (methodParameters == null) ? Collections.emptyMap() : new LinkedHashMap<>(methodParameters)); this.rawParam = rawParam; this.timestamp = System.currentTimeMillis(); this.enableCompressed = true; } /** * Weather there contains some parameter match method * * @param method method name * @return contains or not */ public boolean hasMethodParameter(String method) { if (method == null) { return false; } String methodsString = getParameter(METHODS_KEY); if (StringUtils.isNotEmpty(methodsString)) { if (!methodsString.contains(method)) { return false; } } for (Map.Entry<String, Map<String, String>> methods : METHOD_PARAMETERS.entrySet()) { if (methods.getValue().containsKey(method)) { return true; } } return false; } /** * Get method related parameter. If not contains, use getParameter(key) instead. * Specially, in some situation like `method1.1.callback=true`, key is `1.callback`. * * @param method method name * @param key key * @return value */ public String getMethodParameter(String method, String key) { String strictResult = getMethodParameterStrict(method, key); return StringUtils.isNotEmpty(strictResult) ? strictResult : getParameter(key); } /** * Get method related parameter. If not contains, return null. * Specially, in some situation like `method1.1.callback=true`, key is `1.callback`. * * @param method method name * @param key key * @return value */ public String getMethodParameterStrict(String method, String key) { String methodsString = getParameter(METHODS_KEY); if (StringUtils.isNotEmpty(methodsString)) { if (!methodsString.contains(method)) { return null; } } Map<String, String> methodMap = METHOD_PARAMETERS.get(key); if (CollectionUtils.isNotEmptyMap(methodMap)) { return methodMap.get(method); } else { return null; } } public static Map<String, Map<String, String>> initMethodParameters(Map<String, String> parameters) { Map<String, Map<String, String>> methodParameters = new HashMap<>(); if (parameters == null) { return methodParameters; } String methodsString = parameters.get(METHODS_KEY); if (StringUtils.isNotEmpty(methodsString)) { String[] methods = methodsString.split(","); for (Map.Entry<String, String> entry : parameters.entrySet()) { String key = entry.getKey(); for (String method : methods) { String methodPrefix = method + '.'; if (key.startsWith(methodPrefix)) { String realKey = key.substring(methodPrefix.length()); URL.putMethodParameter(method, realKey, entry.getValue(), methodParameters); } } } } else { for (Map.Entry<String, String> entry : parameters.entrySet()) { String key = entry.getKey(); int methodSeparator = key.indexOf('.'); if (methodSeparator > 0) { String method = key.substring(0, methodSeparator); String realKey = key.substring(methodSeparator + 1); URL.putMethodParameter(method, realKey, entry.getValue(), methodParameters); } } } return methodParameters; } /** * An embedded Map adapt to URLParam * <br/> * copy-on-write mode, urlParam reference will be changed after modify actions. * If wishes to get the result after modify, please use {@link URLParamMap#getUrlParam()} */ public static class URLParamMap extends AbstractMap<String, String> { private URLParam urlParam; public URLParamMap(URLParam urlParam) { this.urlParam = urlParam; } public static class Node implements Map.Entry<String, String> { private final String key; private String value; public Node(String key, String value) { this.key = key; this.value = value; } @Override public String getKey() { return key; } @Override public String getValue() { return value; } @Override public String setValue(String value) { throw new UnsupportedOperationException(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Node node = (Node) o; return Objects.equals(key, node.key) && Objects.equals(value, node.value); } @Override public int hashCode() { return Objects.hash(key, value); } } @Override public int size() { return urlParam.KEY.cardinality() + urlParam.EXTRA_PARAMS.size(); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean containsKey(Object key) { if (key instanceof String) { return urlParam.hasParameter((String) key); } else { return false; } } @Override public boolean containsValue(Object value) { return values().contains(value); } @Override public String get(Object key) { if (key instanceof String) { return urlParam.getParameter((String) key); } else { return null; } } @Override public String put(String key, String value) { String previous = urlParam.getParameter(key); urlParam = urlParam.addParameter(key, value); return previous; } @Override public String remove(Object key) { if (key instanceof String) { String previous = urlParam.getParameter((String) key); urlParam = urlParam.removeParameters((String) key); return previous; } else { return null; } } @Override public void putAll(Map<? extends String, ? extends String> m) { urlParam = urlParam.addParameters((Map<String, String>) m); } @Override public void clear() { urlParam = urlParam.clearParameters(); } @Override public Set<String> keySet() { Set<String> set = new LinkedHashSet<>((int) ((urlParam.VALUE.length + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); for (int i = urlParam.KEY.nextSetBit(0); i >= 0; i = urlParam.KEY.nextSetBit(i + 1)) { set.add(DynamicParamTable.getKey(i)); } for (Entry<String, String> entry : urlParam.EXTRA_PARAMS.entrySet()) { set.add(entry.getKey()); } return Collections.unmodifiableSet(set); } @Override public Collection<String> values() { Set<String> set = new LinkedHashSet<>((int) ((urlParam.VALUE.length + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); for (int i = urlParam.KEY.nextSetBit(0); i >= 0; i = urlParam.KEY.nextSetBit(i + 1)) { String value; int offset = urlParam.keyIndexToOffset(i); value = DynamicParamTable.getValue(i, offset); set.add(value); } for (Entry<String, String> entry : urlParam.EXTRA_PARAMS.entrySet()) { set.add(entry.getValue()); } return Collections.unmodifiableSet(set); } @Override public Set<Entry<String, String>> entrySet() { Set<Entry<String, String>> set = new LinkedHashSet<>((int) ((urlParam.KEY.cardinality() + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); for (int i = urlParam.KEY.nextSetBit(0); i >= 0; i = urlParam.KEY.nextSetBit(i + 1)) { String value; int offset = urlParam.keyIndexToOffset(i); value = DynamicParamTable.getValue(i, offset); set.add(new Node(DynamicParamTable.getKey(i), value)); } for (Entry<String, String> entry : urlParam.EXTRA_PARAMS.entrySet()) { set.add(new Node(entry.getKey(), entry.getValue())); } return Collections.unmodifiableSet(set); } public URLParam getUrlParam() { return urlParam; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } URLParamMap that = (URLParamMap) o; return Objects.equals(urlParam, that.urlParam); } @Override public int hashCode() { return Objects.hash(urlParam); } } /** * Get a Map like URLParam * * @return a {@link URLParamMap} adapt to URLParam */ public Map<String, String> getParameters() { return new URLParamMap(this); } /** * Get any method related parameter which match key * * @param key key * @return result ( if any, random choose one ) */ public String getAnyMethodParameter(String key) { Map<String, String> methodMap = METHOD_PARAMETERS.get(key); if (CollectionUtils.isNotEmptyMap(methodMap)) { String methods = getParameter(METHODS_KEY); if (StringUtils.isNotEmpty(methods)) { for (String method : methods.split(",")) { String value = methodMap.get(method); if (StringUtils.isNotEmpty(value)) { return value; } } } else { return methodMap.values().iterator().next(); } } return null; } /** * Add parameters to a new URLParam. * * @param key key * @param value value * @return A new URLParam */ public URLParam addParameter(String key, String value) { if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } return addParameters(Collections.singletonMap(key, value)); } /** * Add absent parameters to a new URLParam. * * @param key key * @param value value * @return A new URLParam */ public URLParam addParameterIfAbsent(String key, String value) { if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } if (hasParameter(key)) { return this; } return addParametersIfAbsent(Collections.singletonMap(key, value)); } /** * Add parameters to a new URLParam. * If key-pair is present, this will cover it. * * @param parameters parameters in key-value pairs * @return A new URLParam */ public URLParam addParameters(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } boolean hasAndEqual = true; Map<String, String> urlParamMap = getParameters(); for (Map.Entry<String, String> entry : parameters.entrySet()) { String value = urlParamMap.get(entry.getKey()); if (value == null) { if (entry.getValue() != null) { hasAndEqual = false; break; } } else { if (!value.equals(entry.getValue())) { hasAndEqual = false; break; } } } // return immediately if there's no change if (hasAndEqual) { return this; } return doAddParameters(parameters, false); } /** * Add absent parameters to a new URLParam. * * @param parameters parameters in key-value pairs * @return A new URL */ public URLParam addParametersIfAbsent(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } return doAddParameters(parameters, true); } private URLParam doAddParameters(Map<String, String> parameters, boolean skipIfPresent) { // lazy init, null if no modify BitSet newKey = null; int[] newValueArray = null; Map<Integer, Integer> newValueMap = null; Map<String, String> newExtraParams = null; Map<String, Map<String, String>> newMethodParams = null; for (Map.Entry<String, String> entry : parameters.entrySet()) { if (skipIfPresent && hasParameter(entry.getKey())) { continue; } if (entry.getKey() == null || entry.getValue() == null) { continue; } int keyIndex = DynamicParamTable.getKeyIndex(enableCompressed, entry.getKey()); if (keyIndex < 0) { // entry key is not present in DynamicParamTable, add it to EXTRA_PARAMS if (newExtraParams == null) { newExtraParams = new HashMap<>(EXTRA_PARAMS); } newExtraParams.put(entry.getKey(), entry.getValue()); String[] methodSplit = entry.getKey().split("\\."); if (methodSplit.length == 2) { if (newMethodParams == null) { newMethodParams = new HashMap<>(METHOD_PARAMETERS); } Map<String, String> methodMap = newMethodParams.computeIfAbsent(methodSplit[1], (k) -> new HashMap<>()); methodMap.put(methodSplit[0], entry.getValue()); } } else { if (KEY.get(keyIndex)) { // contains key, replace value if (parameters.size() > ADD_PARAMETER_ON_MOVE_THRESHOLD) { // recover VALUE back to Map, use map to replace key pair if (newValueMap == null) { newValueMap = recoverValue(); } newValueMap.put(keyIndex, DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } else { newValueArray = replaceOffset( VALUE, keyIndexToIndex(KEY, keyIndex), DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } } else { // key is absent, add it if (newKey == null) { newKey = (BitSet) KEY.clone(); } newKey.set(keyIndex); if (parameters.size() > ADD_PARAMETER_ON_MOVE_THRESHOLD) { // recover VALUE back to Map if (newValueMap == null) { newValueMap = recoverValue(); } newValueMap.put(keyIndex, DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } else { // add parameter by moving array, only support for adding once newValueArray = addByMove( VALUE, keyIndexToIndex(newKey, keyIndex), DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } } } } if (newKey == null) { newKey = KEY; } if (newValueArray == null && newValueMap == null) { newValueArray = VALUE; } if (newExtraParams == null) { newExtraParams = EXTRA_PARAMS; } if (newMethodParams == null) { newMethodParams = METHOD_PARAMETERS; } if (newValueMap == null) { return new URLParam(newKey, newValueArray, newExtraParams, newMethodParams, null); } else { return new URLParam(newKey, newValueMap, newExtraParams, newMethodParams, null); } } private Map<Integer, Integer> recoverValue() { Map<Integer, Integer> map = new HashMap<>((int) (KEY.size() / 0.75) + 1); for (int i = KEY.nextSetBit(0), offset = 0; i >= 0; i = KEY.nextSetBit(i + 1)) { map.put(i, VALUE[offset++]); } return map; } private int[] addByMove(int[] array, int index, Integer value) { if (index < 0 || index > array.length) { throw new IllegalArgumentException(); } // copy-on-write int[] result = new int[array.length + 1]; System.arraycopy(array, 0, result, 0, index); result[index] = value; System.arraycopy(array, index, result, index + 1, array.length - index); return result; } private int[] replaceOffset(int[] array, int index, Integer value) { if (index < 0 || index > array.length) { throw new IllegalArgumentException(); } // copy-on-write int[] result = new int[array.length]; System.arraycopy(array, 0, result, 0, array.length); result[index] = value; return result; } /** * remove specified parameters in URLParam * * @param keys keys to being removed * @return A new URLParam */ public URLParam removeParameters(String... keys) { if (keys == null || keys.length == 0) { return this; } // lazy init, null if no modify BitSet newKey = null; int[] newValueArray = null; Map<String, String> newExtraParams = null; Map<String, Map<String, String>> newMethodParams = null; for (String key : keys) { int keyIndex = DynamicParamTable.getKeyIndex(enableCompressed, key); if (keyIndex >= 0 && KEY.get(keyIndex)) { if (newKey == null) { newKey = (BitSet) KEY.clone(); } newKey.clear(keyIndex); // which offset is in VALUE array, set value as -1, compress in the end if (newValueArray == null) { newValueArray = new int[VALUE.length]; System.arraycopy(VALUE, 0, newValueArray, 0, VALUE.length); } // KEY is immutable newValueArray[keyIndexToIndex(KEY, keyIndex)] = -1; } if (EXTRA_PARAMS.containsKey(key)) { if (newExtraParams == null) { newExtraParams = new HashMap<>(EXTRA_PARAMS); } newExtraParams.remove(key); String[] methodSplit = key.split("\\."); if (methodSplit.length == 2) { if (newMethodParams == null) { newMethodParams = new HashMap<>(METHOD_PARAMETERS); } Map<String, String> methodMap = newMethodParams.get(methodSplit[1]); if (CollectionUtils.isNotEmptyMap(methodMap)) { methodMap.remove(methodSplit[0]); } } } // ignore if key is absent } if (newKey == null) { newKey = KEY; } if (newValueArray == null) { newValueArray = VALUE; } else { // remove -1 value newValueArray = compressArray(newValueArray); } if (newExtraParams == null) { newExtraParams = EXTRA_PARAMS; } if (newMethodParams == null) { newMethodParams = METHOD_PARAMETERS; } if (newKey.cardinality() + newExtraParams.size() == 0) { // empty, directly return cache return EMPTY_PARAM; } else { return new URLParam(newKey, newValueArray, newExtraParams, newMethodParams, null); } } private int[] compressArray(int[] array) { int total = 0; for (int i : array) { if (i > -1) { total++; } } if (total == 0) { return new int[0]; } int[] result = new int[total]; for (int i = 0, offset = 0; i < array.length; i++) { // skip if value if less than 0 if (array[i] > -1) { result[offset++] = array[i]; } } return result; } /** * remove all of the parameters in URLParam * * @return An empty URLParam */ public URLParam clearParameters() { return EMPTY_PARAM; } /** * check if specified key is present in URLParam * * @param key specified key * @return present or not */ public boolean hasParameter(String key) { int keyIndex = DynamicParamTable.getKeyIndex(enableCompressed, key); if (keyIndex < 0) { return EXTRA_PARAMS.containsKey(key); } return KEY.get(keyIndex); } /** * get value of specified key in URLParam * * @param key specified key * @return value, null if key is absent */ public String getParameter(String key) { int keyIndex = DynamicParamTable.getKeyIndex(enableCompressed, key); if (keyIndex < 0) { return EXTRA_PARAMS.get(key); } if (KEY.get(keyIndex)) { String value; int offset = keyIndexToOffset(keyIndex); value = DynamicParamTable.getValue(keyIndex, offset); return value; // if (StringUtils.isEmpty(value)) { // // Forward compatible, make sure key dynamic increment can work. // // In that case, some values which are proceed before increment will set in EXTRA_PARAMS. // return EXTRA_PARAMS.get(key); // } else { // return value; // } } return null; } private int keyIndexToIndex(BitSet key, int keyIndex) { return key.get(0, keyIndex).cardinality(); } private int keyIndexToOffset(int keyIndex) { int arrayOffset = keyIndexToIndex(KEY, keyIndex); return VALUE[arrayOffset]; } /** * get raw string like parameters * * @return raw string like parameters */ public String getRawParam() { // If rawParam is not null, return it directly // If rawParam is null, it means that the parameters have been modified return toString(); } protected Map<String, Map<String, String>> getMethodParameters() { return METHOD_PARAMETERS; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } URLParam urlParam = (URLParam) o; if (Objects.equals(KEY, urlParam.KEY) && Arrays.equals(VALUE, urlParam.VALUE)) { if (CollectionUtils.isNotEmptyMap(EXTRA_PARAMS)) { if (CollectionUtils.isEmptyMap(urlParam.EXTRA_PARAMS) || EXTRA_PARAMS.size() != urlParam.EXTRA_PARAMS.size()) { return false; } for (Map.Entry<String, String> entry : EXTRA_PARAMS.entrySet()) { if (TIMESTAMP_KEY.equals(entry.getKey())) { continue; } if (!entry.getValue().equals(urlParam.EXTRA_PARAMS.get(entry.getKey()))) { return false; } } return true; } return CollectionUtils.isEmptyMap(urlParam.EXTRA_PARAMS); } return false; } private int hashCodeCache = -1; @Override public int hashCode() { if (hashCodeCache == -1) { int result = 1; for (Map.Entry<String, String> entry : EXTRA_PARAMS.entrySet()) { if (!TIMESTAMP_KEY.equals(entry.getKey())) { result += entry.hashCode(); } } result = 31 * result + Arrays.hashCode(VALUE); result = 31 * result + ((KEY == null) ? 0 : KEY.hashCode()); hashCodeCache = result; } return hashCodeCache; } @Override public String toString() { if (StringUtils.isNotEmpty(rawParam)) { return rawParam; } if ((KEY.cardinality() + EXTRA_PARAMS.size()) == 0) { return ""; } StringJoiner stringJoiner = new StringJoiner("&"); for (int i = KEY.nextSetBit(0); i >= 0; i = KEY.nextSetBit(i + 1)) { String key = DynamicParamTable.getKey(i); String value = DynamicParamTable.getValue(i, keyIndexToOffset(i)); value = value == null ? "" : value.trim(); stringJoiner.add(String.format("%s=%s", key, value)); } for (Map.Entry<String, String> entry : EXTRA_PARAMS.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); value = value == null ? "" : value.trim(); stringJoiner.add(String.format("%s=%s", key, value)); } return stringJoiner.toString(); } /** * Parse URLParam * Init URLParam by constructor is not allowed * rawParam field in result will be null while {@link URLParam#getRawParam()} will automatically create it * * @param params params map added into URLParam * @return a new URLParam */ public static URLParam parse(Map<String, String> params) {
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
true
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/DubboServiceAddressURL.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/DubboServiceAddressURL.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.url.component; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; public class DubboServiceAddressURL extends ServiceAddressURL { public static DubboServiceAddressURL valueOf(String rawURL, URL consumerURL) { return valueOf(rawURL, consumerURL, null); } public static DubboServiceAddressURL valueOf(String rawURL, URL consumerURL, ServiceConfigURL overriddenURL) { URL url = valueOf(rawURL, true); return new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, overriddenURL); } private ServiceConfigURL overrideURL; public DubboServiceAddressURL( URLAddress urlAddress, URLParam urlParam, URL consumerURL, ServiceConfigURL overrideURL) { super(urlAddress, urlParam, consumerURL); this.overrideURL = overrideURL; } @Override protected <T extends URL> T newURL(URLAddress urlAddress, URLParam urlParam) { return (T) new DubboServiceAddressURL(urlAddress, urlParam, this.consumerURL, this.overrideURL); } @Override public String getSide() { return consumerURL.getParameter(SIDE_KEY); } @Override public String getParameter(String key) { String value = null; if (overrideURL != null) { value = overrideURL.getParameter(key); } if (StringUtils.isEmpty(value)) { value = super.getParameter(key); } return value; } @Override public String getMethodParameter(String method, String key) { String value = null; if (overrideURL != null) { value = overrideURL.getMethodParameterStrict(method, key); } if (StringUtils.isEmpty(value)) { value = super.getMethodParameter(method, key); } return value; } @Override public String getAnyMethodParameter(String key) { String value = null; if (overrideURL != null) { value = overrideURL.getAnyMethodParameter(key); } if (StringUtils.isEmpty(value)) { value = super.getAnyMethodParameter(key); } return value; } /** * The returned parameters is imprecise regarding override priorities of consumer url and provider url. * This method is only used to pass the configuration in the 'client'. */ @Override public Map<String, String> getAllParameters() { Map<String, String> allParameters = new HashMap<>((int) (super.getParameters().size() / .75 + 1)); allParameters.putAll(super.getParameters()); if (consumerURL != null) { allParameters.putAll(consumerURL.getParameters()); } if (overrideURL != null) { allParameters.putAll(overrideURL.getParameters()); } return Collections.unmodifiableMap(allParameters); } public ServiceConfigURL getOverrideURL() { return overrideURL; } public void setOverrideURL(ServiceConfigURL overrideURL) { this.overrideURL = overrideURL; } @Override public ScopeModel getScopeModel() { return consumerURL.getScopeModel(); } @Override public ServiceModel getServiceModel() { return consumerURL.getServiceModel(); } @Override public int hashCode() { final int prime = 31; return prime * super.hashCode() + (overrideURL == null ? 0 : overrideURL.hashCode()); } /** * ignore consumer url compare. * It's only meaningful for comparing two AddressURLs related to the same consumerURL. * * @param obj * @return */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof DubboServiceAddressURL)) { return false; } if (overrideURL == null) { return super.equals(obj); } else { DubboServiceAddressURL other = (DubboServiceAddressURL) obj; boolean overrideEquals = Objects.equals( overrideURL.getParameters(), other.getOverrideURL().getParameters()); if (!overrideEquals) { return false; } Map<String, String> params = this.getParameters(); for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); if (overrideURL.getParameters().containsKey(key)) { continue; } if (!entry.getValue().equals(other.getUrlParam().getParameter(key))) { return false; } } } return true; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceConfigURL.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceConfigURL.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.url.component; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.StringUtils; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class ServiceConfigURL extends URL { private transient volatile ConcurrentMap<String, URL> urls; private transient volatile ConcurrentMap<String, Number> numbers; private transient volatile ConcurrentMap<String, Map<String, Number>> methodNumbers; private transient volatile String full; private transient volatile String string; private transient volatile String identity; private transient volatile String parameter; public ServiceConfigURL() { super(); } public ServiceConfigURL(URLAddress urlAddress, URLParam urlParam, Map<String, Object> attributes) { super(urlAddress, urlParam, attributes); } public ServiceConfigURL(String protocol, String host, int port) { this(protocol, null, null, host, port, null, (Map<String, String>) null); } public ServiceConfigURL( 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 ServiceConfigURL(String protocol, String host, int port, Map<String, String> parameters) { this(protocol, null, null, host, port, null, parameters); } public ServiceConfigURL(String protocol, String host, int port, String path) { this(protocol, null, null, host, port, path, (Map<String, String>) null); } public ServiceConfigURL(String protocol, String host, int port, String path, String... pairs) { this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs)); } public ServiceConfigURL(String protocol, String host, int port, String path, Map<String, String> parameters) { this(protocol, null, null, host, port, path, parameters); } public ServiceConfigURL(String protocol, String username, String password, String host, int port, String path) { this(protocol, username, password, host, port, path, (Map<String, String>) null); } public ServiceConfigURL( 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 ServiceConfigURL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) { this(new PathURLAddress(protocol, username, password, path, host, port), URLParam.parse(parameters), null); } public ServiceConfigURL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters, Map<String, Object> attributes) { this( new PathURLAddress(protocol, username, password, path, host, port), URLParam.parse(parameters), attributes); } @Override protected <T extends URL> T newURL(URLAddress urlAddress, URLParam urlParam) { return (T) new ServiceConfigURL(urlAddress, urlParam, attributes); } @Override public URL addAttributes(Map<String, Object> attributeMap) { Map<String, Object> newAttributes = new HashMap<>(); if (this.attributes != null) { newAttributes.putAll(this.attributes); } newAttributes.putAll(attributeMap); return new ServiceConfigURL(getUrlAddress(), getUrlParam(), newAttributes); } @Override public ServiceConfigURL putAttribute(String key, Object obj) { Map<String, Object> newAttributes = new HashMap<>(); if (attributes != null) { newAttributes.putAll(attributes); } newAttributes.put(key, obj); return new ServiceConfigURL(getUrlAddress(), getUrlParam(), newAttributes); } @Override public URL removeAttribute(String key) { Map<String, Object> newAttributes = new HashMap<>(); if (attributes != null) { newAttributes.putAll(attributes); } newAttributes.remove(key); return new ServiceConfigURL(getUrlAddress(), getUrlParam(), newAttributes); } @Override public String toString() { if (string != null) { return string; } return string = super.toString(); } @Override public String toFullString() { if (full != null) { return full; } return full = super.toFullString(); } @Override public String toIdentityString() { if (identity != null) { return identity; } return identity = super.toIdentityString(); } @Override public String toParameterString() { if (parameter != null) { return parameter; } return parameter = super.toParameterString(); } @Override public URL getUrlParameter(String key) { URL u = getUrls().get(key); if (u != null) { return u; } String value = getParameterAndDecoded(key); if (StringUtils.isEmpty(value)) { return null; } u = URL.valueOf(value); getUrls().put(key, u); return u; } @Override public double getParameter(String key, double defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.doubleValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } double d = Double.parseDouble(value); getNumbers().put(key, d); return d; } @Override public float getParameter(String key, float defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.floatValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } float f = Float.parseFloat(value); getNumbers().put(key, f); return f; } @Override public long getParameter(String key, long defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.longValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } long l = Long.parseLong(value); getNumbers().put(key, l); return l; } @Override public int getParameter(String key, int defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.intValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); getNumbers().put(key, i); return i; } @Override public short getParameter(String key, short defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.shortValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } short s = Short.parseShort(value); getNumbers().put(key, s); return s; } @Override public byte getParameter(String key, byte defaultValue) { Number n = getNumbers().get(key); if (n != null) { return n.byteValue(); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } byte b = Byte.parseByte(value); getNumbers().put(key, b); return b; } @Override public double getMethodParameter(String method, String key, double defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.doubleValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } double d = Double.parseDouble(value); updateCachedNumber(method, key, d); return d; } @Override public float getMethodParameter(String method, String key, float defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.floatValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } float f = Float.parseFloat(value); updateCachedNumber(method, key, f); return f; } @Override public long getMethodParameter(String method, String key, long defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.longValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } long l = Long.parseLong(value); updateCachedNumber(method, key, l); return l; } @Override public int getMethodParameter(String method, String key, int defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.intValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); updateCachedNumber(method, key, i); return i; } @Override public short getMethodParameter(String method, String key, short defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.shortValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } short s = Short.parseShort(value); updateCachedNumber(method, key, s); return s; } @Override public byte getMethodParameter(String method, String key, byte defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.byteValue(); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } byte b = Byte.parseByte(value); updateCachedNumber(method, key, b); return b; } @Override public double getServiceParameter(String service, String key, double defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.doubleValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } double d = Double.parseDouble(value); getNumbers().put(key, d); return d; } @Override public float getServiceParameter(String service, String key, float defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.floatValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } float f = Float.parseFloat(value); getNumbers().put(key, f); return f; } @Override public long getServiceParameter(String service, String key, long defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.longValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } long l = Long.parseLong(value); getNumbers().put(key, l); return l; } @Override public short getServiceParameter(String service, String key, short defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.shortValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } short s = Short.parseShort(value); getNumbers().put(key, s); return s; } @Override public byte getServiceParameter(String service, String key, byte defaultValue) { Number n = getServiceNumbers(service).get(key); if (n != null) { return n.byteValue(); } String value = getServiceParameter(service, key); if (StringUtils.isEmpty(value)) { return defaultValue; } byte b = Byte.parseByte(value); getNumbers().put(key, b); return b; } @Override public double getServiceMethodParameter(String service, String method, String key, double defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.doubleValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } double d = Double.parseDouble(value); updateCachedNumber(method, key, d); return d; } @Override public float getServiceMethodParameter(String service, String method, String key, float defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.floatValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } float f = Float.parseFloat(value); updateCachedNumber(method, key, f); return f; } @Override public long getServiceMethodParameter(String service, String method, String key, long defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.longValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } long l = Long.parseLong(value); updateCachedNumber(method, key, l); return l; } @Override public int getServiceMethodParameter(String service, String method, String key, int defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.intValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); updateCachedNumber(method, key, i); return i; } @Override public short getServiceMethodParameter(String service, String method, String key, short defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.shortValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } short s = Short.parseShort(value); updateCachedNumber(method, key, s); return s; } @Override public byte getServiceMethodParameter(String service, String method, String key, byte defaultValue) { Number n = getCachedNumber(method, key); if (n != null) { return n.byteValue(); } String value = getServiceMethodParameter(service, method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } byte b = Byte.parseByte(value); updateCachedNumber(method, key, b); return b; } private Map<String, URL> getUrls() { // concurrent initialization is tolerant if (urls == null) { urls = new ConcurrentHashMap<>(); } return urls; } protected Map<String, Number> getNumbers() { // concurrent initialization is tolerant if (numbers == null) { numbers = new ConcurrentHashMap<>(); } return numbers; } private Number getCachedNumber(String method, String key) { Map<String, Number> keyNumber = getMethodNumbers().get(method); if (keyNumber != null) { return keyNumber.get(key); } return null; } private void updateCachedNumber(String method, String key, Number n) { Map<String, Number> keyNumber = ConcurrentHashMapUtils.computeIfAbsent(getMethodNumbers(), method, m -> new HashMap<>()); keyNumber.put(key, n); } protected ConcurrentMap<String, Map<String, Number>> getMethodNumbers() { if (methodNumbers == null) { // concurrent initialization is tolerant methodNumbers = new ConcurrentHashMap<>(); } return methodNumbers; } protected Map<String, Number> getServiceNumbers(String service) { return getNumbers(); } protected Map<String, Map<String, Number>> getServiceMethodNumbers(String service) { return getMethodNumbers(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLPlainParam.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLPlainParam.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.url.component; import java.io.Serializable; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Act like URLParam, will not use DynamicParamTable to compress parameters, * which can support serializer serialization and deserialization. * DynamicParamTable is environment hard related. */ public class URLPlainParam extends URLParam implements Serializable { private static final long serialVersionUID = 4722019979665434393L; protected URLPlainParam( BitSet key, int[] value, Map<String, String> extraParams, Map<String, Map<String, String>> methodParameters, String rawParam) { super(key, value, extraParams, methodParameters, rawParam); this.enableCompressed = false; } public static URLPlainParam toURLPlainParam(URLParam urlParam) { Map<String, String> params = Collections.unmodifiableMap(new HashMap<>(urlParam.getParameters())); return new URLPlainParam( new BitSet(), new int[0], params, urlParam.getMethodParameters(), urlParam.getRawParam()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLAddress.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLAddress.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.url.component; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Objects; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; public class URLAddress implements Serializable { private static final long serialVersionUID = -1985165475234910535L; protected String host; protected int port; // cache protected transient String rawAddress; protected transient long timestamp; public URLAddress(String host, int port) { this(host, port, null); } public URLAddress(String host, int port, String rawAddress) { this.host = host; port = Math.max(port, 0); this.port = port; this.rawAddress = rawAddress; this.timestamp = System.currentTimeMillis(); } public String getProtocol() { return ""; } public URLAddress setProtocol(String protocol) { return this; } public String getUsername() { return ""; } public URLAddress setUsername(String username) { return this; } public String getPassword() { return ""; } public URLAddress setPassword(String password) { return this; } public String getPath() { return ""; } public URLAddress setPath(String path) { return this; } public String getHost() { return host; } public URLAddress setHost(String host) { return new URLAddress(host, port, null); } public int getPort() { return port; } public URLAddress setPort(int port) { return new URLAddress(host, port, null); } public String getAddress() { if (rawAddress == null) { rawAddress = getAddress(getHost(), getPort()); } return rawAddress; } public URLAddress setAddress(String host, int port) { return new URLAddress(host, port, rawAddress); } public String getIp() { return NetUtils.getIpByHost(getHost()); } public String getRawAddress() { return rawAddress; } protected String getAddress(String host, int port) { return port <= 0 ? host : host + ':' + port; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @Override public int hashCode() { return host.hashCode() * 31 + port; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof URLAddress)) return false; URLAddress that = (URLAddress) obj; return Objects.equals(this.getProtocol(), that.getProtocol()) && Objects.equals(this.getUsername(), that.getUsername()) && Objects.equals(this.getPassword(), that.getPassword()) && Objects.equals(this.getPath(), that.getPath()) && Objects.equals(this.getHost(), that.getHost()) && Objects.equals(this.getPort(), that.getPort()); } @Override public String toString() { if (rawAddress != null) { return rawAddress; } StringBuilder buf = new StringBuilder(); if (StringUtils.isNotEmpty(host)) { buf.append(host); if (port > 0) { buf.append(':'); buf.append(port); } } return buf.toString(); } public static URLAddress parse(String rawAddress, String defaultProtocol, boolean encoded) { try { String decodeStr = rawAddress; if (encoded) { decodeStr = URLDecoder.decode(rawAddress, "UTF-8"); } boolean isPathAddress = decodeStr.contains(PATH_SEPARATOR); if (isPathAddress) { return createPathURLAddress(decodeStr, rawAddress, defaultProtocol); } return createURLAddress(decodeStr, rawAddress, defaultProtocol); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } private static URLAddress createURLAddress(String decodeStr, String rawAddress, String defaultProtocol) { String host = null; int port = 0; int i = decodeStr.lastIndexOf(':'); if (i >= 0 && i < decodeStr.length() - 1) { if (decodeStr.lastIndexOf('%') > i) { // 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(decodeStr.substring(i + 1)); host = decodeStr.substring(0, i); } } else { host = decodeStr; } return new URLAddress(host, port, rawAddress); } private static PathURLAddress createPathURLAddress(String decodeStr, String rawAddress, String defaultProtocol) { String protocol = defaultProtocol; String path = null, username = null, password = null, host = null; int port = 0; int i = decodeStr.indexOf("://"); if (i >= 0) { if (i == 0) { throw new IllegalStateException("url missing protocol: \"" + decodeStr + "\""); } protocol = decodeStr.substring(0, i); decodeStr = decodeStr.substring(i + 3); } else { // case: file:/path/to/file.txt i = decodeStr.indexOf(":/"); if (i >= 0) { if (i == 0) { throw new IllegalStateException("url missing protocol: \"" + decodeStr + "\""); } protocol = decodeStr.substring(0, i); decodeStr = decodeStr.substring(i + 1); } } i = decodeStr.indexOf('/'); if (i >= 0) { path = decodeStr.substring(i + 1); decodeStr = decodeStr.substring(0, i); } i = decodeStr.lastIndexOf('@'); if (i >= 0) { username = decodeStr.substring(0, i); int j = username.indexOf(':'); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } decodeStr = decodeStr.substring(i + 1); } i = decodeStr.lastIndexOf(':'); if (i >= 0 && i < decodeStr.length() - 1) { if (decodeStr.lastIndexOf('%') > i) { // 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(decodeStr.substring(i + 1)); host = decodeStr.substring(0, i); } } // check cache protocol = URLItemCache.intern(protocol); path = URLItemCache.checkPath(path); return new PathURLAddress(protocol, username, password, path, host, port, rawAddress); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/FixedParamValue.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/FixedParamValue.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.url.component.param; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * In lower case */ public class FixedParamValue implements ParamValue { private final String[] values; private final Map<String, Integer> val2Index; public FixedParamValue(String... values) { if (values.length == 0) { throw new IllegalArgumentException("the array size of values should be larger than 0"); } this.values = values; Map<String, Integer> valueMap = new HashMap<>(values.length); for (int i = 0; i < values.length; i++) { if (values[i] != null) { valueMap.put(values[i].toLowerCase(Locale.ROOT), i); } } val2Index = Collections.unmodifiableMap(valueMap); } /** * DEFAULT value will be returned if n = 0 * @param n */ @Override public String getN(int n) { return values[n]; } @Override public int getIndex(String value) { Integer offset = val2Index.get(value.toLowerCase(Locale.ROOT)); if (offset == null) { throw new IllegalArgumentException("unrecognized value " + value + " , please check if value is illegal. " + "Permitted values: " + Arrays.asList(values)); } return offset; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicValues.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicValues.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.url.component.param; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class DynamicValues implements ParamValue { private volatile String[] index2Value = new String[1]; private final Map<String, Integer> value2Index = new ConcurrentHashMap<>(); private int indexSeq = 0; public DynamicValues(String defaultVal) { if (defaultVal == null) { indexSeq += 1; } else { add(defaultVal); } } public int add(String value) { Integer index = value2Index.get(value); if (index != null) { return index; } else { synchronized (this) { // thread safe if (!value2Index.containsKey(value)) { if (indexSeq == Integer.MAX_VALUE) { throw new IllegalStateException("URL Param Cache is full."); } // copy on write, only support append now String[] newValues = new String[indexSeq + 1]; System.arraycopy(index2Value, 0, newValues, 0, indexSeq); newValues[indexSeq] = value; index2Value = newValues; value2Index.put(value, indexSeq); indexSeq += 1; } } } return value2Index.get(value); } @Override public String getN(int n) { if (n == -1) { return null; } return index2Value[n]; } @Override public int getIndex(String value) { if (value == null) { return -1; } Integer index = value2Index.get(value); if (index == null) { return add(value); } return index; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DefaultDynamicParamSource.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DefaultDynamicParamSource.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.url.component.param; import org.apache.dubbo.common.constants.CommonConstants; import java.util.List; public class DefaultDynamicParamSource implements DynamicParamSource { @Override public void init(List<String> keys, List<ParamValue> values) { keys.add(CommonConstants.VERSION_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.SIDE_KEY); values.add(new FixedParamValue(CommonConstants.CONSUMER_SIDE, CommonConstants.PROVIDER_SIDE)); keys.add(CommonConstants.INTERFACE_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.PID_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.THREADPOOL_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.GROUP_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.VERSION_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.METADATA_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.APPLICATION_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.DUBBO_VERSION_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.RELEASE_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.PATH_KEY); values.add(new DynamicValues(null)); keys.add(CommonConstants.ANYHOST_KEY); values.add(new DynamicValues(null)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamTable.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamTable.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.url.component.param; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Global Param Cache Table * Not support method parameters */ public final class DynamicParamTable { /** * Keys array, value is string */ private static String[] ORIGIN_KEYS; private static ParamValue[] VALUES; private static final Map<String, Integer> KEY2INDEX = new HashMap<>(64); private DynamicParamTable() { throw new IllegalStateException(); } static { init(); } public static int getKeyIndex(boolean enabled, String key) { if (!enabled) { return -1; } Integer indexFromMap = KEY2INDEX.get(key); return indexFromMap == null ? -1 : indexFromMap; } public static int getValueIndex(String key, String value) { int idx = getKeyIndex(true, key); if (idx < 0) { throw new IllegalArgumentException("Cannot found key in url param:" + key); } ParamValue paramValue = VALUES[idx]; return paramValue.getIndex(value); } public static String getKey(int offset) { return ORIGIN_KEYS[offset]; } public static String getValue(int vi, int offset) { return VALUES[vi].getN(offset); } private static void init() { List<String> keys = new LinkedList<>(); List<ParamValue> values = new LinkedList<>(); Map<String, Integer> key2Index = new HashMap<>(64); keys.add(""); values.add(new DynamicValues(null)); FrameworkModel.defaultModel() .getExtensionLoader(DynamicParamSource.class) .getSupportedExtensionInstances() .forEach(source -> source.init(keys, values)); TreeMap<String, ParamValue> resultMap = new TreeMap<>(Comparator.comparingInt(System::identityHashCode)); for (int i = 0; i < keys.size(); i++) { resultMap.put(keys.get(i), values.get(i)); } ORIGIN_KEYS = resultMap.keySet().toArray(new String[0]); VALUES = resultMap.values().toArray(new ParamValue[0]); for (int i = 0; i < ORIGIN_KEYS.length; i++) { key2Index.put(ORIGIN_KEYS[i], i); } KEY2INDEX.putAll(key2Index); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/IgnoredParam.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/IgnoredParam.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.url.component.param; import java.util.HashSet; public class IgnoredParam { private static final HashSet<String> IGNORED = new HashSet<>(); static { IGNORED.add("timestamp"); } static boolean ignore(String key) { return IGNORED.contains(key); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamSource.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamSource.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.url.component.param; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.util.List; @SPI(scope = ExtensionScope.FRAMEWORK) public interface DynamicParamSource { void init(List<String> keys, List<ParamValue> values); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/ParamValue.java
dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/ParamValue.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.url.component.param; public interface ParamValue { /** * get value at the specified index. * * @param n the nth value * @return the value stored at index = n */ String getN(int n); /** * max index is 2^31 - 1 * * @param value the stored value * @return the index of value */ int getIndex(String value); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.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.utils; import org.apache.dubbo.common.logger.Level; import java.io.Serializable; public class Log implements Serializable { private static final long serialVersionUID = -534113138054377073L; private String logName; private Level logLevel; private String logMessage; private String logThread; public String getLogName() { return logName; } public void setLogName(String logName) { this.logName = logName; } public Level getLogLevel() { return logLevel; } public void setLogLevel(Level logLevel) { this.logLevel = logLevel; } public String getLogMessage() { return logMessage; } public void setLogMessage(String logMessage) { this.logMessage = logMessage; } public String getLogThread() { return logThread; } public void setLogThread(String logThread) { this.logThread = logThread; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((logLevel == null) ? 0 : logLevel.hashCode()); result = prime * result + ((logMessage == null) ? 0 : logMessage.hashCode()); result = prime * result + ((logName == null) ? 0 : logName.hashCode()); result = prime * result + ((logThread == null) ? 0 : logThread.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Log other = (Log) obj; if (logLevel == null) { if (other.logLevel != null) { return false; } } else if (!logLevel.equals(other.logLevel)) { return false; } if (logMessage == null) { if (other.logMessage != null) { return false; } } else if (!logMessage.equals(other.logMessage)) { return false; } if (logName == null) { if (other.logName != null) { return false; } } else if (!logName.equals(other.logName)) { return false; } if (logThread == null) { if (other.logThread != null) { return false; } } else if (!logThread.equals(other.logThread)) { return false; } return true; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.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.utils; import java.util.List; /** * The model class of pagination * * @since 2.7.5 */ public interface Page<T> { /** * Gets the offset of request * * @return positive integer */ int getOffset(); /** * Gets the size of request for pagination query * * @return positive integer */ int getPageSize(); /** * Gets the total amount of elements. * * @return the total amount of elements */ int getTotalSize(); /** * Get the number of total pages. * * @return the number of total pages. */ int getTotalPages(); /** * The data of current page * * @return non-null {@link List} */ List<T> getData(); /** * The size of {@link #getData() data} * * @return positive integer */ default int getDataSize() { return getData().size(); } /** * It indicates has next page or not * * @return if has , return <code>true</code>, or <code>false</code> */ boolean hasNext(); /** * Returns whether the page has data at all. * * @return */ default boolean hasData() { return getDataSize() > 0; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.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.utils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_JAVA_VERSION; /** * JRE version */ public enum JRE { JAVA_8, JAVA_9, JAVA_10, JAVA_11, JAVA_12, JAVA_13, JAVA_14, JAVA_15, JAVA_16, JAVA_17, JAVA_18, JAVA_19, JAVA_20, JAVA_21, JAVA_22, JAVA_23, JAVA_24, JAVA_25, OTHER; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JRE.class); private static final JRE VERSION = getJre(); /** * get current JRE version * * @return JRE version */ public static JRE currentVersion() { return VERSION; } /** * is current version * * @return true if current version */ public boolean isCurrentVersion() { return this == VERSION; } private static JRE getJre() { // get java version from system property String version = SystemPropertyConfigUtils.getSystemProperty(SYSTEM_JAVA_VERSION); boolean isBlank = StringUtils.isBlank(version); if (isBlank) { logger.debug("java.version is blank"); } // if start with 1.8 return java 8 if (!isBlank && version.startsWith("1.8")) { return JAVA_8; } // if JRE version is 9 or above, we can get version from java.lang.Runtime.version() try { Object javaRunTimeVersion = MethodUtils.invokeMethod(Runtime.getRuntime(), "version"); int majorVersion = MethodUtils.invokeMethod(javaRunTimeVersion, "major"); switch (majorVersion) { case 9: return JAVA_9; case 10: return JAVA_10; case 11: return JAVA_11; case 12: return JAVA_12; case 13: return JAVA_13; case 14: return JAVA_14; case 15: return JAVA_15; case 16: return JAVA_16; case 17: return JAVA_17; case 18: return JAVA_18; case 19: return JAVA_19; case 20: return JAVA_20; case 21: return JAVA_21; case 22: return JAVA_22; case 23: return JAVA_23; case 24: return JAVA_24; case 25: return JAVA_25; default: return OTHER; } } catch (Exception e) { logger.debug( "Can't determine current JRE version (maybe java.version is null), assuming that JRE version is 8.", e); } // default java 8 return JAVA_8; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultParameterNameReader.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultParameterNameReader.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.utils; import org.apache.dubbo.rpc.model.FrameworkModel; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.List; import java.util.Map; import java.util.Optional; public final class DefaultParameterNameReader implements ParameterNameReader { private final Map<Object, Optional<String[]>> cache = CollectionUtils.newConcurrentHashMap(); private final List<ParameterNameReader> readers; public DefaultParameterNameReader(FrameworkModel frameworkModel) { readers = frameworkModel.getActivateExtensions(ParameterNameReader.class); } @Override public String[] readParameterNames(Method method) { return cache.computeIfAbsent(method, k -> { String[] names = readByReflection(method.getParameters()); if (names == null) { for (ParameterNameReader reader : readers) { names = reader.readParameterNames(method); if (names != null) { break; } } } return Optional.ofNullable(names); }) .orElse(null); } @Override public String[] readParameterNames(Constructor<?> ctor) { return cache.computeIfAbsent(ctor, k -> { String[] names = readByReflection(ctor.getParameters()); if (names == null) { for (ParameterNameReader reader : readers) { names = reader.readParameterNames(ctor); if (names != null) { break; } } } return Optional.ofNullable(names); }) .orElse(null); } private static String[] readByReflection(Parameter[] parameters) { int len = parameters.length; if (len == 0) { return StringUtils.EMPTY_STRING_ARRAY; } String[] names = new String[len]; for (int i = 0; i < len; i++) { Parameter param = parameters[i]; if (!param.isNamePresent()) { return null; } names[i] = param.getName(); } return names; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/FieldUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/FieldUtils.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.utils; import java.lang.reflect.Field; import static org.apache.dubbo.common.utils.ClassUtils.getAllInheritedTypes; /** * The utilities class for Java Reflection {@link Field} * * @since 2.7.6 */ public interface FieldUtils { /** * Like the {@link Class#getDeclaredField(String)} method without throwing any {@link Exception} * * @param declaredClass the declared class * @param fieldName the name of {@link Field} * @return if field can't be found, return <code>null</code> */ static Field getDeclaredField(Class<?> declaredClass, String fieldName) { try { Field[] fields = declaredClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getName().equals(fieldName)) { return fields[i]; } } return null; } catch (Exception exception) { throw new RuntimeException(exception); } } /** * Find the {@link Field} by the name in the specified class and its inherited types * * @param declaredClass the declared class * @param fieldName the name of {@link Field} * @return if can't be found, return <code>null</code> */ static Field findField(Class<?> declaredClass, String fieldName) { Field field = getDeclaredField(declaredClass, fieldName); if (field != null) { return field; } for (Class superType : getAllInheritedTypes(declaredClass)) { field = getDeclaredField(superType, fieldName); if (field != null) { break; } } if (field == null) { throw new IllegalStateException(String.format("cannot find field %s,field is null", fieldName)); } return field; } /** * Find the {@link Field} by the name in the specified class and its inherited types * * @param object the object whose field should be modified * @param fieldName the name of {@link Field} * @return if can't be found, return <code>null</code> */ static Field findField(Object object, String fieldName) { return findField(object.getClass(), fieldName); } /** * Get the value of the specified {@link Field} * * @param object the object whose field should be modified * @param fieldName the name of {@link Field} * @return the value of the specified {@link Field} */ static Object getFieldValue(Object object, String fieldName) { return getFieldValue(object, findField(object, fieldName)); } /** * Get the value of the specified {@link Field} * * @param object the object whose field should be modified * @param field {@link Field} * @return the value of the specified {@link Field} */ static <T> T getFieldValue(Object object, Field field) { boolean accessible = field.isAccessible(); Object value = null; try { if (!accessible) { field.setAccessible(true); } value = field.get(object); } catch (IllegalAccessException ignored) { } finally { field.setAccessible(accessible); } return (T) value; } /** * Set the value for the specified {@link Field} * * @param object the object whose field should be modified * @param fieldName the name of {@link Field} * @param value the value of field to be set * @return the previous value of the specified {@link Field} */ static <T> T setFieldValue(Object object, String fieldName, T value) { return setFieldValue(object, findField(object, fieldName), value); } /** * Set the value for the specified {@link Field} * * @param object the object whose field should be modified * @param field {@link Field} * @param value the value of field to be set * @return the previous value of the specified {@link Field} */ static <T> T setFieldValue(Object object, Field field, T value) { boolean accessible = field.isAccessible(); Object previousValue = null; try { if (!accessible) { field.setAccessible(true); } previousValue = field.get(object); field.set(object, value); } catch (IllegalAccessException ignored) { } finally { field.setAccessible(accessible); } return (T) previousValue; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.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.utils; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN; public class ExecutorUtil { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExecutorUtil.class); private static final ThreadPoolExecutor SHUTDOWN_EXECUTOR = new ThreadPoolExecutor( 0, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100), new NamedThreadFactory("Close-ExecutorService-Timer", true)); public static boolean isTerminated(Executor executor) { if (!(executor instanceof ExecutorService)) { return false; } return ((ExecutorService) executor).isTerminated(); } public static boolean isShutdown(Executor executor) { if (!(executor instanceof ExecutorService)) { return false; } return ((ExecutorService) executor).isShutdown(); } /** * Use the shutdown pattern from: * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html * * @param executor the Executor to shutdown * @param timeout the timeout in milliseconds before termination */ public static void gracefulShutdown(Executor executor, int timeout) { if (!(executor instanceof ExecutorService) || isTerminated(executor)) { return; } final ExecutorService es = (ExecutorService) executor; try { // Disable new tasks from being submitted es.shutdown(); } catch (SecurityException | NullPointerException ex2) { return; } try { // Wait a while for existing tasks to terminate if (!es.awaitTermination(timeout, TimeUnit.MILLISECONDS)) { es.shutdownNow(); } } catch (InterruptedException ex) { es.shutdownNow(); Thread.currentThread().interrupt(); } if (!isTerminated(es)) { newThreadToCloseExecutor(es); } } public static void shutdownNow(Executor executor, final int timeout) { if (!(executor instanceof ExecutorService) || isTerminated(executor)) { return; } final ExecutorService es = (ExecutorService) executor; try { es.shutdownNow(); } catch (SecurityException | NullPointerException ex2) { return; } try { es.awaitTermination(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } if (!isTerminated(es)) { newThreadToCloseExecutor(es); } } private static void newThreadToCloseExecutor(final ExecutorService es) { if (!isTerminated(es)) { SHUTDOWN_EXECUTOR.execute(() -> { try { for (int i = 0; i < 1000; i++) { es.shutdownNow(); if (es.awaitTermination(10, TimeUnit.MILLISECONDS)) { break; } } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } catch (Throwable e) { logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", e.getMessage(), e); } }); } } /** * append thread name with url address * * @return new url with updated thread name */ public static URL setThreadName(URL url, String defaultName) { String name = url.getParameter(THREAD_NAME_KEY, defaultName); name = name + "-" + url.getAddress(); url = url.addParameter(THREAD_NAME_KEY, name); return url; } public static void cancelScheduledFuture(ScheduledFuture<?> scheduledFuture) { ScheduledFuture<?> future = scheduledFuture; if (future != null && !future.isCancelled()) { future.cancel(true); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/RegexProperties.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/RegexProperties.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.utils; import org.apache.dubbo.common.constants.CommonConstants; import java.util.Comparator; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Regex matching of keys is supported. */ public class RegexProperties extends Properties { @Override public String getProperty(String key) { String value = super.getProperty(key); if (value != null) { return value; } // Sort the keys to solve the problem of matching priority. List<String> sortedKeyList = keySet().stream() .map(k -> (String) k) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); String keyPattern = sortedKeyList.stream() .filter(k -> { String matchingKey = k; if (matchingKey.startsWith(CommonConstants.ANY_VALUE)) { matchingKey = CommonConstants.HIDE_KEY_PREFIX + matchingKey; } return Pattern.matches(matchingKey, key); }) .findFirst() .orElse(null); return keyPattern == null ? null : super.getProperty(keyPattern); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboAppender.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboAppender.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.utils; import org.apache.dubbo.common.logger.Level; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender; import org.apache.logging.log4j.core.appender.FileAppender; import org.apache.logging.log4j.core.config.Property; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute; import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory; @Plugin(name = "Dubbo", category = "Core", elementType = "appender") public class DubboAppender extends AbstractAppender { public static class Builder extends AbstractOutputStreamAppender.Builder<Builder> implements org.apache.logging.log4j.core.util.Builder<DubboAppender> { @PluginBuilderAttribute private String fileName; @PluginBuilderAttribute private boolean append = true; @PluginBuilderAttribute private boolean locking; public Builder setFileName(String fileName) { this.fileName = fileName; return this; } public Builder setAppend(boolean append) { this.append = append; return this; } public Builder setLocking(boolean locking) { this.locking = locking; return this; } @Override public DubboAppender build() { return new DubboAppender(getName(), buildFileAppender()); } private <B extends FileAppender.Builder<B>> FileAppender buildFileAppender() { FileAppender.Builder<B> builder = FileAppender.newBuilder(); builder.setIgnoreExceptions(isIgnoreExceptions()); builder.setLayout(getLayout()); builder.setName(getName() + "-File"); builder.setConfiguration(getConfiguration()); builder.setBufferedIo(isBufferedIo()); builder.setBufferSize(getBufferSize()); builder.setImmediateFlush(isImmediateFlush()); builder.withFileName(fileName == null || fileName.isEmpty() ? DEFAULT_FILE_NAME : fileName); builder.withAppend(append); builder.withLocking(locking); return builder.build(); } } private static final String DEFAULT_FILE_NAME = "dubbo.log"; public static boolean available = false; public static List<Log> logList = new ArrayList<>(); private final FileAppender fileAppender; public DubboAppender() { this("Dubbo", null); } private DubboAppender(String name, FileAppender fileAppender) { super(name, null, null, true, Property.EMPTY_ARRAY); this.fileAppender = fileAppender; } @PluginBuilderFactory public static Builder newBuilder() { return new Builder().asBuilder(); } public static void doStart() { available = true; } public static void doStop() { available = false; } public static void clear() { logList.clear(); } @Override public void append(LogEvent event) { if (fileAppender != null) { fileAppender.append(event); } if (available) { logList.add(parseLog(event)); } } @Override public void initialize() { fileAppender.initialize(); super.initialize(); } @Override public void start() { fileAppender.start(); super.start(); } @Override public void stop() { super.stop(); fileAppender.stop(); } private Log parseLog(LogEvent event) { Log log = new Log(); log.setLogName(event.getLoggerName()); log.setLogLevel(Level.valueOf(event.getLevel().name())); log.setLogThread(event.getThreadName()); log.setLogMessage(event.getMessage().getFormattedMessage()); return log; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.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.utils; import java.lang.reflect.Field; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; /** * Miscellaneous collection utility methods. * Mainly for internal use within the framework. * * @since 2.0.7 */ public class CollectionUtils { private static final Comparator<String> SIMPLE_NAME_COMPARATOR = (s1, s2) -> { if (s1 == null && s2 == null) { return 0; } if (s1 == null) { return -1; } if (s2 == null) { return 1; } int i1 = s1.lastIndexOf('.'); if (i1 >= 0) { s1 = s1.substring(i1 + 1); } int i2 = s2.lastIndexOf('.'); if (i2 >= 0) { s2 = s2.substring(i2 + 1); } return s1.compareToIgnoreCase(s2); }; private CollectionUtils() {} @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> List<T> sort(List<T> list) { if (isNotEmpty(list)) { Collections.sort((List) list); } return list; } public static List<String> sortSimpleName(List<String> list) { if (list != null && list.size() > 0) { Collections.sort(list, SIMPLE_NAME_COMPARATOR); } return list; } /** * Flip the specified {@link Map} * * @param map The specified {@link Map},Its value must be unique * @param <K> The key type of specified {@link Map} * @param <V> The value type of specified {@link Map} * @return {@link Map} */ @SuppressWarnings("unchecked") public static <K, V> Map<V, K> flip(Map<K, V> map) { if (isEmptyMap(map)) { return (Map<V, K>) map; } Set<V> set = new HashSet<>(map.values()); if (set.size() != map.size()) { throw new IllegalArgumentException("The map value must be unique."); } return map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); } public static Map<String, Map<String, String>> splitAll(Map<String, List<String>> list, String separator) { if (list == null) { return null; } Map<String, Map<String, String>> result = new HashMap<>(); for (Map.Entry<String, List<String>> entry : list.entrySet()) { result.put(entry.getKey(), split(entry.getValue(), separator)); } return result; } public static Map<String, List<String>> joinAll(Map<String, Map<String, String>> map, String separator) { if (map == null) { return null; } Map<String, List<String>> result = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : map.entrySet()) { result.put(entry.getKey(), join(entry.getValue(), separator)); } return result; } public static Map<String, String> split(List<String> list, String separator) { if (list == null) { return null; } Map<String, String> map = new HashMap<>(); if (list.isEmpty()) { return map; } for (String item : list) { int index = item.indexOf(separator); if (index == -1) { map.put(item, ""); } else { map.put(item.substring(0, index), item.substring(index + 1)); } } return map; } public static List<String> join(Map<String, String> map, String separator) { if (map == null) { return null; } List<String> list = new ArrayList<>(); if (map.size() == 0) { return list; } for (Map.Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (StringUtils.isEmpty(value)) { list.add(key); } else { list.add(key + separator + value); } } return list; } public static String join(List<String> list, String separator) { StringBuilder sb = new StringBuilder(); for (String ele : list) { if (sb.length() > 0) { sb.append(separator); } sb.append(ele); } return sb.toString(); } public static boolean mapEquals(Map<?, ?> map1, Map<?, ?> map2) { if (map1 == null && map2 == null) { return true; } if (map1 == null || map2 == null) { return false; } if (map1.size() != map2.size()) { return false; } for (Map.Entry<?, ?> entry : map1.entrySet()) { Object key = entry.getKey(); Object value1 = entry.getValue(); Object value2 = map2.get(key); if (!objectEquals(value1, value2)) { return false; } } return true; } private static boolean objectEquals(Object obj1, Object obj2) { if (obj1 == null && obj2 == null) { return true; } if (obj1 == null || obj2 == null) { return false; } return obj1.equals(obj2); } public static Map<String, String> toStringMap(String... pairs) { Map<String, String> parameters = new HashMap<>(); if (ArrayUtils.isEmpty(pairs)) { return parameters; } if (pairs.length > 0) { if (pairs.length % 2 != 0) { throw new IllegalArgumentException("pairs must be even."); } for (int i = 0; i < pairs.length; i = i + 2) { parameters.put(pairs[i], pairs[i + 1]); } } return parameters; } @SuppressWarnings("unchecked") public static <K, V> Map<K, V> toMap(Object... pairs) { Map<K, V> ret = new HashMap<>(); if (pairs == null || pairs.length == 0) { return ret; } if (pairs.length % 2 != 0) { throw new IllegalArgumentException("Map pairs can not be odd number."); } int len = pairs.length / 2; for (int i = 0; i < len; i++) { ret.put((K) pairs[2 * i], (V) pairs[2 * i + 1]); } return ret; } @SuppressWarnings("unchecked") public static <K, V> Map<K, V> objToMap(Object object) throws IllegalAccessException { Map<K, V> ret = new HashMap<>(); if (object != null) { Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); Object value = field.get(object); if (value != null) { ret.put((K) field.getName(), (V) value); } } } return ret; } /** * Return {@code true} if the supplied Collection is {@code null} or empty. * Otherwise, return {@code false}. * * @param collection the Collection to check * @return whether the given Collection is empty */ public static boolean isEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } /** * Return {@code true} if the supplied Collection is {@code not null} or not empty. * Otherwise, return {@code false}. * * @param collection the Collection to check * @return whether the given Collection is not empty */ public static boolean isNotEmpty(Collection<?> collection) { return !isEmpty(collection); } /** * Return {@code true} if the supplied Map is {@code null} or empty. * Otherwise, return {@code false}. * * @param map the Map to check * @return whether the given Map is empty */ public static boolean isEmptyMap(Map map) { return map == null || map.isEmpty(); } /** * Return {@code true} if the supplied Map is {@code not null} or not empty. * Otherwise, return {@code false}. * * @param map the Map to check * @return whether the given Map is not empty */ public static boolean isNotEmptyMap(Map map) { return !isEmptyMap(map); } /** * Convert to multiple values to be {@link LinkedHashSet} * * @param values one or more values * @param <T> the type of <code>values</code> * @return read-only {@link Set} */ public static <T> Set<T> ofSet(T... values) { int size = values == null ? 0 : values.length; if (size < 1) { return emptySet(); } float loadFactor = 1f / ((size + 1) * 1.0f); if (loadFactor > 0.75f) { loadFactor = 0.75f; } Set<T> elements = new LinkedHashSet<>(size, loadFactor); for (int i = 0; i < size; i++) { elements.add(values[i]); } return unmodifiableSet(elements); } /** * Get the size of the specified {@link Collection} * * @param collection the specified {@link Collection} * @return must be positive number * @since 2.7.6 */ public static int size(Collection<?> collection) { return collection == null ? 0 : collection.size(); } /** * Compares the specified collection with another, the main implementation references * {@link AbstractSet} * * @param one {@link Collection} * @param another {@link Collection} * @return if equals, return <code>true</code>, or <code>false</code> * @since 2.7.6 */ public static boolean equals(Collection<?> one, Collection<?> another) { if (one == another) { return true; } if (isEmpty(one) && isEmpty(another)) { return true; } if (size(one) != size(another)) { return false; } try { return one.containsAll(another); } catch (ClassCastException | NullPointerException unused) { return false; } } /** * Add the multiple values into {@link Collection the specified collection} * * @param collection {@link Collection the specified collection} * @param values the multiple values * @param <T> the type of values * @return the effected count after added * @since 2.7.6 */ public static <T> int addAll(Collection<T> collection, T... values) { int size = values == null ? 0 : values.length; if (collection == null || size < 1) { return 0; } int effectedCount = 0; for (int i = 0; i < size; i++) { if (collection.add(values[i])) { effectedCount++; } } return effectedCount; } /** * Take the first element from the specified collection * * @param values the collection object * @param <T> the type of element of collection * @return if found, return the first one, or <code>null</code> * @since 2.7.6 */ public static <T> T first(Collection<T> values) { if (isEmpty(values)) { return null; } if (values instanceof List) { return ((List<T>) values).get(0); } else { return values.iterator().next(); } } public static <T> T first(List<T> values) { if (isEmpty(values)) { return null; } return values.get(0); } public static <T> Set<T> toTreeSet(Set<T> set) { if (isEmpty(set)) { return set; } if (!(set instanceof TreeSet)) { set = new TreeSet<>(set); } return set; } public static <T> Set<T> newHashSet(int expectedSize) { return new HashSet<>(capacity(expectedSize)); } public static <T> Set<T> newLinkedHashSet(int expectedSize) { return new LinkedHashSet<>(capacity(expectedSize)); } public static <K, T> Map<K, T> newHashMap(int expectedSize) { return new HashMap<>(capacity(expectedSize)); } public static <K, T> Map<K, T> newLinkedHashMap(int expectedSize) { return new LinkedHashMap<>(capacity(expectedSize)); } public static <K, T> Map<K, T> newConcurrentHashMap(int expectedSize) { if (JRE.JAVA_8.isCurrentVersion()) { return new SafeConcurrentHashMap<>(capacity(expectedSize)); } return new ConcurrentHashMap<>(capacity(expectedSize)); } public static <K, T> Map<K, T> newConcurrentHashMap() { if (JRE.JAVA_8.isCurrentVersion()) { return new SafeConcurrentHashMap<>(); } return new ConcurrentHashMap<>(); } public static int capacity(int expectedSize) { if (expectedSize < 3) { if (expectedSize < 0) { throw new IllegalArgumentException("expectedSize cannot be negative but was: " + expectedSize); } return expectedSize + 1; } if (expectedSize < 1 << (Integer.SIZE - 2)) { return (int) (expectedSize / 0.75F + 1.0F); } return Integer.MAX_VALUE; } public static class SafeConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> { private static final long serialVersionUID = 1L; public SafeConcurrentHashMap() {} public SafeConcurrentHashMap(int initialCapacity) { super(initialCapacity); } public SafeConcurrentHashMap(Map<? extends K, ? extends V> m) { super(m); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { V value = get(key); if (value != null) { return value; } value = mappingFunction.apply(key); if (value == null) { return null; } V exists = putIfAbsent(key, value); if (exists != null) { return exists; } return value; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SystemPropertyConfigUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/SystemPropertyConfigUtils.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.utils; import org.apache.dubbo.common.constants.CommonConstants; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; public class SystemPropertyConfigUtils { private static Set<String> systemProperties = new HashSet<>(); static { Class<?>[] classes = new Class[] { CommonConstants.SystemProperty.class, CommonConstants.ThirdPartyProperty.class, CommonConstants.DubboProperty.class }; for (Class<?> clazz : classes) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { try { assert systemProperties != null; Object value = field.get(null); if (value instanceof String) { systemProperties.add((String) value); } } catch (IllegalAccessException e) { throw new IllegalStateException( String.format("%s does not have field of %s", clazz.getName(), field.getName())); } } } } /** * Return property of VM. * * @param key * @return */ public static String getSystemProperty(String key) { if (containsKey(key)) { return System.getProperty(key); } else { throw new IllegalStateException(String.format( "System property [%s] does not define in org.apache.dubbo.common.constants.CommonConstants", key)); } } /** * Return property of VM. If not exist, the default value is returned. * * @param key * @param defaultValue * @return */ public static String getSystemProperty(String key, String defaultValue) { if (containsKey(key)) { return System.getProperty(key, defaultValue); } else { throw new IllegalStateException(String.format( "System property [%s] does not define in org.apache.dubbo.common.constants.CommonConstants", key)); } } /** * Set property of VM. * * @param key * @param value * @return */ public static String setSystemProperty(String key, String value) { if (containsKey(key)) { return System.setProperty(key, value); } else { throw new IllegalStateException(String.format( "System property [%s] does not define in org.apache.dubbo.common.constants.CommonConstants", key)); } } /** * Clear property of VM. * * @param key * @return */ public static String clearSystemProperty(String key) { if (containsKey(key)) { return System.clearProperty(key); } else { throw new IllegalStateException(String.format( "System property [%s] does not define in org.apache.dubbo.common.constants.CommonConstants", key)); } } /** * Check whether the key is valid. * * @param key * @return */ private static boolean containsKey(String key) { return systemProperties.contains(key); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LFUCache.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/LFUCache.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.utils; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; public class LFUCache<K, V> { private final Map<K, CacheNode<K, V>> map; private final CacheDeque<K, V>[] freqTable; private final int capacity; private final int evictionCount; private int curSize = 0; private final ReentrantLock lock = new ReentrantLock(); private static final int DEFAULT_INITIAL_CAPACITY = 1000; private static final float DEFAULT_EVICTION_FACTOR = 0.75f; public LFUCache() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_EVICTION_FACTOR); } /** * Constructs and initializes cache with specified capacity and eviction * factor. Unacceptable parameter values followed with * {@link IllegalArgumentException}. * * @param maxCapacity cache max capacity * @param evictionFactor cache proceedEviction factor */ @SuppressWarnings("unchecked") public LFUCache(final int maxCapacity, final float evictionFactor) { if (maxCapacity <= 0) { throw new IllegalArgumentException("Illegal initial capacity: " + maxCapacity); } boolean factorInRange = evictionFactor <= 1 && evictionFactor > 0; if (!factorInRange || Float.isNaN(evictionFactor)) { throw new IllegalArgumentException("Illegal eviction factor value:" + evictionFactor); } this.capacity = maxCapacity; this.evictionCount = (int) (capacity * evictionFactor); this.map = new HashMap<>(); this.freqTable = new CacheDeque[capacity + 1]; for (int i = 0; i <= capacity; i++) { freqTable[i] = new CacheDeque<>(); } for (int i = 0; i < capacity; i++) { freqTable[i].nextDeque = freqTable[i + 1]; } freqTable[capacity].nextDeque = freqTable[capacity]; } public int getCapacity() { return capacity; } public V put(final K key, final V value) { CacheNode<K, V> node; lock.lock(); try { node = map.get(key); if (node != null) { CacheNode.withdrawNode(node); node.value = value; freqTable[0].addLastNode(node); map.put(key, node); } else { curSize++; if (curSize > capacity) { proceedEviction(); } node = freqTable[0].addLast(key, value); map.put(key, node); } } finally { lock.unlock(); } return node.value; } public V remove(final K key) { CacheNode<K, V> node = null; lock.lock(); try { if (map.containsKey(key)) { node = map.remove(key); if (node != null) { CacheNode.withdrawNode(node); } curSize--; } } finally { lock.unlock(); } return (node != null) ? node.value : null; } public V get(final K key) { CacheNode<K, V> node = null; lock.lock(); try { if (map.containsKey(key)) { node = map.get(key); CacheNode.withdrawNode(node); node.owner.nextDeque.addLastNode(node); } } finally { lock.unlock(); } return (node != null) ? node.value : null; } /** * Evicts less frequently used elements corresponding to eviction factor, * specified at instantiation step. * * @return number of evicted elements */ private int proceedEviction() { int targetSize = capacity - evictionCount; int evictedElements = 0; FREQ_TABLE_ITER_LOOP: for (int i = 0; i <= capacity; i++) { CacheNode<K, V> node; while (!freqTable[i].isEmpty()) { node = freqTable[i].pollFirst(); remove(node.key); if (targetSize >= curSize) { break FREQ_TABLE_ITER_LOOP; } evictedElements++; } } return evictedElements; } /** * Returns cache current size. * * @return cache size */ public int getSize() { return curSize; } static class CacheNode<K, V> { CacheNode<K, V> prev; CacheNode<K, V> next; K key; V value; CacheDeque<K, V> owner; CacheNode() {} CacheNode(final K key, final V value) { this.key = key; this.value = value; } /** * This method takes specified node and reattaches it neighbors nodes * links to each other, so specified node will no longer tied with them. * Returns united node, returns null if argument is null. * * @param node note to retrieve * @param <K> key * @param <V> value * @return retrieved node */ static <K, V> CacheNode<K, V> withdrawNode(final CacheNode<K, V> node) { if (node != null && node.prev != null) { node.prev.next = node.next; if (node.next != null) { node.next.prev = node.prev; } } return node; } } /** * Custom deque implementation of LIFO type. Allows to place element at top * of deque and poll very last added elements. An arbitrary node from the * deque can be removed with {@link CacheNode#withdrawNode(CacheNode)} * method. * * @param <K> key * @param <V> value */ static class CacheDeque<K, V> { CacheNode<K, V> last; CacheNode<K, V> first; CacheDeque<K, V> nextDeque; /** * Constructs list and initializes last and first pointers. */ CacheDeque() { last = new CacheNode<>(); first = new CacheNode<>(); last.next = first; first.prev = last; } /** * Puts the node with specified key and value at the end of the deque * and returns node. * * @param key key * @param value value * @return added node */ CacheNode<K, V> addLast(final K key, final V value) { CacheNode<K, V> node = new CacheNode<>(key, value); node.owner = this; node.next = last.next; node.prev = last; node.next.prev = node; last.next = node; return node; } CacheNode<K, V> addLastNode(final CacheNode<K, V> node) { node.owner = this; node.next = last.next; node.prev = last; node.next.prev = node; last.next = node; return node; } /** * Retrieves and removes the first node of this deque. * * @return removed node */ CacheNode<K, V> pollFirst() { CacheNode<K, V> node = null; if (first.prev != last) { node = first.prev; first.prev = node.prev; first.prev.next = first; node.prev = null; node.next = null; } return node; } /** * Checks if link to the last node points to link to the first node. * * @return is deque empty */ boolean isEmpty() { return last.next == first; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Utf8Utils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/Utf8Utils.java
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package org.apache.dubbo.common.utils; import static java.lang.Character.MIN_HIGH_SURROGATE; import static java.lang.Character.MIN_LOW_SURROGATE; import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT; /** * See original <a href= * "https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/Utf8.java" * >Utf8.java</a> */ public final class Utf8Utils { private Utf8Utils() { //empty } public static int decodeUtf8(byte[] srcBytes, int srcIdx, int srcSize, char[] destChars, int destIdx) { // Bitwise OR combines the sign bits so any negative value fails the check. if ((srcIdx | srcSize | srcBytes.length - srcIdx - srcSize) < 0 || (destIdx | destChars.length - destIdx - srcSize) < 0) { String exMsg = String.format("buffer srcBytes.length=%d, srcIdx=%d, srcSize=%d, destChars.length=%d, " + "destIdx=%d", srcBytes.length, srcIdx, srcSize, destChars.length, destIdx); throw new ArrayIndexOutOfBoundsException( exMsg); } int offset = srcIdx; final int limit = offset + srcSize; final int destIdx0 = destIdx; // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (offset < limit) { byte b = srcBytes[offset]; if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByteSafe(b, destChars, destIdx++); } while (offset < limit) { byte byte1 = srcBytes[offset++]; if (DecodeUtil.isOneByte(byte1)) { DecodeUtil.handleOneByteSafe(byte1, destChars, destIdx++); // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (offset < limit) { byte b = srcBytes[offset]; if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByteSafe(b, destChars, destIdx++); } } else if (DecodeUtil.isTwoBytes(byte1)) { if (offset >= limit) { throw new IllegalArgumentException("invalid UTF-8."); } DecodeUtil.handleTwoBytesSafe(byte1, /* byte2 */ srcBytes[offset++], destChars, destIdx++); } else if (DecodeUtil.isThreeBytes(byte1)) { if (offset >= limit - 1) { throw new IllegalArgumentException("invalid UTF-8."); } DecodeUtil.handleThreeBytesSafe( byte1, /* byte2 */ srcBytes[offset++], /* byte3 */ srcBytes[offset++], destChars, destIdx++); } else { if (offset >= limit - 2) { throw new IllegalArgumentException("invalid UTF-8."); } DecodeUtil.handleFourBytesSafe( byte1, /* byte2 */ srcBytes[offset++], /* byte3 */ srcBytes[offset++], /* byte4 */ srcBytes[offset++], destChars, destIdx); destIdx += 2; } } return destIdx - destIdx0; } private static class DecodeUtil { /** * Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. */ private static boolean isOneByte(byte b) { return b >= 0; } /** * Returns whether this is a two-byte codepoint with the form '10XXXXXX'. */ private static boolean isTwoBytes(byte b) { return b < (byte) 0xE0; } /** * Returns whether this is a three-byte codepoint with the form '110XXXXX'. */ private static boolean isThreeBytes(byte b) { return b < (byte) 0xF0; } private static void handleOneByteSafe(byte byte1, char[] resultArr, int resultPos) { resultArr[resultPos] = (char) byte1; } private static void handleTwoBytesSafe(byte byte1, byte byte2, char[] resultArr, int resultPos) { checkUtf8(byte1, byte2); resultArr[resultPos] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2)); } private static void checkUtf8(byte byte1, byte byte2) { // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and // overlong 2-byte, '11000001'. if (byte1 < (byte) 0xC2 || isNotTrailingByte(byte2)) { throw new IllegalArgumentException("invalid UTF-8."); } } private static void handleThreeBytesSafe(byte byte1, byte byte2, byte byte3, char[] resultArr, int resultPos) { checkUtf8(byte1, byte2, byte3); resultArr[resultPos] = (char) (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)); } private static void checkUtf8(byte byte1, byte byte2, byte byte3) { if (isNotTrailingByte(byte2) // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) || isNotTrailingByte(byte3)) { throw new IllegalArgumentException("invalid UTF-8."); } } private static void handleFourBytesSafe(byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos) { checkUtf8(byte1, byte2, byte3, byte4); int codepoint = ((byte1 & 0x07) << 18) | (trailingByteValue(byte2) << 12) | (trailingByteValue(byte3) << 6) | trailingByteValue(byte4); resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint); resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint); } private static void checkUtf8(byte byte1, byte byte2, byte byte3, byte byte4) { if (isNotTrailingByte(byte2) // Check that 1 <= plane <= 16. Tricky optimized form of: // valid 4-byte leading byte? // if (byte1 > (byte) 0xF4 || // overlong? 4 most significant bits must not all be zero // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // codepoint larger than the highest code point (U+10FFFF)? // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 || isNotTrailingByte(byte3) || isNotTrailingByte(byte4)) { throw new IllegalArgumentException("invalid UTF-8."); } } /** * Returns whether the byte is not a valid continuation of the form '10XXXXXX'. */ private static boolean isNotTrailingByte(byte b) { return b > (byte) 0xBF; } /** * Returns the actual value of the trailing byte (removes the prefix '10') for composition. */ private static int trailingByteValue(byte b) { return b & 0x3F; } private static char highSurrogate(int codePoint) { return (char) ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) + (codePoint >>> 10)); } private static char lowSurrogate(int codePoint) { return (char) (MIN_LOW_SURROGATE + (codePoint & 0x3ff)); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LockUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/LockUtils.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.utils; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Lock; public class LockUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(LockUtils.class); public static final int DEFAULT_TIMEOUT = 60_000; public static void safeLock(Lock lock, int timeout, Runnable runnable) { try { boolean interrupted = false; try { if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { logger.error( LoggerCodeConstants.INTERNAL_ERROR, "", "", "Try to lock failed, timeout: " + timeout, new TimeoutException()); } } catch (InterruptedException e) { logger.warn(LoggerCodeConstants.INTERNAL_ERROR, "", "", "Try to lock failed", e); interrupted = true; } runnable.run(); if (interrupted) { Thread.currentThread().interrupt(); } } finally { try { lock.unlock(); } catch (Exception e) { // ignore } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRUCache.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRUCache.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.utils; import java.util.LinkedHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Function; /** * A 'least recently used' cache based on LinkedHashMap. * * @param <K> key * @param <V> value */ public class LRUCache<K, V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = -5167631809472116969L; private static final float DEFAULT_LOAD_FACTOR = 0.75f; private static final int DEFAULT_MAX_CAPACITY = 1000; private final Lock lock = new ReentrantLock(); private volatile int maxCapacity; public LRUCache() { this(DEFAULT_MAX_CAPACITY); } public LRUCache(int maxCapacity) { super(16, DEFAULT_LOAD_FACTOR, true); this.maxCapacity = maxCapacity; } @Override protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) { return size() > maxCapacity; } @Override public boolean containsKey(Object key) { lock.lock(); try { return super.containsKey(key); } finally { lock.unlock(); } } @Override public V get(Object key) { lock.lock(); try { return super.get(key); } finally { lock.unlock(); } } @Override public V put(K key, V value) { lock.lock(); try { return super.put(key, value); } finally { lock.unlock(); } } @Override public V remove(Object key) { lock.lock(); try { return super.remove(key); } finally { lock.unlock(); } } @Override public int size() { lock.lock(); try { return super.size(); } finally { lock.unlock(); } } @Override public void clear() { lock.lock(); try { super.clear(); } finally { lock.unlock(); } } @Override public V putIfAbsent(K key, V value) { lock.lock(); try { return super.putIfAbsent(key, value); } finally { lock.unlock(); } } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> fn) { V value = get(key); if (value == null) { lock.lock(); try { return super.computeIfAbsent(key, fn); } finally { lock.unlock(); } } return value; } public void lock() { lock.lock(); } public void releaseLock() { lock.unlock(); } public int getMaxCapacity() { return maxCapacity; } public void setMaxCapacity(int maxCapacity) { this.maxCapacity = maxCapacity; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.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.utils; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.MethodDescriptor; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.NotFoundException; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableSet; import static org.apache.dubbo.common.utils.ArrayUtils.isEmpty; public final class ReflectUtils { /** * void(V). */ public static final char JVM_VOID = 'V'; /** * boolean(Z). */ public static final char JVM_BOOLEAN = 'Z'; /** * byte(B). */ public static final char JVM_BYTE = 'B'; /** * char(C). */ public static final char JVM_CHAR = 'C'; /** * double(D). */ public static final char JVM_DOUBLE = 'D'; /** * float(F). */ public static final char JVM_FLOAT = 'F'; /** * int(I). */ public static final char JVM_INT = 'I'; /** * long(J). */ public static final char JVM_LONG = 'J'; /** * short(S). */ public static final char JVM_SHORT = 'S'; public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0]; public static final String JAVA_IDENT_REGEX = "(?:[_$a-zA-Z][_$a-zA-Z0-9]*)"; public static final String JAVA_NAME_REGEX = "(?:" + JAVA_IDENT_REGEX + "(?:\\." + JAVA_IDENT_REGEX + ")*)"; public static final String CLASS_DESC = "(?:L" + JAVA_IDENT_REGEX + "(?:\\/" + JAVA_IDENT_REGEX + ")*;)"; public static final String ARRAY_DESC = "(?:\\[+(?:(?:[VZBCDFIJS])|" + CLASS_DESC + "))"; public static final String DESC_REGEX = "(?:(?:[VZBCDFIJS])|" + CLASS_DESC + "|" + ARRAY_DESC + ")"; public static final Pattern DESC_PATTERN = Pattern.compile(DESC_REGEX); public static final String METHOD_DESC_REGEX = "(?:(" + JAVA_IDENT_REGEX + ")?\\((" + DESC_REGEX + "*)\\)(" + DESC_REGEX + ")?)"; public static final Pattern METHOD_DESC_PATTERN = Pattern.compile(METHOD_DESC_REGEX); public static final Pattern GETTER_METHOD_DESC_PATTERN = Pattern.compile("get([A-Z][_a-zA-Z0-9]*)\\(\\)(" + DESC_REGEX + ")"); public static final Pattern SETTER_METHOD_DESC_PATTERN = Pattern.compile("set([A-Z][_a-zA-Z0-9]*)\\((" + DESC_REGEX + ")\\)V"); public static final Pattern IS_HAS_CAN_METHOD_DESC_PATTERN = Pattern.compile("(?:is|has|can)([A-Z][_a-zA-Z0-9]*)\\(\\)Z"); private static Map<Class<?>, Object> primitiveDefaults = new HashMap<>(); static { primitiveDefaults.put(int.class, 0); primitiveDefaults.put(long.class, 0L); primitiveDefaults.put(byte.class, (byte) 0); primitiveDefaults.put(char.class, (char) 0); primitiveDefaults.put(short.class, (short) 0); primitiveDefaults.put(float.class, (float) 0); primitiveDefaults.put(double.class, (double) 0); primitiveDefaults.put(boolean.class, false); primitiveDefaults.put(void.class, null); } private ReflectUtils() {} public static boolean isPrimitives(Class<?> cls) { while (cls.isArray()) { cls = cls.getComponentType(); } return isPrimitive(cls); } public static boolean isPrimitive(Class<?> cls) { return cls.isPrimitive() || cls == String.class || cls == Boolean.class || cls == Character.class || Number.class.isAssignableFrom(cls) || Date.class.isAssignableFrom(cls); } public static Class<?> getBoxedClass(Class<?> c) { if (c == int.class) { c = Integer.class; } else if (c == boolean.class) { c = Boolean.class; } else if (c == long.class) { c = Long.class; } else if (c == float.class) { c = Float.class; } else if (c == double.class) { c = Double.class; } else if (c == char.class) { c = Character.class; } else if (c == byte.class) { c = Byte.class; } else if (c == short.class) { c = Short.class; } return c; } /** * is compatible. * * @param c class. * @param o instance. * @return compatible or not. */ public static boolean isCompatible(Class<?> c, Object o) { boolean pt = c.isPrimitive(); if (o == null) { return !pt; } if (pt) { c = getBoxedClass(c); } return c == o.getClass() || c.isInstance(o); } /** * is compatible. * * @param cs class array. * @param os object array. * @return compatible or not. */ public static boolean isCompatible(Class<?>[] cs, Object[] os) { int len = cs.length; if (len != os.length) { return false; } if (len == 0) { return true; } for (int i = 0; i < len; i++) { if (!isCompatible(cs[i], os[i])) { return false; } } return true; } public static String getCodeBase(Class<?> cls) { if (cls == null) { return null; } ProtectionDomain domain = cls.getProtectionDomain(); if (domain == null) { return null; } CodeSource source = domain.getCodeSource(); if (source == null) { return null; } URL location = source.getLocation(); if (location == null) { return null; } return location.getFile(); } /** * get name. * java.lang.Object[][].class => "java.lang.Object[][]" * * @param c class. * @return name. */ public static String getName(Class<?> c) { if (c.isArray()) { StringBuilder sb = new StringBuilder(); do { sb.append("[]"); c = c.getComponentType(); } while (c.isArray()); return c.getName() + sb.toString(); } return c.getName(); } public static Class<?> getGenericClass(Class<?> cls) { return getGenericClass(cls, 0); } public static Class<?> getGenericClass(Class<?> cls, int i) { try { ParameterizedType parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]); Object genericClass = parameterizedType.getActualTypeArguments()[i]; // handle nested generic type if (genericClass instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) genericClass).getRawType(); } // handle array generic type if (genericClass instanceof GenericArrayType) { return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType(); } // Requires JDK 7 or higher, Foo<int[]> is no longer GenericArrayType if (((Class) genericClass).isArray()) { return ((Class) genericClass).getComponentType(); } return (Class<?>) genericClass; } catch (Throwable e) { throw new IllegalArgumentException(cls.getName() + " generic type undefined!", e); } } /** * get method name. * "void do(int)", "void do()", "int do(java.lang.String,boolean)" * * @param m method. * @return name. */ public static String getName(final Method m) { StringBuilder ret = new StringBuilder(); ret.append(getName(m.getReturnType())).append(' '); ret.append(m.getName()).append('('); Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if (i > 0) { ret.append(','); } ret.append(getName(parameterTypes[i])); } ret.append(')'); return ret.toString(); } public static String getSignature(String methodName, Class<?>[] parameterTypes) { StringBuilder sb = new StringBuilder(methodName); sb.append('('); if (parameterTypes != null && parameterTypes.length > 0) { boolean first = true; for (Class<?> type : parameterTypes) { if (first) { first = false; } else { sb.append(','); } sb.append(type.getName()); } } sb.append(')'); return sb.toString(); } /** * get constructor name. * "()", "(java.lang.String,int)" * * @param c constructor. * @return name. */ public static String getName(final Constructor<?> c) { StringBuilder ret = new StringBuilder("("); Class<?>[] parameterTypes = c.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if (i > 0) { ret.append(','); } ret.append(getName(parameterTypes[i])); } ret.append(')'); return ret.toString(); } /** * get class desc. * boolean[].class => "[Z" * Object.class => "Ljava/lang/Object;" * * @param c class. * @return desc. * @throws NotFoundException */ public static String getDesc(Class<?> c) { StringBuilder ret = new StringBuilder(); while (c.isArray()) { ret.append('['); c = c.getComponentType(); } if (c.isPrimitive()) { String t = c.getName(); if ("void".equals(t)) { ret.append(JVM_VOID); } else if ("boolean".equals(t)) { ret.append(JVM_BOOLEAN); } else if ("byte".equals(t)) { ret.append(JVM_BYTE); } else if ("char".equals(t)) { ret.append(JVM_CHAR); } else if ("double".equals(t)) { ret.append(JVM_DOUBLE); } else if ("float".equals(t)) { ret.append(JVM_FLOAT); } else if ("int".equals(t)) { ret.append(JVM_INT); } else if ("long".equals(t)) { ret.append(JVM_LONG); } else if ("short".equals(t)) { ret.append(JVM_SHORT); } } else { ret.append('L'); ret.append(c.getName().replace('.', '/')); ret.append(';'); } return ret.toString(); } /** * get class array desc. * [int.class, boolean[].class, Object.class] => "I[ZLjava/lang/Object;" * * @param cs class array. * @return desc. * @throws NotFoundException */ public static String getDesc(final Class<?>[] cs) { if (cs.length == 0) { return ""; } StringBuilder sb = new StringBuilder(64); for (Class<?> c : cs) { sb.append(getDesc(c)); } return sb.toString(); } /** * get method desc. * int do(int arg1) => "do(I)I" * void do(String arg1,boolean arg2) => "do(Ljava/lang/String;Z)V" * * @param m method. * @return desc. */ public static String getDesc(final Method m) { StringBuilder ret = new StringBuilder(m.getName()).append('('); Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } public static String[] getDescArray(final Method m) { Class<?>[] parameterTypes = m.getParameterTypes(); String[] arr = new String[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { arr[i] = getDesc(parameterTypes[i]); } return arr; } /** * get constructor desc. * "()V", "(Ljava/lang/String;I)V" * * @param c constructor. * @return desc */ public static String getDesc(final Constructor<?> c) { StringBuilder ret = new StringBuilder("("); Class<?>[] parameterTypes = c.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append('V'); return ret.toString(); } /** * get method desc. * "(I)I", "()V", "(Ljava/lang/String;Z)V" * * @param m method. * @return desc. */ public static String getDescWithoutMethodName(Method m) { StringBuilder ret = new StringBuilder(); ret.append('('); Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } /** * get class desc. * Object.class => "Ljava/lang/Object;" * boolean[].class => "[Z" * * @param c class. * @return desc. * @throws NotFoundException */ public static String getDesc(final CtClass c) throws NotFoundException { StringBuilder ret = new StringBuilder(); if (c.isArray()) { ret.append('['); ret.append(getDesc(c.getComponentType())); } else if (c.isPrimitive()) { String t = c.getName(); if ("void".equals(t)) { ret.append(JVM_VOID); } else if ("boolean".equals(t)) { ret.append(JVM_BOOLEAN); } else if ("byte".equals(t)) { ret.append(JVM_BYTE); } else if ("char".equals(t)) { ret.append(JVM_CHAR); } else if ("double".equals(t)) { ret.append(JVM_DOUBLE); } else if ("float".equals(t)) { ret.append(JVM_FLOAT); } else if ("int".equals(t)) { ret.append(JVM_INT); } else if ("long".equals(t)) { ret.append(JVM_LONG); } else if ("short".equals(t)) { ret.append(JVM_SHORT); } } else { ret.append('L'); ret.append(c.getName().replace('.', '/')); ret.append(';'); } return ret.toString(); } /** * get method desc. * "do(I)I", "do()V", "do(Ljava/lang/String;Z)V" * * @param m method. * @return desc. */ public static String getDesc(final CtMethod m) throws NotFoundException { StringBuilder ret = new StringBuilder(m.getName()).append('('); CtClass[] parameterTypes = m.getParameterTypes(); for (CtClass parameterType : parameterTypes) { ret.append(getDesc(parameterType)); } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } /** * get constructor desc. * "()V", "(Ljava/lang/String;I)V" * * @param c constructor. * @return desc */ public static String getDesc(final CtConstructor c) throws NotFoundException { StringBuilder ret = new StringBuilder("("); CtClass[] parameterTypes = c.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append('V'); return ret.toString(); } /** * get method desc. * "(I)I", "()V", "(Ljava/lang/String;Z)V". * * @param m method. * @return desc. */ public static String getDescWithoutMethodName(final CtMethod m) throws NotFoundException { StringBuilder ret = new StringBuilder(); ret.append('('); CtClass[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ret.append(getDesc(parameterTypes[i])); } ret.append(')').append(getDesc(m.getReturnType())); return ret.toString(); } /** * name to desc. * java.util.Map[][] => "[[Ljava/util/Map;" * * @param name name. * @return desc. */ public static String name2desc(String name) { StringBuilder sb = new StringBuilder(); int c = 0, index = name.indexOf('['); if (index > 0) { c = (name.length() - index) / 2; name = name.substring(0, index); } while (c-- > 0) { sb.append('['); } if ("void".equals(name)) { sb.append(JVM_VOID); } else if ("boolean".equals(name)) { sb.append(JVM_BOOLEAN); } else if ("byte".equals(name)) { sb.append(JVM_BYTE); } else if ("char".equals(name)) { sb.append(JVM_CHAR); } else if ("double".equals(name)) { sb.append(JVM_DOUBLE); } else if ("float".equals(name)) { sb.append(JVM_FLOAT); } else if ("int".equals(name)) { sb.append(JVM_INT); } else if ("long".equals(name)) { sb.append(JVM_LONG); } else if ("short".equals(name)) { sb.append(JVM_SHORT); } else { sb.append('L').append(name.replace('.', '/')).append(';'); } return sb.toString(); } /** * desc to name. * "[[I" => "int[][]" * * @param desc desc. * @return name. */ public static String desc2name(String desc) { StringBuilder sb = new StringBuilder(); int c = desc.lastIndexOf('[') + 1; if (desc.length() == c + 1) { switch (desc.charAt(c)) { case JVM_VOID: { sb.append("void"); break; } case JVM_BOOLEAN: { sb.append("boolean"); break; } case JVM_BYTE: { sb.append("byte"); break; } case JVM_CHAR: { sb.append("char"); break; } case JVM_DOUBLE: { sb.append("double"); break; } case JVM_FLOAT: { sb.append("float"); break; } case JVM_INT: { sb.append("int"); break; } case JVM_LONG: { sb.append("long"); break; } case JVM_SHORT: { sb.append("short"); break; } default: throw new RuntimeException(); } } else { sb.append(desc.substring(c + 1, desc.length() - 1).replace('/', '.')); } while (c-- > 0) { sb.append("[]"); } return sb.toString(); } public static Class<?> forName(String name) { try { return name2class(name); } catch (ClassNotFoundException e) { throw new IllegalStateException("Not found class " + name + ", cause: " + e.getMessage(), e); } } public static Class<?> forName(ClassLoader cl, String name) { try { return name2class(cl, name); } catch (ClassNotFoundException e) { throw new IllegalStateException("Not found class " + name + ", cause: " + e.getMessage(), e); } } /** * name to class. * "boolean" => boolean.class * "java.util.Map[][]" => java.util.Map[][].class * * @param name name. * @return Class instance. */ public static Class<?> name2class(String name) throws ClassNotFoundException { return name2class(ClassUtils.getClassLoader(), name); } /** * name to class. * "boolean" => boolean.class * "java.util.Map[][]" => java.util.Map[][].class * * @param cl ClassLoader instance. * @param name name. * @return Class instance. */ private static Class<?> name2class(ClassLoader cl, String name) throws ClassNotFoundException { int c = 0, index = name.indexOf('['); if (index > 0) { c = (name.length() - index) / 2; name = name.substring(0, index); } if (c > 0) { StringBuilder sb = new StringBuilder(); while (c-- > 0) { sb.append('['); } if ("void".equals(name)) { sb.append(JVM_VOID); } else if ("boolean".equals(name)) { sb.append(JVM_BOOLEAN); } else if ("byte".equals(name)) { sb.append(JVM_BYTE); } else if ("char".equals(name)) { sb.append(JVM_CHAR); } else if ("double".equals(name)) { sb.append(JVM_DOUBLE); } else if ("float".equals(name)) { sb.append(JVM_FLOAT); } else if ("int".equals(name)) { sb.append(JVM_INT); } else if ("long".equals(name)) { sb.append(JVM_LONG); } else if ("short".equals(name)) { sb.append(JVM_SHORT); } else { // "java.lang.Object" ==> "Ljava.lang.Object;" sb.append('L').append(name).append(';'); } name = sb.toString(); } else { if ("void".equals(name)) { return void.class; } if ("boolean".equals(name)) { return boolean.class; } if ("byte".equals(name)) { return byte.class; } if ("char".equals(name)) { return char.class; } if ("double".equals(name)) { return double.class; } if ("float".equals(name)) { return float.class; } if ("int".equals(name)) { return int.class; } if ("long".equals(name)) { return long.class; } if ("short".equals(name)) { return short.class; } } if (cl == null) { cl = ClassUtils.getClassLoader(); } return Class.forName(name, true, cl); } /** * desc to class. * "[Z" => boolean[].class * "[[Ljava/util/Map;" => java.util.Map[][].class * * @param desc desc. * @return Class instance. * @throws ClassNotFoundException */ public static Class<?> desc2class(String desc) throws ClassNotFoundException { return desc2class(ClassUtils.getClassLoader(), desc); } /** * desc to class. * "[Z" => boolean[].class * "[[Ljava/util/Map;" => java.util.Map[][].class * * @param cl ClassLoader instance. * @param desc desc. * @return Class instance. * @throws ClassNotFoundException */ private static Class<?> desc2class(ClassLoader cl, String desc) throws ClassNotFoundException { switch (desc.charAt(0)) { case JVM_VOID: return void.class; case JVM_BOOLEAN: return boolean.class; case JVM_BYTE: return byte.class; case JVM_CHAR: return char.class; case JVM_DOUBLE: return double.class; case JVM_FLOAT: return float.class; case JVM_INT: return int.class; case JVM_LONG: return long.class; case JVM_SHORT: return short.class; case 'L': // "Ljava/lang/Object;" ==> "java.lang.Object" desc = desc.substring(1, desc.length() - 1).replace('/', '.'); break; case '[': // "[[Ljava/lang/Object;" ==> "[[Ljava.lang.Object;" desc = desc.replace('/', '.'); break; default: throw new ClassNotFoundException("Class not found: " + desc); } if (cl == null) { cl = ClassUtils.getClassLoader(); } return Class.forName(desc, true, cl); } /** * get class array instance. * * @param desc desc. * @return Class class array. * @throws ClassNotFoundException */ public static Class<?>[] desc2classArray(String desc) throws ClassNotFoundException { Class<?>[] ret = desc2classArray(ClassUtils.getClassLoader(), desc); return ret; } /** * get class array instance. * * @param cl ClassLoader instance. * @param desc desc. * @return Class[] class array. * @throws ClassNotFoundException */ private static Class<?>[] desc2classArray(ClassLoader cl, String desc) throws ClassNotFoundException { if (desc.length() == 0) { return EMPTY_CLASS_ARRAY; } List<Class<?>> cs = new ArrayList<>(); Matcher m = DESC_PATTERN.matcher(desc); while (m.find()) { cs.add(desc2class(cl, m.group())); } return cs.toArray(EMPTY_CLASS_ARRAY); } /** * Find method from method signature * * @param clazz Target class to find method * @param methodName Method signature, e.g.: method1(int, String). It is allowed to provide method name only, e.g.: method2 * @return target method * @throws NoSuchMethodException * @throws ClassNotFoundException * @throws IllegalStateException when multiple methods are found (overridden method when parameter info is not provided) * @deprecated Recommend {@link MethodUtils#findMethod(Class, String, Class[])} */ @Deprecated public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { Method method; if (parameterTypes == null) { List<Method> found = new ArrayList<>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { found.add(m); } } if (found.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (found.size() > 1) { String msg = String.format( "Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), found.size()); throw new IllegalStateException(msg); } method = found.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } return method; } /** * @param clazz Target class to find method * @param methodName Method signature, e.g.: method1(int, String). It is allowed to provide method name only, e.g.: method2 * @return target method * @throws NoSuchMethodException * @throws ClassNotFoundException * @throws IllegalStateException when multiple methods are found (overridden method when parameter info is not provided) * @deprecated Recommend {@link MethodUtils#findMethod(Class, String, Class[])} */ @Deprecated public static Method findMethodByMethodName(Class<?> clazz, String methodName) throws NoSuchMethodException, ClassNotFoundException { return findMethodByMethodSignature(clazz, methodName, null); } public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType) throws NoSuchMethodException { Constructor<?> targetConstructor; try { targetConstructor = clazz.getConstructor(new Class<?>[] {paramType}); } catch (NoSuchMethodException e) { targetConstructor = null; Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].isAssignableFrom(paramType)) { targetConstructor = constructor; break; } } if (targetConstructor == null) { throw e; } } return targetConstructor; } /** * Check if one object is the implementation for a given interface. * <p> * This method will not trigger classloading for the given interface, therefore it will not lead to error when * the given interface is not visible by the classloader * * @param obj Object to examine * @param interfaceClazzName The given interface * @return true if the object implements the given interface, otherwise return false */ public static boolean isInstance(Object obj, String interfaceClazzName) { for (Class<?> clazz = obj.getClass(); clazz != null && !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> itf : interfaces) { if (itf.getName().equals(interfaceClazzName)) { return true; } } } return false; } public static Object getEmptyObject(Class<?> returnType) { return getEmptyObject(returnType, new HashMap<>(), 0); } private static Object getEmptyObject(Class<?> returnType, Map<Class<?>, Object> emptyInstances, int level) { if (level > 2) { return null; } if (returnType == null) { return null; } if (returnType == boolean.class || returnType == Boolean.class) { return false; } if (returnType == char.class || returnType == Character.class) { return '\0'; } if (returnType == byte.class || returnType == Byte.class) { return (byte) 0; } if (returnType == short.class || returnType == Short.class) { return (short) 0; } if (returnType == int.class || returnType == Integer.class) { return 0; } if (returnType == long.class || returnType == Long.class) { return 0L; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
true
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodComparator.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodComparator.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.utils; import java.lang.reflect.Method; import java.util.Comparator; /** * The Comparator class for {@link Method}, the comparison rule : * <ol> * <li>Comparing to two {@link Method#getName() method names} {@link String#compareTo(String) lexicographically}. * If equals, go to step 2</li> * <li>Comparing to the count of two method parameters. If equals, go to step 3</li> * <li>Comparing to the type names of methods parameter {@link String#compareTo(String) lexicographically}</li> * </ol> * * @since 2.7.6 */ public class MethodComparator implements Comparator<Method> { public static final MethodComparator INSTANCE = new MethodComparator(); private MethodComparator() {} @Override public int compare(Method m1, Method m2) { if (m1.equals(m2)) { return 0; } // Step 1 String n1 = m1.getName(); String n2 = m2.getName(); int value = n1.compareTo(n2); if (value == 0) { // Step 2 Class[] types1 = m1.getParameterTypes(); Class[] types2 = m2.getParameterTypes(); value = types1.length - types2.length; if (value == 0) { // Step 3 for (int i = 0; i < types1.length; i++) { value = types1[i].getName().compareTo(types2[i].getName()); if (value != 0) { break; } } } } return Integer.compare(value, 0); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonCompatibilityUtil.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonCompatibilityUtil.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.utils; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class JsonCompatibilityUtil { private static final Logger logger = LoggerFactory.getLogger(JsonCompatibilityUtil.class); private static final Set<String> unsupportedClasses = new HashSet<>(Arrays.asList( "java.util.Optional", "java.util.Calendar", "java.util.Iterator", "java.io.InputStream", "java.io.OutputStream")); /** * Determine whether a Class can be serialized by JSON. * @param clazz Incoming Class. * @return If a Class can be serialized by JSON, return true; * else return false. */ public static boolean checkClassCompatibility(Class<?> clazz) { Method[] methods = clazz.getDeclaredMethods(); boolean result; for (Method method : methods) { result = checkMethodCompatibility(method); if (!result) { return false; } } return true; } /** * Determine whether a Method can be serialized by JSON. * @param method Incoming Method. * @return If a Method can be serialized by JSON, return true; * else return false. */ public static boolean checkMethodCompatibility(Method method) { boolean result; Type[] types = method.getGenericParameterTypes(); List<Type> typeList = new ArrayList<>(Arrays.asList(types)); Type returnType = method.getGenericReturnType(); typeList.add(returnType); for (Type type : typeList) { result = checkType(type); if (!result) { return false; } } return true; } /** * Get unsupported methods. * @param clazz * @return If there are unsupported methods, return them by List; * else return null. */ public static List<String> getUnsupportedMethods(Class<?> clazz) { ArrayList<String> unsupportedMethods = new ArrayList<>(); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (!checkMethodCompatibility(method)) { unsupportedMethods.add(method.getName()); } } return unsupportedMethods.size() > 0 ? unsupportedMethods : null; } /** * Determine whether a Type can be serialized by JSON. * @param classType Incoming Type. * @return If a Type can be serialized by JSON, return true; * else return false. */ private static boolean checkType(Type classType) { boolean result; if (classType instanceof TypeVariable) { return true; } if (classType instanceof ParameterizedType) { Type[] types = ((ParameterizedType) classType).getActualTypeArguments(); List<Type> typeList = new ArrayList<>(Arrays.asList(types)); classType = ((ParameterizedType) classType).getRawType(); typeList.add(classType); for (Type type : typeList) { result = checkType(type); if (!result) { return false; } } } else if (classType instanceof GenericArrayType) { Type componentType = ((GenericArrayType) classType).getGenericComponentType(); result = checkType(componentType); return result; } else if (classType instanceof Class<?>) { Class<?> clazz = (Class<?>) classType; String className = clazz.getName(); if (clazz.isArray()) { Type componentType = clazz.getComponentType(); result = checkType(componentType); return result; } else if (clazz.isPrimitive()) { // deal with case of basic byte return !unsupportedClasses.contains(className); } else if (className.startsWith("java") || className.startsWith("javax")) { return !unsupportedClasses.contains(className); } else { // deal with case of interface if (clazz.isInterface()) { return false; } // deal with case of abstract if (Modifier.isAbstract(clazz.getModifiers())) { return false; } if (clazz.isEnum()) { return true; } // deal with case of record // if (clazz.isRecord()) { // return false; // } // deal with field one by one for (Field field : clazz.getDeclaredFields()) { Type type = field.getGenericType(); Class<?> fieldClass = field.getType(); result = checkType(type); if (!result) { return false; } } } } return true; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MemberUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/MemberUtils.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.utils; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * Java Reflection {@link Member} Utilities class * * @since 2.7.6 */ public interface MemberUtils { /** * check the specified {@link Member member} is static or not ? * * @param member {@link Member} instance, e.g, {@link Constructor}, {@link Method} or {@link Field} * @return Iff <code>member</code> is static one, return <code>true</code>, or <code>false</code> */ static boolean isStatic(Member member) { return member != null && Modifier.isStatic(member.getModifiers()); } /** * check the specified {@link Member member} is private or not ? * * @param member {@link Member} instance, e.g, {@link Constructor}, {@link Method} or {@link Field} * @return Iff <code>member</code> is private one, return <code>true</code>, or <code>false</code> */ static boolean isPrivate(Member member) { return member != null && Modifier.isPrivate(member.getModifiers()); } /** * check the specified {@link Member member} is public or not ? * * @param member {@link Member} instance, e.g, {@link Constructor}, {@link Method} or {@link Field} * @return Iff <code>member</code> is public one, return <code>true</code>, or <code>false</code> */ static boolean isPublic(Member member) { return member != null && Modifier.isPublic(member.getModifiers()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.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.utils; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLStrParser; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.Collections.emptyMap; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CLASSIFIER_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.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; 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.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.REGISTRY_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; 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.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; public class UrlUtils { /** * Forbids the instantiation. */ private UrlUtils() { throw new UnsupportedOperationException("No instance of 'UrlUtils' for you! "); } /** * in the url string,mark the param begin */ private static final String URL_PARAM_STARTING_SYMBOL = "?"; public static URL parseURL(String address, Map<String, String> defaults) { if (StringUtils.isEmpty(address)) { throw new IllegalArgumentException("Address is not allowed to be empty, please re-enter."); } String url; if (address.contains("://") || address.contains(URL_PARAM_STARTING_SYMBOL)) { url = address; } else { String[] addresses = COMMA_SPLIT_PATTERN.split(address); url = addresses[0]; if (addresses.length > 1) { StringBuilder backup = new StringBuilder(); for (int i = 1; i < addresses.length; i++) { if (i > 1) { backup.append(','); } backup.append(addresses[i]); } url += URL_PARAM_STARTING_SYMBOL + RemotingConstants.BACKUP_KEY + "=" + backup.toString(); } } String defaultProtocol = defaults == null ? null : defaults.get(PROTOCOL_KEY); if (StringUtils.isEmpty(defaultProtocol)) { defaultProtocol = DUBBO_PROTOCOL; } String defaultUsername = defaults == null ? null : defaults.get(USERNAME_KEY); String defaultPassword = defaults == null ? null : defaults.get(PASSWORD_KEY); int defaultPort = StringUtils.parseInteger(defaults == null ? null : defaults.get(PORT_KEY)); String defaultPath = defaults == null ? null : defaults.get(PATH_KEY); Map<String, String> defaultParameters = defaults == null ? null : new HashMap<>(defaults); if (defaultParameters != null) { defaultParameters.remove(PROTOCOL_KEY); defaultParameters.remove(USERNAME_KEY); defaultParameters.remove(PASSWORD_KEY); defaultParameters.remove(HOST_KEY); defaultParameters.remove(PORT_KEY); defaultParameters.remove(PATH_KEY); } URL u = URL.cacheableValueOf(url); boolean changed = false; String protocol = u.getProtocol(); String username = u.getUsername(); String password = u.getPassword(); String host = u.getHost(); int port = u.getPort(); String path = u.getPath(); Map<String, String> parameters = new HashMap<>(u.getParameters()); if (StringUtils.isEmpty(protocol)) { changed = true; protocol = defaultProtocol; } if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(defaultUsername)) { changed = true; username = defaultUsername; } if (StringUtils.isEmpty(password) && StringUtils.isNotEmpty(defaultPassword)) { changed = true; password = defaultPassword; } /*if (u.isAnyHost() || u.isLocalHost()) { changed = true; host = NetUtils.getLocalHost(); }*/ if (port <= 0) { if (defaultPort > 0) { changed = true; port = defaultPort; } else { changed = true; port = 9090; } } if (StringUtils.isEmpty(path)) { if (StringUtils.isNotEmpty(defaultPath)) { changed = true; path = defaultPath; } } if (defaultParameters != null && defaultParameters.size() > 0) { for (Map.Entry<String, String> entry : defaultParameters.entrySet()) { String key = entry.getKey(); String defaultValue = entry.getValue(); if (StringUtils.isNotEmpty(defaultValue)) { String value = parameters.get(key); if (StringUtils.isEmpty(value)) { changed = true; parameters.put(key, defaultValue); } } } } if (changed) { u = new ServiceConfigURL(protocol, username, password, host, port, path, parameters); } return u; } public static List<URL> parseURLs(String address, Map<String, String> defaults) { if (StringUtils.isEmpty(address)) { throw new IllegalArgumentException("Address is not allowed to be empty, please re-enter."); } String[] addresses = REGISTRY_SPLIT_PATTERN.split(address); if (addresses == null || addresses.length == 0) { throw new IllegalArgumentException( "Addresses is not allowed to be empty, please re-enter."); // here won't be empty } List<URL> registries = new ArrayList<>(); for (String addr : addresses) { registries.add(parseURL(addr, defaults)); } return registries; } public static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register) { Map<String, Map<String, String>> newRegister = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : register.entrySet()) { String serviceName = entry.getKey(); Map<String, String> serviceUrls = entry.getValue(); if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isNotContains(serviceName, '/')) { for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) { String serviceUrl = entry2.getKey(); String serviceQuery = entry2.getValue(); Map<String, String> params = StringUtils.parseQueryString(serviceQuery); String group = params.get(GROUP_KEY); String version = params.get(VERSION_KEY); // params.remove("group"); // params.remove("version"); String name = serviceName; if (StringUtils.isNotEmpty(group)) { name = group + "/" + name; } if (StringUtils.isNotEmpty(version)) { name = name + ":" + version; } Map<String, String> newUrls = newRegister.computeIfAbsent(name, k -> new HashMap<>()); newUrls.put(serviceUrl, StringUtils.toQueryString(params)); } } else { newRegister.put(serviceName, serviceUrls); } } return newRegister; } public static Map<String, String> convertSubscribe(Map<String, String> subscribe) { Map<String, String> newSubscribe = new HashMap<>(); for (Map.Entry<String, String> entry : subscribe.entrySet()) { String serviceName = entry.getKey(); String serviceQuery = entry.getValue(); if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isNotContains(serviceName, '/')) { Map<String, String> params = StringUtils.parseQueryString(serviceQuery); String group = params.get(GROUP_KEY); String version = params.get(VERSION_KEY); // params.remove("group"); // params.remove("version"); String name = serviceName; if (StringUtils.isNotEmpty(group)) { name = group + "/" + name; } if (StringUtils.isNotEmpty(version)) { name = name + ":" + version; } newSubscribe.put(name, StringUtils.toQueryString(params)); } else { newSubscribe.put(serviceName, serviceQuery); } } return newSubscribe; } public static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register) { Map<String, Map<String, String>> newRegister = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : register.entrySet()) { String serviceName = entry.getKey(); Map<String, String> serviceUrls = entry.getValue(); if (StringUtils.isContains(serviceName, ':') && StringUtils.isContains(serviceName, '/')) { for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) { String serviceUrl = entry2.getKey(); String serviceQuery = entry2.getValue(); Map<String, String> params = StringUtils.parseQueryString(serviceQuery); String name = serviceName; int i = name.indexOf('/'); if (i >= 0) { params.put(GROUP_KEY, name.substring(0, i)); name = name.substring(i + 1); } i = name.lastIndexOf(':'); if (i >= 0) { params.put(VERSION_KEY, name.substring(i + 1)); name = name.substring(0, i); } Map<String, String> newUrls = newRegister.computeIfAbsent(name, k -> new HashMap<String, String>()); newUrls.put(serviceUrl, StringUtils.toQueryString(params)); } } else { newRegister.put(serviceName, serviceUrls); } } return newRegister; } public static Map<String, String> revertSubscribe(Map<String, String> subscribe) { Map<String, String> newSubscribe = new HashMap<>(); for (Map.Entry<String, String> entry : subscribe.entrySet()) { String serviceName = entry.getKey(); String serviceQuery = entry.getValue(); if (StringUtils.isContains(serviceName, ':') && StringUtils.isContains(serviceName, '/')) { Map<String, String> params = StringUtils.parseQueryString(serviceQuery); String name = serviceName; int i = name.indexOf('/'); if (i >= 0) { params.put(GROUP_KEY, name.substring(0, i)); name = name.substring(i + 1); } i = name.lastIndexOf(':'); if (i >= 0) { params.put(VERSION_KEY, name.substring(i + 1)); name = name.substring(0, i); } newSubscribe.put(name, StringUtils.toQueryString(params)); } else { newSubscribe.put(serviceName, serviceQuery); } } return newSubscribe; } public static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify) { if (notify != null && notify.size() > 0) { Map<String, Map<String, String>> newNotify = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : notify.entrySet()) { String serviceName = entry.getKey(); Map<String, String> serviceUrls = entry.getValue(); if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isNotContains(serviceName, '/')) { if (CollectionUtils.isNotEmptyMap(serviceUrls)) { for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) { String url = entry2.getKey(); String query = entry2.getValue(); Map<String, String> params = StringUtils.parseQueryString(query); String group = params.get(GROUP_KEY); String version = params.get(VERSION_KEY); // params.remove("group"); // params.remove("version"); String name = serviceName; if (StringUtils.isNotEmpty(group)) { name = group + "/" + name; } if (StringUtils.isNotEmpty(version)) { name = name + ":" + version; } Map<String, String> newUrls = newNotify.computeIfAbsent(name, k -> new HashMap<>()); newUrls.put(url, StringUtils.toQueryString(params)); } } } else { newNotify.put(serviceName, serviceUrls); } } return newNotify; } return notify; } // compatible for dubbo-2.0.0 public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (CollectionUtils.isNotEmpty(forbid)) { List<String> newForbid = new ArrayList<>(); for (String serviceName : forbid) { if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isNotContains(serviceName, '/')) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } public static URL getEmptyUrl(String service, String category) { String group = null; String version = null; int i = service.indexOf('/'); if (i > 0) { group = service.substring(0, i); service = service.substring(i + 1); } i = service.lastIndexOf(':'); if (i > 0) { version = service.substring(i + 1); service = service.substring(0, i); } return URL.valueOf(EMPTY_PROTOCOL + "://0.0.0.0/" + service + URL_PARAM_STARTING_SYMBOL + CATEGORY_KEY + "=" + category + (group == null ? "" : "&" + GROUP_KEY + "=" + group) + (version == null ? "" : "&" + VERSION_KEY + "=" + version)); } public static boolean isMatchCategory(String category, String categories) { if (categories == null || categories.length() == 0) { return DEFAULT_CATEGORY.equals(category); } else if (categories.contains(ANY_VALUE)) { return true; } else if (categories.contains(REMOVE_VALUE_PREFIX)) { return !categories.contains(REMOVE_VALUE_PREFIX + category); } else { return categories.contains(category); } } public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); // FIXME accept providerUrl with '*' as interface name, after carefully thought about all possible scenarios I // think it's ok to add this condition. // Return false if the consumer interface is not equals the provider interface, // except one of the interface configurations is equals '*' (i.e. any value). if (!(ANY_VALUE.equals(consumerInterface) || ANY_VALUE.equals(providerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) { return false; } // If the category of provider URL does not match the category of consumer URL. // Usually, the provider URL's category is empty, and the default category ('providers') is present. // Hence, the category of the provider URL is 'providers'. // Through observing of debugging process, I found that the category of the consumer URL is // 'providers,configurators,routers'. if (!isMatchCategory(providerUrl.getCategory(DEFAULT_CATEGORY), consumerUrl.getCategory(DEFAULT_CATEGORY))) { return false; } // If the provider is not enabled, return false. if (!providerUrl.getParameter(ENABLED_KEY, true) && !ANY_VALUE.equals(consumerUrl.getParameter(ENABLED_KEY))) { return false; } // Obtain consumer's group, version and classifier. String consumerGroup = consumerUrl.getGroup(); String consumerVersion = consumerUrl.getVersion(); String consumerClassifier = consumerUrl.getParameter(CLASSIFIER_KEY, ANY_VALUE); // Obtain provider's group, version and classifier. String providerGroup = providerUrl.getGroup(); String providerVersion = providerUrl.getVersion(); String providerClassifier = providerUrl.getParameter(CLASSIFIER_KEY, ANY_VALUE); // If Group, Version, Classifier all matches, return true. boolean groupMatches = ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup); boolean versionMatches = ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion); boolean classifierMatches = consumerClassifier == null || ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier); return groupMatches && versionMatches && classifierMatches; } public static boolean isMatchGlobPattern(String pattern, String value, URL param) { if (param != null && pattern.startsWith("$")) { pattern = param.getRawParameter(pattern.substring(1)); } return isMatchGlobPattern(pattern, value); } public static boolean isMatchGlobPattern(String pattern, String value) { if ("*".equals(pattern)) { return true; } if (StringUtils.isEmpty(pattern) && StringUtils.isEmpty(value)) { return true; } if (StringUtils.isEmpty(pattern) || StringUtils.isEmpty(value)) { return false; } int i = pattern.lastIndexOf('*'); // doesn't find "*" if (i == -1) { return value.equals(pattern); } // "*" is at the end else if (i == pattern.length() - 1) { return value.startsWith(pattern.substring(0, i)); } // "*" is at the beginning else if (i == 0) { return value.endsWith(pattern.substring(i + 1)); } // "*" is in the middle else { String prefix = pattern.substring(0, i); String suffix = pattern.substring(i + 1); return value.startsWith(prefix) && value.endsWith(suffix); } } public static boolean isServiceKeyMatch(URL pattern, URL value) { return pattern.getParameter(INTERFACE_KEY).equals(value.getParameter(INTERFACE_KEY)) && isItemMatch(pattern.getGroup(), value.getGroup()) && isItemMatch(pattern.getVersion(), value.getVersion()); } public static List<URL> classifyUrls(List<URL> urls, Predicate<URL> predicate) { return urls.stream().filter(predicate).collect(Collectors.toList()); } public static boolean isConfigurator(URL url) { return OVERRIDE_PROTOCOL.equals(url.getProtocol()) || CONFIGURATORS_CATEGORY.equals(url.getCategory(DEFAULT_CATEGORY)); } public static boolean isRoute(URL url) { return ROUTE_PROTOCOL.equals(url.getProtocol()) || ROUTERS_CATEGORY.equals(url.getCategory(DEFAULT_CATEGORY)); } public static boolean isProvider(URL url) { return !OVERRIDE_PROTOCOL.equals(url.getProtocol()) && !ROUTE_PROTOCOL.equals(url.getProtocol()) && PROVIDERS_CATEGORY.equals(url.getCategory(PROVIDERS_CATEGORY)); } public static boolean isRegistry(URL url) { return REGISTRY_PROTOCOL.equals(url.getProtocol()) || SERVICE_REGISTRY_PROTOCOL.equalsIgnoreCase(url.getProtocol()) || (url.getProtocol() != null && url.getProtocol().endsWith("-registry-protocol")); } public static boolean isCheck(URL url) { return url.getParameter(CHECK_KEY, true) && url.getPort() != 0; } /** * The specified {@link URL} is service discovery registry type or not * * @param url the {@link URL} connects to the registry * @return If it is, return <code>true</code>, or <code>false</code> * @since 2.7.5 */ public static boolean hasServiceDiscoveryRegistryTypeKey(URL url) { return hasServiceDiscoveryRegistryTypeKey(url == null ? emptyMap() : url.getParameters()); } public static boolean hasServiceDiscoveryRegistryProtocol(URL url) { return SERVICE_REGISTRY_PROTOCOL.equalsIgnoreCase(url.getProtocol()); } public static boolean isServiceDiscoveryURL(URL url) { return hasServiceDiscoveryRegistryProtocol(url) || hasServiceDiscoveryRegistryTypeKey(url); } /** * The specified parameters of {@link URL} is service discovery registry type or not * * @param parameters the parameters of {@link URL} that connects to the registry * @return If it is, return <code>true</code>, or <code>false</code> * @since 2.7.5 */ public static boolean hasServiceDiscoveryRegistryTypeKey(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return false; } return SERVICE_REGISTRY_TYPE.equals(parameters.get(REGISTRY_TYPE_KEY)); } /** * Check if the given value matches the given pattern. The pattern supports wildcard "*". * * @param pattern pattern * @param value value * @return true if match otherwise false */ static boolean isItemMatch(String pattern, String value) { if (StringUtils.isEmpty(pattern)) { return value == null; } else { return "*".equals(pattern) || pattern.equals(value); } } /** * @param serviceKey, {group}/{interfaceName}:{version} * @return [group, interfaceName, version] */ public static String[] parseServiceKey(String serviceKey) { String[] arr = new String[3]; int i = serviceKey.indexOf('/'); if (i > 0) { arr[0] = serviceKey.substring(0, i); serviceKey = serviceKey.substring(i + 1); } int j = serviceKey.indexOf(':'); if (j > 0) { arr[2] = serviceKey.substring(j + 1); serviceKey = serviceKey.substring(0, j); } arr[1] = serviceKey; return arr; } /** * NOTICE: This method allocate too much objects, we can use {@link URLStrParser#parseDecodedStr(String)} instead. * <p> * Parse url string * * @param url URL string * @return URL instance * @see URL */ public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf('?'); // separator between body and parameters if (i >= 0) { String[] parts = url.substring(i + 1).split("&"); parameters = new HashMap<>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { String key = part.substring(0, j); String value = part.substring(j + 1); parameters.put(key, value); // compatible with lower versions registering "default." keys if (key.startsWith(DEFAULT_KEY_PREFIX)) { parameters.putIfAbsent(key.substring(DEFAULT_KEY_PREFIX.length()), value); } } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf("://"); if (i >= 0) { if (i == 0) { throw new IllegalStateException("url missing protocol: \"" + url + "\""); } protocol = url.substring(0, i); url = url.substring(i + 3); } else { // case: file:/path/to/file.txt i = url.indexOf(":/"); if (i >= 0) { if (i == 0) { throw new IllegalStateException("url missing protocol: \"" + url + "\""); } protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf('/'); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.lastIndexOf('@'); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(':'); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.lastIndexOf(':'); if (i >= 0 && i < url.length() - 1) { if (url.lastIndexOf('%') > i) { // 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(url.substring(i + 1)); url = url.substring(0, i); } } if (url.length() > 0) { host = url; } return new ServiceConfigURL(protocol, username, password, host, port, path, parameters); } public static boolean isConsumer(URL url) { return url.getProtocol().equalsIgnoreCase(CONSUMER) || url.getPort() == 0; } @SuppressWarnings("unchecked") public static <T> T computeServiceAttribute(URL url, String key, Function<URL, T> fn) { return Optional.ofNullable(url.getServiceModel()) .map(ServiceModel::getServiceMetadata) .map(ServiceMetadata::getAttributeMap) .map(stringObjectMap -> (T) ConcurrentHashMapUtils.computeIfAbsent(stringObjectMap, key, k -> fn.apply(url))) .orElse(null); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.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.utils; import org.apache.dubbo.common.io.UnsafeStringWriter; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.valueOf; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.DOT_REGEX; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SEPARATOR_REGEX; import static org.apache.dubbo.common.constants.CommonConstants.UNDERLINE_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION; public final class StringUtils { public static final String EMPTY_STRING = ""; public static final int INDEX_NOT_FOUND = -1; public static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(StringUtils.class); private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)"); // key value pair pattern. private static final Pattern NUM_PATTERN = Pattern.compile("^\\d+$"); private static final Pattern PARAMETERS_PATTERN = Pattern.compile("^\\[((\\s*\\{\\s*[\\w_\\-\\.]+\\s*:\\s*.+?\\s*\\}\\s*,?\\s*)+)\\s*\\]$"); private static final Pattern PAIR_PARAMETERS_PATTERN = Pattern.compile("^\\{\\s*([\\w-_\\.]+)\\s*:\\s*(.+)\\s*\\}$"); private static final int PAD_LIMIT = 8192; private static final byte[] HEX2B; /** * @since 2.7.5 */ public static final char EQUAL_CHAR = '='; public static final String EQUAL = valueOf(EQUAL_CHAR); public static final char AND_CHAR = '&'; public static final String AND = valueOf(AND_CHAR); public static final char SEMICOLON_CHAR = ';'; public static final String SEMICOLON = valueOf(SEMICOLON_CHAR); public static final char QUESTION_MASK_CHAR = '?'; public static final String QUESTION_MASK = valueOf(QUESTION_MASK_CHAR); public static final char SLASH_CHAR = '/'; public static final String SLASH = valueOf(SLASH_CHAR); public static final char HYPHEN_CHAR = '-'; public static final String HYPHEN = valueOf(HYPHEN_CHAR); static { HEX2B = new byte[128]; Arrays.fill(HEX2B, (byte) -1); HEX2B['0'] = (byte) 0; HEX2B['1'] = (byte) 1; HEX2B['2'] = (byte) 2; HEX2B['3'] = (byte) 3; HEX2B['4'] = (byte) 4; HEX2B['5'] = (byte) 5; HEX2B['6'] = (byte) 6; HEX2B['7'] = (byte) 7; HEX2B['8'] = (byte) 8; HEX2B['9'] = (byte) 9; HEX2B['A'] = (byte) 10; HEX2B['B'] = (byte) 11; HEX2B['C'] = (byte) 12; HEX2B['D'] = (byte) 13; HEX2B['E'] = (byte) 14; HEX2B['F'] = (byte) 15; HEX2B['a'] = (byte) 10; HEX2B['b'] = (byte) 11; HEX2B['c'] = (byte) 12; HEX2B['d'] = (byte) 13; HEX2B['e'] = (byte) 14; HEX2B['f'] = (byte) 15; } private StringUtils() {} /** * Gets a CharSequence length or {@code 0} if the CharSequence is * {@code null}. * * @param cs a CharSequence or {@code null} * @return CharSequence length or {@code 0} if the CharSequence is * {@code null}. */ public static int length(final CharSequence cs) { return cs == null ? 0 : cs.length(); } /** * <p>Repeat a String {@code repeat} times to form a * new String.</p> * * <pre> * StringUtils.repeat(null, 2) = null * StringUtils.repeat("", 0) = "" * StringUtils.repeat("", 2) = "" * StringUtils.repeat("a", 3) = "aaa" * StringUtils.repeat("ab", 2) = "abab" * StringUtils.repeat("a", -2) = "" * </pre> * * @param str the String to repeat, may be null * @param repeat number of times to repeat str, negative treated as zero * @return a new String consisting of the original String repeated, * {@code null} if null String input */ public static String repeat(final String str, final int repeat) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } if (repeat <= 0) { return EMPTY_STRING; } final int inputLength = str.length(); if (repeat == 1 || inputLength == 0) { return str; } if (inputLength == 1 && repeat <= PAD_LIMIT) { return repeat(str.charAt(0), repeat); } final int outputLength = inputLength * repeat; switch (inputLength) { case 1: return repeat(str.charAt(0), repeat); case 2: final char ch0 = str.charAt(0); final char ch1 = str.charAt(1); final char[] output2 = new char[outputLength]; for (int i = repeat * 2 - 2; i >= 0; i--, i--) { output2[i] = ch0; output2[i + 1] = ch1; } return new String(output2); default: final StringBuilder buf = new StringBuilder(outputLength); for (int i = 0; i < repeat; i++) { buf.append(str); } return buf.toString(); } } /** * <p>Repeat a String {@code repeat} times to form a * new String, with a String separator injected each time. </p> * * <pre> * StringUtils.repeat(null, null, 2) = null * StringUtils.repeat(null, "x", 2) = null * StringUtils.repeat("", null, 0) = "" * StringUtils.repeat("", "", 2) = "" * StringUtils.repeat("", "x", 3) = "xxx" * StringUtils.repeat("?", ", ", 3) = "?, ?, ?" * </pre> * * @param str the String to repeat, may be null * @param separator the String to inject, may be null * @param repeat number of times to repeat str, negative treated as zero * @return a new String consisting of the original String repeated, * {@code null} if null String input * @since 2.5 */ public static String repeat(final String str, final String separator, final int repeat) { if (str == null || separator == null) { return repeat(str, repeat); } // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it final String result = repeat(str + separator, repeat); return removeEnd(result, separator); } /** * <p>Removes a substring only if it is at the end of a source string, * otherwise returns the source string.</p> * * <p>A {@code null} source string will return {@code null}. * An empty ("") source string will return the empty string. * A {@code null} search string will return the source string.</p> * * <pre> * StringUtils.removeEnd(null, *) = null * StringUtils.removeEnd("", *) = "" * StringUtils.removeEnd(*, null) = * * StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com" * StringUtils.removeEnd("www.domain.com", ".com") = "www.domain" * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com" * StringUtils.removeEnd("abc", "") = "abc" * </pre> * * @param str the source String to search, may be null * @param remove the String to search for and remove, may be null * @return the substring with the string removed if found, * {@code null} if null String input */ public static String removeEnd(final String str, final String remove) { if (isAnyEmpty(str, remove)) { return str; } if (str.endsWith(remove)) { return str.substring(0, str.length() - remove.length()); } return str; } /** * <p>Returns padding using the specified delimiter repeated * to a given length.</p> * * <pre> * StringUtils.repeat('e', 0) = "" * StringUtils.repeat('e', 3) = "eee" * StringUtils.repeat('e', -2) = "" * </pre> * * <p>Note: this method doesn't not support padding with * <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a> * as they require a pair of {@code char}s to be represented. * If you are needing to support full I18N of your applications * consider using {@link #repeat(String, int)} instead. * </p> * * @param ch character to repeat * @param repeat number of times to repeat char, negative treated as zero * @return String with repeated character * @see #repeat(String, int) */ public static String repeat(final char ch, final int repeat) { final char[] buf = new char[repeat]; for (int i = repeat - 1; i >= 0; i--) { buf[i] = ch; } return new String(buf); } /** * <p>Strips any of a set of characters from the end of a String.</p> * * <p>A {@code null} input String returns {@code null}. * An empty string ("") input returns the empty string.</p> * * <p>If the stripChars String is {@code null}, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripEnd(null, *) = null * StringUtils.stripEnd("", *) = "" * StringUtils.stripEnd("abc", "") = "abc" * StringUtils.stripEnd("abc", null) = "abc" * StringUtils.stripEnd(" abc", null) = " abc" * StringUtils.stripEnd("abc ", null) = "abc" * StringUtils.stripEnd(" abc ", null) = " abc" * StringUtils.stripEnd(" abcyx", "xyz") = " abc" * StringUtils.stripEnd("120.00", ".0") = "12" * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the set of characters to remove, null treated as whitespace * @return the stripped String, {@code null} if null String input */ public static String stripEnd(final String str, final String stripChars) { int end; if (str == null || (end = str.length()) == 0) { return str; } if (stripChars == null) { while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) { end--; } } else if (stripChars.isEmpty()) { return str; } else { while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) { end--; } } return str.substring(0, end); } /** * <p>Replaces all occurrences of a String within another String.</p> * * <p>A {@code null} reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replace(null, *, *) = null * StringUtils.replace("", *, *) = "" * StringUtils.replace("any", null, *) = "any" * StringUtils.replace("any", *, null) = "any" * StringUtils.replace("any", "", *) = "any" * StringUtils.replace("aba", "a", null) = "aba" * StringUtils.replace("aba", "a", "") = "b" * StringUtils.replace("aba", "a", "z") = "zbz" * </pre> * * @param text text to search and replace in, may be null * @param searchString the String to search for, may be null * @param replacement the String to replace it with, may be null * @return the text with any replacements processed, * {@code null} if null String input * @see #replace(String text, String searchString, String replacement, int max) */ public static String replace(final String text, final String searchString, final String replacement) { return replace(text, searchString, replacement, -1); } /** * <p>Replaces a String with another String inside a larger String, * for the first {@code max} values of the search String.</p> * * <p>A {@code null} reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replace(null, *, *, *) = null * StringUtils.replace("", *, *, *) = "" * StringUtils.replace("any", null, *, *) = "any" * StringUtils.replace("any", *, null, *) = "any" * StringUtils.replace("any", "", *, *) = "any" * StringUtils.replace("any", *, *, 0) = "any" * StringUtils.replace("abaa", "a", null, -1) = "abaa" * StringUtils.replace("abaa", "a", "", -1) = "b" * StringUtils.replace("abaa", "a", "z", 0) = "abaa" * StringUtils.replace("abaa", "a", "z", 1) = "zbaa" * StringUtils.replace("abaa", "a", "z", 2) = "zbza" * StringUtils.replace("abaa", "a", "z", -1) = "zbzz" * </pre> * * @param text text to search and replace in, may be null * @param searchString the String to search for, may be null * @param replacement the String to replace it with, may be null * @param max maximum number of values to replace, or {@code -1} if no maximum * @return the text with any replacements processed, * {@code null} if null String input */ public static String replace(final String text, final String searchString, final String replacement, int max) { if (isAnyEmpty(text, searchString) || replacement == null || max == 0) { return text; } int start = 0; int end = text.indexOf(searchString, start); if (end == INDEX_NOT_FOUND) { return text; } final int replLength = searchString.length(); int increase = replacement.length() - replLength; increase = increase < 0 ? 0 : increase; increase *= max < 0 ? 16 : max > 64 ? 64 : max; final StringBuilder buf = new StringBuilder(text.length() + increase); while (end != INDEX_NOT_FOUND) { buf.append(text, start, end).append(replacement); start = end + replLength; if (--max == 0) { break; } end = text.indexOf(searchString, start); } buf.append(text.substring(start)); return buf.toString(); } public static boolean isBlank(CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } /** * is not blank string. * * @param cs source string. * @return is not blank. */ public static boolean isNotBlank(CharSequence cs) { return !isBlank(cs); } /** * Check the cs String whether contains non whitespace characters. * * @param cs * @return */ public static boolean hasText(CharSequence cs) { return !isBlank(cs); } /** * is empty string. * * @param str source string. * @return is empty. */ public static boolean isEmpty(String str) { return str == null || str.isEmpty(); } /** * <p>Checks if the strings contain empty or null elements. <p/> * * <pre> * StringUtils.isNoneEmpty(null) = false * StringUtils.isNoneEmpty("") = false * StringUtils.isNoneEmpty(" ") = true * StringUtils.isNoneEmpty("abc") = true * StringUtils.isNoneEmpty("abc", "def") = true * StringUtils.isNoneEmpty("abc", null) = false * StringUtils.isNoneEmpty("abc", "") = false * StringUtils.isNoneEmpty("abc", " ") = true * </pre> * * @param ss the strings to check * @return {@code true} if all strings are not empty or null */ public static boolean isNoneEmpty(final String... ss) { if (ArrayUtils.isEmpty(ss)) { return false; } for (final String s : ss) { if (isEmpty(s)) { return false; } } return true; } /** * <p>Checks if the strings contain at least on empty or null element. <p/> * * <pre> * StringUtils.isAnyEmpty(null) = true * StringUtils.isAnyEmpty("") = true * StringUtils.isAnyEmpty(" ") = false * StringUtils.isAnyEmpty("abc") = false * StringUtils.isAnyEmpty("abc", "def") = false * StringUtils.isAnyEmpty("abc", null) = true * StringUtils.isAnyEmpty("abc", "") = true * StringUtils.isAnyEmpty("abc", " ") = false * </pre> * * @param ss the strings to check * @return {@code true} if at least one in the strings is empty or null */ public static boolean isAnyEmpty(final String... ss) { return !isNoneEmpty(ss); } /** * is not empty string. * * @param str source string. * @return is not empty. */ public static boolean isNotEmpty(String str) { return !isEmpty(str); } /** * if s1 is null and s2 is null, then return true * * @param s1 str1 * @param s2 str2 * @return equals */ public static boolean isEquals(String s1, String s2) { if (s1 == null && s2 == null) { return true; } if (s1 == null || s2 == null) { return false; } return s1.equals(s2); } /** * is positive integer or zero string. * * @param str a string * @return is positive integer or zero */ public static boolean isNumber(String str) { return isNotEmpty(str) && NUM_PATTERN.matcher(str).matches(); } /** * parse str to Integer(if str is not number or n < 0, then return 0) * * @param str a number str * @return positive integer or zero */ public static int parseInteger(String str) { return isNumber(str) ? Integer.parseInt(str) : 0; } /** * parse str to Long(if str is not number or n < 0, then return 0) * * @param str a number str * @return positive long or zero */ public static long parseLong(String str) { return isNumber(str) ? Long.parseLong(str) : 0; } /** * Returns true if s is a legal Java identifier.<p> * <a href="http://www.exampledepot.com/egs/java.lang/IsJavaId.html">more info.</a> */ public static boolean isJavaIdentifier(String s) { if (isEmpty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } for (int i = 1; i < s.length(); i++) { if (!Character.isJavaIdentifierPart(s.charAt(i))) { return false; } } return true; } public static boolean isContains(String values, String value) { return isNotEmpty(values) && isContains(COMMA_SPLIT_PATTERN.split(values), value); } public static boolean isContains(String str, char ch) { return isNotEmpty(str) && str.indexOf(ch) >= 0; } public static boolean isNotContains(String str, char ch) { return !isContains(str, ch); } /** * @param values * @param value * @return contains */ public static boolean isContains(String[] values, String value) { if (isNotEmpty(value) && ArrayUtils.isNotEmpty(values)) { for (String v : values) { if (value.equals(v)) { return true; } } } return false; } public static boolean isNumeric(String str, boolean allowDot) { if (str == null || str.isEmpty()) { return false; } boolean hasDot = false; int sz = str.length(); for (int i = 0; i < sz; i++) { if (str.charAt(i) == '.') { if (hasDot || !allowDot) { return false; } hasDot = true; continue; } if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } /** * @param e * @return string */ public static String toString(Throwable e) { UnsafeStringWriter w = new UnsafeStringWriter(); PrintWriter p = new PrintWriter(w); p.print(e.getClass().getName()); if (e.getMessage() != null) { p.print(": " + e.getMessage()); } p.println(); try { e.printStackTrace(p); return w.toString(); } finally { p.close(); } } /** * @param msg * @param e * @return string */ public static String toString(String msg, Throwable e) { UnsafeStringWriter w = new UnsafeStringWriter(); w.write(msg + "\n"); PrintWriter p = new PrintWriter(w); try { e.printStackTrace(p); return w.toString(); } finally { p.close(); } } /** * translate. * * @param src source string. * @param from src char table. * @param to target char table. * @return String. */ public static String translate(String src, String from, String to) { if (isEmpty(src)) { return src; } StringBuilder sb = null; int ix; char c; for (int i = 0, len = src.length(); i < len; i++) { c = src.charAt(i); ix = from.indexOf(c); if (ix == -1) { if (sb != null) { sb.append(c); } } else { if (sb == null) { sb = new StringBuilder(len); sb.append(src, 0, i); } if (ix < to.length()) { sb.append(to.charAt(ix)); } } } return sb == null ? src : sb.toString(); } /** * split. * * @param ch char. * @return string array. */ public static String[] split(String str, char ch) { if (isEmpty(str)) { return EMPTY_STRING_ARRAY; } return splitToList0(str, ch).toArray(EMPTY_STRING_ARRAY); } private static List<String> splitToList0(String str, char ch) { List<String> result = new ArrayList<>(); int ix = 0, len = str.length(); for (int i = 0; i < len; i++) { if (str.charAt(i) == ch) { result.add(str.substring(ix, i)); ix = i + 1; } } if (ix >= 0) { result.add(str.substring(ix)); } return result; } /** * Splits String around matches of the given character. * <p> * Note: Compare with {@link StringUtils#split(String, char)}, this method reduce memory copy. */ public static List<String> splitToList(String str, char ch) { if (isEmpty(str)) { return Collections.emptyList(); } return splitToList0(str, ch); } /** * Split the specified value to be a {@link Set} * * @param value the content to be split * @param separatorChar a char to separate * @return non-null read-only {@link Set} * @since 2.7.8 */ public static Set<String> splitToSet(String value, char separatorChar) { return splitToSet(value, separatorChar, false); } /** * Split the specified value to be a {@link Set} * * @param value the content to be split * @param separatorChar a char to separate * @param trimElements require to trim the elements or not * @return non-null read-only {@link Set} * @since 2.7.8 */ public static Set<String> splitToSet(String value, char separatorChar, boolean trimElements) { List<String> values = splitToList(value, separatorChar); int size = values.size(); if (size < 1) { // empty condition return emptySet(); } if (!trimElements) { // Do not require to trim the elements return new LinkedHashSet(values); } return unmodifiableSet(values.stream().map(String::trim).collect(LinkedHashSet::new, Set::add, Set::addAll)); } /** * join string. * * @param array String array. * @return String. */ public static String join(String[] array) { if (ArrayUtils.isEmpty(array)) { return EMPTY_STRING; } StringBuilder sb = new StringBuilder(); for (String s : array) { sb.append(s); } return sb.toString(); } /** * join string like javascript. * * @param array String array. * @param split split * @return String. */ public static String join(String[] array, char split) { if (ArrayUtils.isEmpty(array)) { return EMPTY_STRING; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; i++) { if (i > 0) { sb.append(split); } sb.append(array[i]); } return sb.toString(); } /** * join string like javascript. * * @param array String array. * @param split split * @return String. */ public static String join(String[] array, String split) { if (ArrayUtils.isEmpty(array)) { return EMPTY_STRING; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; i++) { if (i > 0) { sb.append(split); } sb.append(array[i]); } return sb.toString(); } public static String join(Collection<String> coll, String split) { if (CollectionUtils.isEmpty(coll)) { return EMPTY_STRING; } StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (String s : coll) { if (isFirst) { isFirst = false; } else { sb.append(split); } sb.append(s); } return sb.toString(); } public static String join(final Object[] array, final char delimiter, final int startIndex, final int endIndex) { if (ArrayUtils.isEmpty(array)) { return EMPTY_STRING; } if (endIndex - startIndex <= 0) { return EMPTY_STRING; } StringBuilder sb = new StringBuilder(); for (int i = startIndex; i < endIndex; i++) { if (i > 0) { sb.append(delimiter); } sb.append(array[i]); } return sb.toString(); } /** * parse key-value pair. * * @param str string. * @param itemSeparator item separator. * @return key-value map; */ private static Map<String, String> parseKeyValuePair(String str, String itemSeparator) { String[] tmp = str.split(itemSeparator); Map<String, String> map = new HashMap<>(tmp.length); for (int i = 0; i < tmp.length; i++) { Matcher matcher = KVP_PATTERN.matcher(tmp[i]); if (!matcher.matches()) { continue; } map.put(matcher.group(1), matcher.group(2)); } return map; } public static String getQueryStringValue(String qs, String key) { Map<String, String> map = parseQueryString(qs); return map.get(key); } /** * parse query string to Parameters. * * @param qs query string. * @return Parameters instance. */ public static Map<String, String> parseQueryString(String qs) { if (isEmpty(qs)) { return new HashMap<>(); } return parseKeyValuePair(qs, "\\&"); } public static String getServiceKey(Map<String, String> ps) { StringBuilder buf = new StringBuilder(); String group = ps.get(GROUP_KEY); if (isNotEmpty(group)) { buf.append(group).append('/'); } buf.append(ps.get(INTERFACE_KEY)); String version = ps.get(VERSION_KEY); if (isNotEmpty(group)) { buf.append(':').append(version); } return buf.toString(); } public static String toQueryString(Map<String, String> ps) { StringBuilder buf = new StringBuilder(); if (ps != null && ps.size() > 0) { for (Map.Entry<String, String> entry : new TreeMap<String, String>(ps).entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (isNoneEmpty(key, value)) { if (buf.length() > 0) { buf.append('&'); } buf.append(key); buf.append('='); buf.append(value); } } } return buf.toString(); } public static String camelToSplitName(String camelName, String split) { if (isEmpty(camelName)) { return camelName; } if (!isWord(camelName)) { // convert Ab-Cd-Ef to ab-cd-ef if (isSplitCase(camelName, split.charAt(0))) { return camelName.toLowerCase(); } // not camel case return camelName; } StringBuilder buf = null; for (int i = 0; i < camelName.length(); i++) { char ch = camelName.charAt(i); if (ch >= 'A' && ch <= 'Z') { if (buf == null) { buf = new StringBuilder(); if (i > 0) { buf.append(camelName, 0, i); } } if (i > 0) { buf.append(split); } buf.append(Character.toLowerCase(ch)); } else if (buf != null) { buf.append(ch); } } return buf == null ? camelName.toLowerCase() : buf.toString().toLowerCase(); } private static boolean isSplitCase(String str, char separator) { if (str == null) { return false; } return str.chars().allMatch(ch -> (ch == separator) || isWord((char) ch)); } private static boolean isWord(String str) { if (str == null) { return false; } return str.chars().allMatch(ch -> isWord((char) ch)); } private static boolean isWord(char ch) { if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) { return true; } return false; } /**
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
true
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.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.utils; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.TreeMap; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Consumer; import java.util.function.Supplier; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED; import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom; /** * PojoUtils. Travel object deeply, and convert complex type to simple type. * <p/> * Simple type below will be remained: * <ul> * <li> Primitive Type, also include <b>String</b>, <b>Number</b>(Integer, Long), <b>Date</b> * <li> Array of Primitive Type * <li> Collection, eg: List, Map, Set etc. * </ul> * <p/> * Other type will be covert to a map which contains the attributes and value pair of object. * <p> * TODO: exact PojoUtils to scope bean */ public class PojoUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PojoUtils.class); private static final ConcurrentMap<String, Method> NAME_METHODS_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentMap<Class<?>, ConcurrentMap<String, Field>> CLASS_FIELD_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, Object> CLASS_NOT_FOUND_CACHE = new ConcurrentHashMap<>(); private static final Object NOT_FOUND_VALUE = new Object(); private static final boolean GENERIC_WITH_CLZ = Boolean.parseBoolean(ConfigurationUtils.getProperty( ApplicationModel.defaultModel(), CommonConstants.GENERIC_WITH_CLZ_KEY, "true")); private static final List<Class<?>> CLASS_CAN_BE_STRING = Arrays.asList( Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Boolean.class, Character.class); public static Object[] generalize(Object[] objs) { Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = generalize(objs[i]); } return dests; } public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } public static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes) { if (objs.length != types.length || objs.length != gtypes.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i], gtypes[i]); } return dests; } public static Object generalize(Object pojo) { return generalize(pojo, new IdentityHashMap<>()); } @SuppressWarnings("unchecked") private static Object generalize(Object pojo, Map<Object, Object> history) { if (pojo == null) { return null; } if (pojo instanceof Enum<?>) { return ((Enum<?>) pojo).name(); } if (pojo.getClass().isArray() && Enum.class.isAssignableFrom(pojo.getClass().getComponentType())) { int len = Array.getLength(pojo); String[] values = new String[len]; for (int i = 0; i < len; i++) { values[i] = ((Enum<?>) Array.get(pojo, i)).name(); } return values; } if (ReflectUtils.isPrimitives(pojo.getClass())) { return pojo; } if (pojo instanceof LocalDate || pojo instanceof LocalDateTime || pojo instanceof LocalTime) { return pojo.toString(); } if (pojo instanceof Class) { return ((Class) pojo).getName(); } Object o = history.get(pojo); if (o != null) { return o; } history.put(pojo, pojo); if (pojo.getClass().isArray()) { int len = Array.getLength(pojo); Object[] dest = new Object[len]; history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); dest[i] = generalize(obj, history); } return dest; } if (pojo instanceof Collection<?>) { Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Collection<Object> dest = (pojo instanceof List<?>) ? new ArrayList<>(len) : new HashSet<>(len); history.put(pojo, dest); for (Object obj : src) { dest.add(generalize(obj, history)); } return dest; } if (pojo instanceof Map<?, ?>) { Map<Object, Object> src = (Map<Object, Object>) pojo; Map<Object, Object> dest = createMap(src); history.put(pojo, dest); for (Map.Entry<Object, Object> obj : src.entrySet()) { dest.put(generalize(obj.getKey(), history), generalize(obj.getValue(), history)); } return dest; } Map<String, Object> map = new HashMap<>(); history.put(pojo, map); if (GENERIC_WITH_CLZ) { map.put("class", pojo.getClass().getName()); } for (Method method : pojo.getClass().getMethods()) { if (ReflectUtils.isBeanPropertyReadMethod(method)) { ReflectUtils.makeAccessible(method); try { map.put( ReflectUtils.getPropertyNameFromBeanReadMethod(method), generalize(method.invoke(pojo), history)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } // public field for (Field field : pojo.getClass().getFields()) { if (ReflectUtils.isPublicInstanceField(field)) { try { Object fieldValue = field.get(pojo); if (history.containsKey(pojo)) { Object pojoGeneralizedValue = history.get(pojo); if (pojoGeneralizedValue instanceof Map && ((Map) pojoGeneralizedValue).containsKey(field.getName())) { continue; } } if (fieldValue != null) { map.put(field.getName(), generalize(fieldValue, history)); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } return map; } public static Object realize(Object pojo, Class<?> type) { return realize0(pojo, type, null, new IdentityHashMap<>()); } public static Object realize(Object pojo, Class<?> type, Type genericType) { return realize0(pojo, type, genericType, new IdentityHashMap<>()); } private static class PojoInvocationHandler implements InvocationHandler { private final Map<Object, Object> map; public PojoInvocationHandler(Map<Object, Object> map) { this.map = map; } @Override @SuppressWarnings("unchecked") public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(map, args); } String methodName = method.getName(); Object value = null; if (methodName.length() > 3 && methodName.startsWith("get")) { value = map.get(methodName.substring(3, 4).toLowerCase() + methodName.substring(4)); } else if (methodName.length() > 2 && methodName.startsWith("is")) { value = map.get(methodName.substring(2, 3).toLowerCase() + methodName.substring(3)); } else { value = map.get(methodName.substring(0, 1).toLowerCase() + methodName.substring(1)); } if (value instanceof Map<?, ?> && !Map.class.isAssignableFrom(method.getReturnType())) { value = realize0(value, method.getReturnType(), null, new IdentityHashMap<>()); } return value; } } @SuppressWarnings("unchecked") private static Collection<Object> createCollection(Class<?> type, int len) { if (type.isAssignableFrom(ArrayList.class)) { return new ArrayList<>(len); } if (type.isAssignableFrom(HashSet.class)) { return new HashSet<>(len); } if (!type.isInterface() && !Modifier.isAbstract(type.getModifiers())) { try { return (Collection<Object>) type.getDeclaredConstructor().newInstance(); } catch (Exception e) { // ignore } } return new ArrayList<>(); } private static Map createMap(Map src) { Class<? extends Map> cl = src.getClass(); Map result = null; if (HashMap.class == cl) { result = new HashMap(); } else if (Hashtable.class == cl) { result = new Hashtable(); } else if (IdentityHashMap.class == cl) { result = new IdentityHashMap(); } else if (LinkedHashMap.class == cl) { result = new LinkedHashMap(); } else if (Properties.class == cl) { result = new Properties(); } else if (TreeMap.class == cl) { result = new TreeMap(); } else if (WeakHashMap.class == cl) { return new WeakHashMap(); } else if (ConcurrentHashMap.class == cl) { result = new ConcurrentHashMap(); } else if (ConcurrentSkipListMap.class == cl) { result = new ConcurrentSkipListMap(); } else { try { result = cl.getDeclaredConstructor().newInstance(); } catch (Exception e) { /* ignore */ } if (result == null) { try { Constructor<?> constructor = cl.getConstructor(Map.class); result = (Map) constructor.newInstance(Collections.EMPTY_MAP); } catch (Exception e) { /* ignore */ } } } if (result == null) { result = new HashMap<>(); } return result; } @SuppressWarnings({"unchecked", "rawtypes"}) private static Object realize0(Object pojo, Class<?> type, Type genericType, final Map<Object, Object> history) { return realize1(pojo, type, genericType, new HashMap<>(8), history); } private static Object realize1( Object pojo, Class<?> type, Type genericType, final Map<String, Type> mapParent, final Map<Object, Object> history) { if (pojo == null) { return null; } if (type != null && type.isEnum() && pojo.getClass() == String.class) { return Enum.valueOf((Class<Enum>) type, (String) pojo); } if (ReflectUtils.isPrimitives(pojo.getClass()) && !(type != null && type.isArray() && type.getComponentType().isEnum() && pojo.getClass() == String[].class)) { return CompatibleTypeUtils.compatibleTypeConvert(pojo, type); } Object o = history.get(pojo); if (o != null) { return o; } history.put(pojo, pojo); Map<String, Type> mapGeneric = new HashMap<>(8); mapGeneric.putAll(mapParent); TypeVariable<? extends Class<?>>[] typeParameters = type.getTypeParameters(); if (genericType instanceof ParameterizedType && typeParameters.length > 0) { ParameterizedType parameterizedType = (ParameterizedType) genericType; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < typeParameters.length; i++) { if (!(actualTypeArguments[i] instanceof TypeVariable)) { mapGeneric.put(typeParameters[i].getTypeName(), actualTypeArguments[i]); } } } if (pojo.getClass().isArray()) { if (Collection.class.isAssignableFrom(type)) { Class<?> ctype = pojo.getClass().getComponentType(); int len = Array.getLength(pojo); Collection dest = createCollection(type, len); history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); Object value = realize1(obj, ctype, null, mapGeneric, history); dest.add(value); } return dest; } else { Class<?> ctype = (type != null && type.isArray() ? type.getComponentType() : pojo.getClass().getComponentType()); int len = Array.getLength(pojo); Object dest = Array.newInstance(ctype, len); history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); Object value = realize1(obj, ctype, null, mapGeneric, history); Array.set(dest, i, value); } return dest; } } if (pojo instanceof Collection<?>) { if (type.isArray()) { Class<?> ctype = type.getComponentType(); Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Object dest = Array.newInstance(ctype, len); history.put(pojo, dest); int i = 0; for (Object obj : src) { Object value = realize1(obj, ctype, null, mapGeneric, history); Array.set(dest, i, value); i++; } return dest; } else { Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Collection<Object> dest = createCollection(type, len); history.put(pojo, dest); for (Object obj : src) { Type keyType = getGenericClassByIndex(genericType, 0); Class<?> keyClazz = obj == null ? null : obj.getClass(); if (keyType instanceof Class) { keyClazz = (Class<?>) keyType; } Object value = realize1(obj, keyClazz, keyType, mapGeneric, history); dest.add(value); } return dest; } } if (pojo instanceof Map<?, ?> && type != null) { Object className = ((Map<Object, Object>) pojo).get("class"); if (className instanceof String) { if (!CLASS_NOT_FOUND_CACHE.containsKey(className)) { try { type = DefaultSerializeClassChecker.getInstance() .loadClass(ClassUtils.getClassLoader(), (String) className); } catch (ClassNotFoundException e) { CLASS_NOT_FOUND_CACHE.put((String) className, NOT_FOUND_VALUE); } } } // special logic for enum if (type.isEnum()) { Object name = ((Map<Object, Object>) pojo).get("name"); if (name != null) { if (!(name instanceof String)) { throw new IllegalArgumentException("`name` filed should be string!"); } else { return Enum.valueOf((Class<Enum>) type, (String) name); } } } Map<Object, Object> map; // when return type is not the subclass of return type from the signature and not an interface if (!type.isInterface() && !type.isAssignableFrom(pojo.getClass())) { try { map = (Map<Object, Object>) type.getDeclaredConstructor().newInstance(); Map<Object, Object> mapPojo = (Map<Object, Object>) pojo; map.putAll(mapPojo); if (GENERIC_WITH_CLZ) { map.remove("class"); } } catch (Exception e) { // ignore error map = (Map<Object, Object>) pojo; } } else { map = (Map<Object, Object>) pojo; } if (Map.class.isAssignableFrom(type) || type == Object.class) { final Map<Object, Object> result; // fix issue#5939 Type mapKeyType = getKeyTypeForMap(map.getClass()); Type typeKeyType = getGenericClassByIndex(genericType, 0); boolean typeMismatch = mapKeyType instanceof Class && typeKeyType instanceof Class && !typeKeyType.getTypeName().equals(mapKeyType.getTypeName()); if (typeMismatch) { result = createMap(new HashMap(0)); } else { result = createMap(map); } history.put(pojo, result); for (Map.Entry<Object, Object> entry : map.entrySet()) { Type keyType = getGenericClassByIndex(genericType, 0); Type valueType = getGenericClassByIndex(genericType, 1); Class<?> keyClazz; if (keyType instanceof Class) { keyClazz = (Class<?>) keyType; } else if (keyType instanceof ParameterizedType) { keyClazz = (Class<?>) ((ParameterizedType) keyType).getRawType(); } else { keyClazz = entry.getKey() == null ? null : entry.getKey().getClass(); } Class<?> valueClazz; if (valueType instanceof Class) { valueClazz = (Class<?>) valueType; } else if (valueType instanceof ParameterizedType) { valueClazz = (Class<?>) ((ParameterizedType) valueType).getRawType(); } else { valueClazz = entry.getValue() == null ? null : entry.getValue().getClass(); } Object key = keyClazz == null ? entry.getKey() : realize1(entry.getKey(), keyClazz, keyType, mapGeneric, history); Object value = valueClazz == null ? entry.getValue() : realize1(entry.getValue(), valueClazz, valueType, mapGeneric, history); result.put(key, value); } return result; } else if (type.isInterface()) { Object dest = Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class<?>[] {type}, new PojoInvocationHandler(map)); history.put(pojo, dest); return dest; } else { Object dest; if (Throwable.class.isAssignableFrom(type)) { Object message = map.get("message"); if (message instanceof String) { dest = newThrowableInstance(type, (String) message); } else { dest = newInstance(type); } } else { dest = newInstance(type); } history.put(pojo, dest); for (Map.Entry<Object, Object> entry : map.entrySet()) { Object key = entry.getKey(); if (key instanceof String) { String name = (String) key; Object value = entry.getValue(); if (value != null) { Method method = getSetterMethod(dest.getClass(), name, value.getClass()); Field field = getAndCacheField(dest.getClass(), name); if (method != null) { if (!method.isAccessible()) { method.setAccessible(true); } Type containType = Optional.ofNullable(field) .map(Field::getGenericType) .map(Type::getTypeName) .map(mapGeneric::get) .orElse(null); if (containType != null) { // is generic if (containType instanceof ParameterizedType) { value = realize1( value, (Class<?>) ((ParameterizedType) containType).getRawType(), containType, mapGeneric, history); } else if (containType instanceof Class) { value = realize1( value, (Class<?>) containType, containType, mapGeneric, history); } else { Type ptype = method.getGenericParameterTypes()[0]; value = realize1( value, method.getParameterTypes()[0], ptype, mapGeneric, history); } } else { Type ptype = method.getGenericParameterTypes()[0]; value = realize1(value, method.getParameterTypes()[0], ptype, mapGeneric, history); } try { method.invoke(dest, value); } catch (Exception e) { String exceptionDescription = "Failed to set pojo " + dest.getClass().getSimpleName() + " property " + name + " value " + value.getClass() + ", cause: " + e.getMessage(); logger.error(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", exceptionDescription, e); throw new RuntimeException(exceptionDescription, e); } } else if (field != null) { value = realize1(value, field.getType(), field.getGenericType(), mapGeneric, history); try { field.set(dest, value); } catch (IllegalAccessException e) { throw new RuntimeException( "Failed to set field " + name + " of pojo " + dest.getClass().getName() + " : " + e.getMessage(), e); } } } } } return dest; } } return pojo; } /** * Get key type for {@link Map} directly implemented by {@code clazz}. * If {@code clazz} does not implement {@link Map} directly, return {@code null}. * * @param clazz {@link Class} * @return Return String.class for {@link com.alibaba.fastjson.JSONObject} */ private static Type getKeyTypeForMap(Class<?> clazz) { Type[] interfaces = clazz.getGenericInterfaces(); if (!ArrayUtils.isEmpty(interfaces)) { for (Type type : interfaces) { if (type instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) type; if ("java.util.Map".equals(t.getRawType().getTypeName())) { return t.getActualTypeArguments()[0]; } } } } return null; } /** * Get parameterized type * * @param genericType generic type * @param index index of the target parameterized type * @return Return Person.class for List<Person>, return Person.class for Map<String, Person> when index=0 */ private static Type getGenericClassByIndex(Type genericType, int index) { Type clazz = null; // find parameterized type if (genericType instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) genericType; Type[] types = t.getActualTypeArguments(); clazz = types[index]; } return clazz; } private static Object newThrowableInstance(Class<?> cls, String message) { try { Constructor<?> messagedConstructor = cls.getDeclaredConstructor(String.class); return messagedConstructor.newInstance(message); } catch (Exception t) { return newInstance(cls); } } private static Object newInstance(Class<?> cls) { try { return cls.getDeclaredConstructor().newInstance(); } catch (Exception t) { Constructor<?>[] constructors = cls.getDeclaredConstructors(); /* From Javadoc java.lang.Class#getDeclaredConstructors This method returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. This method returns an array of length 0, if this Class object represents an interface, a primitive type, an array class, or void. */ if (constructors.length == 0) { throw new RuntimeException("Illegal constructor: " + cls.getName()); } Throwable lastError = null; Arrays.sort(constructors, Comparator.comparingInt(a -> a.getParameterTypes().length)); for (Constructor<?> constructor : constructors) { try { constructor.setAccessible(true); Object[] parameters = Arrays.stream(constructor.getParameterTypes()) .map(PojoUtils::getDefaultValue) .toArray(); return constructor.newInstance(parameters); } catch (Exception e) { lastError = e; } } throw new RuntimeException(lastError.getMessage(), lastError); } } /** * return init value * * @param parameterType * @return */ private static Object getDefaultValue(Class<?> parameterType) { if ("char".equals(parameterType.getName())) { return Character.MIN_VALUE; } if ("boolean".equals(parameterType.getName())) { return false; } if ("byte".equals(parameterType.getName())) { return (byte) 0; } if ("short".equals(parameterType.getName())) { return (short) 0; } return parameterType.isPrimitive() ? 0 : null; } private static Method getSetterMethod(Class<?> cls, String property, Class<?> valueCls) { String name = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); Method method = NAME_METHODS_CACHE.get(cls.getName() + "." + name + "(" + valueCls.getName() + ")"); if (method == null) { try { method = cls.getMethod(name, valueCls); } catch (NoSuchMethodException e) { for (Method m : cls.getMethods()) { if (ReflectUtils.isBeanPropertyWriteMethod(m) && m.getName().equals(name)) { method = m; break; } } } if (method != null) { NAME_METHODS_CACHE.put(cls.getName() + "." + name + "(" + valueCls.getName() + ")", method); } } return method; } private static Field getAndCacheField(Class<?> cls, String fieldName) { Field result; if (CLASS_FIELD_CACHE.containsKey(cls) && CLASS_FIELD_CACHE.get(cls).containsKey(fieldName)) { return CLASS_FIELD_CACHE.get(cls).get(fieldName); } result = getField(cls, fieldName); if (result != null) { ConcurrentMap<String, Field> fields = ConcurrentHashMapUtils.computeIfAbsent(CLASS_FIELD_CACHE, cls, k -> new ConcurrentHashMap<>()); fields.putIfAbsent(fieldName, result); } return result; } private static Field getField(Class<?> cls, String fieldName) { Field result = null; for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) { try { result = acls.getDeclaredField(fieldName); if (!Modifier.isPublic(result.getModifiers())) { result.setAccessible(true); } } catch (NoSuchFieldException e) { }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
true
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.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.utils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.convert.ConverterUtil; import org.apache.dubbo.rpc.model.FrameworkModel; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Queue; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.utils.ArrayUtils.isNotEmpty; import static org.apache.dubbo.common.utils.CollectionUtils.flip; import static org.apache.dubbo.common.utils.CollectionUtils.ofSet; import static org.apache.dubbo.common.utils.StringUtils.isEmpty; public class ClassUtils { /** * Suffix for array class names: "[]" */ public static final String ARRAY_SUFFIX = "[]"; /** * Simple Types including: * <ul> * <li>{@link Void}</li> * <li>{@link Boolean}</li> * <li>{@link Character}</li> * <li>{@link Byte}</li> * <li>{@link Integer}</li> * <li>{@link Float}</li> * <li>{@link Double}</li> * <li>{@link String}</li> * <li>{@link BigDecimal}</li> * <li>{@link BigInteger}</li> * <li>{@link Date}</li> * <li>{@link Object}</li> * </ul> * * @see javax.management.openmbean.SimpleType * @since 2.7.6 */ public static final Set<Class<?>> SIMPLE_TYPES = ofSet( Void.class, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, String.class, BigDecimal.class, BigInteger.class, Date.class, Object.class, Duration.class); /** * Prefix for internal array class names: "[L" */ private static final String INTERNAL_ARRAY_PREFIX = "[L"; /** * Map with primitive type name as key and corresponding primitive type as * value, for example: "int" -> "int.class". */ private static final Map<String, Class<?>> PRIMITIVE_TYPE_NAME_MAP = new HashMap<>(32); /** * Map with primitive wrapper type as key and corresponding primitive type * as value, for example: Integer.class -> int.class. */ private static final Map<Class<?>, Class<?>> PRIMITIVE_WRAPPER_TYPE_MAP = new HashMap<>(16); static { PRIMITIVE_WRAPPER_TYPE_MAP.put(Boolean.class, boolean.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Byte.class, byte.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Character.class, char.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Double.class, double.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Float.class, float.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Integer.class, int.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Long.class, long.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Short.class, short.class); PRIMITIVE_WRAPPER_TYPE_MAP.put(Void.class, void.class); Set<Class<?>> primitiveTypeNames = new HashSet<>(32); primitiveTypeNames.addAll(PRIMITIVE_WRAPPER_TYPE_MAP.values()); primitiveTypeNames.addAll(Arrays.asList( boolean[].class, byte[].class, char[].class, double[].class, float[].class, int[].class, long[].class, short[].class)); for (Class<?> primitiveTypeName : primitiveTypeNames) { PRIMITIVE_TYPE_NAME_MAP.put(primitiveTypeName.getName(), primitiveTypeName); } } /** * Map with primitive type as key and corresponding primitive wrapper type * as value, for example: int.class -> Integer.class. */ private static final Map<Class<?>, Class<?>> WRAPPER_PRIMITIVE_TYPE_MAP = flip(PRIMITIVE_WRAPPER_TYPE_MAP); /** * Separator char for package */ private static final char PACKAGE_SEPARATOR_CHAR = '.'; public static Class<?> forNameWithThreadContextClassLoader(String name) throws ClassNotFoundException { return forName(name, Thread.currentThread().getContextClassLoader()); } public static Class<?> forNameWithCallerClassLoader(String name, Class<?> caller) throws ClassNotFoundException { return forName(name, caller.getClassLoader()); } public static ClassLoader getCallerClassLoader(Class<?> caller) { return caller.getClassLoader(); } /** * get class loader * * @param clazz * @return class loader */ public static ClassLoader getClassLoader(Class<?> clazz) { ClassLoader cl = null; if (!clazz.getName().startsWith("org.apache.dubbo")) { cl = clazz.getClassLoader(); } if (cl == null) { try { cl = Thread.currentThread().getContextClassLoader(); } catch (Exception ignored) { // Cannot access thread context ClassLoader - falling back to system class loader... } if (cl == null) { // No thread context class loader -> use class loader of this class. cl = clazz.getClassLoader(); if (cl == null) { // getClassLoader() returning null indicates the bootstrap ClassLoader try { cl = ClassLoader.getSystemClassLoader(); } catch (Exception ignored) { // Cannot access system ClassLoader - oh well, maybe the caller can live with null... } } } } return cl; } /** * Return the default ClassLoader to use: typically the thread context * ClassLoader, if available; the ClassLoader that loaded the ClassUtils * class will be used as fallback. * <p> * Call this method if you intend to use the thread context ClassLoader in a * scenario where you absolutely need a non-null ClassLoader reference: for * example, for class path resource loading (but not necessarily for * <code>Class.forName</code>, which accepts a <code>null</code> ClassLoader * reference as well). * * @return the default ClassLoader (never <code>null</code>) * @see java.lang.Thread#getContextClassLoader() */ public static ClassLoader getClassLoader() { return getClassLoader(ClassUtils.class); } /** * Same as <code>Class.forName()</code>, except that it works for primitive * types. */ public static Class<?> forName(String name) throws ClassNotFoundException { return forName(name, getClassLoader()); } /** * find class and don`t expect to throw exception * @param name * @return */ public static Class<?> forNameAndTryCatch(String name) { try { return forName(name, getClassLoader()); } catch (Throwable e) { return null; } } /** * Replacement for <code>Class.forName()</code> that also returns Class * instances for primitives (like "int") and array class names (like * "String[]"). * * @param name the name of the Class * @param classLoader the class loader to use (may be <code>null</code>, * which indicates the default class loader) * @return Class instance for the supplied name * @throws ClassNotFoundException if the class was not found * @throws LinkageError if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) */ public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { Class<?> clazz = resolvePrimitiveClassName(name); if (clazz != null) { return clazz; } // "java.lang.String[]" style arrays if (name.endsWith(ARRAY_SUFFIX)) { String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length()); Class<?> elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } // "[Ljava.lang.String;" style arrays int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX); if (internalArrayMarker != -1 && name.endsWith(";")) { String elementClassName = null; if (internalArrayMarker == 0) { elementClassName = name.substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1); } else if (name.startsWith("[")) { elementClassName = name.substring(1); } Class<?> elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = getClassLoader(); } return classLoaderToUse.loadClass(name); } /** * Resolve the given class name as primitive class, if appropriate, * according to the JVM's naming rules for primitive classes. * <p> * Also supports the JVM's internal class names for primitive arrays. Does * <i>not</i> support the "[]" suffix notation for primitive arrays; this is * only supported by {@link #forName}. * * @param name the name of the potentially primitive class * @return the primitive class, or <code>null</code> if the name does not * denote a primitive class or primitive array class */ public static Class<?> resolvePrimitiveClassName(String name) { Class<?> result = null; // Most class names will be quite long, considering that they // SHOULD sit in a package, so a length check is worthwhile. if (name != null && name.length() <= 8) { // Could be a primitive - likely. result = (Class<?>) PRIMITIVE_TYPE_NAME_MAP.get(name); } return result; } public static String toShortString(Object obj) { if (obj == null) { return "null"; } return obj.getClass().getSimpleName() + "@" + System.identityHashCode(obj); } public static String simpleClassName(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } String className = clazz.getName(); final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); if (lastDotIdx > -1) { return className.substring(lastDotIdx + 1); } return className; } /** * The specified type is primitive type or simple type * * @param type the type to test * @return * @deprecated as 2.7.6, use {@link Class#isPrimitive()} plus {@link #isSimpleType(Class)} instead */ public static boolean isPrimitive(Class<?> type) { return type != null && (type.isPrimitive() || isSimpleType(type)); } public static boolean isPrimitiveWrapper(Class<?> type) { return PRIMITIVE_WRAPPER_TYPE_MAP.containsKey(type); } /** * The specified type is simple type or not * * @param type the type to test * @return if <code>type</code> is one element of {@link #SIMPLE_TYPES}, return <code>true</code>, or <code>false</code> * @see #SIMPLE_TYPES * @since 2.7.6 */ public static boolean isSimpleType(Class<?> type) { return SIMPLE_TYPES.contains(type); } public static Object convertPrimitive(Class<?> type, String value) { return convertPrimitive(FrameworkModel.defaultModel(), type, value); } public static Object convertPrimitive(FrameworkModel frameworkModel, Class<?> type, String value) { if (isEmpty(value)) { return null; } Class<?> wrapperType = WRAPPER_PRIMITIVE_TYPE_MAP.getOrDefault(type, type); Object result = null; try { result = frameworkModel.getBeanFactory().getBean(ConverterUtil.class).convertIfPossible(value, wrapperType); } catch (Exception e) { // ignore exception } return result; } /** * We only check boolean value at this moment. * * @param type * @param value * @return */ public static boolean isTypeMatch(Class<?> type, String value) { if ((type == boolean.class || type == Boolean.class) && !("true".equals(value) || "false".equals(value))) { return false; } return true; } /** * Get all super classes from the specified type * * @param type the specified type * @param classFilters the filters for classes * @return non-null read-only {@link Set} * @since 2.7.6 */ public static Set<Class<?>> getAllSuperClasses(Class<?> type, Predicate<Class<?>>... classFilters) { Set<Class<?>> allSuperClasses = new LinkedHashSet<>(); Class<?> superClass = type.getSuperclass(); while (superClass != null) { // add current super class allSuperClasses.add(superClass); superClass = superClass.getSuperclass(); } return unmodifiableSet(filterAll(allSuperClasses, classFilters)); } /** * Get all interfaces from the specified type * * @param type the specified type * @param interfaceFilters the filters for interfaces * @return non-null read-only {@link Set} * @since 2.7.6 */ public static Set<Class<?>> getAllInterfaces(Class<?> type, Predicate<Class<?>>... interfaceFilters) { if (type == null || type.isPrimitive()) { return emptySet(); } Set<Class<?>> allInterfaces = new LinkedHashSet<>(); Set<Class<?>> resolved = new LinkedHashSet<>(); Queue<Class<?>> waitResolve = new LinkedList<>(); resolved.add(type); Class<?> clazz = type; while (clazz != null) { Class<?>[] interfaces = clazz.getInterfaces(); if (isNotEmpty(interfaces)) { // add current interfaces Arrays.stream(interfaces).filter(resolved::add).forEach(cls -> { allInterfaces.add(cls); waitResolve.add(cls); }); } // add all super classes to waitResolve getAllSuperClasses(clazz).stream().filter(resolved::add).forEach(waitResolve::add); clazz = waitResolve.poll(); } return filterAll(allInterfaces, interfaceFilters); } /** * Get all inherited types from the specified type * * @param type the specified type * @param typeFilters the filters for types * @return non-null read-only {@link Set} * @since 2.7.6 */ public static Set<Class<?>> getAllInheritedTypes(Class<?> type, Predicate<Class<?>>... typeFilters) { // Add all super classes Set<Class<?>> types = new LinkedHashSet<>(getAllSuperClasses(type, typeFilters)); // Add all interface classes types.addAll(getAllInterfaces(type, typeFilters)); return unmodifiableSet(types); } /** * the semantics is same as {@link Class#isAssignableFrom(Class)} * * @param superType the super type * @param targetType the target type * @return see {@link Class#isAssignableFrom(Class)} * @since 2.7.6 */ public static boolean isAssignableFrom(Class<?> superType, Class<?> targetType) { // any argument is null if (superType == null || targetType == null) { return false; } // equals if (Objects.equals(superType, targetType)) { return true; } // isAssignableFrom return superType.isAssignableFrom(targetType); } /** * Test the specified class name is present in the {@link ClassLoader} * * @param className the name of {@link Class} * @param classLoader {@link ClassLoader} * @return If found, return <code>true</code> * @since 2.7.6 */ public static boolean isPresent(String className, ClassLoader classLoader) { try { forName(className, classLoader); } catch (Exception ignored) { // Ignored return false; } return true; } /** * Test the specified class name is present, array class is not supported */ public static boolean isPresent(String className) { try { loadClass(className); return true; } catch (Throwable ignored) { return false; } } /** * Load the {@link Class} by the specified name, array class is not supported */ public static Class<?> loadClass(String className) throws ClassNotFoundException { ClassLoader cl = null; if (!className.startsWith("org.apache.dubbo")) { try { cl = Thread.currentThread().getContextClassLoader(); } catch (Throwable ignored) { } } if (cl == null) { cl = ClassUtils.class.getClassLoader(); } return cl.loadClass(className); } public static void runWith(ClassLoader classLoader, Runnable runnable) { Thread thread = Thread.currentThread(); ClassLoader tccl = thread.getContextClassLoader(); if (classLoader == null || classLoader.equals(tccl)) { runnable.run(); return; } thread.setContextClassLoader(classLoader); try { runnable.run(); } finally { thread.setContextClassLoader(tccl); } } /** * Resolve the {@link Class} by the specified name and {@link ClassLoader} * * @param className the name of {@link Class} * @param classLoader {@link ClassLoader} * @return If can't be resolved , return <code>null</code> * @since 2.7.6 */ public static Class<?> resolveClass(String className, ClassLoader classLoader) { Class<?> targetClass = null; try { targetClass = forName(className, classLoader); } catch (Exception ignored) { // Ignored } return targetClass; } /** * Is generic class or not? * * @param type the target type * @return if the target type is not null or <code>void</code> or Void.class, return <code>true</code>, or false * @since 2.7.6 */ public static boolean isGenericClass(Class<?> type) { return type != null && !void.class.equals(type) && !Void.class.equals(type); } public static boolean hasMethods(Method[] methods) { if (methods == null || methods.length == 0) { return false; } for (Method m : methods) { if (m.getDeclaringClass() != Object.class) { return true; } } return false; } private static final String[] OBJECT_METHODS = new String[] {"getClass", "hashCode", "toString", "equals"}; /** * get method name array. * * @return method name array. */ public static String[] getMethodNames(Class<?> tClass) { if (tClass == Object.class) { return OBJECT_METHODS; } Method[] methods = Arrays.stream(tClass.getMethods()).collect(Collectors.toList()).toArray(new Method[] {}); List<String> mns = new ArrayList<>(); // method names. boolean hasMethod = hasMethods(methods); if (hasMethod) { for (Method m : methods) { // ignore Object's method. if (m.getDeclaringClass() == Object.class) { continue; } String mn = m.getName(); mns.add(mn); } } return mns.toArray(new String[0]); } public static boolean isMatch(Class<?> from, Class<?> to) { if (from == to) { return true; } boolean isMatch; if (from.isPrimitive()) { isMatch = matchPrimitive(from, to); } else if (to.isPrimitive()) { isMatch = matchPrimitive(to, from); } else { isMatch = to.isAssignableFrom(from); } return isMatch; } private static boolean matchPrimitive(Class<?> from, Class<?> to) { if (from == boolean.class) { return to == Boolean.class; } else if (from == byte.class) { return to == Byte.class; } else if (from == char.class) { return to == Character.class; } else if (from == short.class) { return to == Short.class; } else if (from == int.class) { return to == Integer.class; } else if (from == long.class) { return to == Long.class; } else if (from == float.class) { return to == Float.class; } else if (from == double.class) { return to == Double.class; } else if (from == void.class) { return to == Void.class; } return false; } /** * get method name array. * * @return method name array. */ public static String[] getDeclaredMethodNames(Class<?> tClass) { if (tClass == Object.class) { return OBJECT_METHODS; } Method[] methods = Arrays.stream(tClass.getMethods()).collect(Collectors.toList()).toArray(new Method[] {}); List<String> dmns = new ArrayList<>(); // method names. boolean hasMethod = hasMethods(methods); if (hasMethod) { for (Method m : methods) { // ignore Object's method. if (m.getDeclaringClass() == Object.class) { continue; } String mn = m.getName(); if (m.getDeclaringClass() == tClass) { dmns.add(mn); } } } dmns.sort(Comparator.naturalOrder()); return dmns.toArray(new String[0]); } public static boolean hasProtobuf() { return isPresent(CommonConstants.PROTOBUF_MESSAGE_CLASS_NAME); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultSerializeClassChecker.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultSerializeClassChecker.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.utils; import org.apache.dubbo.common.aot.NativeDetector; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialization.ClassHolder; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.Serializable; import java.util.Arrays; import java.util.Set; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNTRUSTED_SERIALIZE_CLASS; /** * Inspired by Fastjson2 * see com.alibaba.fastjson2.filter.ContextAutoTypeBeforeHandler#apply(java.lang.String, java.lang.Class, long) */ public class DefaultSerializeClassChecker implements AllowClassNotifyListener { private static final long MAGIC_HASH_CODE = 0xcbf29ce484222325L; private static final long MAGIC_PRIME = 0x100000001b3L; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultSerializeClassChecker.class); private volatile SerializeCheckStatus checkStatus = AllowClassNotifyListener.DEFAULT_STATUS; private volatile boolean checkSerializable = true; private final SerializeSecurityManager serializeSecurityManager; private final ClassHolder classHolder; private volatile long[] allowPrefixes = new long[0]; private volatile long[] disAllowPrefixes = new long[0]; public DefaultSerializeClassChecker(FrameworkModel frameworkModel) { serializeSecurityManager = frameworkModel.getBeanFactory().getOrRegisterBean(SerializeSecurityManager.class); serializeSecurityManager.registerListener(this); classHolder = NativeDetector.inNativeImage() ? frameworkModel.getBeanFactory().getBean(ClassHolder.class) : null; } @Override public synchronized void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList) { this.allowPrefixes = loadPrefix(allowedList); this.disAllowPrefixes = loadPrefix(disAllowedList); } @Override public synchronized void notifyCheckStatus(SerializeCheckStatus status) { this.checkStatus = status; } @Override public synchronized void notifyCheckSerializable(boolean checkSerializable) { this.checkSerializable = checkSerializable; } private static long[] loadPrefix(Set<String> allowedList) { long[] array = new long[allowedList.size()]; int index = 0; for (String name : allowedList) { if (name == null || name.isEmpty()) { continue; } long hashCode = MAGIC_HASH_CODE; for (int j = 0; j < name.length(); ++j) { char ch = name.charAt(j); if (ch == '$') { ch = '.'; } hashCode ^= ch; hashCode *= MAGIC_PRIME; } array[index++] = hashCode; } if (index != array.length) { array = Arrays.copyOf(array, index); } Arrays.sort(array); return array; } /** * Try load class * * @param className class name * @throws IllegalArgumentException if class is blocked */ public Class<?> loadClass(ClassLoader classLoader, String className) throws ClassNotFoundException { Class<?> aClass = loadClass0(classLoader, className); if (!aClass.isPrimitive() && !Serializable.class.isAssignableFrom(aClass)) { String msg = "[Serialization Security] Serialized class " + className + " has not implement Serializable interface. " + "Current mode is strict check, will disallow to deserialize it by default. "; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.error(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } if (checkSerializable) { throw new IllegalArgumentException(msg); } } return aClass; } private Class<?> loadClass0(ClassLoader classLoader, String className) throws ClassNotFoundException { if (checkStatus == SerializeCheckStatus.DISABLE) { return classForName(classLoader, className); } long hash = MAGIC_HASH_CODE; for (int i = 0, typeNameLength = className.length(); i < typeNameLength; ++i) { char ch = className.charAt(i); if (ch == '$') { ch = '.'; } hash ^= ch; hash *= MAGIC_PRIME; if (Arrays.binarySearch(allowPrefixes, hash) >= 0) { return classForName(classLoader, className); } } if (checkStatus == SerializeCheckStatus.STRICT) { String msg = "[Serialization Security] Serialized class " + className + " is not in allow list. " + "Current mode is `STRICT`, will disallow to deserialize it by default. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.error(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } throw new IllegalArgumentException(msg); } hash = MAGIC_HASH_CODE; for (int i = 0, typeNameLength = className.length(); i < typeNameLength; ++i) { char ch = className.charAt(i); if (ch == '$') { ch = '.'; } hash ^= ch; hash *= MAGIC_PRIME; if (Arrays.binarySearch(disAllowPrefixes, hash) >= 0) { String msg = "[Serialization Security] Serialized class " + className + " is in disallow list. " + "Current mode is `WARN`, will disallow to deserialize it by default. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } throw new IllegalArgumentException(msg); } } hash = MAGIC_HASH_CODE; for (int i = 0, typeNameLength = className.length(); i < typeNameLength; ++i) { char ch = Character.toLowerCase(className.charAt(i)); if (ch == '$') { ch = '.'; } hash ^= ch; hash *= MAGIC_PRIME; if (Arrays.binarySearch(disAllowPrefixes, hash) >= 0) { String msg = "[Serialization Security] Serialized class " + className + " is in disallow list. " + "Current mode is `WARN`, will disallow to deserialize it by default. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } throw new IllegalArgumentException(msg); } } Class<?> clazz = classForName(classLoader, className); if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.warn( PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", "[Serialization Security] Serialized class " + className + " is not in allow list. " + "Current mode is `WARN`, will allow to deserialize it by default. " + "Dubbo will set to `STRICT` mode by default in the future. " + "Please add it into security/serialize.allowlist or follow FAQ to configure it."); } return clazz; } private Class<?> classForName(ClassLoader classLoader, String className) throws ClassNotFoundException { if (classHolder != null) { Class<?> aClass = classHolder.loadClass(className, classLoader); if (aClass != null) { return aClass; } } return ClassUtils.forName(className, classLoader); } public static DefaultSerializeClassChecker getInstance() { return FrameworkModel.defaultModel().getBeanFactory().getBean(DefaultSerializeClassChecker.class); } public boolean isCheckSerializable() { return checkSerializable; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ProtobufUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ProtobufUtils.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.utils; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import static org.apache.dubbo.common.constants.CommonConstants.PROTOBUF_MESSAGE_CLASS_NAME; public class ProtobufUtils { private static final Logger logger = LoggerFactory.getLogger(ProtobufUtils.class); private static Class<?> protobufClss; private ProtobufUtils() {} static { try { protobufClss = ClassUtils.forName(PROTOBUF_MESSAGE_CLASS_NAME, ProtobufUtils.class.getClassLoader()); } catch (Throwable t) { logger.info("protobuf's dependency is absent"); } } public static boolean isProtobufClass(Class<?> pojoClazz) { if (protobufClss != null) { return protobufClss.isAssignableFrom(pojoClazz); } return false; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JVMUtil.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/JVMUtil.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.utils; import org.apache.dubbo.common.constants.CommonConstants; import java.io.OutputStream; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.nio.charset.StandardCharsets; import static java.lang.Thread.State.BLOCKED; import static java.lang.Thread.State.TIMED_WAITING; import static java.lang.Thread.State.WAITING; public class JVMUtil { public static void jstack(OutputStream stream) throws Exception { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); for (ThreadInfo threadInfo : threadMxBean.dumpAllThreads(true, true)) { stream.write(getThreadDumpString(threadInfo).getBytes(StandardCharsets.UTF_8)); } } private static String getThreadDumpString(ThreadInfo threadInfo) { StringBuilder sb = new StringBuilder("\"" + threadInfo.getThreadName() + "\"" + " Id=" + threadInfo.getThreadId() + " " + threadInfo.getThreadState()); if (threadInfo.getLockName() != null) { sb.append(" on " + threadInfo.getLockName()); } if (threadInfo.getLockOwnerName() != null) { sb.append(" owned by \"" + threadInfo.getLockOwnerName() + "\" Id=" + threadInfo.getLockOwnerId()); } if (threadInfo.isSuspended()) { sb.append(" (suspended)"); } if (threadInfo.isInNative()) { sb.append(" (in native)"); } sb.append('\n'); int i = 0; // default is 32, means only print up to 32 lines int jstackMaxLine = 32; String jstackMaxLineStr = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_JSTACK_MAXLINE); if (StringUtils.isNotEmpty(jstackMaxLineStr)) { try { jstackMaxLine = Integer.parseInt(jstackMaxLineStr); } catch (Exception ignore) { } } StackTraceElement[] stackTrace = threadInfo.getStackTrace(); MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors(); for (; i < stackTrace.length && i < jstackMaxLine; i++) { StackTraceElement ste = stackTrace[i]; sb.append("\tat ").append(ste.toString()); sb.append('\n'); if (i == 0 && threadInfo.getLockInfo() != null) { Thread.State ts = threadInfo.getThreadState(); if (BLOCKED.equals(ts)) { sb.append("\t- blocked on ").append(threadInfo.getLockInfo()); sb.append('\n'); } else if (WAITING.equals(ts) || TIMED_WAITING.equals(ts)) { sb.append("\t- waiting on ").append(threadInfo.getLockInfo()); sb.append('\n'); } } for (MonitorInfo mi : lockedMonitors) { if (mi.getLockedStackDepth() == i) { sb.append("\t- locked ").append(mi); sb.append('\n'); } } } if (i < stackTrace.length) { sb.append("\t..."); sb.append('\n'); } LockInfo[] locks = threadInfo.getLockedSynchronizers(); if (locks.length > 0) { sb.append("\n\tNumber of locked synchronizers = " + locks.length); sb.append('\n'); for (LockInfo li : locks) { sb.append("\t- " + li); sb.append('\n'); } } sb.append('\n'); return sb.toString(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AllowClassNotifyListener.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/AllowClassNotifyListener.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.utils; import java.util.Set; public interface AllowClassNotifyListener { SerializeCheckStatus DEFAULT_STATUS = SerializeCheckStatus.STRICT; void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList); void notifyCheckStatus(SerializeCheckStatus status); void notifyCheckSerializable(boolean checkSerializable); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.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.utils; import org.apache.dubbo.common.constants.CommonConstants; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Miscellaneous io utility methods. * Mainly for internal use within the framework. * * @since 2.0.7 */ public class IOUtils { private static final int BUFFER_SIZE = 1024 * 8; public static final int EOF = -1; private IOUtils() {} /** * write. * * @param is InputStream instance. * @param os OutputStream instance. * @return count. * @throws IOException If an I/O error occurs */ public static long write(InputStream is, OutputStream os) throws IOException { return write(is, os, BUFFER_SIZE); } /** * write. * * @param is InputStream instance. * @param os OutputStream instance. * @param bufferSize buffer size. * @return count. * @throws IOException If an I/O error occurs */ public static long write(InputStream is, OutputStream os, int bufferSize) throws IOException { byte[] buff = new byte[bufferSize]; return write(is, os, buff); } /** * write. * * @param input InputStream instance. * @param output OutputStream instance. * @param buffer buffer byte array * @return count. * @throws IOException If an I/O error occurs */ public static long write(final InputStream input, final OutputStream output, final byte[] buffer) throws IOException { long count = 0; int n; while (EOF != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } /** * read string. * * @param reader Reader instance. * @return String. * @throws IOException If an I/O error occurs */ public static String read(Reader reader) throws IOException { try (StringWriter writer = new StringWriter()) { write(reader, writer); return writer.getBuffer().toString(); } } /** * write string. * * @param writer Writer instance. * @param string String. * @throws IOException If an I/O error occurs */ public static long write(Writer writer, String string) throws IOException { try (Reader reader = new StringReader(string)) { return write(reader, writer); } } /** * write. * * @param reader Reader. * @param writer Writer. * @return count. * @throws IOException If an I/O error occurs */ public static long write(Reader reader, Writer writer) throws IOException { return write(reader, writer, BUFFER_SIZE); } /** * write. * * @param reader Reader. * @param writer Writer. * @param bufferSize buffer size. * @return count. * @throws IOException If an I/O error occurs */ public static long write(Reader reader, Writer writer, int bufferSize) throws IOException { int read; long total = 0; char[] buf = new char[bufferSize]; while ((read = reader.read(buf)) != -1) { writer.write(buf, 0, read); total += read; } return total; } /** * read lines. * * @param file file. * @return lines. * @throws IOException If an I/O error occurs */ public static String[] readLines(File file) throws IOException { if (file == null || !file.exists() || !file.canRead()) { return new String[0]; } return readLines(new FileInputStream(file)); } /** * read lines. * * @param is input stream. * @return lines. * @throws IOException If an I/O error occurs */ public static String[] readLines(InputStream is) throws IOException { List<String> lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } return lines.toArray(new String[0]); } } public static String read(InputStream is, String encoding) throws IOException { StringBuilder stringBuilder = new StringBuilder(); InputStreamReader inputStreamReader = new InputStreamReader(is, encoding); char[] buf = new char[1024]; int len; while ((len = inputStreamReader.read(buf)) != -1) { stringBuilder.append(buf, 0, len); } inputStreamReader.close(); return stringBuilder.toString(); } /** * write lines. * * @param os output stream. * @param lines lines. * @throws IOException If an I/O error occurs */ public static void writeLines(OutputStream os, String[] lines) throws IOException { try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(os))) { for (String line : lines) { writer.println(line); } writer.flush(); } } /** * write lines. * * @param file file. * @param lines lines. * @throws IOException If an I/O error occurs */ public static void writeLines(File file, String[] lines) throws IOException { if (file == null) { throw new IOException("File is null."); } writeLines(new FileOutputStream(file), lines); } /** * append lines. * * @param file file. * @param lines lines. * @throws IOException If an I/O error occurs */ public static void appendLines(File file, String[] lines) throws IOException { if (file == null) { throw new IOException("File is null."); } writeLines(new FileOutputStream(file, true), lines); } /** * use like spring code * * @param resourceLocation * @return */ public static URL getURL(String resourceLocation) throws FileNotFoundException { Assert.notNull(resourceLocation, "Resource location must not be null"); if (resourceLocation.startsWith(CommonConstants.CLASSPATH_URL_PREFIX)) { String path = resourceLocation.substring(CommonConstants.CLASSPATH_URL_PREFIX.length()); ClassLoader cl = ClassUtils.getClassLoader(); URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path)); if (url == null) { String description = "class path resource [" + path + "]"; throw new FileNotFoundException(description + " cannot be resolved to URL because it does not exist"); } return url; } try { // try URL return new URL(resourceLocation); } catch (MalformedURLException ex) { // no URL -> treat as file path try { return new File(resourceLocation).toURI().toURL(); } catch (MalformedURLException ex2) { throw new FileNotFoundException( "Resource location [" + resourceLocation + "] is neither a URL not a well-formed file path"); } } } public static byte[] toByteArray(final InputStream inputStream) throws IOException { try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int n; while (-1 != (n = inputStream.read(buffer))) { byteArrayOutputStream.write(buffer, 0, n); } return byteArrayOutputStream.toByteArray(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/DateUtils.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.utils; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.CopyOnWriteArrayList; public final class DateUtils { public static final ZoneId GMT = ZoneId.of("GMT"); public static final ZoneId UTC = ZoneId.of("UTC"); public static final String DATE = "yyyy-MM-dd"; public static final String DATE_MIN = "yyyy-MM-dd HH:mm"; public static final String DATE_TIME = "yyyy-MM-dd HH:mm:ss"; public static final String JDK_TIME = "EEE MMM dd HH:mm:ss zzz yyyy"; public static final String ASC_TIME = "EEE MMM d HH:mm:ss yyyy"; public static final String RFC1036 = "EEE, dd-MMM-yy HH:mm:ss zzz"; public static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern(DATE); public static final DateTimeFormatter DATE_MIN_FORMAT = DateTimeFormatter.ofPattern(DATE_MIN); public static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern(DATE_TIME); public static final DateTimeFormatter JDK_TIME_FORMAT = DateTimeFormatter.ofPattern(JDK_TIME, Locale.US); public static final DateTimeFormatter ASC_TIME_FORMAT = DateTimeFormatter.ofPattern(ASC_TIME, Locale.US); public static final DateTimeFormatter RFC1036_FORMAT = DateTimeFormatter.ofPattern(RFC1036, Locale.US); private static final Map<String, DateTimeFormatter> CACHE = new LRUCache<>(64); private static final List<DateTimeFormatter> CUSTOM_FORMATTERS = new CopyOnWriteArrayList<>(); private DateUtils() {} public static void registerFormatter(String pattern) { CUSTOM_FORMATTERS.add(DateTimeFormatter.ofPattern(pattern)); } public static void registerFormatter(DateTimeFormatter formatter) { CUSTOM_FORMATTERS.add(formatter); } public static Date parse(String str, String pattern) { if (DATE_TIME.equals(pattern)) { return parse(str, DATE_TIME_FORMAT); } DateTimeFormatter formatter = getFormatter(pattern); return parse(str, formatter); } public static Date parse(String str, DateTimeFormatter formatter) { return toDate(formatter.parse(str)); } public static String format(Date date) { return format(date, DATE_TIME_FORMAT); } public static String format(Date date, String pattern) { if (DATE_TIME.equals(pattern)) { return format(date, DATE_TIME_FORMAT); } DateTimeFormatter formatter = getFormatter(pattern); return format(date, formatter); } public static String format(Date date, DateTimeFormatter formatter) { return formatter.format(ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault())); } public static String format(Date date, DateTimeFormatter formatter, ZoneId zone) { return formatter.format(ZonedDateTime.ofInstant(date.toInstant(), zone)); } public static String formatGMT(Date date, DateTimeFormatter formatter) { return formatter.format(ZonedDateTime.ofInstant(date.toInstant(), GMT)); } public static String formatUTC(Date date, DateTimeFormatter formatter) { return formatter.format(ZonedDateTime.ofInstant(date.toInstant(), UTC)); } public static String formatHeader(Date date) { return DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.ofInstant(date.toInstant(), GMT)); } private static DateTimeFormatter getFormatter(String pattern) { return CACHE.computeIfAbsent(pattern, DateTimeFormatter::ofPattern); } public static Date parse(Object value) { if (value == null) { return null; } if (value instanceof Date) { return (Date) value; } if (value instanceof Calendar) { return ((Calendar) value).getTime(); } if (value.getClass() == Instant.class) { return Date.from((Instant) value); } if (value instanceof TemporalAccessor) { return Date.from(Instant.from((TemporalAccessor) value)); } if (value instanceof Number) { return new Date(((Number) value).longValue()); } if (value instanceof CharSequence) { return parse(value.toString()); } throw new IllegalArgumentException("Can not cast to Date, value : '" + value + "'"); } public static Date parse(String value) { if (value == null) { return null; } String str = value.trim(); int len = str.length(); if (len == 0) { return null; } boolean isIso = true; boolean isNumeric = true; boolean hasDate = false; boolean hasTime = false; for (int i = 0; i < len; i++) { char c = str.charAt(i); switch (c) { case ' ': isIso = false; break; case '-': hasDate = true; break; case 'T': case ':': hasTime = true; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': continue; default: } if (isNumeric) { isNumeric = false; } } DateTimeFormatter formatter = null; if (isIso) { if (hasDate) { formatter = hasTime ? DateTimeFormatter.ISO_DATE_TIME : DateTimeFormatter.ISO_DATE; } else if (hasTime) { formatter = DateTimeFormatter.ISO_TIME; } } if (isNumeric) { long num = Long.parseLong(str); if (num > 21000101 || num < 19700101) { return new Date(num); } formatter = DateTimeFormatter.BASIC_ISO_DATE; } switch (len) { case 10: formatter = DATE_FORMAT; break; case 16: formatter = DATE_MIN_FORMAT; break; case 19: formatter = DATE_TIME_FORMAT; break; case 23: case 24: formatter = ASC_TIME_FORMAT; break; case 27: formatter = RFC1036_FORMAT; break; case 28: formatter = JDK_TIME_FORMAT; break; case 29: formatter = DateTimeFormatter.RFC_1123_DATE_TIME; break; default: } if (formatter != null) { try { return toDate(formatter.parse(str)); } catch (Exception ignored) { } } for (DateTimeFormatter dtf : CUSTOM_FORMATTERS) { try { return parse(str, dtf); } catch (Exception ignored) { } } throw new IllegalArgumentException("Can not cast to Date, value : '" + value + "'"); } public static Date toDate(TemporalAccessor temporal) { if (temporal instanceof Instant) { return Date.from((Instant) temporal); } long timestamp; if (temporal.isSupported(ChronoField.EPOCH_DAY)) { timestamp = temporal.getLong(ChronoField.EPOCH_DAY) * 86400000; } else { timestamp = LocalDate.now().toEpochDay() * 86400000; } if (temporal.isSupported(ChronoField.MILLI_OF_DAY)) { timestamp += temporal.getLong(ChronoField.MILLI_OF_DAY); } if (temporal.isSupported(ChronoField.OFFSET_SECONDS)) { timestamp -= temporal.getLong(ChronoField.OFFSET_SECONDS) * 1000; } else { timestamp -= TimeZone.getDefault().getRawOffset(); } return new Date(timestamp); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.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.utils; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; public class AtomicPositiveInteger extends Number { private static final long serialVersionUID = -3038533876489105940L; private static final AtomicIntegerFieldUpdater<AtomicPositiveInteger> INDEX_UPDATER = AtomicIntegerFieldUpdater.newUpdater(AtomicPositiveInteger.class, "index"); @SuppressWarnings("unused") private volatile int index = 0; public AtomicPositiveInteger() {} public AtomicPositiveInteger(int initialValue) { INDEX_UPDATER.set(this, initialValue); } public final int getAndIncrement() { return INDEX_UPDATER.getAndIncrement(this) & Integer.MAX_VALUE; } public final int getAndDecrement() { return INDEX_UPDATER.getAndDecrement(this) & Integer.MAX_VALUE; } public final int incrementAndGet() { return INDEX_UPDATER.incrementAndGet(this) & Integer.MAX_VALUE; } public final int decrementAndGet() { return INDEX_UPDATER.decrementAndGet(this) & Integer.MAX_VALUE; } public final int get() { return INDEX_UPDATER.get(this) & Integer.MAX_VALUE; } public final void set(int newValue) { if (newValue < 0) { throw new IllegalArgumentException("new value " + newValue + " < 0"); } INDEX_UPDATER.set(this, newValue); } public final int getAndSet(int newValue) { if (newValue < 0) { throw new IllegalArgumentException("new value " + newValue + " < 0"); } return INDEX_UPDATER.getAndSet(this, newValue) & Integer.MAX_VALUE; } public final int getAndAdd(int delta) { if (delta < 0) { throw new IllegalArgumentException("delta " + delta + " < 0"); } return INDEX_UPDATER.getAndAdd(this, delta) & Integer.MAX_VALUE; } public final int addAndGet(int delta) { if (delta < 0) { throw new IllegalArgumentException("delta " + delta + " < 0"); } return INDEX_UPDATER.addAndGet(this, delta) & Integer.MAX_VALUE; } public final boolean compareAndSet(int expect, int update) { if (update < 0) { throw new IllegalArgumentException("update value " + update + " < 0"); } return INDEX_UPDATER.compareAndSet(this, expect, update); } public final boolean weakCompareAndSet(int expect, int update) { if (update < 0) { throw new IllegalArgumentException("update value " + update + " < 0"); } return INDEX_UPDATER.weakCompareAndSet(this, expect, update); } @Override public byte byteValue() { return (byte) get(); } @Override public short shortValue() { return (short) get(); } @Override public int intValue() { return get(); } @Override public long longValue() { return (long) get(); } @Override public float floatValue() { return (float) get(); } @Override public double doubleValue() { return (double) get(); } @Override public String toString() { return Integer.toString(get()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + get(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof AtomicPositiveInteger)) { return false; } AtomicPositiveInteger other = (AtomicPositiveInteger) obj; return intValue() == other.intValue(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NamedThreadFactory.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/NamedThreadFactory.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.utils; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * InternalThreadFactory. */ public class NamedThreadFactory implements ThreadFactory { protected static final AtomicInteger POOL_SEQ = new AtomicInteger(1); protected final AtomicInteger mThreadNum = new AtomicInteger(1); protected final String mPrefix; protected final boolean mDaemon; public NamedThreadFactory() { this("pool-" + POOL_SEQ.getAndIncrement(), false); } public NamedThreadFactory(String prefix) { this(prefix, false); } public NamedThreadFactory(String prefix, boolean daemon) { mPrefix = prefix + "-thread-"; mDaemon = daemon; } @Override public Thread newThread(Runnable runnable) { String name = mPrefix + mThreadNum.getAndIncrement(); Thread ret = new Thread(runnable, name); ret.setDaemon(mDaemon); return ret; } // for test public AtomicInteger getThreadNum() { return mThreadNum; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.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.utils; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.Iterator; import java.util.List; public class LogUtil { private static final Logger Log = LoggerFactory.getLogger(LogUtil.class); public static void start() { DubboAppender.doStart(); } public static void stop() { DubboAppender.doStop(); } public static boolean checkNoError() { if (findLevel(Level.ERROR) == 0) { return true; } else { return false; } } public static int findName(String expectedLogName) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logName = logList.get(i).getLogName(); if (logName.contains(expectedLogName)) { count++; } } return count; } public static int findLevel(Level expectedLevel) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { Level logLevel = logList.get(i).getLogLevel(); if (logLevel.equals(expectedLevel)) { count++; } } return count; } public static int findLevelWithThreadName(Level expectedLevel, String threadName) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { Log log = logList.get(i); if (log.getLogLevel().equals(expectedLevel) && log.getLogThread().equals(threadName)) { count++; } } return count; } public static int findThread(String expectedThread) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logThread = logList.get(i).getLogThread(); if (logThread.contains(expectedThread)) { count++; } } return count; } public static int findMessage(String expectedMessage) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logMessage = logList.get(i).getLogMessage(); if (logMessage.contains(expectedMessage)) { count++; } } return count; } public static int findMessage(Level expectedLevel, String expectedMessage) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { Level logLevel = logList.get(i).getLogLevel(); if (logLevel.equals(expectedLevel)) { String logMessage = logList.get(i).getLogMessage(); if (logMessage.contains(expectedMessage)) { count++; } } } return count; } public static <T> void printList(List<T> list) { Log.info("PrintList:"); Iterator<T> it = list.iterator(); while (it.hasNext()) { Log.info(it.next().toString()); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtils.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.utils; import java.util.Objects; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; /** * ConcurrentHashMap util */ public class ConcurrentHashMapUtils { /** * A temporary workaround for Java 8 ConcurrentHashMap#computeIfAbsent specific performance issue: JDK-8161372.</br> * @see <a href="https://bugs.openjdk.java.net/browse/JDK-8161372">https://bugs.openjdk.java.net/browse/JDK-8161372</a> * */ public static <K, V> V computeIfAbsent(ConcurrentMap<K, V> map, K key, Function<? super K, ? extends V> func) { Objects.requireNonNull(func); if (JRE.JAVA_8.isCurrentVersion()) { V v = map.get(key); if (null == v) { // issue#11986 lock bug // v = map.computeIfAbsent(key, func); // this bug fix methods maybe cause `func.apply` multiple calls. v = func.apply(key); if (null == v) { return null; } final V res = map.putIfAbsent(key, v); if (null != res) { // if pre value present, means other thread put value already, and putIfAbsent not effect // return exist value return res; } // if pre value is null, means putIfAbsent effected, return current value } return v; } else { return map.computeIfAbsent(key, func); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Assert.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/Assert.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.utils; import java.util.function.Supplier; public abstract class Assert { protected Assert() {} public static void notNull(Object obj, String message) { if (obj == null) { throw new IllegalArgumentException(message); } } public static void notNull(Object obj, String format, Object... args) { if (obj == null) { throw new IllegalArgumentException(String.format(format, args)); } } public static void notEmptyString(String str, String message) { if (StringUtils.isEmpty(str)) { throw new IllegalArgumentException(message); } } public static void notNull(Object obj, RuntimeException exception) { if (obj == null) { throw exception; } } public static void assertTrue(boolean condition, String message) { if (!condition) { throw new IllegalArgumentException(message); } } public static void assertTrue(boolean expression, Supplier<String> messageSupplier) { if (!expression) { throw new IllegalStateException(nullSafeGet(messageSupplier)); } } private static String nullSafeGet(Supplier<String> messageSupplier) { return (messageSupplier != null ? messageSupplier.get() : null); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeCheckStatus.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeCheckStatus.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.utils; public enum SerializeCheckStatus { /** * Disable serialize check for all classes */ DISABLE(0), /** * Only deny danger classes, warn if other classes are not in allow list */ WARN(1), /** * Only allow classes in allow list, deny if other classes are not in allow list */ STRICT(2); private final int level; SerializeCheckStatus(int level) { this.level = level; } public int level() { return level; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.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.utils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import java.io.IOException; import java.lang.ref.SoftReference; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EXCEPTION; public class ClassLoaderResourceLoader { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ClassLoaderResourceLoader.class); private static SoftReference<Map<ClassLoader, Map<String, Set<URL>>>> classLoaderResourcesCache = null; static { // register resources destroy listener GlobalResourcesRepository.registerGlobalDisposable(ClassLoaderResourceLoader::destroy); } public static Map<ClassLoader, Set<URL>> loadResources(String fileName, Collection<ClassLoader> classLoaders) throws InterruptedException { Map<ClassLoader, Set<URL>> resources = new ConcurrentHashMap<>(); CountDownLatch countDownLatch = new CountDownLatch(classLoaders.size()); for (ClassLoader classLoader : classLoaders) { GlobalResourcesRepository.getGlobalExecutorService().submit(() -> { resources.put(classLoader, loadResources(fileName, classLoader)); countDownLatch.countDown(); }); } countDownLatch.await(); return Collections.unmodifiableMap(new LinkedHashMap<>(resources)); } public static Set<URL> loadResources(String fileName, ClassLoader currentClassLoader) { Map<ClassLoader, Map<String, Set<URL>>> classLoaderCache; if (classLoaderResourcesCache == null || (classLoaderCache = classLoaderResourcesCache.get()) == null) { synchronized (ClassLoaderResourceLoader.class) { if (classLoaderResourcesCache == null || (classLoaderCache = classLoaderResourcesCache.get()) == null) { classLoaderCache = new ConcurrentHashMap<>(); classLoaderResourcesCache = new SoftReference<>(classLoaderCache); } } } if (!classLoaderCache.containsKey(currentClassLoader)) { classLoaderCache.putIfAbsent(currentClassLoader, new ConcurrentHashMap<>()); } Map<String, Set<URL>> urlCache = classLoaderCache.get(currentClassLoader); if (!urlCache.containsKey(fileName)) { Set<URL> set = new LinkedHashSet<>(); Enumeration<URL> urls; try { urls = currentClassLoader.getResources(fileName); if (urls != null) { while (urls.hasMoreElements()) { URL url = urls.nextElement(); set.add(url); } } } catch (IOException e) { logger.error( COMMON_IO_EXCEPTION, "", "", "Exception occurred when reading SPI definitions. SPI path: " + fileName + " ClassLoader name: " + currentClassLoader, e); } urlCache.put(fileName, set); } return urlCache.get(fileName); } public static void destroy() { synchronized (ClassLoaderResourceLoader.class) { classLoaderResourcesCache = null; } } // for test protected static SoftReference<Map<ClassLoader, Map<String, Set<URL>>>> getClassLoaderResourcesCache() { return classLoaderResourcesCache; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimeUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimeUtils.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.utils; import java.util.concurrent.TimeUnit; /** * Provide currentTimeMillis acquisition for high-frequency access scenarios. */ public final class TimeUtils { private static volatile long currentTimeMillis; private static volatile boolean isTickerAlive = false; private static volatile boolean isFallback = false; private TimeUtils() {} public static long currentTimeMillis() { // When an exception occurs in the Ticker mechanism, fall back. if (isFallback) { return System.currentTimeMillis(); } if (!isTickerAlive) { try { startTicker(); } catch (Exception e) { isFallback = true; } } return currentTimeMillis; } private static synchronized void startTicker() { if (!isTickerAlive) { currentTimeMillis = System.currentTimeMillis(); Thread ticker = new Thread(() -> { while (isTickerAlive) { currentTimeMillis = System.currentTimeMillis(); try { TimeUnit.MILLISECONDS.sleep(1); } catch (InterruptedException e) { isTickerAlive = false; Thread.currentThread().interrupt(); } catch (Exception ignored) { // } } }); ticker.setDaemon(true); ticker.setName("time-millis-ticker-thread"); ticker.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { isFallback = true; ticker.interrupt(); })); isTickerAlive = true; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.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.utils; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; public class CompatibleTypeUtils { private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * the text to parse such as "2007-12-03T10:15:30" */ private static final int ISO_LOCAL_DATE_TIME_MIN_LEN = 19; private CompatibleTypeUtils() {} /** * Compatible type convert. Null value is allowed to pass in. If no conversion is needed, then the original value * will be returned. * <p> * Supported compatible type conversions include (primary types and corresponding wrappers are not listed): * <ul> * <li> String -> char, enum, Date * <li> byte, short, int, long -> byte, short, int, long * <li> float, double -> float, double * </ul> */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format( "CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } if (type == BigInteger.class) { return new BigInteger(string); } if (type == BigDecimal.class) { return new BigDecimal(string); } if (type == Short.class || type == short.class) { return new Short(string); } if (type == Integer.class || type == int.class) { return new Integer(string); } if (type == Long.class || type == long.class) { return new Long(string); } if (type == Double.class || type == double.class) { return new Double(string); } if (type == Float.class || type == float.class) { return new Float(string); } if (type == Byte.class || type == byte.class) { return new Byte(string); } if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } if (type == Date.class || type == java.sql.Date.class || type == java.sql.Timestamp.class || type == java.sql.Time.class) { try { Date date = new SimpleDateFormat(DATE_FORMAT).parse(string); if (type == java.sql.Date.class) { return new java.sql.Date(date.getTime()); } if (type == java.sql.Timestamp.class) { return new java.sql.Timestamp(date.getTime()); } if (type == java.sql.Time.class) { return new java.sql.Time(date.getTime()); } return date; } catch (ParseException e) { throw new IllegalStateException( "Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } if (type == java.time.LocalDateTime.class) { if (StringUtils.isEmpty(string)) { return null; } return LocalDateTime.parse(string); } if (type == java.time.LocalDate.class) { if (StringUtils.isEmpty(string)) { return null; } return LocalDate.parse(string); } if (type == java.time.LocalTime.class) { if (StringUtils.isEmpty(string)) { return null; } if (string.length() >= ISO_LOCAL_DATE_TIME_MIN_LEN) { return LocalDateTime.parse(string).toLocalTime(); } else { return LocalTime.parse(string); } } if (type == Class.class) { try { return ReflectUtils.name2class(string); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } if (char[].class.equals(type)) { // Process string to char array for generic invoke // See // - https://github.com/apache/dubbo/issues/2003 int len = string.length(); char[] chars = new char[len]; string.getChars(0, len, chars, 0); return chars; } } if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } if (type == short.class || type == Short.class) { return number.shortValue(); } if (type == int.class || type == Integer.class) { return number.intValue(); } if (type == long.class || type == Long.class) { return number.longValue(); } if (type == float.class || type == Float.class) { return number.floatValue(); } if (type == double.class || type == Double.class) { return number.doubleValue(); } if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } if (type == BigDecimal.class) { return new BigDecimal(number.toString()); } if (type == Date.class) { return new Date(number.longValue()); } if (type == boolean.class || type == Boolean.class) { return 0 != number.intValue(); } } if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } if (!type.isInterface()) { try { Collection result = (Collection) type.getDeclaredConstructor().newInstance(); result.addAll(collection); return result; } catch (Throwable ignored) { } } if (type == List.class) { return new ArrayList<Object>(collection); } if (type == Set.class) { return new HashSet<Object>(collection); } } if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { int length = Array.getLength(value); Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.getDeclaredConstructor().newInstance(); } catch (Exception e) { collection = new ArrayList<Object>(length); } } else if (type == Set.class) { collection = new HashSet<Object>(Math.max((int) (length / .75f) + 1, 16)); } else { collection = new ArrayList<Object>(length); } for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CharSequenceComparator.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/CharSequenceComparator.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.utils; import java.util.Comparator; /** * The {@link Comparator} for {@link CharSequence} * * @since 2.7.6 */ public class CharSequenceComparator implements Comparator<CharSequence> { public static final CharSequenceComparator INSTANCE = new CharSequenceComparator(); private CharSequenceComparator() {} @Override public int compare(CharSequence c1, CharSequence c2) { return c1.toString().compareTo(c2.toString()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.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.utils; import org.apache.dubbo.rpc.model.MethodDescriptor; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.utils.ClassUtils.getAllInheritedTypes; import static org.apache.dubbo.common.utils.MemberUtils.isPrivate; import static org.apache.dubbo.common.utils.MemberUtils.isStatic; import static org.apache.dubbo.common.utils.ReflectUtils.EMPTY_CLASS_ARRAY; import static org.apache.dubbo.common.utils.ReflectUtils.resolveTypes; import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty; /** * Miscellaneous method utility methods. * Mainly for internal use within the framework. * * @since 2.7.2 */ public interface MethodUtils { /** * Return {@code true} if the provided method is a set method. * Otherwise, return {@code false}. * * @param method the method to check * @return whether the given method is setter method */ static boolean isSetter(Method method) { return method.getName().startsWith("set") && !"set".equals(method.getName()) && Modifier.isPublic(method.getModifiers()) && method.getParameterCount() == 1 && ClassUtils.isPrimitive(method.getParameterTypes()[0]); } /** * Return {@code true} if the provided method is a get method. * Otherwise, return {@code false}. * * @param method the method to check * @return whether the given method is getter method */ static boolean isGetter(Method method) { String name = method.getName(); return (name.startsWith("get") || name.startsWith("is")) && !"get".equals(name) && !"is".equals(name) && !"getClass".equals(name) && !"getObject".equals(name) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && ClassUtils.isPrimitive(method.getReturnType()); } /** * Return {@code true} If this method is a meta method. * Otherwise, return {@code false}. * * @param method the method to check * @return whether the given method is meta method */ static boolean isMetaMethod(Method method) { String name = method.getName(); if (!(name.startsWith("get") || name.startsWith("is"))) { return false; } if ("get".equals(name)) { return false; } if ("getClass".equals(name)) { return false; } if (!Modifier.isPublic(method.getModifiers())) { return false; } if (method.getParameterTypes().length != 0) { return false; } if (!ClassUtils.isPrimitive(method.getReturnType())) { return false; } return true; } /** * Check if the method is a deprecated method. The standard is whether the {@link java.lang.Deprecated} annotation is declared on the class. * Return {@code true} if this annotation is present. * Otherwise, return {@code false}. * * @param method the method to check * @return whether the given method is deprecated method */ static boolean isDeprecated(Method method) { return method.getAnnotation(Deprecated.class) != null; } /** * Create an instance of {@link Predicate} for {@link Method} to exclude the specified declared class * * @param declaredClass the declared class to exclude * @return non-null * @since 2.7.6 */ static Predicate<Method> excludedDeclaredClass(Class<?> declaredClass) { return method -> !Objects.equals(declaredClass, method.getDeclaringClass()); } /** * Get all {@link Method methods} of the declared class * * @param declaringClass the declared class * @param includeInheritedTypes include the inherited types, e,g. super classes or interfaces * @param publicOnly only public method * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @since 2.7.6 */ static List<Method> getMethods( Class<?> declaringClass, boolean includeInheritedTypes, boolean publicOnly, Predicate<Method>... methodsToFilter) { if (declaringClass == null || declaringClass.isPrimitive()) { return emptyList(); } // All declared classes List<Class<?>> declaredClasses = new LinkedList<>(); // Add the top declaring class declaredClasses.add(declaringClass); // If the super classes are resolved, all them into declaredClasses if (includeInheritedTypes) { declaredClasses.addAll(getAllInheritedTypes(declaringClass)); } // All methods List<Method> allMethods = new LinkedList<>(); for (Class<?> classToSearch : declaredClasses) { Method[] methods = publicOnly ? classToSearch.getMethods() : classToSearch.getDeclaredMethods(); // Add the declared methods or public methods for (Method method : methods) { allMethods.add(method); } } return unmodifiableList(filterAll(allMethods, methodsToFilter)); } /** * Get all declared {@link Method methods} of the declared class, excluding the inherited methods * * @param declaringClass the declared class * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @see #getMethods(Class, boolean, boolean, Predicate[]) * @since 2.7.6 */ static List<Method> getDeclaredMethods(Class<?> declaringClass, Predicate<Method>... methodsToFilter) { return getMethods(declaringClass, false, false, methodsToFilter); } /** * Get all public {@link Method methods} of the declared class, including the inherited methods. * * @param declaringClass the declared class * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @see #getMethods(Class, boolean, boolean, Predicate[]) * @since 2.7.6 */ static List<Method> getMethods(Class<?> declaringClass, Predicate<Method>... methodsToFilter) { return getMethods(declaringClass, false, true, methodsToFilter); } /** * Get all declared {@link Method methods} of the declared class, including the inherited methods. * * @param declaringClass the declared class * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @see #getMethods(Class, boolean, boolean, Predicate[]) * @since 2.7.6 */ static List<Method> getAllDeclaredMethods(Class<?> declaringClass, Predicate<Method>... methodsToFilter) { return getMethods(declaringClass, true, false, methodsToFilter); } /** * Get all public {@link Method methods} of the declared class, including the inherited methods. * * @param declaringClass the declared class * @param methodsToFilter (optional) the methods to be filtered * @return non-null read-only {@link List} * @see #getMethods(Class, boolean, boolean, Predicate[]) * @since 2.7.6 */ static List<Method> getAllMethods(Class<?> declaringClass, Predicate<Method>... methodsToFilter) { return getMethods(declaringClass, true, true, methodsToFilter); } // static List<Method> getOverriderMethods(Class<?> implementationClass, Class<?>... superTypes) { // // } /** * Find the {@link Method} by the the specified type and method name without the parameter types * * @param type the target type * @param methodName the specified method name * @return if not found, return <code>null</code> * @since 2.7.6 */ static Method findMethod(Class type, String methodName) { return findMethod(type, methodName, EMPTY_CLASS_ARRAY); } /** * Find the {@link Method} by the the specified type, method name and parameter types * * @param type the target type * @param methodName the method name * @param parameterTypes the parameter types * @return if not found, return <code>null</code> * @since 2.7.6 */ static Method findMethod(Class type, String methodName, Class<?>... parameterTypes) { Method method = null; try { if (type != null && isNotEmpty(methodName)) { method = type.getDeclaredMethod(methodName, parameterTypes); } } catch (NoSuchMethodException e) { } return method; } /** * Invoke the target object and method * * @param object the target object * @param methodName the method name * @param methodParameters the method parameters * @param <T> the return type * @return the target method's execution result * @since 2.7.6 */ static <T> T invokeMethod(Object object, String methodName, Object... methodParameters) { Class type = object.getClass(); Class[] parameterTypes = resolveTypes(methodParameters); Method method = findMethod(type, methodName, parameterTypes); T value = null; if (method == null) { throw new IllegalStateException( String.format("cannot find method %s,class: %s", methodName, type.getName())); } try { final boolean isAccessible = method.isAccessible(); if (!isAccessible) { method.setAccessible(true); } value = (T) method.invoke(object, methodParameters); method.setAccessible(isAccessible); } catch (Exception e) { throw new IllegalArgumentException(e); } return value; } /** * Tests whether one method, as a member of a given type, * overrides another method. * * @param overrider the first method, possible overrider * @param overridden the second method, possibly being overridden * @return {@code true} if and only if the first method overrides * the second * @jls 8.4.8 Inheritance, Overriding, and Hiding * @jls 9.4.1 Inheritance and Overriding * @see Elements#overrides(ExecutableElement, ExecutableElement, TypeElement) */ static boolean overrides(Method overrider, Method overridden) { if (overrider == null || overridden == null) { return false; } // equality comparison: If two methods are same if (Objects.equals(overrider, overridden)) { return false; } // Modifiers comparison: Any method must be non-static method if (isStatic(overrider) || isStatic(overridden)) { // return false; } // Modifiers comparison: the accessibility of any method must not be private if (isPrivate(overrider) || isPrivate(overridden)) { return false; } // Inheritance comparison: The declaring class of overrider must be inherit from the overridden's if (!overridden.getDeclaringClass().isAssignableFrom(overrider.getDeclaringClass())) { return false; } // Method comparison: must not be "default" method if (overrider.isDefault()) { return false; } // Method comparison: The method name must be equal if (!Objects.equals(overrider.getName(), overridden.getName())) { return false; } // Method comparison: The count of method parameters must be equal if (!Objects.equals(overrider.getParameterCount(), overridden.getParameterCount())) { return false; } // Method comparison: Any parameter type of overrider must equal the overridden's for (int i = 0; i < overrider.getParameterCount(); i++) { if (!Objects.equals(overridden.getParameterTypes()[i], overrider.getParameterTypes()[i])) { return false; } } // Method comparison: The return type of overrider must be inherit from the overridden's if (!overridden.getReturnType().isAssignableFrom(overrider.getReturnType())) { return false; } // Throwable comparison: "throws" Throwable list will be ignored, trust the compiler verify return true; } /** * Find the nearest overridden {@link Method method} from the inherited class * * @param overrider the overrider {@link Method method} * @return if found, the overrider <code>method</code>, or <code>null</code> */ static Method findNearestOverriddenMethod(Method overrider) { Class<?> declaringClass = overrider.getDeclaringClass(); Method overriddenMethod = null; for (Class<?> inheritedType : getAllInheritedTypes(declaringClass)) { overriddenMethod = findOverriddenMethod(overrider, inheritedType); if (overriddenMethod != null) { break; } } return overriddenMethod; } /** * Find the overridden {@link Method method} from the declaring class * * @param overrider the overrider {@link Method method} * @param declaringClass the class that is declaring the overridden {@link Method method} * @return if found, the overrider <code>method</code>, or <code>null</code> */ static Method findOverriddenMethod(Method overrider, Class<?> declaringClass) { List<Method> matchedMethods = getAllMethods(declaringClass, method -> overrides(overrider, method)); return matchedMethods.isEmpty() ? null : matchedMethods.get(0); } /** * Extract fieldName from set/get/is method. if it's not a set/get/is method, return empty string. * If method equals get/is/getClass/getObject, also return empty string. * * @param method method * @return fieldName */ static String extractFieldName(Method method) { List<String> emptyFieldMethod = Arrays.asList("is", "get", "getObject", "getClass"); String methodName = method.getName(); String fieldName = ""; if (emptyFieldMethod.contains(methodName)) { return fieldName; } else if (methodName.startsWith("get")) { fieldName = methodName.substring("get".length()); } else if (methodName.startsWith("set")) { fieldName = methodName.substring("set".length()); } else if (methodName.startsWith("is")) { fieldName = methodName.substring("is".length()); } else { return fieldName; } if (StringUtils.isNotEmpty(fieldName)) { fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); } return fieldName; } /** * Invoke and return double value. * * @param method method * @param targetObj the object the method is invoked from * @return double value */ static double invokeAndReturnDouble(Method method, Object targetObj) { try { return method != null ? (double) method.invoke(targetObj) : Double.NaN; } catch (Exception e) { return Double.NaN; } } /** * Invoke and return long value. * * @param method method * @param targetObj the object the method is invoked from * @return long value */ static long invokeAndReturnLong(Method method, Object targetObj) { try { return method != null ? (long) method.invoke(targetObj) : -1; } catch (Exception e) { return -1; } } static String toShortString(Method method) { StringBuilder sb = new StringBuilder(64); sb.append(method.getDeclaringClass().getName()); sb.append('.').append(method.getName()).append('('); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0, len = parameterTypes.length; i < len; i++) { if (i > 0) { sb.append(", "); } sb.append(parameterTypes[i].getSimpleName()); } sb.append(')'); return sb.toString(); } static String toShortString(MethodDescriptor md) { Method method = md.getMethod(); if (method == null) { StringBuilder sb = new StringBuilder(64); sb.append(md.getMethodName()).append('('); Class<?>[] parameterTypes = md.getParameterClasses(); for (int i = 0, len = parameterTypes.length; i < len; i++) { if (i > 0) { sb.append(", "); } sb.append(parameterTypes[i].getSimpleName()); } sb.append(')'); return sb.toString(); } return toShortString(method); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ParameterNameReader.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ParameterNameReader.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.utils; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.lang.reflect.Constructor; import java.lang.reflect.Method; @SPI(scope = ExtensionScope.FRAMEWORK) public interface ParameterNameReader { String[] readParameterNames(Method method); String[] readParameterNames(Constructor<?> ctor); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.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.utils; import java.util.ArrayList; import java.util.EmptyStackException; import java.util.List; /** * Stack. */ public class Stack<E> { private int mSize = 0; private final List<E> mElements = new ArrayList<>(); public Stack() {} /** * push. * * @param ele */ public void push(E ele) { if (mElements.size() > mSize) { mElements.set(mSize, ele); } else { mElements.add(ele); } mSize++; } /** * pop. * * @return the last element. */ public E pop() { if (mSize == 0) { throw new EmptyStackException(); } return mElements.set(--mSize, null); } /** * peek. * * @return the last element. */ public E peek() { if (mSize == 0) { throw new EmptyStackException(); } return mElements.get(mSize - 1); } /** * get. * * @param index index. * @return element. */ public E get(int index) { if (index >= mSize || index + mSize < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); } return index < 0 ? mElements.get(index + mSize) : mElements.get(index); } /** * set. * * @param index index. * @param value element. * @return old element. */ public E set(int index, E value) { if (index >= mSize || index + mSize < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); } return mElements.set(index < 0 ? index + mSize : index, value); } /** * remove. * * @param index * @return element */ public E remove(int index) { if (index >= mSize || index + mSize < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); } E ret = mElements.remove(index < 0 ? index + mSize : index); mSize--; return ret; } /** * get stack size. * * @return size. */ public int size() { return mSize; } /** * is empty. * * @return empty or not. */ public boolean isEmpty() { return mSize == 0; } /** * clear stack. */ public void clear() { mSize = 0; mElements.clear(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CIDRUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/CIDRUtils.java
/* * The MIT License * * Copyright (c) 2013 Edin Dazdarevic (edin.dazdarevic@gmail.com) * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package org.apache.dubbo.common.utils; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * A class that enables to get an IP range from CIDR specification. It supports * both IPv4 and IPv6. * <p> * From https://github.com/edazdarevic/CIDRUtils/blob/master/CIDRUtils.java */ public class CIDRUtils { private final String cidr; private InetAddress inetAddress; private InetAddress startAddress; private InetAddress endAddress; private final int prefixLength; public CIDRUtils(String cidr) throws UnknownHostException { this.cidr = cidr; /* split CIDR to address and prefix part */ if (this.cidr.contains("/")) { int index = this.cidr.indexOf("/"); String addressPart = this.cidr.substring(0, index); String networkPart = this.cidr.substring(index + 1); inetAddress = InetAddress.getByName(addressPart); prefixLength = Integer.parseInt(networkPart); calculate(); } else { throw new IllegalArgumentException("not an valid CIDR format!"); } } private void calculate() throws UnknownHostException { ByteBuffer maskBuffer; int targetSize; if (inetAddress.getAddress().length == 4) { maskBuffer = ByteBuffer .allocate(4) .putInt(-1); targetSize = 4; } else { maskBuffer = ByteBuffer.allocate(16) .putLong(-1L) .putLong(-1L); targetSize = 16; } BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength); ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress()); BigInteger ipVal = new BigInteger(1, buffer.array()); BigInteger startIp = ipVal.and(mask); BigInteger endIp = startIp.add(mask.not()); byte[] startIpArr = toBytes(startIp.toByteArray(), targetSize); byte[] endIpArr = toBytes(endIp.toByteArray(), targetSize); this.startAddress = InetAddress.getByAddress(startIpArr); this.endAddress = InetAddress.getByAddress(endIpArr); } private byte[] toBytes(byte[] array, int targetSize) { int counter = 0; List<Byte> newArr = new ArrayList<>(); while (counter < targetSize && (array.length - 1 - counter >= 0)) { newArr.add(0, array[array.length - 1 - counter]); counter++; } int size = newArr.size(); for (int i = 0; i < (targetSize - size); i++) { newArr.add(0, (byte) 0); } byte[] ret = new byte[newArr.size()]; for (int i = 0; i < newArr.size(); i++) { ret[i] = newArr.get(i); } return ret; } public String getNetworkAddress() { return this.startAddress.getHostAddress(); } public String getBroadcastAddress() { return this.endAddress.getHostAddress(); } public boolean isInRange(String ipAddress) throws UnknownHostException { InetAddress address = InetAddress.getByName(ipAddress); BigInteger start = new BigInteger(1, this.startAddress.getAddress()); BigInteger end = new BigInteger(1, this.endAddress.getAddress()); BigInteger target = new BigInteger(1, address.getAddress()); int st = start.compareTo(target); int te = target.compareTo(end); return (st == -1 || st == 0) && (te == -1 || te == 0); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogHelper.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogHelper.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.utils; import org.apache.dubbo.common.logger.Logger; public class LogHelper { private LogHelper() {} public static void trace(Logger logger, String msg) { if (logger == null) { return; } if (logger.isTraceEnabled()) { logger.trace(msg); } } public static void trace(Logger logger, Throwable throwable) { if (logger == null) { return; } if (logger.isTraceEnabled()) { logger.trace(throwable); } } public static void trace(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isTraceEnabled()) { logger.trace(msg, e); } } public static void debug(Logger logger, String msg) { if (logger == null) { return; } if (logger.isDebugEnabled()) { logger.debug(msg); } } public static void debug(Logger logger, Throwable e) { if (logger == null) { return; } if (logger.isDebugEnabled()) { logger.debug(e); } } public static void debug(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isDebugEnabled()) { logger.debug(msg, e); } } public static void info(Logger logger, String msg) { if (logger == null) { return; } if (logger.isInfoEnabled()) { logger.info(msg); } } public static void info(Logger logger, Throwable e) { if (logger == null) { return; } if (logger.isInfoEnabled()) { logger.info(e); } } public static void info(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isInfoEnabled()) { logger.info(msg, e); } } public static void warn(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isWarnEnabled()) { logger.warn(msg, e); } } public static void warn(Logger logger, String msg) { if (logger == null) { return; } if (logger.isWarnEnabled()) { logger.warn(msg); } } public static void warn(Logger logger, Throwable e) { if (logger == null) { return; } if (logger.isWarnEnabled()) { logger.warn(e); } } public static void error(Logger logger, Throwable e) { if (logger == null) { return; } if (logger.isErrorEnabled()) { logger.error(e); } } public static void error(Logger logger, String msg) { if (logger == null) { return; } if (logger.isErrorEnabled()) { logger.error(msg); } } public static void error(Logger logger, String msg, Throwable e) { if (logger == null) { return; } if (logger.isErrorEnabled()) { logger.error(msg, e); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.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.utils; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; 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.Set; import java.util.function.Predicate; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static org.apache.dubbo.common.function.Predicates.and; import static org.apache.dubbo.common.function.Streams.filterAll; import static org.apache.dubbo.common.function.Streams.filterFirst; import static org.apache.dubbo.common.utils.ClassUtils.getAllInheritedTypes; import static org.apache.dubbo.common.utils.ClassUtils.resolveClass; import static org.apache.dubbo.common.utils.CollectionUtils.first; import static org.apache.dubbo.common.utils.MethodUtils.findMethod; import static org.apache.dubbo.common.utils.MethodUtils.invokeMethod; /** * Commons Annotation Utilities class * * @since 2.7.6 */ public interface AnnotationUtils { /** * Resolve the annotation type by the annotated element and resolved class name * * @param annotatedElement the annotated element * @param annotationClassName the class name of annotation * @param <A> the type of annotation * @return If resolved, return the type of annotation, or <code>null</code> */ @SuppressWarnings("unchecked") static <A extends Annotation> Class<A> resolveAnnotationType( AnnotatedElement annotatedElement, String annotationClassName) { ClassLoader classLoader = annotatedElement.getClass().getClassLoader(); Class<?> annotationType = resolveClass(annotationClassName, classLoader); if (annotationType == null || !Annotation.class.isAssignableFrom(annotationType)) { return null; } return (Class<A>) annotationType; } /** * Is the specified type a generic {@link Class type} * * @param annotatedElement the annotated element * @return if <code>annotatedElement</code> is the {@link Class}, return <code>true</code>, or <code>false</code> * @see ElementType#TYPE */ static boolean isType(AnnotatedElement annotatedElement) { return annotatedElement instanceof Class; } /** * Is the type of specified annotation same to the expected type? * * @param annotation the specified {@link Annotation} * @param annotationType the expected annotation type * @return if same, return <code>true</code>, or <code>false</code> */ static boolean isSameType(Annotation annotation, Class<? extends Annotation> annotationType) { if (annotation == null || annotationType == null) { return false; } return Objects.equals(annotation.annotationType(), annotationType); } /** * Build an instance of {@link Predicate} to excluded annotation type * * @param excludedAnnotationType excluded annotation type * @return non-null */ static Predicate<Annotation> excludedType(Class<? extends Annotation> excludedAnnotationType) { return annotation -> !isSameType(annotation, excludedAnnotationType); } /** * Get the attribute from the specified {@link Annotation annotation} * * @param annotation the specified {@link Annotation annotation} * @param attributeName the attribute name * @param <T> the type of attribute * @return the attribute value * @throws IllegalArgumentException If the attribute name can't be found */ static <T> T getAttribute(Annotation annotation, String attributeName) throws IllegalArgumentException { return annotation == null ? null : invokeMethod(annotation, attributeName); } /** * Get the "value" attribute from the specified {@link Annotation annotation} * * @param annotation the specified {@link Annotation annotation} * @param <T> the type of attribute * @return the value of "value" attribute * @throws IllegalArgumentException If the attribute name can't be found */ static <T> T getValue(Annotation annotation) throws IllegalArgumentException { return getAttribute(annotation, "value"); } /** * Get the attribute from the specified {@link Annotation annotation} * * @param annotation the specified {@link Annotation annotation} * @param attributeNames the multiply attribute name arrays * @param <T> the type of attribute * @return the attribute value * @throws IllegalArgumentException If the attribute name can't be found */ static <T> T getAttribute(Annotation annotation, String... attributeNames) throws IllegalArgumentException { if (attributeNames == null || attributeNames.length == 0) { return null; } for (String attributeName : attributeNames) { T attribute = getAttribute(annotation, attributeName); if (attribute == null) { continue; } // exclude string attribute default is empty if ((attribute instanceof String) && ((String) attribute).length() == 0) { continue; } return attribute; } return null; } /** * Get the {@link Annotation} from the specified {@link AnnotatedElement the annotated element} and * {@link Annotation annotation} class name * * @param annotatedElement {@link AnnotatedElement} * @param annotationClassName the class name of annotation * @param <A> The type of {@link Annotation} * @return the {@link Annotation} if found * @throws ClassCastException If the {@link Annotation annotation} type that client requires can't match actual type */ static <A extends Annotation> A getAnnotation(AnnotatedElement annotatedElement, String annotationClassName) throws ClassCastException { Class<? extends Annotation> annotationType = resolveAnnotationType(annotatedElement, annotationClassName); if (annotationType == null) { return null; } return (A) annotatedElement.getAnnotation(annotationType); } /** * Get annotations that are <em>directly present</em> on this element. * This method ignores inherited annotations. * * @param annotatedElement the annotated element * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ static List<Annotation> getDeclaredAnnotations( AnnotatedElement annotatedElement, Predicate<Annotation>... annotationsToFilter) { if (annotatedElement == null) { return emptyList(); } return unmodifiableList(filterAll(asList(annotatedElement.getDeclaredAnnotations()), annotationsToFilter)); } /** * Get all directly declared annotations of the the annotated element, not including * meta annotations. * * @param annotatedElement the annotated element * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ static List<Annotation> getAllDeclaredAnnotations( AnnotatedElement annotatedElement, Predicate<Annotation>... annotationsToFilter) { if (isType(annotatedElement)) { return getAllDeclaredAnnotations((Class) annotatedElement, annotationsToFilter); } else { return getDeclaredAnnotations(annotatedElement, annotationsToFilter); } } /** * Get all directly declared annotations of the specified type and its' all hierarchical types, not including * meta annotations. * * @param type the specified type * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ @SuppressWarnings("unchecked") static List<Annotation> getAllDeclaredAnnotations(Class<?> type, Predicate<Annotation>... annotationsToFilter) { if (type == null) { return emptyList(); } List<Annotation> allAnnotations = new LinkedList<>(); // All types Set<Class<?>> allTypes = new LinkedHashSet<>(); // Add current type allTypes.add(type); // Add all inherited types allTypes.addAll(getAllInheritedTypes(type, t -> !Object.class.equals(t))); for (Class<?> t : allTypes) { allAnnotations.addAll(getDeclaredAnnotations(t, annotationsToFilter)); } return unmodifiableList(allAnnotations); } /** * Get the meta-annotated {@link Annotation annotations} directly, excluding {@link Target}, {@link Retention} * and {@link Documented} * * @param annotationType the {@link Annotation annotation} type * @param metaAnnotationsToFilter the meta annotations to filter * @return non-null read-only {@link List} */ @SuppressWarnings("unchecked") static List<Annotation> getMetaAnnotations( Class<? extends Annotation> annotationType, Predicate<Annotation>... metaAnnotationsToFilter) { return getDeclaredAnnotations( annotationType, // Excludes the Java native annotation types or it causes the stack overflow, e.g, // @Target annotates itself excludedType(Target.class), excludedType(Retention.class), excludedType(Documented.class), // Add other predicates and(metaAnnotationsToFilter)); } /** * Get all meta annotations from the specified {@link Annotation annotation} type * * @param annotationType the {@link Annotation annotation} type * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ @SuppressWarnings("unchecked") static List<Annotation> getAllMetaAnnotations( Class<? extends Annotation> annotationType, Predicate<Annotation>... annotationsToFilter) { List<Annotation> allMetaAnnotations = new LinkedList<>(); List<Annotation> metaAnnotations = getMetaAnnotations(annotationType); allMetaAnnotations.addAll(metaAnnotations); for (Annotation metaAnnotation : metaAnnotations) { // Get the nested meta annotations recursively allMetaAnnotations.addAll(getAllMetaAnnotations(metaAnnotation.annotationType())); } return unmodifiableList(filterAll(allMetaAnnotations, annotationsToFilter)); } /** * Find the annotation that is annotated on the specified element may be a meta-annotation * * @param annotatedElement the annotated element * @param annotationClassName the class name of annotation * @param <A> the required type of annotation * @return If found, return first matched-type {@link Annotation annotation}, or <code>null</code> */ static <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement, String annotationClassName) { return findAnnotation(annotatedElement, resolveAnnotationType(annotatedElement, annotationClassName)); } /** * Find the annotation that is annotated on the specified element may be a meta-annotation * * @param annotatedElement the annotated element * @param annotationType the type of annotation * @param <A> the required type of annotation * @return If found, return first matched-type {@link Annotation annotation}, or <code>null</code> */ @SuppressWarnings("unchecked") static <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement, Class<A> annotationType) { return (A) filterFirst(getAllDeclaredAnnotations(annotatedElement), a -> isSameType(a, annotationType)); } /** * Find the meta annotations from the the {@link Annotation annotation} type by meta annotation type * * @param annotationType the {@link Annotation annotation} type * @param metaAnnotationType the meta annotation type * @param <A> the type of required annotation * @return if found, return all matched results, or get an {@link Collections#emptyList() empty list} */ @SuppressWarnings("unchecked") static <A extends Annotation> List<A> findMetaAnnotations( Class<? extends Annotation> annotationType, Class<A> metaAnnotationType) { return (List<A>) getAllMetaAnnotations(annotationType, a -> isSameType(a, metaAnnotationType)); } /** * Find the meta annotations from the the the annotated element by meta annotation type * * @param annotatedElement the annotated element * @param metaAnnotationType the meta annotation type * @param <A> the type of required annotation * @return if found, return all matched results, or get an {@link Collections#emptyList() empty list} */ @SuppressWarnings("unchecked") static <A extends Annotation> List<A> findMetaAnnotations( AnnotatedElement annotatedElement, Class<A> metaAnnotationType) { List<A> metaAnnotations = new LinkedList<>(); for (Annotation annotation : getAllDeclaredAnnotations(annotatedElement)) { metaAnnotations.addAll(findMetaAnnotations(annotation.annotationType(), metaAnnotationType)); } return unmodifiableList(metaAnnotations); } /** * Find the meta annotation from the annotated element by meta annotation type * * @param annotatedElement the annotated element * @param metaAnnotationClassName the class name of meta annotation * @param <A> the type of required annotation * @return {@link #findMetaAnnotation(Class, Class)} */ static <A extends Annotation> A findMetaAnnotation( AnnotatedElement annotatedElement, String metaAnnotationClassName) { return findMetaAnnotation(annotatedElement, resolveAnnotationType(annotatedElement, metaAnnotationClassName)); } /** * Find the meta annotation from the annotation type by meta annotation type * * @param annotationType the {@link Annotation annotation} type * @param metaAnnotationType the meta annotation type * @param <A> the type of required annotation * @return If found, return the {@link CollectionUtils#first(Collection)} matched result, return <code>null</code>. * If it requires more result, please consider to use {@link #findMetaAnnotations(Class, Class)} * @see #findMetaAnnotations(Class, Class) */ static <A extends Annotation> A findMetaAnnotation( Class<? extends Annotation> annotationType, Class<A> metaAnnotationType) { return first(findMetaAnnotations(annotationType, metaAnnotationType)); } /** * Find the meta annotation from the annotated element by meta annotation type * * @param annotatedElement the annotated element * @param metaAnnotationType the meta annotation type * @param <A> the type of required annotation * @return If found, return the {@link CollectionUtils#first(Collection)} matched result, return <code>null</code>. * If it requires more result, please consider to use {@link #findMetaAnnotations(AnnotatedElement, Class)} * @see #findMetaAnnotations(AnnotatedElement, Class) */ static <A extends Annotation> A findMetaAnnotation(AnnotatedElement annotatedElement, Class<A> metaAnnotationType) { return first(findMetaAnnotations(annotatedElement, metaAnnotationType)); } /** * Tests the annotated element is annotated the specified annotations or not * * @param type the annotated type * @param matchAll If <code>true</code>, checking all annotation types are present or not, or match any * @param annotationTypes the specified annotation types * @return If the specified annotation types are present, return <code>true</code>, or <code>false</code> */ static boolean isAnnotationPresent( Class<?> type, boolean matchAll, Class<? extends Annotation>... annotationTypes) { int size = annotationTypes == null ? 0 : annotationTypes.length; if (size < 1) { return false; } int presentCount = 0; for (int i = 0; i < size; i++) { Class<? extends Annotation> annotationType = annotationTypes[i]; if (findAnnotation(type, annotationType) != null || findMetaAnnotation(type, annotationType) != null) { presentCount++; } } return matchAll ? presentCount == size : presentCount > 0; } /** * Tests the annotated element is annotated the specified annotation or not * * @param type the annotated type * @param annotationType the class of annotation * @return If the specified annotation type is present, return <code>true</code>, or <code>false</code> */ @SuppressWarnings("unchecked") static boolean isAnnotationPresent(Class<?> type, Class<? extends Annotation> annotationType) { return isAnnotationPresent(type, true, annotationType); } /** * Tests the annotated element is present any specified annotation types * * @param annotatedElement the annotated element * @param annotationClassName the class name of annotation * @return If any specified annotation types are present, return <code>true</code> */ @SuppressWarnings("unchecked") static boolean isAnnotationPresent(AnnotatedElement annotatedElement, String annotationClassName) { ClassLoader classLoader = annotatedElement.getClass().getClassLoader(); Class<?> resolvedType = resolveClass(annotationClassName, classLoader); if (resolvedType == null || !Annotation.class.isAssignableFrom(resolvedType)) { return false; } return isAnnotationPresent(annotatedElement, (Class<? extends Annotation>) resolvedType); } /** * Tests the annotated element is present any specified annotation types * * @param annotatedElement the annotated element * @param annotationType the class of annotation * @return If any specified annotation types are present, return <code>true</code> */ static boolean isAnnotationPresent(AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType) { if (isType(annotatedElement)) { return isAnnotationPresent((Class) annotatedElement, annotationType); } else { return annotatedElement.isAnnotationPresent(annotationType) || findMetaAnnotation(annotatedElement, annotationType) != null; // to find meta-annotation } } /** * Tests the annotated element is annotated all specified annotations or not * * @param type the annotated type * @param annotationTypes the specified annotation types * @return If the specified annotation types are present, return <code>true</code>, or <code>false</code> */ static boolean isAllAnnotationPresent(Class<?> type, Class<? extends Annotation>... annotationTypes) { return isAnnotationPresent(type, true, annotationTypes); } /** * Tests the annotated element is present any specified annotation types * * @param type the annotated type * @param annotationTypes the specified annotation types * @return If any specified annotation types are present, return <code>true</code> */ static boolean isAnyAnnotationPresent(Class<?> type, Class<? extends Annotation>... annotationTypes) { return isAnnotationPresent(type, false, annotationTypes); } /** * Get the default value of attribute on the specified annotation * * @param annotation {@link Annotation} object * @param attributeName the name of attribute * @param <T> the type of value * @return <code>null</code> if not found * @since 2.7.9 */ static <T> T getDefaultValue(Annotation annotation, String attributeName) { return getDefaultValue(annotation.annotationType(), attributeName); } /** * Get the default value of attribute on the specified annotation * * @param annotationType the type of {@link Annotation} * @param attributeName the name of attribute * @param <T> the type of value * @return <code>null</code> if not found * @since 2.7.9 */ @SuppressWarnings("unchecked") static <T> T getDefaultValue(Class<? extends Annotation> annotationType, String attributeName) { Method method = findMethod(annotationType, attributeName); return (T) (method == null ? null : method.getDefaultValue()); } /** * Filter default value of Annotation type * @param annotationType annotation type from {@link Annotation#annotationType()} * @param attributes * @return */ static Map<String, Object> filterDefaultValues( Class<? extends Annotation> annotationType, Map<String, Object> attributes) { Map<String, Object> filteredAttributes = new LinkedHashMap<>(attributes.size()); attributes.forEach((key, val) -> { if (!Objects.deepEquals(val, getDefaultValue(annotationType, key))) { filteredAttributes.put(key, val); } }); // remove void class, compatible with spring 3.x Object interfaceClassValue = filteredAttributes.get("interfaceClass"); if (interfaceClassValue instanceof String && StringUtils.isEquals((String) interfaceClassValue, "void")) { filteredAttributes.remove("interfaceClass"); } return filteredAttributes; } /** * Filter default value of Annotation type * @param annotation * @param attributes * @return */ static Map<String, Object> filterDefaultValues(Annotation annotation, Map<String, Object> attributes) { return filterDefaultValues(annotation.annotationType(), attributes); } /** * Get attributes of annotation * @param annotation * @return */ static Map<String, Object> getAttributes(Annotation annotation, boolean filterDefaultValue) { Class<?> annotationType = annotation.annotationType(); Method[] methods = annotationType.getMethods(); Map<String, Object> attributes = new LinkedHashMap<>(methods.length); for (Method method : methods) { try { if (method.getDeclaringClass() == Annotation.class) { continue; } String name = method.getName(); Object value = method.invoke(annotation); if (!filterDefaultValue || !Objects.deepEquals(value, method.getDefaultValue())) { attributes.put(name, value); } } catch (Exception e) { throw new IllegalStateException("get attribute value of annotation failed: " + method, e); } } return attributes; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.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.utils; /** * Contains some methods to check array. */ public final class ArrayUtils { private ArrayUtils() {} /** * <p>Checks if the array is null or empty. <p/> * * @param array th array to check * @return {@code true} if the array is null or empty. */ public static boolean isEmpty(final Object[] array) { return array == null || array.length == 0; } /** * <p>Checks if the array is not null or empty. <p/> * * @param array th array to check * @return {@code true} if the array is not null or empty. */ public static boolean isNotEmpty(final Object[] array) { return !isEmpty(array); } public static boolean contains(final String[] array, String valueToFind) { return indexOf(array, valueToFind, 0) != -1; } public static int indexOf(String[] array, String valueToFind, int startIndex) { if (isEmpty(array) || valueToFind == null) { return -1; } else { if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; ++i) { if (valueToFind.equals(array[i])) { return i; } } return -1; } } /** * Convert from variable arguments to array * * @param values variable arguments * @param <T> The class * @return array * @since 2.7.9 */ public static <T> T[] of(T... values) { return values; } public static <T> T first(T[] data) { return isEmpty(data) ? null : data[0]; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PathUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/PathUtils.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.utils; import java.util.LinkedHashSet; import java.util.Set; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.apache.dubbo.common.utils.StringUtils.QUESTION_MASK; import static org.apache.dubbo.common.utils.StringUtils.SLASH; import static org.apache.dubbo.common.utils.StringUtils.isEmpty; import static org.apache.dubbo.common.utils.StringUtils.replace; /** * Path Utilities class * * @since 2.7.6 */ public interface PathUtils { static String buildPath(String rootPath, String... subPaths) { Set<String> paths = new LinkedHashSet<>(); paths.add(rootPath); paths.addAll(asList(subPaths)); return normalize(paths.stream().filter(StringUtils::isNotEmpty).collect(Collectors.joining(SLASH))); } /** * Normalize path: * <ol> * <li>To remove query string if presents</li> * <li>To remove duplicated slash("/") if exists</li> * </ol> * * @param path path to be normalized * @return a normalized path if required */ static String normalize(String path) { if (isEmpty(path)) { return SLASH; } String normalizedPath = path; int index = normalizedPath.indexOf(QUESTION_MASK); if (index > -1) { normalizedPath = normalizedPath.substring(0, index); } while (normalizedPath.contains("//")) { normalizedPath = replace(normalizedPath, "//", "/"); } return normalizedPath; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.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.utils; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; 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.logger.support.FailsafeLogger; import org.apache.dubbo.rpc.model.ScopeModel; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.BitSet; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import static java.util.Collections.emptyList; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_IP_TO_BIND; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; import static org.apache.dubbo.common.utils.CollectionUtils.first; /** * IP and Port Helper for RPC */ public final class NetUtils { /** * Forbids instantiation. */ private NetUtils() { throw new UnsupportedOperationException("No instance of 'NetUtils' for you! "); } private static Logger logger; static { /* DO NOT replace this logger to error type aware logger (or fail-safe logger), since its logging method calls NetUtils.getLocalHost(). According to issue #4992, getLocalHost() method will be endless recursively invoked when network disconnected. */ logger = LoggerFactory.getLogger(NetUtils.class); if (logger instanceof FailsafeLogger) { logger = ((FailsafeLogger) logger).getLogger(); } } // returned port range is [30000, 39999] private static final int RND_PORT_START = 30000; private static final int RND_PORT_RANGE = 10000; // valid port range is (0, 65535] private static final int MIN_PORT = 1; private static final int MAX_PORT = 65535; private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$"); private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$"); private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$"); private static final Map<String, String> HOST_NAME_CACHE = new LRUCache<>(1000); private static volatile InetAddress LOCAL_ADDRESS = null; private static volatile Inet6Address LOCAL_ADDRESS_V6 = null; private static final String SPLIT_IPV4_CHARACTER = "\\."; private static final String SPLIT_IPV6_CHARACTER = ":"; /** * store the used port. * the set used only on the synchronized method. */ private static BitSet USED_PORT = new BitSet(65536); private static boolean reuseAddressSupported; static { try (ServerSocket serverSocket = new ServerSocket()) { serverSocket.setReuseAddress(true); reuseAddressSupported = true; } catch (Throwable ignored) { // ignore. } } public static boolean isReuseAddressSupported() { return reuseAddressSupported; } public static int getRandomPort() { return RND_PORT_START + ThreadLocalRandom.current().nextInt(RND_PORT_RANGE); } public static synchronized int getAvailablePort() { int randomPort = getRandomPort(); return getAvailablePort(randomPort); } public static synchronized int getAvailablePort(int port) { if (port < MIN_PORT) { return MIN_PORT; } for (int i = port; i < MAX_PORT; i++) { if (USED_PORT.get(i)) { continue; } try (ServerSocket serverSocket = new ServerSocket()) { if (reuseAddressSupported) { // SO_REUSEADDR should be enabled before bind. serverSocket.setReuseAddress(true); } serverSocket.bind(new InetSocketAddress(i)); USED_PORT.set(i); port = i; break; } catch (IOException e) { // continue } } return port; } /** * Check the port whether is in use in os * * @param port port to check * @return true if it's occupied */ public static boolean isPortInUsed(int port) { try (ServerSocket serverSocket = new ServerSocket()) { if (reuseAddressSupported) { // SO_REUSEADDR should be enabled before bind. serverSocket.setReuseAddress(true); } serverSocket.bind(new InetSocketAddress(port)); return false; } catch (IOException e) { // continue } return true; } /** * Tells whether the port to test is an invalid port. * * @param port port to test * @return true if invalid * @implNote Numeric comparison only. */ public static boolean isInvalidPort(int port) { return port < MIN_PORT || port > MAX_PORT; } /** * Tells whether the address to test is an invalid address. * * @param address address to test * @return true if invalid * @implNote Pattern matching only. */ public static boolean isValidAddress(String address) { return ADDRESS_PATTERN.matcher(address).matches(); } public static boolean isLocalHost(String host) { return host != null && (LOCAL_IP_PATTERN.matcher(host).matches() || host.equalsIgnoreCase(LOCALHOST_KEY)); } public static boolean isAnyHost(String host) { return ANYHOST_VALUE.equals(host); } public static boolean isInvalidLocalHost(String host) { return host == null || host.length() == 0 || host.equalsIgnoreCase(LOCALHOST_KEY) || host.equals(ANYHOST_VALUE) || host.startsWith("127."); } public static boolean isValidLocalHost(String host) { return !isInvalidLocalHost(host); } public static InetSocketAddress getLocalSocketAddress(String host, int port) { return isInvalidLocalHost(host) ? new InetSocketAddress(port) : new InetSocketAddress(host, port); } static boolean isValidV4Address(InetAddress address) { if (address == null || address.isLoopbackAddress() || address.isLinkLocalAddress()) { return false; } String name = address.getHostAddress(); return (name != null && IP_PATTERN.matcher(name).matches() && !ANYHOST_VALUE.equals(name) && !LOCALHOST_VALUE.equals(name)); } /** * Check if an ipv6 address * * @return true if it is reachable */ static boolean isPreferIPV6Address() { return Boolean.getBoolean("java.net.preferIPv6Addresses"); } /** * normalize the ipv6 Address, convert scope name to scope id. * e.g. * convert * fe80:0:0:0:894:aeec:f37d:23e1%en0 * to * fe80:0:0:0:894:aeec:f37d:23e1%5 * <p> * The %5 after ipv6 address is called scope id. * see java doc of {@link Inet6Address} for more details. * * @param address the input address * @return the normalized address, with scope id converted to int */ static InetAddress normalizeV6Address(Inet6Address address) { String addr = address.getHostAddress(); int i = addr.lastIndexOf('%'); if (i > 0) { try { return InetAddress.getByName(addr.substring(0, i) + '%' + address.getScopeId()); } catch (UnknownHostException e) { // ignore logger.debug("Unknown IPV6 address: ", e); } } return address; } private static volatile String HOST_ADDRESS; private static volatile String HOST_NAME; private static volatile String HOST_ADDRESS_V6; public static String getLocalHost() { if (HOST_ADDRESS != null) { return HOST_ADDRESS; } InetAddress address = getLocalAddress(); if (address != null) { if (address instanceof Inet6Address) { String ipv6AddressString = address.getHostAddress(); if (ipv6AddressString.contains("%")) { ipv6AddressString = ipv6AddressString.substring(0, ipv6AddressString.indexOf("%")); } HOST_ADDRESS = ipv6AddressString; return HOST_ADDRESS; } HOST_ADDRESS = address.getHostAddress(); return HOST_ADDRESS; } return LOCALHOST_VALUE; } public static String getLocalHostV6() { if (StringUtils.isNotEmpty(HOST_ADDRESS_V6)) { return HOST_ADDRESS_V6; } // avoid to search network interface card many times if ("".equals(HOST_ADDRESS_V6)) { return null; } Inet6Address address = getLocalAddressV6(); if (address != null) { String ipv6AddressString = address.getHostAddress(); if (ipv6AddressString.contains("%")) { ipv6AddressString = ipv6AddressString.substring(0, ipv6AddressString.indexOf("%")); } HOST_ADDRESS_V6 = ipv6AddressString; return HOST_ADDRESS_V6; } HOST_ADDRESS_V6 = ""; return null; } public static String filterLocalHost(String host) { if (host == null || host.length() == 0) { return host; } if (host.contains("://")) { URL u = URL.valueOf(host); if (NetUtils.isInvalidLocalHost(u.getHost())) { return u.setHost(NetUtils.getLocalHost()).toFullString(); } } else if (host.contains(":")) { int i = host.lastIndexOf(':'); if (NetUtils.isInvalidLocalHost(host.substring(0, i))) { return NetUtils.getLocalHost() + host.substring(i); } } else { if (NetUtils.isInvalidLocalHost(host)) { return NetUtils.getLocalHost(); } } return host; } public static String getIpByConfig(ScopeModel scopeModel) { String configIp = ConfigurationUtils.getProperty(scopeModel, DUBBO_IP_TO_BIND); if (configIp != null) { return configIp; } return getLocalHost(); } /** * Find first valid IP from local network card * * @return first valid local IP */ public static InetAddress getLocalAddress() { if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; } InetAddress localAddress = getLocalAddress0(); LOCAL_ADDRESS = localAddress; return localAddress; } public static Inet6Address getLocalAddressV6() { if (LOCAL_ADDRESS_V6 != null) { return LOCAL_ADDRESS_V6; } Inet6Address localAddress = getLocalAddress0V6(); LOCAL_ADDRESS_V6 = localAddress; return localAddress; } private static Optional<InetAddress> toValidAddress(InetAddress address) { if (address instanceof Inet6Address) { Inet6Address v6Address = (Inet6Address) address; if (isPreferIPV6Address()) { return Optional.ofNullable(normalizeV6Address(v6Address)); } } if (isValidV4Address(address)) { return Optional.of(address); } return Optional.empty(); } private static InetAddress getLocalAddress0() { InetAddress localAddress = null; // @since 2.7.6, choose the {@link NetworkInterface} first try { NetworkInterface networkInterface = findNetworkInterface(); Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { Optional<InetAddress> addressOp = toValidAddress(addresses.nextElement()); if (addressOp.isPresent()) { try { if (addressOp.get().isReachable(100)) { return addressOp.get(); } } catch (IOException e) { // ignore } } } } catch (Throwable e) { logger.warn(e); } try { localAddress = InetAddress.getLocalHost(); Optional<InetAddress> addressOp = toValidAddress(localAddress); if (addressOp.isPresent()) { return addressOp.get(); } } catch (Throwable e) { logger.warn(e); } localAddress = getLocalAddressV6(); return localAddress; } private static Inet6Address getLocalAddress0V6() { // @since 2.7.6, choose the {@link NetworkInterface} first try { NetworkInterface networkInterface = findNetworkInterface(); Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet6Address) { if (!address.isLoopbackAddress() // filter ::1 && !address.isAnyLocalAddress() // filter ::/128 && !address.isLinkLocalAddress() // filter fe80::/10 && !address.isSiteLocalAddress() // filter fec0::/10 && !isUniqueLocalAddress(address) // filter fd00::/8 && address.getHostAddress().contains(":")) { // filter IPv6 return (Inet6Address) address; } } } } catch (Throwable e) { logger.warn(e); } return null; } /** * If the address is Unique Local Address. * * @param address {@link InetAddress} * @return {@code true} if the address is Unique Local Address,otherwise {@code false} */ private static boolean isUniqueLocalAddress(InetAddress address) { byte[] ip = address.getAddress(); return (ip[0] & 0xff) == 0xfd; } /** * Returns {@code true} if the specified {@link NetworkInterface} should be ignored with the given conditions. * * @param networkInterface the {@link NetworkInterface} to check * @return {@code true} if the specified {@link NetworkInterface} should be ignored, otherwise {@code false} * @throws SocketException SocketException if an I/O error occurs. */ private static boolean ignoreNetworkInterface(NetworkInterface networkInterface) throws SocketException { if (networkInterface == null || networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) { return true; } if (Boolean.parseBoolean(SystemPropertyConfigUtils.getSystemProperty( CommonConstants.DubboProperty.DUBBO_NETWORK_INTERFACE_POINT_TO_POINT_IGNORED, "false")) && networkInterface.isPointToPoint()) { return true; } String ignoredInterfaces = SystemPropertyConfigUtils.getSystemProperty( CommonConstants.DubboProperty.DUBBO_NETWORK_IGNORED_INTERFACE); String networkInterfaceDisplayName; if (StringUtils.isNotEmpty(ignoredInterfaces) && StringUtils.isNotEmpty(networkInterfaceDisplayName = networkInterface.getDisplayName())) { for (String ignoredInterface : ignoredInterfaces.split(",")) { String trimIgnoredInterface = ignoredInterface.trim(); boolean matched = false; try { matched = networkInterfaceDisplayName.matches(trimIgnoredInterface); } catch (PatternSyntaxException e) { // if trimIgnoredInterface is an invalid regular expression, a PatternSyntaxException will be thrown // out logger.warn( "exception occurred: " + networkInterfaceDisplayName + " matches " + trimIgnoredInterface, e); } finally { if (matched) { return true; } if (networkInterfaceDisplayName.equals(trimIgnoredInterface)) { return true; } } } } return false; } /** * Get the valid {@link NetworkInterface network interfaces} * * @return the valid {@link NetworkInterface}s * @throws SocketException SocketException if an I/O error occurs. * @since 2.7.6 */ private static List<NetworkInterface> getValidNetworkInterfaces() throws SocketException { List<NetworkInterface> validNetworkInterfaces = new LinkedList<>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (ignoreNetworkInterface(networkInterface)) { // ignore continue; } validNetworkInterfaces.add(networkInterface); } return validNetworkInterfaces; } /** * Is preferred {@link NetworkInterface} or not * * @param networkInterface {@link NetworkInterface} * @return if the name of the specified {@link NetworkInterface} matches * the property value from {@link CommonConstants.DubboProperty#DUBBO_PREFERRED_NETWORK_INTERFACE}, return <code>true</code>, * or <code>false</code> */ public static boolean isPreferredNetworkInterface(NetworkInterface networkInterface) { String preferredNetworkInterface = SystemPropertyConfigUtils.getSystemProperty( CommonConstants.DubboProperty.DUBBO_PREFERRED_NETWORK_INTERFACE); return Objects.equals(networkInterface.getDisplayName(), preferredNetworkInterface); } /** * Get the suitable {@link NetworkInterface} * * @return If no {@link NetworkInterface} is available , return <code>null</code> * @since 2.7.6 */ public static NetworkInterface findNetworkInterface() { List<NetworkInterface> validNetworkInterfaces = emptyList(); try { validNetworkInterfaces = getValidNetworkInterfaces(); } catch (Throwable e) { logger.warn(e); } NetworkInterface result = null; // Try to find the preferred one for (NetworkInterface networkInterface : validNetworkInterfaces) { if (isPreferredNetworkInterface(networkInterface)) { result = networkInterface; break; } } if (result == null) { // If not found, try to get the first one for (NetworkInterface networkInterface : validNetworkInterfaces) { Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { Optional<InetAddress> addressOp = toValidAddress(addresses.nextElement()); if (addressOp.isPresent()) { try { if (addressOp.get().isReachable(100)) { if (addressOp.get().isSiteLocalAddress()) { return networkInterface; } else { result = networkInterface; } } } catch (IOException e) { // ignore } } } } } if (result == null) { result = first(validNetworkInterfaces); } return result; } public static String getHostName(String address) { try { int i = address.indexOf(':'); if (i > -1) { address = address.substring(0, i); } String hostname = HOST_NAME_CACHE.get(address); if (hostname != null && hostname.length() > 0) { return hostname; } InetAddress inetAddress = InetAddress.getByName(address); if (inetAddress != null) { hostname = inetAddress.getHostName(); HOST_NAME_CACHE.put(address, hostname); return hostname; } } catch (Throwable e) { // ignore } return address; } public static String getLocalHostName() { if (HOST_NAME != null) { return HOST_NAME; } try { HOST_NAME = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { HOST_NAME = Optional.ofNullable(getLocalAddress()) .map(k -> k.getHostName()) .orElse(null); } return HOST_NAME; } /** * @param hostName * @return ip address or hostName if UnknownHostException */ public static String getIpByHost(String hostName) { try { return InetAddress.getByName(hostName).getHostAddress(); } catch (UnknownHostException e) { return hostName; } } public static String toAddressString(InetSocketAddress address) { return address.getAddress().getHostAddress() + ":" + address.getPort(); } public static InetSocketAddress toAddress(String address) { int i = address.indexOf(':'); String host; int port; if (i > -1) { host = address.substring(0, i); port = Integer.parseInt(address.substring(i + 1)); } else { host = address; port = 0; } return new InetSocketAddress(host, port); } public static String toURL(String protocol, String host, int port, String path) { StringBuilder sb = new StringBuilder(); sb.append(protocol).append("://"); sb.append(host).append(':').append(port); if (path.charAt(0) != '/') { sb.append('/'); } sb.append(path); return sb.toString(); } @SuppressWarnings("deprecation") public static void joinMulticastGroup(MulticastSocket multicastSocket, InetAddress multicastAddress) throws IOException { setInterface(multicastSocket, multicastAddress instanceof Inet6Address); // For the deprecation notice: the equivalent only appears in JDK 9+. multicastSocket.setLoopbackMode(false); multicastSocket.joinGroup(multicastAddress); } @SuppressWarnings("deprecation") public static void setInterface(MulticastSocket multicastSocket, boolean preferIpv6) throws IOException { boolean interfaceSet = false; for (NetworkInterface networkInterface : getValidNetworkInterfaces()) { Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (preferIpv6 && address instanceof Inet6Address) { try { if (address.isReachable(100)) { multicastSocket.setInterface(address); interfaceSet = true; break; } } catch (IOException e) { // ignore } } else if (!preferIpv6 && address instanceof Inet4Address) { try { if (address.isReachable(100)) { multicastSocket.setInterface(address); interfaceSet = true; break; } } catch (IOException e) { // ignore } } } if (interfaceSet) { break; } } } /** * Check if address matches with specified pattern, currently only supports ipv4, use {@link this#matchIpExpression(String, String, int)} for ipv6 addresses. * * @param pattern cird pattern * @param address 'ip:port' * @return true if address matches with the pattern */ public static boolean matchIpExpression(String pattern, String address) throws UnknownHostException { if (address == null) { return false; } String host = address; int port = 0; // only works for ipv4 address with 'ip:port' format if (address.endsWith(":")) { String[] hostPort = address.split(":"); host = hostPort[0]; port = StringUtils.parseInteger(hostPort[1]); } // if the pattern is subnet format, it will not be allowed to config port param in pattern. if (pattern.contains("/")) { CIDRUtils utils = new CIDRUtils(pattern); return utils.isInRange(host); } return matchIpRange(pattern, host, port); } public static boolean matchIpExpression(String pattern, String host, int port) throws UnknownHostException { // if the pattern is subnet format, it will not be allowed to config port param in pattern. if (pattern.contains("/")) { CIDRUtils utils = new CIDRUtils(pattern); return utils.isInRange(host); } return matchIpRange(pattern, host, port); } /** * @param pattern * @param host * @param port * @return * @throws UnknownHostException */ public static boolean matchIpRange(String pattern, String host, int port) throws UnknownHostException { if (pattern == null || host == null) { throw new IllegalArgumentException( "Illegal Argument pattern or hostName. Pattern:" + pattern + ", Host:" + host); } pattern = pattern.trim(); if ("*.*.*.*".equals(pattern) || "*".equals(pattern)) { return true; } InetAddress inetAddress = InetAddress.getByName(host); boolean isIpv4 = isValidV4Address(inetAddress); String[] hostAndPort = getPatternHostAndPort(pattern, isIpv4); if (hostAndPort[1] != null && !hostAndPort[1].equals(String.valueOf(port))) { return false; } pattern = hostAndPort[0]; String splitCharacter = SPLIT_IPV4_CHARACTER; if (!isIpv4) { splitCharacter = SPLIT_IPV6_CHARACTER; } String[] mask = pattern.split(splitCharacter); // check format of pattern checkHostPattern(pattern, mask, isIpv4); host = inetAddress.getHostAddress(); if (pattern.equals(host)) { return true; } // short name condition if (!ipPatternContainExpression(pattern)) { InetAddress patternAddress = InetAddress.getByName(pattern); return patternAddress.getHostAddress().equals(host); } String[] ipAddress = host.split(splitCharacter); for (int i = 0; i < mask.length; i++) { if ("*".equals(mask[i]) || mask[i].equals(ipAddress[i])) { continue; } else if (mask[i].contains("-")) { String[] rangeNumStrs = StringUtils.split(mask[i], '-'); if (rangeNumStrs.length != 2) { throw new IllegalArgumentException("There is wrong format of ip Address: " + mask[i]); } Integer min = getNumOfIpSegment(rangeNumStrs[0], isIpv4); Integer max = getNumOfIpSegment(rangeNumStrs[1], isIpv4); Integer ip = getNumOfIpSegment(ipAddress[i], isIpv4); if (ip < min || ip > max) { return false; } } else if ("0".equals(ipAddress[i]) && ("0".equals(mask[i]) || "00".equals(mask[i]) || "000".equals(mask[i]) || "0000".equals(mask[i]))) { continue; } else if (!mask[i].equals(ipAddress[i])) { return false; } } return true; } /** * is multicast address or not * * @param host ipv4 address * @return {@code true} if is multicast address */ public static boolean isMulticastAddress(String host) { int i = host.indexOf('.'); if (i > 0) { String prefix = host.substring(0, i); if (StringUtils.isNumber(prefix)) { int p = Integer.parseInt(prefix); return p >= 224 && p <= 239; } } return false; } private static boolean ipPatternContainExpression(String pattern) { return pattern.contains("*") || pattern.contains("-"); } private static void checkHostPattern(String pattern, String[] mask, boolean isIpv4) { if (!isIpv4) { if (mask.length != 8 && ipPatternContainExpression(pattern)) { throw new IllegalArgumentException( "If you config ip expression that contains '*' or '-', please fill qualified ip pattern like 234e:0:4567:0:0:0:3d:*. "); } if (mask.length != 8 && !pattern.contains("::")) { throw new IllegalArgumentException( "The host is ipv6, but the pattern is not ipv6 pattern : " + pattern); } } else { if (mask.length != 4) { throw new IllegalArgumentException( "The host is ipv4, but the pattern is not ipv4 pattern : " + pattern); } } } private static String[] getPatternHostAndPort(String pattern, boolean isIpv4) { String[] result = new String[2]; if (pattern.startsWith("[") && pattern.contains("]:")) { int end = pattern.indexOf("]:"); result[0] = pattern.substring(1, end); result[1] = pattern.substring(end + 2); return result; } else if (pattern.startsWith("[") && pattern.endsWith("]")) { result[0] = pattern.substring(1, pattern.length() - 1); result[1] = null; return result; } else if (isIpv4 && pattern.contains(":")) { int end = pattern.indexOf(":"); result[0] = pattern.substring(0, end); result[1] = pattern.substring(end + 1); return result; } else { result[0] = pattern; return result; } } private static Integer getNumOfIpSegment(String ipSegment, boolean isIpv4) { if (isIpv4) { return Integer.parseInt(ipSegment); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
true
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectionUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectionUtils.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.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * A utility class that provides methods for accessing and manipulating private fields and methods of an object. * This is useful for white-box testing, where the internal workings of a class need to be tested directly. * <p> * Note: Usage of this class should be limited to testing purposes only, as it violates the encapsulation principle. */ public class ReflectionUtils { private ReflectionUtils() {} /** * Retrieves the value of the specified field from the given object. * * @param source The object from which to retrieve the field value. * @param fieldName The name of the field to retrieve. * @return The value of the specified field in the given object. * @throws RuntimeException If the specified field does not exist. */ public static Object getField(Object source, String fieldName) { try { Field f = source.getClass().getDeclaredField(fieldName); f.setAccessible(true); return f.get(source); } catch (Exception e) { throw new ReflectionException(e); } } /** * Invokes the specified method on the given object with the provided parameters. * * @param source The object on which to invoke the method. * @param methodName The name of the method to invoke. * @param params The parameters to pass to the method. * @return The result of invoking the specified method on the given object. */ public static Object invoke(Object source, String methodName, Object... params) { try { Class<?>[] classes = Arrays.stream(params) .map(param -> param != null ? param.getClass() : null) .toArray(Class<?>[]::new); for (Method method : source.getClass().getDeclaredMethods()) { if (method.getName().equals(methodName) && matchParameters(method.getParameterTypes(), classes)) { method.setAccessible(true); return method.invoke(source, params); } } throw new NoSuchMethodException("No method found with the specified name and parameter types"); } catch (Exception e) { throw new ReflectionException(e); } } private static boolean matchParameters(Class<?>[] methodParamTypes, Class<?>[] givenParamTypes) { if (methodParamTypes.length != givenParamTypes.length) { return false; } for (int i = 0; i < methodParamTypes.length; i++) { if (givenParamTypes[i] == null) { if (methodParamTypes[i].isPrimitive()) { return false; } } else if (!methodParamTypes[i].isAssignableFrom(givenParamTypes[i])) { return false; } } return true; } /** * Returns a list of distinct {@link Class} objects representing the generics of the given class that implement the * given interface. * * @param clazz the class to retrieve the generics for * @param interfaceClass the interface to retrieve the generics for * @return a list of distinct {@link Class} objects representing the generics of the given class that implement the * given interface */ public static List<Class<?>> getClassGenerics(Class<?> clazz, Class<?> interfaceClass) { List<Class<?>> generics = new ArrayList<>(); Type[] genericInterfaces = clazz.getGenericInterfaces(); for (Type genericInterface : genericInterfaces) { if (genericInterface instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericInterface; Type rawType = parameterizedType.getRawType(); if (rawType instanceof Class && interfaceClass.isAssignableFrom((Class<?>) rawType)) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (Type actualTypeArgument : actualTypeArguments) { if (actualTypeArgument instanceof Class) { generics.add((Class<?>) actualTypeArgument); } } } } } Type genericSuperclass = clazz.getGenericSuperclass(); if (genericSuperclass instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (Type actualTypeArgument : actualTypeArguments) { if (actualTypeArgument instanceof Class) { generics.add((Class<?>) actualTypeArgument); } } } Class<?> superclass = clazz.getSuperclass(); if (superclass != null) { generics.addAll(getClassGenerics(superclass, interfaceClass)); } return generics.stream().distinct().collect(Collectors.toList()); } public static class ReflectionException extends RuntimeException { public ReflectionException(Throwable cause) { super(cause); } } public static boolean match(Class<?> clazz, Class<?> interfaceClass, Object event) { List<Class<?>> eventTypes = ReflectionUtils.getClassGenerics(clazz, interfaceClass); return eventTypes.stream().allMatch(eventType -> eventType.isInstance(event)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityConfigurator.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityConfigurator.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.utils; import org.apache.dubbo.common.aot.NativeDetector; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialization.ClassHolder; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeClassLoaderListener; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.CommonConstants.SERIALIZE_ALLOW_LIST_FILE_PATH; import static org.apache.dubbo.common.constants.CommonConstants.SERIALIZE_BLOCKED_LIST_FILE_PATH; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EXCEPTION; public class SerializeSecurityConfigurator implements ScopeClassLoaderListener<ModuleModel> { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(SerializeSecurityConfigurator.class); private final Set<Type> markedTypeCache = new HashSet<>(); private final SerializeSecurityManager serializeSecurityManager; private final ModuleModel moduleModel; private final ClassHolder classHolder; private volatile boolean autoTrustSerializeClass = true; private volatile int trustSerializeClassLevel = Integer.MAX_VALUE; public SerializeSecurityConfigurator(ModuleModel moduleModel) { this.moduleModel = moduleModel; moduleModel.addClassLoaderListener(this); FrameworkModel frameworkModel = moduleModel.getApplicationModel().getFrameworkModel(); serializeSecurityManager = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); classHolder = NativeDetector.inNativeImage() ? frameworkModel.getBeanFactory().getBean(ClassHolder.class) : null; refreshStatus(); refreshCheck(); refreshConfig(); onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); } public void refreshCheck() { Optional<ApplicationConfig> applicationConfig = moduleModel.getApplicationModel().getApplicationConfigManager().getApplication(); autoTrustSerializeClass = applicationConfig .map(ApplicationConfig::getAutoTrustSerializeClass) .orElse(true); trustSerializeClassLevel = applicationConfig .map(ApplicationConfig::getTrustSerializeClassLevel) .orElse(Integer.MAX_VALUE); serializeSecurityManager.setCheckSerializable( applicationConfig.map(ApplicationConfig::getCheckSerializable).orElse(true)); } @Override public void onAddClassLoader(ModuleModel scopeModel, ClassLoader classLoader) { refreshClassLoader(classLoader); } @Override public void onRemoveClassLoader(ModuleModel scopeModel, ClassLoader classLoader) { // ignore } private void refreshClassLoader(ClassLoader classLoader) { loadAllow(classLoader); loadBlocked(classLoader); } private void refreshConfig() { String allowedClassList = SystemPropertyConfigUtils.getSystemProperty( CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST, "") .trim(); String blockedClassList = SystemPropertyConfigUtils.getSystemProperty( CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCKED_LIST, "") .trim(); if (StringUtils.isNotEmpty(allowedClassList)) { String[] classStrings = allowedClassList.trim().split(","); for (String className : classStrings) { className = className.trim(); if (StringUtils.isNotEmpty(className)) { serializeSecurityManager.addToAlwaysAllowed(className); } } } if (StringUtils.isNotEmpty(blockedClassList)) { String[] classStrings = blockedClassList.trim().split(","); for (String className : classStrings) { className = className.trim(); if (StringUtils.isNotEmpty(className)) { serializeSecurityManager.addToDisAllowed(className); } } } } private void loadAllow(ClassLoader classLoader) { Set<URL> urls = ClassLoaderResourceLoader.loadResources(SERIALIZE_ALLOW_LIST_FILE_PATH, classLoader); for (URL u : urls) { try { LOGGER.info("Read serialize allow list from " + u); String[] lines = IOUtils.readLines(u.openStream()); for (String line : lines) { line = line.trim(); if (StringUtils.isEmpty(line) || line.startsWith("#")) { continue; } serializeSecurityManager.addToAlwaysAllowed(line); } } catch (IOException e) { LOGGER.error( COMMON_IO_EXCEPTION, "", "", "Failed to load allow class list! Will ignore allow lis from " + u, e); } } } private void loadBlocked(ClassLoader classLoader) { Set<URL> urls = ClassLoaderResourceLoader.loadResources(SERIALIZE_BLOCKED_LIST_FILE_PATH, classLoader); for (URL u : urls) { try { LOGGER.info("Read serialize blocked list from " + u); String[] lines = IOUtils.readLines(u.openStream()); for (String line : lines) { line = line.trim(); if (StringUtils.isEmpty(line) || line.startsWith("#")) { continue; } serializeSecurityManager.addToDisAllowed(line); } } catch (IOException e) { LOGGER.error( COMMON_IO_EXCEPTION, "", "", "Failed to load blocked class list! Will ignore blocked lis from " + u, e); } } } public void refreshStatus() { Optional<ApplicationConfig> application = moduleModel.getApplicationModel().getApplicationConfigManager().getApplication(); String statusString = application.map(ApplicationConfig::getSerializeCheckStatus).orElse(null); SerializeCheckStatus checkStatus = null; if (StringUtils.isEmpty(statusString)) { String openCheckClass = SystemPropertyConfigUtils.getSystemProperty( CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_OPEN_CHECK, "true"); if (!Boolean.parseBoolean(openCheckClass)) { checkStatus = SerializeCheckStatus.DISABLE; } String blockAllClassExceptAllow = SystemPropertyConfigUtils.getSystemProperty( CommonConstants.DubboProperty.DUBBO_CLASS_DESERIALIZE_BLOCK_ALL, "false"); if (Boolean.parseBoolean(blockAllClassExceptAllow)) { checkStatus = SerializeCheckStatus.STRICT; } } else { checkStatus = SerializeCheckStatus.valueOf(statusString); } if (checkStatus != null) { serializeSecurityManager.setCheckStatus(checkStatus); } } public synchronized void registerInterface(Class<?> clazz) { if (!autoTrustSerializeClass) { return; } if (!checkClass(clazz)) { return; } addToAllow(clazz); Method[] methodsToExport = clazz.getMethods(); for (Method method : methodsToExport) { Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> parameterType : parameterTypes) { checkClass(parameterType); } Type[] genericParameterTypes = method.getGenericParameterTypes(); for (Type genericParameterType : genericParameterTypes) { checkType(genericParameterType); } Class<?> returnType = method.getReturnType(); checkClass(returnType); Type genericReturnType = method.getGenericReturnType(); checkType(genericReturnType); Class<?>[] exceptionTypes = method.getExceptionTypes(); for (Class<?> exceptionType : exceptionTypes) { checkClass(exceptionType); } Type[] genericExceptionTypes = method.getGenericExceptionTypes(); for (Type genericExceptionType : genericExceptionTypes) { checkType(genericExceptionType); } } } private void checkType(Type type) { if (type == null) { return; } if (type instanceof Class) { checkClass((Class<?>) type); return; } if (!markedTypeCache.add(type)) { return; } if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; checkClass((Class<?>) parameterizedType.getRawType()); for (Type actualTypeArgument : parameterizedType.getActualTypeArguments()) { checkType(actualTypeArgument); } } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; checkType(genericArrayType.getGenericComponentType()); } else if (type instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) type; for (Type bound : typeVariable.getBounds()) { checkType(bound); } } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; for (Type bound : wildcardType.getUpperBounds()) { checkType(bound); } for (Type bound : wildcardType.getLowerBounds()) { checkType(bound); } } } private boolean checkClass(Class<?> clazz) { if (clazz == null) { return false; } if (!markedTypeCache.add(clazz)) { return false; } addToAllow(clazz); if (ClassUtils.isSimpleType(clazz) || clazz.isPrimitive() || clazz.isArray()) { return true; } String className = clazz.getName(); if (className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("com.sun.") || className.startsWith("sun.") || className.startsWith("jdk.")) { return true; } Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> interfaceClass : interfaces) { checkClass(interfaceClass); } for (Type genericInterface : clazz.getGenericInterfaces()) { checkType(genericInterface); } Class<?> superclass = clazz.getSuperclass(); if (superclass != null) { checkClass(superclass); } Type genericSuperclass = clazz.getGenericSuperclass(); if (genericSuperclass != null) { checkType(genericSuperclass); } Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (Modifier.isTransient(field.getModifiers())) { continue; } Class<?> fieldClass = field.getType(); checkClass(fieldClass); checkType(field.getGenericType()); } return true; } private void addToAllow(Class<?> clazz) { if (classHolder != null) { classHolder.storeClass(clazz); } String className = clazz.getName(); // ignore jdk if (className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("com.sun.") || className.startsWith("jakarta.") || className.startsWith("sun.") || className.startsWith("jdk.")) { serializeSecurityManager.addToAllowed(className); return; } // add group package String[] subs = className.split("\\."); if (subs.length > trustSerializeClassLevel) { serializeSecurityManager.addToAllowed( Arrays.stream(subs).limit(trustSerializeClassLevel).collect(Collectors.joining(".")) + "."); } else { serializeSecurityManager.addToAllowed(className); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Pair.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/Pair.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.utils; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; public final class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable { private static final long serialVersionUID = 1L; @SuppressWarnings("rawtypes") private static final Pair NULL = new Pair<>(null, null); private final L left; private final R right; public static <L, R> Pair<L, R> of(L left, R right) { return left == null && right == null ? nullPair() : new Pair<>(left, right); } @SuppressWarnings("unchecked") public static <L, R> Pair<L, R> nullPair() { return NULL; } @SafeVarargs public static <L, R> Map<L, R> toMap(Pair<L, R>... pairs) { if (pairs == null) { return Collections.emptyMap(); } return toMap(Arrays.asList(pairs)); } public static <L, R> Map<L, R> toMap(Collection<Pair<L, R>> pairs) { if (pairs == null) { return Collections.emptyMap(); } Map<L, R> map = CollectionUtils.newLinkedHashMap(pairs.size()); for (Pair<L, R> pair : pairs) { map.put(pair.getLeft(), pair.getRight()); } return map; } public static <L, R> List<Pair<L, R>> toPairs(Map<L, R> map) { if (map == null) { return Collections.emptyList(); } List<Pair<L, R>> pairs = new ArrayList<>(map.size()); for (Map.Entry<L, R> entry : map.entrySet()) { pairs.add(of(entry.getKey(), entry.getValue())); } return pairs; } public Pair(L left, R right) { this.left = left; this.right = right; } public L getLeft() { return left; } public R getRight() { return right; } public boolean isNull() { return this == NULL || left == null && right == null; } @Override public L getKey() { return left; } @Override public R getValue() { return right; } @Override public R setValue(R value) { throw new UnsupportedOperationException(); } @Override @SuppressWarnings("unchecked") public int compareTo(Pair<L, R> other) { return left.equals(other.left) ? ((Comparable<R>) right).compareTo(other.right) : ((Comparable<L>) left).compareTo(other.left); } @Override public int hashCode() { return Objects.hashCode(left) ^ Objects.hashCode(right); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof Map.Entry) { Map.Entry<?, ?> that = (Map.Entry<?, ?>) other; return Objects.equals(left, that.getKey()) && Objects.equals(right, that.getValue()); } return false; } @Override public String toString() { return "(" + left + ", " + right + ')'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonUtils.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.utils; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.json.JsonUtil; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.TreeMap; import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_PREFER_JSON_FRAMEWORK_NAME; public class JsonUtils { private static volatile JsonUtil jsonUtil; public static JsonUtil getJson() { if (jsonUtil == null) { synchronized (JsonUtils.class) { if (jsonUtil == null) { jsonUtil = createJsonUtil(); } } } return jsonUtil; } private static JsonUtil createJsonUtil() { Map<String, JsonUtil> extensions = new HashMap<>(); String preferName = SystemPropertyConfigUtils.getSystemProperty(DUBBO_PREFER_JSON_FRAMEWORK_NAME); ClassLoader classLoader = JsonUtil.class.getClassLoader(); JsonUtil jsonUtil = loadExtensions(preferName, classLoader, extensions); if (jsonUtil != null) { return jsonUtil; } ClassLoader tccl = Thread.currentThread().getContextClassLoader(); if (tccl != null && tccl != classLoader) { jsonUtil = loadExtensions(preferName, classLoader, extensions); if (jsonUtil != null) { return jsonUtil; } } TreeMap<Integer, JsonUtil> sortedExtensions = new TreeMap<>(); for (JsonUtil extension : extensions.values()) { Activate activate = extension.getClass().getAnnotation(Activate.class); sortedExtensions.put(activate == null ? 0 : activate.order(), extension); } if (sortedExtensions.isEmpty()) { throw new IllegalStateException("Dubbo unable to find out any json framework (e.g. fastjson2, " + "fastjson, gson, jackson) from jvm env. Please import at least one json framework."); } return sortedExtensions.firstEntry().getValue(); } private static JsonUtil loadExtensions(String name, ClassLoader classLoader, Map<String, JsonUtil> extensions) { ServiceLoader<JsonUtil> loader = ServiceLoader.load(JsonUtil.class, classLoader); Iterator<JsonUtil> it = loader.iterator(); // In JDK 21+, ServiceLoader.hasNext() may throw NoClassDefFoundError // when checking class dependencies, so we need to catch it here while (true) { try { if (!it.hasNext()) { break; } JsonUtil extension = it.next(); if (extension.isSupport()) { if (name != null && name.equals(extension.getName())) { return extension; } extensions.put(extension.getName(), extension); } } catch (Throwable ignored) { // Ignore loading failures (e.g., NoClassDefFoundError in JDK 25) // and continue with the next extension } } return null; } /** * @deprecated for unit test only */ @Deprecated @SuppressWarnings("DeprecatedIsStillUsed") protected static void setJson(JsonUtil json) { jsonUtil = json; } public static <T> T toJavaObject(String json, Type type) { return getJson().toJavaObject(json, type); } public static <T> List<T> toJavaList(String json, Class<T> clazz) { return getJson().toJavaList(json, clazz); } public static String toJson(Object obj) { return getJson().toJson(obj); } public static String toPrettyJson(Object obj) { return getJson().toPrettyJson(obj); } public static List<?> getList(Map<String, ?> obj, String key) { return getJson().getList(obj, key); } public static List<Map<String, ?>> getListOfObjects(Map<String, ?> obj, String key) { return getJson().getListOfObjects(obj, key); } public static List<String> getListOfStrings(Map<String, ?> obj, String key) { return getJson().getListOfStrings(obj, key); } public static Map<String, ?> getObject(Map<String, ?> obj, String key) { return getJson().getObject(obj, key); } public static Object convertObject(Object obj, Type targetType) { return getJson().convertObject(obj, targetType); } public static Object convertObject(Object obj, Class<?> targetType) { return getJson().convertObject(obj, targetType); } public static Double getNumberAsDouble(Map<String, ?> obj, String key) { return getJson().getNumberAsDouble(obj, key); } public static Integer getNumberAsInteger(Map<String, ?> obj, String key) { return getJson().getNumberAsInteger(obj, key); } public static Long getNumberAsLong(Map<String, ?> obj, String key) { return getJson().getNumberAsLong(obj, key); } public static String getString(Map<String, ?> obj, String key) { return getJson().getString(obj, key); } public static List<Map<String, ?>> checkObjectList(List<?> rawList) { return getJson().checkObjectList(rawList); } public static List<String> checkStringList(List<?> rawList) { return getJson().checkStringList(rawList); } public static boolean checkJson(String json) { return getJson().isJson(json); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.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.utils; 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.extension.ExtensionDirector; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; 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_IO_EXCEPTION; public class ConfigUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigUtils.class); private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\$\\s*\\{?\\s*([\\._0-9a-zA-Z]+)\\s*\\}?"); private static int PID = -1; private ConfigUtils() {} public static boolean isNotEmpty(String value) { return !isEmpty(value); } public static boolean isEmpty(String value) { return StringUtils.isEmpty(value) || "false".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value) || "null".equalsIgnoreCase(value) || "N/A".equalsIgnoreCase(value); } public static boolean isDefault(String value) { return "true".equalsIgnoreCase(value) || "default".equalsIgnoreCase(value); } /** * Insert default extension into extension list. * <p> * Extension list support<ul> * <li>Special value <code><strong>default</strong></code>, means the location for default extensions. * <li>Special symbol<code><strong>-</strong></code>, means remove. <code>-foo1</code> will remove default extension 'foo'; <code>-default</code> will remove all default extensions. * </ul> * * @param type Extension type * @param cfg Extension name list * @param def Default extension list * @return result extension list */ public static List<String> mergeValues( ExtensionDirector extensionDirector, Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<>(); if (def != null) { for (String name : def) { if (extensionDirector.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<>(); // add initial values String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } // -default is not included if (!names.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) { // add default extension int i = names.indexOf(DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(DEFAULT_KEY); } else { names.remove(DEFAULT_KEY); } // merge - configuration for (String name : new ArrayList<String>(names)) { if (name.startsWith(REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } public static String replaceProperty(String expression, Map<String, String> params) { return replaceProperty(expression, new InmemoryConfiguration(params)); } public static String replaceProperty(String expression, Configuration configuration) { if (StringUtils.isEmpty(expression) || expression.indexOf('$') < 0) { return expression; } Matcher matcher = VARIABLE_PATTERN.matcher(expression); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String key = matcher.group(1); String value = System.getProperty(key); if (value == null && configuration != null) { Object val = configuration.getProperty(key); value = (val != null) ? val.toString() : null; } if (value == null) { // maybe not placeholders, use origin express value = matcher.group(); } matcher.appendReplacement(sb, Matcher.quoteReplacement(value)); } matcher.appendTail(sb); return sb.toString(); } /** * Get dubbo properties. * It is not recommended using this method to modify dubbo properties. * * @return */ public static Properties getProperties(Set<ClassLoader> classLoaders) { String path = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY); if (StringUtils.isEmpty(path)) { path = System.getenv(CommonConstants.DubboProperty.DUBBO_PROPERTIES_KEY); if (StringUtils.isEmpty(path)) { path = CommonConstants.DEFAULT_DUBBO_PROPERTIES; } } return ConfigUtils.loadProperties(classLoaders, path, false, true); } /** * System environment -> System properties * * @param key key * @return value */ public static String getSystemProperty(String key) { String value = System.getenv(key); if (StringUtils.isEmpty(value)) { value = System.getProperty(key); } return value; } public static Properties loadProperties(Set<ClassLoader> classLoaders, String fileName) { return loadProperties(classLoaders, fileName, false, false); } public static Properties loadProperties(Set<ClassLoader> classLoaders, String fileName, boolean allowMultiFile) { return loadProperties(classLoaders, fileName, allowMultiFile, false); } /** * Load properties file to {@link Properties} from class path. * * @param fileName properties file name. for example: <code>dubbo.properties</code>, <code>METE-INF/conf/foo.properties</code> * @param allowMultiFile if <code>false</code>, throw {@link IllegalStateException} when found multi file on the class path. * @param optional is optional. if <code>false</code>, log warn when properties config file not found!s * @return loaded {@link Properties} content. <ul> * <li>return empty Properties if no file found. * <li>merge multi properties file if found multi file * </ul> * @throws IllegalStateException not allow multi-file, but multi-file exist on class path. */ public static Properties loadProperties( Set<ClassLoader> classLoaders, String fileName, boolean allowMultiFile, boolean optional) { Properties properties = new Properties(); // add scene judgement in windows environment Fix 2557 if (checkFileNameExist(fileName)) { try { FileInputStream input = new FileInputStream(fileName); try { properties.load(input); } finally { input.close(); } } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } return properties; } Set<java.net.URL> set = null; try { List<ClassLoader> classLoadersToLoad = new LinkedList<>(); classLoadersToLoad.add(ClassUtils.getClassLoader()); classLoadersToLoad.addAll(classLoaders); set = ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad).values().stream() .reduce(new LinkedHashSet<>(), (a, i) -> { a.addAll(i); return a; }); } catch (Throwable t) { logger.warn(COMMON_IO_EXCEPTION, "", "", "Fail to load " + fileName + " file: " + t.getMessage(), t); } if (CollectionUtils.isEmpty(set)) { if (!optional) { logger.warn(COMMON_IO_EXCEPTION, "", "", "No " + fileName + " found on the class path."); } return properties; } if (!allowMultiFile) { if (set.size() > 1) { String errMsg = String.format( "only 1 %s file is expected, but %d dubbo.properties files found on class path: %s", fileName, set.size(), set); logger.warn(COMMON_IO_EXCEPTION, "", "", errMsg); } // fall back to use method getResourceAsStream try { properties.load(ClassUtils.getClassLoader().getResourceAsStream(fileName)); } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } return properties; } logger.info("load " + fileName + " properties file from " + set); for (java.net.URL url : set) { try { Properties p = new Properties(); InputStream input = url.openStream(); if (input != null) { try { p.load(input); properties.putAll(p); } finally { try { input.close(); } catch (Throwable t) { } } } } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Fail to load " + fileName + " file from " + url + "(ignore this file): " + e.getMessage(), e); } } return properties; } public static String loadMigrationRule(Set<ClassLoader> classLoaders, String fileName) { String rawRule = ""; if (checkFileNameExist(fileName)) { try { try (FileInputStream input = new FileInputStream(fileName)) { return readString(input); } } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } } try { List<ClassLoader> classLoadersToLoad = new LinkedList<>(); classLoadersToLoad.add(ClassUtils.getClassLoader()); classLoadersToLoad.addAll(classLoaders); for (Set<URL> urls : ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad) .values()) { for (URL url : urls) { InputStream is = url.openStream(); if (is != null) { return readString(is); } } } } catch (Throwable e) { logger.warn( COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); } return rawRule; } private static String readString(InputStream is) { StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[10]; try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { int n; while ((n = reader.read(buffer)) != -1) { if (n < 10) { buffer = Arrays.copyOf(buffer, n); } stringBuilder.append(String.valueOf(buffer)); buffer = new char[10]; } } catch (IOException e) { logger.error(COMMON_IO_EXCEPTION, "", "", "Read migration file error.", e); } return stringBuilder.toString(); } /** * check if the fileName can be found in filesystem * * @param fileName * @return */ private static boolean checkFileNameExist(String fileName) { File file = new File(fileName); return file.exists(); } public static int getPid() { if (PID < 0) { try { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); // format: "pid@hostname" String name = runtime.getName(); PID = Integer.parseInt(name.substring(0, name.indexOf('@'))); } catch (Throwable e) { PID = 0; } } return PID; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicate.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicate.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.utils; import java.lang.reflect.Field; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.lang.reflect.Modifier.isFinal; import static java.lang.reflect.Modifier.isPublic; import static java.lang.reflect.Modifier.isStatic; import static org.apache.dubbo.common.utils.FieldUtils.getFieldValue; /** * The constant field value {@link Predicate} for the specified {@link Class} * * @see Predicate * @since 2.7.8 */ public class StringConstantFieldValuePredicate implements Predicate<String> { private final Set<String> constantFieldValues; public StringConstantFieldValuePredicate(Class<?> targetClass) { this.constantFieldValues = getConstantFieldValues(targetClass); } public static Predicate<String> of(Class<?> targetClass) { return new StringConstantFieldValuePredicate(targetClass); } private Set<String> getConstantFieldValues(Class<?> targetClass) { return Stream.of(targetClass.getFields()) .filter(f -> isStatic(f.getModifiers())) // static .filter(f -> isPublic(f.getModifiers())) // public .filter(f -> isFinal(f.getModifiers())) // final .map(this::getConstantValue) .filter(v -> v instanceof String) // filters String type .map(String.class::cast) // Casts String type .collect(Collectors.toSet()); } @Override public boolean test(String s) { return constantFieldValues.contains(s); } private Object getConstantValue(Field field) { return getFieldValue(null, field); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.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.utils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * MD5 util. */ public class MD5Utils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MD5Utils.class); private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private MessageDigest mdInst; public MD5Utils() { try { mdInst = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to obtain md5", e); } } /** * Calculation md5 value of specify string * * @param input */ public String getMd5(String input) { byte[] md5; // MessageDigest instance is NOT thread-safe synchronized (mdInst) { mdInst.update(input.getBytes(UTF_8)); md5 = mdInst.digest(); } int j = md5.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md5[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ToStringUtils.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ToStringUtils.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.utils; import org.apache.dubbo.config.AbstractConfig; import java.util.Arrays; import java.util.List; import java.util.Map; public class ToStringUtils { private ToStringUtils() {} public static String printToString(Object obj) { if (obj == null) { return "null"; } try { return JsonUtils.toJson(obj); } catch (Throwable throwable) { if (obj instanceof Object[]) { return Arrays.toString((Object[]) obj); } return obj.toString(); } } public static String toString(Object obj) { if (obj == null) { return "null"; } if (ClassUtils.isSimpleType(obj.getClass())) { return obj.toString(); } if (obj.getClass().isPrimitive()) { return obj.toString(); } if (obj instanceof Object[]) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); Object[] objects = (Object[]) obj; for (int i = 0; i < objects.length; i++) { stringBuilder.append(toString(objects[i])); if (i != objects.length - 1) { stringBuilder.append(", "); } } stringBuilder.append("]"); return stringBuilder.toString(); } if (obj instanceof List) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); List list = (List) obj; for (int i = 0; i < list.size(); i++) { stringBuilder.append(toString(list.get(i))); if (i != list.size() - 1) { stringBuilder.append(", "); } } stringBuilder.append("]"); return stringBuilder.toString(); } if (obj instanceof Map) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("{"); Map map = (Map) obj; int i = 0; for (Object key : map.keySet()) { stringBuilder.append(toString(key)); stringBuilder.append("="); stringBuilder.append(toString(map.get(key))); if (i != map.size() - 1) { stringBuilder.append(", "); } i++; } stringBuilder.append("}"); return stringBuilder.toString(); } if (obj instanceof AbstractConfig) { return obj.toString(); } return obj.getClass() + "@" + Integer.toHexString(System.identityHashCode(obj)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRU2Cache.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRU2Cache.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.utils; import java.util.LinkedHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Function; /** * LRU-2 * <p> * When the data accessed for the first time, add it to history list. If the size of history list reaches max capacity, eliminate the earliest data (first in first out). * When the data already exists in the history list, and be accessed for the second time, then it will be put into cache. * </p> * TODO, consider replacing with ConcurrentHashMap to improve performance under concurrency */ public class LRU2Cache<K, V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = -5167631809472116969L; private static final float DEFAULT_LOAD_FACTOR = 0.75f; private static final int DEFAULT_MAX_CAPACITY = 1000; private final Lock lock = new ReentrantLock(); private volatile int maxCapacity; // as history list private final PreCache<K, Boolean> preCache; public LRU2Cache() { this(DEFAULT_MAX_CAPACITY); } public LRU2Cache(int maxCapacity) { super(16, DEFAULT_LOAD_FACTOR, true); this.maxCapacity = maxCapacity; this.preCache = new PreCache<>(maxCapacity); } @Override protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) { return size() > maxCapacity; } @Override public boolean containsKey(Object key) { lock.lock(); try { return super.containsKey(key); } finally { lock.unlock(); } } @Override public V get(Object key) { lock.lock(); try { return super.get(key); } finally { lock.unlock(); } } @Override public V put(K key, V value) { lock.lock(); try { if (preCache.containsKey(key)) { // add it to cache preCache.remove(key); return super.put(key, value); } else { // add it to history list preCache.put(key, true); return value; } } finally { lock.unlock(); } } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> fn) { V value = get(key); if (value == null) { value = fn.apply(key); put(key, value); } return value; } @Override public V remove(Object key) { lock.lock(); try { preCache.remove(key); return super.remove(key); } finally { lock.unlock(); } } @Override public int size() { lock.lock(); try { return super.size(); } finally { lock.unlock(); } } @Override public void clear() { lock.lock(); try { preCache.clear(); super.clear(); } finally { lock.unlock(); } } public int getMaxCapacity() { return maxCapacity; } public void setMaxCapacity(int maxCapacity) { preCache.setMaxCapacity(maxCapacity); this.maxCapacity = maxCapacity; } static class PreCache<K, V> extends LinkedHashMap<K, V> { private volatile int maxCapacity; public PreCache() { this(DEFAULT_MAX_CAPACITY); } public PreCache(int maxCapacity) { super(16, DEFAULT_LOAD_FACTOR, true); this.maxCapacity = maxCapacity; } @Override protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) { return size() > maxCapacity; } public void setMaxCapacity(int maxCapacity) { this.maxCapacity = maxCapacity; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashSet.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashSet.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.utils; import java.util.AbstractSet; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class ConcurrentHashSet<E> extends AbstractSet<E> implements Set<E>, java.io.Serializable { private static final long serialVersionUID = -8672117787651310382L; private static final Object PRESENT = new Object(); private final ConcurrentMap<E, Object> map; public ConcurrentHashSet() { map = new ConcurrentHashMap<>(); } public ConcurrentHashSet(int initialCapacity) { map = new ConcurrentHashMap<>(initialCapacity); } /** * Returns an iterator over the elements in this set. The elements are * returned in no particular order. * * @return an Iterator over the elements in this set * @see ConcurrentModificationException */ @Override public Iterator<E> iterator() { return map.keySet().iterator(); } /** * Returns the number of elements in this set (its cardinality). * * @return the number of elements in this set (its cardinality) */ @Override public int size() { return map.size(); } /** * Returns <tt>true</tt> if this set contains no elements. * * @return <tt>true</tt> if this set contains no elements */ @Override public boolean isEmpty() { return map.isEmpty(); } /** * Returns <tt>true</tt> if this set contains the specified element. More * formally, returns <tt>true</tt> if and only if this set contains an * element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * * @param o element whose presence in this set is to be tested * @return <tt>true</tt> if this set contains the specified element */ @Override public boolean contains(Object o) { return map.containsKey(o); } /** * Adds the specified element to this set if it is not already present. More * formally, adds the specified element <tt>e</tt> to this set if this set * contains no element <tt>e2</tt> such that * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. If this * set already contains the element, the call leaves the set unchanged and * returns <tt>false</tt>. * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */ @Override public boolean add(E e) { return map.put(e, PRESENT) == null; } /** * Removes the specified element from this set if it is present. More * formally, removes an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if this * set contains such an element. Returns <tt>true</tt> if this set contained * the element (or equivalently, if this set changed as a result of the * call). (This set will not contain the element once the call returns.) * * @param o object to be removed from this set, if present * @return <tt>true</tt> if the set contained the specified element */ @Override public boolean remove(Object o) { return map.remove(o) == PRESENT; } /** * Removes all of the elements from this set. The set will be empty after * this call returns. */ @Override public void clear() { map.clear(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java
dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.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.utils; import java.io.Serializable; import java.util.List; /** * The default implementation of {@link Page} * * @since 2.7.5 */ public class DefaultPage<T> implements Page<T>, Serializable { private static final long serialVersionUID = 1099331838954070419L; private final int requestOffset; private final int pageSize; private final int totalSize; private final List<T> data; private final int totalPages; private final boolean hasNext; public DefaultPage(int requestOffset, int pageSize, List<T> data, int totalSize) { this.requestOffset = requestOffset; this.pageSize = pageSize; this.data = data; this.totalSize = totalSize; int remain = totalSize % pageSize; this.totalPages = remain > 0 ? (totalSize / pageSize) + 1 : totalSize / pageSize; this.hasNext = totalSize - requestOffset - pageSize > 0; } @Override public int getOffset() { return requestOffset; } @Override public int getPageSize() { return pageSize; } @Override public int getTotalSize() { return totalSize; } @Override public int getTotalPages() { return totalPages; } @Override public List<T> getData() { return data; } @Override public boolean hasNext() { return hasNext; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false