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.almintegration.ws;
22 import com.google.common.annotations.VisibleForTesting;
23 import java.util.List;
24 import org.apache.commons.lang.StringUtils;
25 import org.sonar.core.util.UuidFactory;
27 import static com.google.common.collect.Lists.asList;
28 import static org.sonar.core.component.ComponentKeys.sanitizeProjectKey;
30 public class ProjectKeyGenerator {
33 static final int MAX_PROJECT_KEY_SIZE = 250;
35 static final Character PROJECT_KEY_SEPARATOR = '_';
37 private final UuidFactory uuidFactory;
39 public ProjectKeyGenerator(UuidFactory uuidFactory) {
40 this.uuidFactory = uuidFactory;
43 public String generateUniqueProjectKey(String projectName, String... extraProjectKeyItems) {
44 String sqProjectKey = generateCompleteProjectKey(projectName, extraProjectKeyItems);
45 sqProjectKey = truncateProjectKeyIfNecessary(sqProjectKey);
46 return sanitizeProjectKey(sqProjectKey);
49 private String generateCompleteProjectKey(String projectName, String[] extraProjectKeyItems) {
50 List<String> projectKeyItems = asList(projectName, extraProjectKeyItems);
51 String projectKey = StringUtils.join(projectKeyItems, PROJECT_KEY_SEPARATOR);
52 String uuid = uuidFactory.create();
53 return projectKey + PROJECT_KEY_SEPARATOR + uuid;
56 private static String truncateProjectKeyIfNecessary(String sqProjectKey) {
57 if (sqProjectKey.length() > MAX_PROJECT_KEY_SIZE) {
58 return sqProjectKey.substring(sqProjectKey.length() - MAX_PROJECT_KEY_SIZE);