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;
29 import org.sonar.core.util.UuidFactory;
31 import static org.sonar.process.ProcessProperties.Property.JDBC_URL;
33 public class ServerIdFactoryImpl implements ServerIdFactory {
35 private final Configuration config;
36 private final UuidFactory uuidFactory;
37 private final JdbcUrlSanitizer jdbcUrlSanitizer;
39 public ServerIdFactoryImpl(Configuration config, UuidFactory uuidFactory, JdbcUrlSanitizer jdbcUrlSanitizer) {
41 this.uuidFactory = uuidFactory;
42 this.jdbcUrlSanitizer = jdbcUrlSanitizer;
46 public ServerId create() {
47 return ServerId.of(computeDatabaseId(), uuidFactory.create());
51 public ServerId create(ServerId currentServerId) {
52 return ServerId.of(computeDatabaseId(), currentServerId.getDatasetId());
55 private String computeDatabaseId() {
56 String jdbcUrl = config.get(JDBC_URL.getKey()).orElseThrow(() -> new IllegalStateException("Missing JDBC URL"));
57 return crc32Hex(jdbcUrlSanitizer.sanitize(jdbcUrl));
61 static String crc32Hex(String str) {
62 CRC32 crc32 = new CRC32();
63 crc32.update(str.getBytes(StandardCharsets.UTF_8));
64 long hash = crc32.getValue();
65 String s = Long.toHexString(hash).toUpperCase(Locale.ENGLISH);
66 return StringUtils.leftPad(s, ServerId.DATABASE_ID_LENGTH, "0");