All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.datarouter.client.mysql.connection.C3p0StatsService Maven / Gradle / Ivy

There is a newer version: 0.0.125
Show newest version
/*
 * Copyright © 2009 HotPads ([email protected])
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.datarouter.client.mysql.connection;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import io.datarouter.util.JmxTool;
import io.datarouter.util.string.StringTool;
import jakarta.inject.Singleton;

@Singleton
public class C3p0StatsService{

	public List getC3p0Stats(){
		ObjectName query;
		try{
			query = new ObjectName("com.mchange.v2.c3p0:type=PooledDataSource,*");
		}catch(MalformedObjectNameException e){
			throw new RuntimeException(e);
		}
		return JmxTool.SERVER.queryNames(query, null).stream()
				.>map(objectName -> {
					String jdbcUrl = (String)JmxTool.getAttribute(objectName, "jdbcUrl");
					Optional clientName = extractClientName(jdbcUrl);
					if(clientName.isEmpty()){
						return Optional.empty();
					}
					int total = (int)JmxTool.getAttribute(objectName, "numConnections");
					int busy = (int)JmxTool.getAttribute(objectName, "numBusyConnections");
					return Optional.of(new C3p0StatsDto(clientName.get(), total, busy));
				})
				.flatMap(Optional::stream)
				.toList();
	}

	protected static Optional extractClientName(String jdbcUrl){
		String queryParams = StringTool.getStringAfterLastOccurrence('?', jdbcUrl);
		return Arrays.stream(queryParams.split("&"))
				.filter(part -> part.startsWith(MysqlConnectionPoolHolder.CLIENT_NAME_KEY))
				.findAny()
				.map(part -> part.substring(MysqlConnectionPoolHolder.CLIENT_NAME_KEY.length()));
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy