Merge branch 'stable-2.15'

* stable-2.15:
  Update git submodules
  Use Logger's built-in string formatting where possible
  Doc: Fix code example in JS API
  Allow some sections of the change list to overflow
  Fix more comparisons of current user
  Revert "WorkQueue: Add metrics"
  Fix permissions checks on Gerrit API on current user
  GroupCacheImpl: Fix log message when UUID is not found
  Update git submodules
  Update git submodules
  WorkQueue.Executor#buildMetrics: Remove MetricMaker parameter
  ChangeQueryBuilder: Allow ownerin predicate to be evaluated by the index
  Update git submodules
  Update git submodules
  Update git submodules
  ldap.Helper: Use local logger and make logger in LdapRealm private
  Remove ValidationError#createLoggerSink to avoid passing around loggers
  LdapLoginServlet: Improve exception handling
  OperatingSystemMXBeanProvider: Log exception for ReflectiveOperationException
  HttpPluginServlet: Don't trim leading whitespace from about.md content
  ProjectConfig: Don't use JGit's StringUtils to convert to lower case
  Do not abort indexing if < 50% projects failed
  Revert "AllChangesIndexer: Don't abort when failing to open repository"
  WorkQueue: Don't fail when queue metric already exists
  WorkQueue: Sanitize metric name when queue is created
  DropWizardMetricMaker: Introduce method to sanitize metric name
  VersionedAccountDestinations: Remove unused createSink(String) method
  ProjectBasicAuthFilter: Add comment why cause is not logged
  BazelBuild: Fix exception message when command was interrupted
  GitwebServlet: Write only one log entry for CGI errors
  GitwebServlet: Log unexpected errors on error level
  PostGpgKeys: Remove unneeded use of Joiner
  Remove some logs for errors that are rethrown
  DropWizardMetricMaker: Improve error messages for invalid arguments
  DropWizardMetricMaker: Improve error message when metric name is invalid
  AllChangesIndexer: Don't abort when failing to open repository

Change-Id: I33e8a1c9498c6adecd4ffc7d8ef0cc78aeb28eea
This commit is contained in:
David Pursehouse
2018-05-24 10:52:53 +09:00
61 changed files with 286 additions and 272 deletions

View File

@@ -770,7 +770,7 @@ Gerrit.get(url, callback)
----
Gerrit.get('/changes/?q=status:open', function (open) {
for (var i = 0; i < open.length; i++) {
console.log(open.get(i).change_id);
console.log(open[i].change_id);
}
});
----

View File

@@ -68,17 +68,6 @@ formatQueryResults invocations in ChangeJson.
* `query/query_latency`: Successful query latency, accumulated over the life
of the process.
=== Queue
The metrics below are per queue.
* `queue/<queueName>/pool_size`: Current number of threads in the pool
* `queue/<queueName>/max_pool_size`: Maximum allowed number of threads in the pool
* `queue/<queueName>/active_threads`: Number of threads that are actively executing tasks
* `queue/<queueName>/scheduled_tasks`: Number of scheduled tasks in the queue
* `queue/<queueName>/total_scheduled_tasks_count`: Total number of tasks that have been scheduled
* `queue/<queueName>/total_completed_tasks_count`: Total number of tasks that have completed execution
=== SSH sessions
* `sshd/sessions/connected`: Number of currently connected SSH sessions.

View File

@@ -0,0 +1,42 @@
// Copyright (C) 2018 The Android Open Source Project
//
// 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 com.google.gerrit.metrics.dropwizard;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.metrics.dropwizard.DropWizardMetricMaker.sanitizeMetricName;
import org.junit.Test;
public class DropWizardMetricMakerTest {
@Test
public void shouldSanitizeUnwantedChars() throws Exception {
assertThat(sanitizeMetricName("very+confusing$long#metric@net/name^1"))
.isEqualTo("very_confusing_long_metric_net/name_1");
assertThat(sanitizeMetricName("/metric/submetric")).isEqualTo("_metric/submetric");
}
@Test
public void shouldReduceConsecutiveSlashesToOne() throws Exception {
assertThat(sanitizeMetricName("/metric//submetric1///submetric2/submetric3"))
.isEqualTo("_metric/submetric1/submetric2/submetric3");
}
@Test
public void shouldNotFinishWithSlash() throws Exception {
assertThat(sanitizeMetricName("metric/")).isEqualTo("metric");
assertThat(sanitizeMetricName("metric//")).isEqualTo("metric");
assertThat(sanitizeMetricName("metric/submetric/")).isEqualTo("metric/submetric");
}
}

View File

@@ -207,7 +207,7 @@ public class GpgKeys implements ChildCollection<AccountResource, GpgKey> {
if (!BouncyCastleUtil.havePGP()) {
throw new ResourceNotFoundException("GPG not enabled");
}
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
throw new ResourceNotFoundException();
}
}

View File

@@ -32,6 +32,7 @@ java_library(
"//lib/auto:auto-value",
"//lib/auto:auto-value-annotations",
"//lib/commons:codec",
"//lib/commons:lang",
"//lib/guice",
"//lib/guice:guice-assistedinject",
"//lib/guice:guice-servlet",

View File

@@ -88,6 +88,7 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.util.IO;
import org.eclipse.jgit.util.RawParseUtils;
@@ -190,7 +191,7 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
try {
filter = plugin.getHttpInjector().getInstance(GuiceFilter.class);
} catch (RuntimeException e) {
log.warn(String.format("Plugin %s cannot load GuiceFilter", name), e);
log.warn("Plugin {} cannot load GuiceFilter", name, e);
return null;
}
@@ -198,7 +199,7 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
ServletContext ctx = PluginServletContext.create(plugin, wrapper.getFullPath(name));
filter.init(new WrappedFilterConfig(ctx));
} catch (ServletException e) {
log.warn(String.format("Plugin %s failed to initialize HTTP", name), e);
log.warn("Plugin {} failed to initialize HTTP", name, e);
return null;
}
@@ -423,10 +424,11 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
&& size.isPresent()) {
if (size.get() <= 0 || size.get() > SMALL_RESOURCE) {
log.warn(
String.format(
"Plugin %s: %s omitted from document index. "
+ "Size %d out of range (0,%d).",
pluginName, name.substring(prefix.length()), size.get(), SMALL_RESOURCE));
"Plugin {}: {} omitted from document index. Size {} out of range (0,{}).",
pluginName,
name.substring(prefix.length()),
size.get(),
SMALL_RESOURCE);
return false;
}
return true;
@@ -449,9 +451,9 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
about = entry;
} else {
log.warn(
String.format(
"Plugin %s: Multiple 'about' documents found; using %s",
pluginName, about.getName().substring(prefix.length())));
"Plugin {}: Multiple 'about' documents found; using {}",
pluginName,
about.getName().substring(prefix.length()));
}
} else {
docs.add(entry);
@@ -472,7 +474,7 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
try (BufferedReader reader = new BufferedReader(isr)) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
line = StringUtils.stripEnd(line, null);
if (line.isEmpty()) {
aboutContent.append("\n");
} else {
@@ -729,9 +731,7 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
}
return def;
} catch (IOException e) {
log.warn(
String.format("Error getting %s for plugin %s, using default", attr, plugin.getName()),
e);
log.warn("Error getting {} for plugin {}, using default", attr, plugin.getName(), e);
return null;
}
}

View File

@@ -139,7 +139,7 @@ public class LfsPluginServlet extends HttpServlet
try {
guiceFilter = plugin.getHttpInjector().getInstance(GuiceFilter.class);
} catch (RuntimeException e) {
log.warn(String.format("Plugin %s cannot load GuiceFilter", name), e);
log.warn("Plugin {} cannot load GuiceFilter", name, e);
return null;
}
@@ -147,7 +147,7 @@ public class LfsPluginServlet extends HttpServlet
ServletContext ctx = PluginServletContext.create(plugin, "/");
guiceFilter.init(new WrappedFilterConfig(ctx));
} catch (ServletException e) {
log.warn(String.format("Plugin %s failed to initialize HTTP", name), e);
log.warn("Plugin {} failed to initialize HTTP", name, e);
return null;
}

View File

@@ -155,7 +155,7 @@ class PluginServletContext {
@Override
public void log(String msg, Throwable reason) {
log.warn(String.format("[plugin %s] %s", plugin.getName(), msg), reason);
log.warn("[plugin {}] {}", plugin.getName(), msg, reason);
}
@Override

View File

@@ -161,7 +161,7 @@ public abstract class ResourceServlet extends HttpServlet {
r = cache.get(p, newLoader(p));
}
} catch (ExecutionException e) {
log.warn("Cannot load static resource " + req.getPathInfo(), e);
log.warn("Cannot load static resource {}", req.getPathInfo(), e);
CacheHeaders.setNotCacheable(rsp);
rsp.setStatus(SC_INTERNAL_SERVER_ERROR);
return;
@@ -214,12 +214,12 @@ public abstract class ResourceServlet extends HttpServlet {
try {
Path p = getResourcePath(name);
if (p == null) {
log.warn(String.format("Path doesn't exist %s", name));
log.warn("Path doesn't exist {}", name);
return null;
}
return cache.get(p, newLoader(p));
} catch (ExecutionException | IOException e) {
log.warn(String.format("Cannot load static resource %s", name), e);
log.warn("Cannot load static resource {}", name, e);
return null;
}
}

View File

@@ -184,7 +184,7 @@ public class Schema<T> {
try {
v = f.get(obj);
} catch (OrmException e) {
log.error(String.format("error getting field %s of %s", f.getName(), obj), e);
log.error("error getting field {} of {}", f.getName(), obj, e);
return null;
}
if (v == null) {

View File

@@ -151,8 +151,8 @@ public class DropWizardMetricMaker extends MetricMaker {
private static void checkCounterDescription(String name, Description desc) {
checkMetricName(name);
checkArgument(!desc.isConstant(), "counters must not be constant");
checkArgument(!desc.isGauge(), "counters must not be gauge");
checkArgument(!desc.isConstant(), "counter must not be constant");
checkArgument(!desc.isGauge(), "counter must not be gauge");
}
CounterImpl newCounterImpl(String name, boolean isRate) {
@@ -326,7 +326,7 @@ public class DropWizardMetricMaker extends MetricMaker {
if (!desc.getAnnotations()
.get(Description.DESCRIPTION)
.equals(annotations.get(Description.DESCRIPTION))) {
throw new IllegalStateException(String.format("metric %s already defined", name));
throw new IllegalStateException(String.format("metric '%s' already defined", name));
}
} else {
descriptions.put(name, desc.getAnnotations());
@@ -339,10 +339,30 @@ public class DropWizardMetricMaker extends MetricMaker {
private static void checkMetricName(String name) {
checkArgument(
METRIC_NAME_PATTERN.matcher(name).matches(),
"metric name must match %s",
"invalid metric name '%s': must match pattern '%s'",
name,
METRIC_NAME_PATTERN.pattern());
}
public static String sanitizeMetricName(String input) {
if (METRIC_NAME_PATTERN.matcher(input).matches()) {
return input;
}
String first = input.substring(0, 1).replaceFirst("[^\\w-]", "_");
if (input.length() == 1) {
return first;
}
String result = first + input.substring(1).replaceAll("/[/]+", "/").replaceAll("[^\\w-/]", "_");
if (result.endsWith("/")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
static String name(Description.FieldOrdering ordering, String codeName, String fieldValues) {
if (ordering == FieldOrdering.PREFIX_FIELDS_BASENAME) {
int s = codeName.lastIndexOf('/');

View File

@@ -68,7 +68,7 @@ public class SwitchSecureStore extends SiteProgram {
SitePaths sitePaths = new SitePaths(getSitePath());
Path newSecureStorePath = Paths.get(newSecureStoreLib);
if (!Files.exists(newSecureStorePath)) {
log.error(String.format("File %s doesn't exist", newSecureStorePath.toAbsolutePath()));
log.error("File {} doesn't exist", newSecureStorePath.toAbsolutePath());
return -1;
}
@@ -77,8 +77,7 @@ public class SwitchSecureStore extends SiteProgram {
if (currentSecureStoreName.equals(newSecureStore)) {
log.error(
"Old and new SecureStore implementation names "
+ "are the same. Migration will not work");
"Old and new SecureStore implementation names are the same. Migration will not work");
return -1;
}

View File

@@ -79,7 +79,7 @@ class HiddenErrorHandler extends ErrorHandler {
if (!Strings.isNullOrEmpty(req.getQueryString())) {
uri += "?" + req.getQueryString();
}
log.error(String.format("Error in %s %s", req.getMethod(), uri), err);
log.error("Error in {} {}", req.getMethod(), uri, err);
}
}
}

View File

@@ -157,4 +157,17 @@ public abstract class CurrentUser {
public Optional<ExternalId.Key> getLastLoginExternalIdKey() {
return get(lastLoginExternalIdPropertyKey);
}
/**
* Checks if the current user has the same account id of another.
*
* <p>Provide a generic interface for allowing subclasses to define whether two accounts represent
* the same account id.
*
* @param other user to compare
* @return true if the two users have the same account id
*/
public boolean hasSameAccountId(CurrentUser other) {
return false;
}
}

View File

@@ -523,6 +523,11 @@ public class IdentifiedUser extends CurrentUser {
realUser);
}
@Override
public boolean hasSameAccountId(CurrentUser other) {
return getAccountId().get() == other.getAccountId().get();
}
private String guessHost() {
String host = null;
SocketAddress remotePeer = null;

View File

@@ -49,7 +49,7 @@ public class WebLinks {
if (link == null) {
return false;
} else if (Strings.isNullOrEmpty(link.name) || Strings.isNullOrEmpty(link.url)) {
log.warn(String.format("%s is missing name and/or url", link.getClass().getName()));
log.warn("{} is missing name and/or url", link.getClass().getName());
return false;
}
return true;
@@ -60,7 +60,7 @@ public class WebLinks {
if (link == null) {
return false;
} else if (Strings.isNullOrEmpty(link.name) || Strings.isNullOrEmpty(link.url)) {
log.warn(String.format("%s is missing name and/or url", link.getClass().getName()));
log.warn("{} is missing name and/or url", link.getClass().getName());
return false;
}
return true;

View File

@@ -82,7 +82,7 @@ public class GroupCacheImpl implements GroupCache {
try {
return byId.get(groupId);
} catch (ExecutionException e) {
log.warn("Cannot load group " + groupId, e);
log.warn("Cannot load group {}", groupId, e);
return Optional.empty();
}
}
@@ -95,7 +95,7 @@ public class GroupCacheImpl implements GroupCache {
try {
return byName.get(name.get());
} catch (ExecutionException e) {
log.warn(String.format("Cannot look up group %s by name", name.get()), e);
log.warn("Cannot look up group {} by name", name.get(), e);
return Optional.empty();
}
}
@@ -109,7 +109,7 @@ public class GroupCacheImpl implements GroupCache {
try {
return byUUID.get(groupUuid.get());
} catch (ExecutionException e) {
log.warn(String.format("Cannot look up group %s by uuid", groupUuid.get()), e);
log.warn("Cannot look up group {} by uuid", groupUuid.get(), e);
return Optional.empty();
}
}

View File

@@ -127,7 +127,7 @@ public class LdapGroupBackend implements GroupBackend {
return null;
}
} catch (ExecutionException e) {
log.warn(String.format("Cannot lookup group %s in LDAP", groupDn), e);
log.warn("Cannot lookup group {} in LDAP", groupDn, e);
return null;
}
}

View File

@@ -65,7 +65,7 @@ class LdapGroupMembership implements GroupMembership {
try {
membership = new ListGroupMembership(membershipCache.get(id));
} catch (ExecutionException e) {
LdapGroupBackend.log.warn(String.format("Cannot lookup membershipsOf %s in LDAP", id), e);
LdapGroupBackend.log.warn("Cannot lookup membershipsOf {} in LDAP", id, e);
membership = GroupMembership.EMPTY;
}
}

View File

@@ -312,7 +312,7 @@ class LdapRealm extends AbstractRealm {
Optional<Account.Id> id = usernameCache.get(accountName);
return id != null ? id.orElse(null) : null;
} catch (ExecutionException e) {
log.warn(String.format("Cannot lookup account %s in LDAP", accountName), e);
log.warn("Cannot lookup account {} in LDAP", accountName, e);
return null;
}
}

View File

@@ -96,7 +96,7 @@ public class AbandonUtil {
log.error(msg.toString(), e);
}
}
log.info(String.format("Auto-Abandoned %d of %d changes.", count, changesToAbandon.size()));
log.info("Auto-Abandoned {} of {} changes.", count, changesToAbandon.size());
} catch (QueryParseException | OrmException e) {
log.error("Failed to query inactive open changes for auto-abandoning.", e);
}

View File

@@ -158,7 +158,7 @@ public class EventFactory {
try {
a.commitMessage = changeDataFactory.create(db, change).commitMessage();
} catch (Exception e) {
log.error("Error while getting full commit message for change " + a.number, e);
log.error("Error while getting full commit message for change {}", a.number, e);
}
a.url = getChangeUrl(change);
a.owner = asAccountAttribute(change.getOwner());
@@ -523,11 +523,11 @@ public class EventFactory {
}
p.kind = changeKindCache.getChangeKind(db, change, patchSet);
} catch (IOException | OrmException e) {
log.error("Cannot load patch set data for " + patchSet.getId(), e);
log.error("Cannot load patch set data for {}", patchSet.getId(), e);
} catch (PatchListObjectTooLargeException e) {
log.warn(String.format("Cannot get size information for %s: %s", pId, e.getMessage()));
} catch (PatchListNotAvailableException e) {
log.error(String.format("Cannot get size information for %s.", pId), e);
log.error("Cannot get size information for {}.", pId, e);
}
return p;
}

View File

@@ -123,9 +123,9 @@ public class EventUtil {
public void logEventListenerError(Object event, Object listener, Exception error) {
if (log.isDebugEnabled()) {
log.debug(
String.format(
"Error in event listener %s for event %s",
listener.getClass().getName(), event.getClass().getName()),
"Error in event listener {} for event {}",
listener.getClass().getName(),
event.getClass().getName(),
error);
} else {
log.warn(
@@ -138,7 +138,7 @@ public class EventUtil {
public static void logEventListenerError(Object listener, Exception error) {
if (log.isDebugEnabled()) {
log.debug(String.format("Error in event listener %s", listener.getClass().getName()), error);
log.debug("Error in event listener {}", listener.getClass().getName(), error);
} else {
log.warn("Error in event listener {}: {}", listener.getClass().getName(), error.getMessage());
}

View File

@@ -98,7 +98,7 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
} else {
desc = String.format("%d", limit);
}
log.info(String.format("Defaulting core.streamFileThreshold to %s", desc));
log.info("Defaulting core.streamFileThreshold to {}", desc);
cfg.setStreamFileThreshold(limit);
}
cfg.install();
@@ -193,9 +193,7 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
//
File metaConfigLog = new File(db.getDirectory(), "logs/" + RefNames.REFS_CONFIG);
if (!metaConfigLog.getParentFile().mkdirs() || !metaConfigLog.createNewFile()) {
log.error(
String.format(
"Failed to create ref log for %s in repository %s", RefNames.REFS_CONFIG, name));
log.error("Failed to create ref log for {} in repository {}", RefNames.REFS_CONFIG, name);
}
return db;
@@ -248,7 +246,7 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
Integer.MAX_VALUE,
visitor);
} catch (IOException e) {
log.error("Error walking repository tree " + visitor.startFolder.toAbsolutePath(), e);
log.error("Error walking repository tree {}", visitor.startFolder.toAbsolutePath(), e);
}
}
@@ -303,7 +301,7 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
Project.NameKey nameKey = getProjectName(startFolder, p);
if (getBasePath(nameKey).equals(startFolder)) {
if (isUnreasonableName(nameKey)) {
log.warn("Ignoring unreasonably named repository " + p.toAbsolutePath());
log.warn("Ignoring unreasonably named repository {}", p.toAbsolutePath());
} else {
found.add(nameKey);
}

View File

@@ -14,12 +14,8 @@
package com.google.gerrit.server.git;
import com.google.common.base.CaseFormat;
import com.google.common.base.Supplier;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.metrics.Description;
import com.google.gerrit.metrics.MetricMaker;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.ScheduleConfig.Schedule;
@@ -88,19 +84,17 @@ public class WorkQueue {
}
};
private final MetricMaker metrics;
private final ScheduledExecutorService defaultQueue;
private final IdGenerator idGenerator;
private final CopyOnWriteArrayList<Executor> queues;
@Inject
WorkQueue(MetricMaker metrics, IdGenerator idGenerator, @GerritServerConfig Config cfg) {
this(metrics, idGenerator, cfg.getInt("execution", "defaultThreadPoolSize", 1));
WorkQueue(IdGenerator idGenerator, @GerritServerConfig Config cfg) {
this(idGenerator, cfg.getInt("execution", "defaultThreadPoolSize", 1));
}
/** Constructor to allow binding the WorkQueue more explicitly in a vhost setup. */
public WorkQueue(MetricMaker metrics, IdGenerator idGenerator, int defaultThreadPoolSize) {
this.metrics = metrics;
public WorkQueue(IdGenerator idGenerator, int defaultThreadPoolSize) {
this.idGenerator = idGenerator;
this.queues = new CopyOnWriteArrayList<>();
this.defaultQueue = createQueue(defaultThreadPoolSize, "WorkQueue");
@@ -230,86 +224,6 @@ public class WorkQueue {
corePoolSize + 4 // concurrency level
);
queueName = prefix;
buildMetrics(queueName, metrics);
}
private void buildMetrics(String queueName, MetricMaker metric) {
metric.newCallbackMetric(
getMetricName(queueName, "max_pool_size"),
Long.class,
new Description("Maximum allowed number of threads in the pool")
.setGauge()
.setUnit("threads"),
new Supplier<Long>() {
@Override
public Long get() {
return (long) getMaximumPoolSize();
}
});
metric.newCallbackMetric(
getMetricName(queueName, "pool_size"),
Long.class,
new Description("Current number of threads in the pool").setGauge().setUnit("threads"),
new Supplier<Long>() {
@Override
public Long get() {
return (long) getPoolSize();
}
});
metric.newCallbackMetric(
getMetricName(queueName, "active_threads"),
Long.class,
new Description("Number number of threads that are actively executing tasks")
.setGauge()
.setUnit("threads"),
new Supplier<Long>() {
@Override
public Long get() {
return (long) getActiveCount();
}
});
metric.newCallbackMetric(
getMetricName(queueName, "scheduled_tasks"),
Integer.class,
new Description("Number of scheduled tasks in the queue").setGauge().setUnit("tasks"),
new Supplier<Integer>() {
@Override
public Integer get() {
return getQueue().size();
}
});
metric.newCallbackMetric(
getMetricName(queueName, "total_scheduled_tasks_count"),
Long.class,
new Description("Total number of tasks that have been scheduled for execution")
.setCumulative()
.setUnit("tasks"),
new Supplier<Long>() {
@Override
public Long get() {
return (long) getTaskCount();
}
});
metric.newCallbackMetric(
getMetricName(queueName, "total_completed_tasks_count"),
Long.class,
new Description("Total number of tasks that have completed execution")
.setCumulative()
.setUnit("tasks"),
new Supplier<Long>() {
@Override
public Long get() {
return (long) getCompletedTaskCount();
}
});
}
private String getMetricName(String queueName, String metricName) {
String name =
CaseFormat.UPPER_CAMEL.to(
CaseFormat.LOWER_UNDERSCORE,
queueName.replaceFirst("SSH", "Ssh").replaceAll("-", ""));
return String.format("queue/%s/%s", name, metricName);
}
@Override

View File

@@ -200,7 +200,7 @@ public class StalenessChecker {
}
return false;
} catch (IOException e) {
log.warn(String.format("error checking staleness of %s in %s", id, project), e);
log.warn("error checking staleness of {} in {}", id, project, e);
return true;
}
}

View File

@@ -146,9 +146,10 @@ public class MailProcessor {
for (DynamicMap.Entry<MailFilter> filter : mailFilters) {
if (!filter.getProvider().get().shouldProcessMessage(message)) {
log.warn(
String.format(
"Message %s filtered by plugin %s %s. Will delete message.",
message.id(), filter.getPluginName(), filter.getExportName()));
"Message {} filtered by plugin {} {}. Will delete message.",
message.id(),
filter.getPluginName(),
filter.getExportName());
return;
}
}
@@ -157,9 +158,9 @@ public class MailProcessor {
if (!metadata.hasRequiredFields()) {
log.error(
String.format(
"Message %s is missing required metadata, have %s. Will delete message.",
message.id(), metadata));
"Message {} is missing required metadata, have {}. Will delete message.",
message.id(),
metadata);
sendRejectionEmail(message, InboundEmailRejectionSender.Error.PARSING_ERROR);
return;
}
@@ -168,10 +169,10 @@ public class MailProcessor {
if (accountIds.size() != 1) {
log.error(
String.format(
"Address %s could not be matched to a unique account. It was matched to %s. Will delete message.",
metadata.author, accountIds));
"Address {} could not be matched to a unique account. It was matched to {}."
+ " Will delete message.",
metadata.author,
accountIds);
// We don't want to send an email if no accounts are linked to it.
if (accountIds.size() > 1) {
sendRejectionEmail(message, InboundEmailRejectionSender.Error.UNKNOWN_ACCOUNT);
@@ -181,7 +182,7 @@ public class MailProcessor {
Account.Id accountId = accountIds.iterator().next();
Optional<AccountState> accountState = accountCache.get(accountId);
if (!accountState.isPresent()) {
log.warn(String.format("Mail: Account %s doesn't exist. Will delete message.", accountId));
log.warn("Mail: Account {} doesn't exist. Will delete message.", accountId);
return;
}
if (!accountState.get().getAccount().isActive()) {
@@ -211,17 +212,18 @@ public class MailProcessor {
queryProvider.get().byLegacyChangeId(new Change.Id(metadata.changeNumber));
if (changeDataList.size() != 1) {
log.error(
String.format(
"Message %s references unique change %s, but there are %d matching changes in the index. Will delete message.",
message.id(), metadata.changeNumber, changeDataList.size()));
"Message {} references unique change {}, but there are {} matching changes in "
+ "the index. Will delete message.",
message.id(),
metadata.changeNumber,
changeDataList.size());
sendRejectionEmail(message, InboundEmailRejectionSender.Error.INTERNAL_EXCEPTION);
return;
}
ChangeData cd = changeDataList.get(0);
if (existingMessageIds(cd).contains(message.id())) {
log.info(
String.format("Message %s was already processed. Will delete message.", message.id()));
log.info("Message {} was already processed. Will delete message.", message.id());
return;
}
// Get all comments; filter and sort them to get the original list of
@@ -244,9 +246,7 @@ public class MailProcessor {
}
if (parsedComments.isEmpty()) {
log.warn(
String.format(
"Could not parse any comments from %s. Will delete message.", message.id()));
log.warn("Could not parse any comments from {}. Will delete message.", message.id());
sendRejectionEmail(message, InboundEmailRejectionSender.Error.PARSING_ERROR);
return;
}

View File

@@ -228,9 +228,10 @@ public class CommentSender extends ReplyToChangeSender {
currentGroup.fileData = new PatchFile(repo, patchList, c.key.filename);
} catch (IOException e) {
log.warn(
String.format(
"Cannot load %s from %s in %s",
c.key.filename, patchList.getNewId().name(), projectState.getName()),
"Cannot load {} from {} in {}",
c.key.filename,
patchList.getNewId().name(),
projectState.getName(),
e);
currentGroup.fileData = null;
}
@@ -321,7 +322,7 @@ public class CommentSender extends ReplyToChangeSender {
try {
return commentsUtil.getPublished(args.db.get(), changeData.notes(), key);
} catch (OrmException e) {
log.warn("Could not find the parent of this comment: " + child.toString());
log.warn("Could not find the parent of this comment: {}", child.toString());
return Optional.empty();
}
}
@@ -539,16 +540,16 @@ public class CommentSender extends ReplyToChangeSender {
return fileInfo.getLine(side, lineNbr);
} catch (IOException err) {
// Default to the empty string if the file cannot be safely read.
log.warn(String.format("Failed to read file on side %d", side), err);
log.warn("Failed to read file on side {}", side, err);
return "";
} catch (IndexOutOfBoundsException err) {
// Default to the empty string if the given line number does not appear
// in the file.
log.debug(String.format("Failed to get line number of file on side %d", side), err);
log.debug("Failed to get line number of file on side {}", side, err);
return "";
} catch (NoSuchEntityException err) {
// Default to the empty string if the side cannot be found.
log.warn(String.format("Side %d of file didn't exist", side), err);
log.warn("Side {} of file didn't exist", side, err);
return "";
}
}

View File

@@ -148,7 +148,7 @@ public class ChangeNotes extends AbstractChangeNotes<ChangeNotes> {
throw new NoSuchChangeException(changeId);
}
if (changes.size() != 1) {
log.error(String.format("Multiple changes found for %d", changeId.get()));
log.error("Multiple changes found for {}", changeId.get());
throw new NoSuchChangeException(changeId);
}
return changes.get(0).notes();

View File

@@ -129,7 +129,7 @@ public class JarPluginProvider implements ServerPluginProvider {
if (overlay != null) {
Path classes = Paths.get(overlay).resolve(name).resolve("main");
if (Files.isDirectory(classes)) {
log.info(String.format("plugin %s: including %s", name, classes));
log.info("plugin {}: including {}", name, classes);
urls.add(classes.toUri().toURL());
}
}

View File

@@ -165,9 +165,9 @@ public class PluginLoader implements LifecycleListener {
String name = MoreObjects.firstNonNull(getGerritPluginName(tmp), PluginUtil.nameOf(fileName));
if (!originalName.equals(name)) {
log.warn(
String.format(
"Plugin provides its own name: <%s>, use it instead of the input name: <%s>",
name, originalName));
"Plugin provides its own name: <{}>, use it instead of the input name: <{}>",
name,
originalName);
}
String fileExtension = getExtension(fileName);
@@ -176,7 +176,7 @@ public class PluginLoader implements LifecycleListener {
Plugin active = running.get(name);
if (active != null) {
fileName = active.getSrcFile().getFileName().toString();
log.info(String.format("Replacing plugin %s", active.getName()));
log.info("Replacing plugin {}", active.getName());
Path old = pluginsDir.resolve(".last_" + fileName);
Files.deleteIfExists(old);
Files.move(active.getSrcFile(), old);
@@ -187,7 +187,7 @@ public class PluginLoader implements LifecycleListener {
try {
Plugin plugin = runPlugin(name, dst, active);
if (active == null) {
log.info(String.format("Installed plugin %s", plugin.getName()));
log.info("Installed plugin {}", plugin.getName());
}
} catch (PluginInstallException e) {
Files.deleteIfExists(dst);
@@ -203,7 +203,7 @@ public class PluginLoader implements LifecycleListener {
private synchronized void unloadPlugin(Plugin plugin) {
persistentCacheFactory.onStop(plugin.getName());
String name = plugin.getName();
log.info(String.format("Unloading plugin %s, version %s", name, plugin.getVersion()));
log.info("Unloading plugin {}, version {}", name, plugin.getVersion());
plugin.stop(env);
env.onStopPlugin(plugin);
running.remove(name);
@@ -213,7 +213,7 @@ public class PluginLoader implements LifecycleListener {
public void disablePlugins(Set<String> names) {
if (!isRemoteAdminEnabled()) {
log.warn("Remote plugin administration is disabled, ignoring disablePlugins(" + names + ")");
log.warn("Remote plugin administration is disabled, ignoring disablePlugins({})", names);
return;
}
@@ -224,7 +224,7 @@ public class PluginLoader implements LifecycleListener {
continue;
}
log.info(String.format("Disabling plugin %s", active.getName()));
log.info("Disabling plugin {}", active.getName());
Path off =
active.getSrcFile().resolveSibling(active.getSrcFile().getFileName() + ".disabled");
try {
@@ -244,7 +244,7 @@ public class PluginLoader implements LifecycleListener {
disabled.put(name, offPlugin);
} catch (Throwable e) {
// This shouldn't happen, as the plugin was loaded earlier.
log.warn(String.format("Cannot load disabled plugin %s", active.getName()), e.getCause());
log.warn("Cannot load disabled plugin {}", active.getName(), e.getCause());
}
}
cleanInBackground();
@@ -253,7 +253,7 @@ public class PluginLoader implements LifecycleListener {
public void enablePlugins(Set<String> names) throws PluginInstallException {
if (!isRemoteAdminEnabled()) {
log.warn("Remote plugin administration is disabled, ignoring enablePlugins(" + names + ")");
log.warn("Remote plugin administration is disabled, ignoring enablePlugins({})", names);
return;
}
@@ -264,7 +264,7 @@ public class PluginLoader implements LifecycleListener {
continue;
}
log.info(String.format("Enabling plugin %s", name));
log.info("Enabling plugin {}", name);
String n = off.getSrcFile().toFile().getName();
if (n.endsWith(".disabled")) {
n = n.substring(0, n.lastIndexOf('.'));
@@ -273,7 +273,7 @@ public class PluginLoader implements LifecycleListener {
try {
Files.move(off.getSrcFile(), on);
} catch (IOException e) {
log.error("Failed to move plugin " + name + " into place", e);
log.error("Failed to move plugin {} into place", name, e);
continue;
}
disabled.remove(name);
@@ -293,18 +293,16 @@ public class PluginLoader implements LifecycleListener {
};
try (DirectoryStream<Path> files = Files.newDirectoryStream(tempDir, filter)) {
for (Path file : files) {
log.info("Removing stale plugin file: " + file.toFile().getName());
log.info("Removing stale plugin file: {}", file.toFile().getName());
try {
Files.delete(file);
} catch (IOException e) {
log.error(
String.format(
"Failed to remove stale plugin file %s: %s",
file.toFile().getName(), e.getMessage()));
"Failed to remove stale plugin file {}: {}", file.toFile().getName(), e.getMessage());
}
}
} catch (IOException e) {
log.warn("Unable to discover stale plugin files: " + e.getMessage());
log.warn("Unable to discover stale plugin files: {}", e.getMessage());
}
}
@@ -313,14 +311,14 @@ public class PluginLoader implements LifecycleListener {
removeStalePluginFiles();
Path absolutePath = pluginsDir.toAbsolutePath();
if (!Files.exists(absolutePath)) {
log.info(absolutePath + " does not exist; creating");
log.info("{} does not exist; creating", absolutePath);
try {
Files.createDirectories(absolutePath);
} catch (IOException e) {
log.error(String.format("Failed to create %s: %s", absolutePath, e.getMessage()));
log.error("Failed to create {}: {}", absolutePath, e.getMessage());
}
}
log.info("Loading plugins from " + absolutePath);
log.info("Loading plugins from {}", absolutePath);
srvInfoImpl.state = ServerInformation.State.STARTUP;
rescan();
srvInfoImpl.state = ServerInformation.State.RUNNING;
@@ -369,13 +367,11 @@ public class PluginLoader implements LifecycleListener {
for (Plugin active : reload) {
String name = active.getName();
try {
log.info(String.format("Reloading plugin %s", name));
log.info("Reloading plugin {}", name);
Plugin newPlugin = runPlugin(name, active.getSrcFile(), active);
log.info(
String.format(
"Reloaded plugin %s, version %s", newPlugin.getName(), newPlugin.getVersion()));
log.info("Reloaded plugin {}, version {}", newPlugin.getName(), newPlugin.getVersion());
} catch (PluginInstallException e) {
log.warn(String.format("Cannot reload plugin %s", name), e.getCause());
log.warn("Cannot reload plugin {}", name, e.getCause());
throw e;
}
}
@@ -413,21 +409,20 @@ public class PluginLoader implements LifecycleListener {
}
if (active != null) {
log.info(String.format("Reloading plugin %s", active.getName()));
log.info("Reloading plugin {}", active.getName());
}
try {
Plugin loadedPlugin = runPlugin(name, path, active);
if (!loadedPlugin.isDisabled()) {
log.info(
String.format(
"%s plugin %s, version %s",
active == null ? "Loaded" : "Reloaded",
loadedPlugin.getName(),
loadedPlugin.getVersion()));
"{} plugin {}, version {}",
active == null ? "Loaded" : "Reloaded",
loadedPlugin.getName(),
loadedPlugin.getVersion());
}
} catch (PluginInstallException e) {
log.warn(String.format("Cannot load plugin %s", name), e.getCause());
log.warn("Cannot load plugin {}", name, e.getCause());
}
}
@@ -661,18 +656,19 @@ public class PluginLoader implements LifecycleListener {
Collection<Path> elementsToAdd = new ArrayList<>();
for (Path loser : Iterables.skip(enabled, 1)) {
log.warn(
String.format(
"Plugin <%s> was disabled, because"
+ " another plugin <%s>"
+ " with the same name <%s> already exists",
loser, winner, plugin));
"Plugin <{}> was disabled, because"
+ " another plugin <{}>"
+ " with the same name <{}> already exists",
loser,
winner,
plugin);
Path disabledPlugin = Paths.get(loser + ".disabled");
elementsToAdd.add(disabledPlugin);
elementsToRemove.add(loser);
try {
Files.move(loser, disabledPlugin);
} catch (IOException e) {
log.warn("Failed to fully disable plugin " + loser, e);
log.warn("Failed to fully disable plugin {}", loser, e);
}
}
Iterables.removeAll(files, elementsToRemove);
@@ -685,7 +681,7 @@ public class PluginLoader implements LifecycleListener {
try {
return PluginUtil.listPlugins(pluginsDir);
} catch (IOException e) {
log.error("Cannot list " + pluginsDir.toAbsolutePath(), e);
log.error("Cannot list {}", pluginsDir.toAbsolutePath(), e);
return ImmutableList.of();
}
}

View File

@@ -66,6 +66,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
@@ -77,7 +78,6 @@ import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.util.StringUtils;
public class ProjectConfig extends VersionedMetaData implements ValidationError.Sink {
public static final String COMMENTLINK = "commentlink";
@@ -1179,7 +1179,7 @@ public class ProjectConfig extends VersionedMetaData implements ValidationError.
List<String> types = new ArrayList<>(4);
for (NotifyType t : NotifyType.values()) {
if (nc.isNotify(t)) {
types.add(StringUtils.toLowerCase(t.name()));
types.add(t.name().toLowerCase(Locale.US));
}
}
rc.setStringList(NOTIFY, nc.getName(), KEY_TYPE, types);

View File

@@ -26,6 +26,7 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import com.google.gerrit.common.data.GroupDescription;
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.common.data.SubmitRecord;
import com.google.gerrit.common.errors.NotSignedInException;
@@ -772,18 +773,8 @@ public class ChangeQueryBuilder extends QueryBuilder<ChangeData> {
}
}
// expand a group predicate into multiple user predicates
if (group != null) {
Set<Account.Id> allMembers =
args.groupMembers.listAccounts(group).stream().map(Account::getId).collect(toSet());
int maxTerms = args.indexConfig.maxTerms();
if (allMembers.size() > maxTerms) {
// limit the number of query terms otherwise Gerrit will barf
accounts = ImmutableSet.copyOf(Iterables.limit(allMembers, maxTerms));
} else {
accounts = allMembers;
}
accounts = getMembers(group);
}
// If the vote piece looks like Code-Review=NEED with a valid non-numeric
@@ -972,12 +963,24 @@ public class ChangeQueryBuilder extends QueryBuilder<ChangeData> {
}
@Operator
public Predicate<ChangeData> ownerin(String group) throws QueryParseException {
public Predicate<ChangeData> ownerin(String group) throws QueryParseException, IOException {
GroupReference g = GroupBackends.findBestSuggestion(args.groupBackend, group);
if (g == null) {
throw error("Group " + group + " not found");
}
return new OwnerinPredicate(args.userFactory, g.getUUID());
AccountGroup.UUID groupId = g.getUUID();
GroupDescription.Basic groupDescription = args.groupBackend.get(groupId);
if (!(groupDescription instanceof GroupDescription.Internal)) {
return new OwnerinPredicate(args.userFactory, groupId);
}
Set<Account.Id> accounts = getMembers(groupId);
List<OwnerPredicate> p = Lists.newArrayListWithCapacity(accounts.size());
for (Account.Id id : accounts) {
p.add(new OwnerPredicate(id));
}
return Predicate.or(p);
}
@Operator
@@ -1248,6 +1251,20 @@ public class ChangeQueryBuilder extends QueryBuilder<ChangeData> {
return Predicate.and(predicates);
}
private Set<Account.Id> getMembers(AccountGroup.UUID g) throws IOException {
Set<Account.Id> accounts;
Set<Account.Id> allMembers =
args.groupMembers.listAccounts(g).stream().map(Account::getId).collect(toSet());
int maxTerms = args.indexConfig.maxTerms();
if (allMembers.size() > maxTerms) {
// limit the number of query terms otherwise Gerrit will barf
accounts = ImmutableSet.copyOf(Iterables.limit(allMembers, maxTerms));
} else {
accounts = allMembers;
}
return accounts;
}
private Set<Account.Id> parseAccount(String who)
throws QueryParseException, OrmException, IOException, ConfigInvalidException {
if (isSelf(who)) {

View File

@@ -74,7 +74,7 @@ public class AddSshKey implements RestModifyView<AccountResource, SshKeyInput> {
public Response<SshKeyInfo> apply(AccountResource rsrc, SshKeyInput input)
throws AuthException, BadRequestException, OrmException, IOException, ConfigInvalidException,
PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
}
return apply(rsrc.getUser(), input);

View File

@@ -66,7 +66,7 @@ class Capabilities implements ChildCollection<AccountResource, AccountResource.C
throws ResourceNotFoundException, AuthException, PermissionBackendException {
permissionBackend.checkUsesDefaultCapabilities();
IdentifiedUser target = parent.getUser();
if (self.get() != target) {
if (!self.get().hasSameAccountId(target)) {
permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
}

View File

@@ -95,7 +95,7 @@ public class CreateEmail implements RestModifyView<AccountResource, EmailInput>
input = new EmailInput();
}
if (self.get() != rsrc.getUser() || input.noConfirmation) {
if (!self.get().hasSameAccountId(rsrc.getUser()) || input.noConfirmation) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
}

View File

@@ -47,7 +47,7 @@ public class DeleteActive implements RestModifyView<AccountResource, Input> {
@Override
public Response<?> apply(AccountResource rsrc, Input input)
throws RestApiException, OrmException, IOException, ConfigInvalidException {
if (self.get() == rsrc.getUser()) {
if (self.get().hasSameAccountId(rsrc.getUser())) {
throw new ResourceConflictException("cannot deactivate own account");
}
return setInactiveFlag.deactivate(rsrc.getUser().getAccountId());

View File

@@ -71,7 +71,7 @@ public class DeleteEmail implements RestModifyView<AccountResource.Email, Input>
throws AuthException, ResourceNotFoundException, ResourceConflictException,
MethodNotAllowedException, OrmException, IOException, ConfigInvalidException,
PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
}
return apply(rsrc.getUser(), rsrc.getEmail());

View File

@@ -68,7 +68,7 @@ public class DeleteExternalIds implements RestModifyView<AccountResource, List<S
public Response<?> apply(AccountResource resource, List<String> extIds)
throws RestApiException, IOException, OrmException, ConfigInvalidException,
PermissionBackendException {
if (self.get() != resource.getUser()) {
if (!self.get().hasSameAccountId(resource.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ACCESS_DATABASE);
}

View File

@@ -57,7 +57,7 @@ public class DeleteSshKey implements RestModifyView<AccountResource.SshKey, Inpu
public Response<?> apply(AccountResource.SshKey rsrc, Input input)
throws AuthException, OrmException, RepositoryNotFoundException, IOException,
ConfigInvalidException, PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
}

View File

@@ -61,7 +61,7 @@ public class DeleteWatchedProjects
public Response<?> apply(AccountResource rsrc, List<ProjectWatchInfo> input)
throws AuthException, UnprocessableEntityException, OrmException, IOException,
ConfigInvalidException, PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
}
if (input == null) {

View File

@@ -64,7 +64,7 @@ public class EmailsCollection
@Override
public AccountResource.Email parse(AccountResource rsrc, IdString id)
throws ResourceNotFoundException, PermissionBackendException, AuthException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
}

View File

@@ -79,12 +79,13 @@ class GetCapabilities implements RestReadView<AccountResource> {
}
@Override
public Object apply(AccountResource rsrc) throws RestApiException, PermissionBackendException {
public Object apply(AccountResource resource)
throws RestApiException, PermissionBackendException {
permissionBackend.checkUsesDefaultCapabilities();
PermissionBackend.WithUser perm = permissionBackend.currentUser();
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(resource.getUser())) {
perm.check(GlobalPermission.ADMINISTRATE_SERVER);
perm = permissionBackend.user(rsrc.getUser());
perm = permissionBackend.user(resource.getUser());
}
Map<String, Object> have = new LinkedHashMap<>();
@@ -92,7 +93,7 @@ class GetCapabilities implements RestReadView<AccountResource> {
have.put(globalOrPluginPermissionName(p), true);
}
AccountLimits limits = limitsFactory.create(rsrc.getUser());
AccountLimits limits = limitsFactory.create(resource.getUser());
addRanges(have, limits);
addPriority(have, limits);

View File

@@ -50,7 +50,7 @@ public class GetEditPreferences implements RestReadView<AccountResource> {
@Override
public EditPreferencesInfo apply(AccountResource rsrc)
throws RestApiException, IOException, ConfigInvalidException, PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
}

View File

@@ -61,7 +61,7 @@ public class GetExternalIds implements RestReadView<AccountResource> {
@Override
public List<AccountExternalIdInfo> apply(AccountResource resource)
throws RestApiException, IOException, OrmException, PermissionBackendException {
if (self.get() != resource.getUser()) {
if (!self.get().hasSameAccountId(resource.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ACCESS_DATABASE);
}

View File

@@ -53,7 +53,7 @@ class GetOAuthToken implements RestReadView<AccountResource> {
@Override
public OAuthTokenInfo apply(AccountResource rsrc)
throws AuthException, ResourceNotFoundException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
throw new AuthException("not allowed to get access token");
}
OAuthToken accessToken = tokenCache.get(rsrc.getUser().getAccountId());

View File

@@ -48,7 +48,7 @@ public class GetPreferences implements RestReadView<AccountResource> {
@Override
public GeneralPreferencesInfo apply(AccountResource rsrc)
throws RestApiException, PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
}

View File

@@ -57,7 +57,7 @@ public class GetSshKeys implements RestReadView<AccountResource> {
public List<SshKeyInfo> apply(AccountResource rsrc)
throws AuthException, OrmException, RepositoryNotFoundException, IOException,
ConfigInvalidException, PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
}
return apply(rsrc.getUser());

View File

@@ -61,7 +61,7 @@ public class GetWatchedProjects implements RestReadView<AccountResource> {
public List<ProjectWatchInfo> apply(AccountResource rsrc)
throws OrmException, AuthException, IOException, ConfigInvalidException,
PermissionBackendException, ResourceNotFoundException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
}

View File

@@ -49,7 +49,7 @@ public class Index implements RestModifyView<AccountResource, Input> {
@Override
public Response<?> apply(AccountResource rsrc, Input input)
throws IOException, AuthException, PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
}

View File

@@ -68,7 +68,7 @@ public class PostWatchedProjects
public List<ProjectWatchInfo> apply(AccountResource rsrc, List<ProjectWatchInfo> input)
throws OrmException, RestApiException, IOException, ConfigInvalidException,
PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
}

View File

@@ -72,7 +72,7 @@ public class PutAgreement implements RestModifyView<AccountResource, AgreementIn
throw new MethodNotAllowedException("contributor agreements disabled");
}
if (self.get() != resource.getUser()) {
if (!self.get().hasSameAccountId(resource.getUser())) {
throw new AuthException("not allowed to enter contributor agreement");
}

View File

@@ -76,7 +76,7 @@ public class PutHttpPassword implements RestModifyView<AccountResource, HttpPass
public Response<String> apply(AccountResource rsrc, HttpPasswordInput input)
throws AuthException, ResourceNotFoundException, ResourceConflictException, OrmException,
IOException, ConfigInvalidException, PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
}

View File

@@ -62,7 +62,7 @@ public class PutName implements RestModifyView<AccountResource, NameInput> {
public Response<String> apply(AccountResource rsrc, NameInput input)
throws AuthException, MethodNotAllowedException, ResourceNotFoundException, OrmException,
IOException, PermissionBackendException, ConfigInvalidException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
}
return apply(rsrc.getUser(), input);

View File

@@ -56,7 +56,7 @@ public class PutStatus implements RestModifyView<AccountResource, StatusInput> {
public Response<String> apply(AccountResource rsrc, StatusInput input)
throws AuthException, ResourceNotFoundException, OrmException, IOException,
PermissionBackendException, ConfigInvalidException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
}
return apply(rsrc.getUser(), input);

View File

@@ -75,7 +75,7 @@ public class PutUsername implements RestModifyView<AccountResource, UsernameInpu
throws AuthException, MethodNotAllowedException, UnprocessableEntityException,
ResourceConflictException, OrmException, IOException, ConfigInvalidException,
PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
}

View File

@@ -66,7 +66,7 @@ public class SshKeys implements ChildCollection<AccountResource, AccountResource
public AccountResource.SshKey parse(AccountResource rsrc, IdString id)
throws ResourceNotFoundException, OrmException, IOException, ConfigInvalidException,
PermissionBackendException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
try {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
} catch (AuthException e) {

View File

@@ -135,7 +135,7 @@ public class StarredChanges
@Override
public Response<?> apply(AccountResource rsrc, EmptyInput in)
throws RestApiException, OrmException, IOException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
throw new AuthException("not allowed to add starred change");
}
try {
@@ -168,7 +168,7 @@ public class StarredChanges
@Override
public Response<?> apply(AccountResource.StarredChange rsrc, EmptyInput in)
throws AuthException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
throw new AuthException("not allowed update starred changes");
}
return Response.none();
@@ -189,7 +189,7 @@ public class StarredChanges
@Override
public Response<?> apply(AccountResource.StarredChange rsrc, EmptyInput in)
throws AuthException, OrmException, IOException, IllegalLabelException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
throw new AuthException("not allowed remove starred change");
}
starredChangesUtil.star(

View File

@@ -100,7 +100,7 @@ public class Stars implements ChildCollection<AccountResource, AccountResource.S
@SuppressWarnings("unchecked")
public List<ChangeInfo> apply(AccountResource rsrc)
throws BadRequestException, AuthException, OrmException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
throw new AuthException("not allowed to list stars of another account");
}
QueryChanges query = changes.list();
@@ -122,7 +122,7 @@ public class Stars implements ChildCollection<AccountResource, AccountResource.S
@Override
public SortedSet<String> apply(AccountResource.Star rsrc) throws AuthException, OrmException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
throw new AuthException("not allowed to get stars of another account");
}
return starredChangesUtil.getLabels(self.get().getAccountId(), rsrc.getChange().getId());
@@ -143,7 +143,7 @@ public class Stars implements ChildCollection<AccountResource, AccountResource.S
@Override
public Collection<String> apply(AccountResource.Star rsrc, StarsInput in)
throws AuthException, BadRequestException, OrmException {
if (self.get() != rsrc.getUser()) {
if (!self.get().hasSameAccountId(rsrc.getUser())) {
throw new AuthException("not allowed to update stars of another account");
}
try {

View File

@@ -164,7 +164,7 @@ public class PutConfig implements RestModifyView<ProjectResource, ConfigInput> {
throw new ResourceConflictException(
"Cannot update " + projectName + ": " + e.getCause().getMessage());
}
log.warn(String.format("Failed to update config of project %s.", projectName), e);
log.warn("Failed to update config of project {}.", projectName, e);
throw new ResourceConflictException("Cannot update " + projectName);
}
@@ -253,9 +253,9 @@ public class PutConfig implements RestModifyView<ProjectResource, ConfigInput> {
break;
default:
log.warn(
String.format(
"The type '%s' of parameter '%s' is not supported.",
projectConfigEntry.getType().name(), v.getKey()));
"The type '{}' of parameter '{}' is not supported.",
projectConfigEntry.getType().name(),
v.getKey());
}
} catch (NumberFormatException ex) {
throw new BadRequestException(

View File

@@ -155,6 +155,24 @@ limitations under the License.
display: none;
}
}
.truncatedProject {
display: none;
}
@media only screen and (max-width: 90em) {
.assignee,
.branch,
.owner {
overflow: hidden;
max-width: 10rem;
text-overflow: ellipsis;
}
.truncatedProject {
display: inline-block;
}
.fullProject {
display: none;
}
}
@media only screen and (max-width: 50em) {
:host {
font-size: var(--font-size-large);