use of com.google.common.collect.ListMultimap in project hbase by apache.
the class AccessControlLists method loadAll.
/**
* Loads all of the permission grants stored in a region of the {@code _acl_}
* table.
*
* @param aclRegion
* @return a map of the permissions for this table.
* @throws IOException
*/
static Map<byte[], ListMultimap<String, TablePermission>> loadAll(Region aclRegion) throws IOException {
if (!isAclRegion(aclRegion)) {
throw new IOException("Can only load permissions from " + ACL_TABLE_NAME);
}
Map<byte[], ListMultimap<String, TablePermission>> allPerms = new TreeMap<>(Bytes.BYTES_RAWCOMPARATOR);
// do a full scan of _acl_ table
Scan scan = new Scan();
scan.addFamily(ACL_LIST_FAMILY);
InternalScanner iScanner = null;
try {
iScanner = aclRegion.getScanner(scan);
while (true) {
List<Cell> row = new ArrayList<>();
boolean hasNext = iScanner.next(row);
ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
byte[] entry = null;
for (Cell kv : row) {
if (entry == null) {
entry = CellUtil.cloneRow(kv);
}
Pair<String, TablePermission> permissionsOfUserOnTable = parsePermissionRecord(entry, kv);
if (permissionsOfUserOnTable != null) {
String username = permissionsOfUserOnTable.getFirst();
TablePermission permissions = permissionsOfUserOnTable.getSecond();
perms.put(username, permissions);
}
}
if (entry != null) {
allPerms.put(entry, perms);
}
if (!hasNext) {
break;
}
}
} finally {
if (iScanner != null) {
iScanner.close();
}
}
return allPerms;
}
use of com.google.common.collect.ListMultimap in project hbase by apache.
the class AccessControlLists method loadAll.
/**
* Load all permissions from the region server holding {@code _acl_},
* primarily intended for testing purposes.
*/
static Map<byte[], ListMultimap<String, TablePermission>> loadAll(Configuration conf) throws IOException {
Map<byte[], ListMultimap<String, TablePermission>> allPerms = new TreeMap<>(Bytes.BYTES_RAWCOMPARATOR);
// do a full scan of _acl_, filtering on only first table region rows
Scan scan = new Scan();
scan.addFamily(ACL_LIST_FAMILY);
ResultScanner scanner = null;
// TODO: Pass in a Connection rather than create one each time.
try (Connection connection = ConnectionFactory.createConnection(conf)) {
try (Table table = connection.getTable(ACL_TABLE_NAME)) {
scanner = table.getScanner(scan);
try {
for (Result row : scanner) {
ListMultimap<String, TablePermission> resultPerms = parsePermissions(row.getRow(), row);
allPerms.put(row.getRow(), resultPerms);
}
} finally {
if (scanner != null)
scanner.close();
}
}
}
return allPerms;
}
use of com.google.common.collect.ListMultimap in project guice by google.
the class CycleDetectingLockTest method testCycleReporting.
/**
* Verifies that factories deadlocks report the correct cycles.
*
* <pre>
* Thread 1: takes locks a, b
* Thread 2: takes locks b, c
* Thread 3: takes locks c, a
* </pre>
*
* <p>In order to ensure a deadlock, each thread will wait on a barrier right after grabbing the
* first lock.
*/
public void testCycleReporting() throws Exception {
final CycleDetectingLockFactory<String> factory = new CycleDetectingLockFactory<String>();
final CycleDetectingLock<String> lockA = factory.create("a");
final CycleDetectingLock<String> lockB = factory.create("b");
final CycleDetectingLock<String> lockC = factory.create("c");
final CyclicBarrier barrier = new CyclicBarrier(3);
ImmutableList<Future<ListMultimap<Thread, String>>> futures = ImmutableList.of(grabLocksInThread(lockA, lockB, barrier), grabLocksInThread(lockB, lockC, barrier), grabLocksInThread(lockC, lockA, barrier));
// At least one of the threads will report a lock cycle, it is possible that they all will, but
// there is no guarantee, so we just scan for the first thread that reported a cycle
ListMultimap<Thread, String> cycle = null;
for (Future<ListMultimap<Thread, String>> future : futures) {
ListMultimap<Thread, String> value = future.get(DEADLOCK_TIMEOUT_SECONDS * 3, TimeUnit.SECONDS);
if (!value.isEmpty()) {
cycle = value;
break;
}
}
// We don't really care about the keys in the multimap, but we want to make sure that all locks
// were reported in the right order.
assertEquals(6, cycle.size());
Collection<List<String>> edges = Multimaps.asMap(cycle).values();
assertTrue(edges.contains(ImmutableList.of("a", "b")));
assertTrue(edges.contains(ImmutableList.of("b", "c")));
assertTrue(edges.contains(ImmutableList.of("c", "a")));
}
use of com.google.common.collect.ListMultimap in project gerrit by GerritCodeReview.
the class PostReview method apply.
public Response<ReviewResult> apply(BatchUpdate.Factory updateFactory, RevisionResource revision, ReviewInput input, Timestamp ts) throws RestApiException, UpdateException, OrmException, IOException, PermissionBackendException {
// Respect timestamp, but truncate at change created-on time.
ts = Ordering.natural().max(ts, revision.getChange().getCreatedOn());
if (revision.getEdit().isPresent()) {
throw new ResourceConflictException("cannot post review on edit");
}
if (input.onBehalfOf != null) {
revision = onBehalfOf(revision, input);
} else if (input.drafts == null) {
input.drafts = DraftHandling.DELETE;
}
if (input.labels != null) {
checkLabels(revision, input.strictLabels, input.labels);
}
if (input.comments != null) {
cleanUpComments(input.comments);
checkComments(revision, input.comments);
}
if (input.robotComments != null) {
if (!migration.readChanges()) {
throw new MethodNotAllowedException("robot comments not supported");
}
checkRobotComments(revision, input.robotComments);
}
if (input.notify == null) {
log.warn("notify = null; assuming notify = NONE");
input.notify = NotifyHandling.NONE;
}
ListMultimap<RecipientType, Account.Id> accountsToNotify = notifyUtil.resolveAccounts(input.notifyDetails);
Map<String, AddReviewerResult> reviewerJsonResults = null;
List<PostReviewers.Addition> reviewerResults = Lists.newArrayList();
boolean hasError = false;
boolean confirm = false;
if (input.reviewers != null) {
reviewerJsonResults = Maps.newHashMap();
for (AddReviewerInput reviewerInput : input.reviewers) {
// Prevent notifications because setting reviewers is batched.
reviewerInput.notify = NotifyHandling.NONE;
PostReviewers.Addition result = postReviewers.prepareApplication(revision.getChangeResource(), reviewerInput, true);
reviewerJsonResults.put(reviewerInput.reviewer, result.result);
if (result.result.error != null) {
hasError = true;
continue;
}
if (result.result.confirm != null) {
confirm = true;
continue;
}
reviewerResults.add(result);
}
}
ReviewResult output = new ReviewResult();
output.reviewers = reviewerJsonResults;
if (hasError || confirm) {
return Response.withStatusCode(SC_BAD_REQUEST, output);
}
output.labels = input.labels;
try (BatchUpdate bu = updateFactory.create(db.get(), revision.getChange().getProject(), revision.getUser(), ts)) {
Account.Id id = revision.getUser().getAccountId();
boolean ccOrReviewer = false;
if (input.labels != null && !input.labels.isEmpty()) {
ccOrReviewer = input.labels.values().stream().filter(v -> v != 0).findFirst().isPresent();
}
if (!ccOrReviewer) {
// Check if user was already CCed or reviewing prior to this review.
ReviewerSet currentReviewers = approvalsUtil.getReviewers(db.get(), revision.getChangeResource().getNotes());
ccOrReviewer = currentReviewers.all().contains(id);
}
// themselves as a reviewer or to the CC list.
for (PostReviewers.Addition reviewerResult : reviewerResults) {
bu.addOp(revision.getChange().getId(), reviewerResult.op);
if (!ccOrReviewer && reviewerResult.result.reviewers != null) {
for (ReviewerInfo reviewerInfo : reviewerResult.result.reviewers) {
if (Objects.equals(id.get(), reviewerInfo._accountId)) {
ccOrReviewer = true;
break;
}
}
}
if (!ccOrReviewer && reviewerResult.result.ccs != null) {
for (AccountInfo accountInfo : reviewerResult.result.ccs) {
if (Objects.equals(id.get(), accountInfo._accountId)) {
ccOrReviewer = true;
break;
}
}
}
}
if (!ccOrReviewer) {
// User posting this review isn't currently in the reviewer or CC list,
// isn't being explicitly added, and isn't voting on any label.
// Automatically CC them on this change so they receive replies.
PostReviewers.Addition selfAddition = postReviewers.ccCurrentUser(revision.getUser(), revision);
bu.addOp(revision.getChange().getId(), selfAddition.op);
}
bu.addOp(revision.getChange().getId(), new Op(revision.getPatchSet().getId(), input, accountsToNotify));
bu.execute();
for (PostReviewers.Addition reviewerResult : reviewerResults) {
reviewerResult.gatherResults();
}
emailReviewers(revision.getChange(), reviewerResults, input.notify, accountsToNotify);
}
return Response.ok(output);
}
use of com.google.common.collect.ListMultimap in project gerrit by GerritCodeReview.
the class JarScanner method scan.
@Override
public Map<Class<? extends Annotation>, Iterable<ExtensionMetaData>> scan(String pluginName, Iterable<Class<? extends Annotation>> annotations) throws InvalidPluginException {
Set<String> descriptors = new HashSet<>();
ListMultimap<String, JarScanner.ClassData> rawMap = MultimapBuilder.hashKeys().arrayListValues().build();
Map<Class<? extends Annotation>, String> classObjToClassDescr = new HashMap<>();
for (Class<? extends Annotation> annotation : annotations) {
String descriptor = Type.getType(annotation).getDescriptor();
descriptors.add(descriptor);
classObjToClassDescr.put(annotation, descriptor);
}
Enumeration<JarEntry> e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry entry = e.nextElement();
if (skip(entry)) {
continue;
}
ClassData def = new ClassData(descriptors);
try {
new ClassReader(read(jarFile, entry)).accept(def, SKIP_ALL);
} catch (IOException err) {
throw new InvalidPluginException("Cannot auto-register", err);
} catch (RuntimeException err) {
PluginLoader.log.warn(String.format("Plugin %s has invalid class file %s inside of %s", pluginName, entry.getName(), jarFile.getName()), err);
continue;
}
if (!Strings.isNullOrEmpty(def.annotationName)) {
if (def.isConcrete()) {
rawMap.put(def.annotationName, def);
} else {
PluginLoader.log.warn(String.format("Plugin %s tries to @%s(\"%s\") abstract class %s", pluginName, def.annotationName, def.annotationValue, def.className));
}
}
}
ImmutableMap.Builder<Class<? extends Annotation>, Iterable<ExtensionMetaData>> result = ImmutableMap.builder();
for (Class<? extends Annotation> annotoation : annotations) {
String descr = classObjToClassDescr.get(annotoation);
Collection<ClassData> discoverdData = rawMap.get(descr);
Collection<ClassData> values = firstNonNull(discoverdData, Collections.<ClassData>emptySet());
result.put(annotoation, transform(values, cd -> new ExtensionMetaData(cd.className, cd.annotationValue)));
}
return result.build();
}
Aggregations