3 * Copyright (C) 2009-2024 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.platform.serverid;
22 import com.google.common.annotations.VisibleForTesting;
23 import java.nio.charset.StandardCharsets;
24 import java.util.Locale;
25 import java.util.zip.CRC32;
26 import org.apache.commons.lang.StringUtils;
27 import org.sonar.api.config.Configuration;
28 import org.sonar.core.platform.ServerId;
30 import static org.sonar.process.ProcessProperties.Property.JDBC_URL;
32 public class ServerIdFactoryImpl implements ServerIdFactory {
34 private final Configuration config;
35 private final ServerIdGenerator serverIdGenerator;
36 private final JdbcUrlSanitizer jdbcUrlSanitizer;
38 public ServerIdFactoryImpl(Configuration config, ServerIdGenerator serverIdGenerator, JdbcUrlSanitizer jdbcUrlSanitizer) {
40 this.serverIdGenerator = serverIdGenerator;
41 this.jdbcUrlSanitizer = jdbcUrlSanitizer;
45 public ServerId create() {
46 return ServerId.of(computeDatabaseId(), serverIdGenerator.generate());
50 public ServerId create(ServerId currentServerId) {
51 return ServerId.of(computeDatabaseId(), currentServerId.getDatasetId());
54 private String computeDatabaseId() {
55 String jdbcUrl = config.get(JDBC_URL.getKey()).orElseThrow(() -> new IllegalStateException("Missing JDBC URL"));
56 return crc32Hex(jdbcUrlSanitizer.sanitize(jdbcUrl));
60 static String crc32Hex(String str) {
61 CRC32 crc32 = new CRC32();
62 crc32.update(str.getBytes(StandardCharsets.UTF_8));
63 long hash = crc32.getValue();
64 String s = Long.toHexString(hash).toUpperCase(Locale.ENGLISH);
65 return StringUtils.leftPad(s, ServerId.DATABASE_ID_LENGTH, "0");