io.dropwizard.jersey.params.LongParam Java Examples

The following examples show how to use io.dropwizard.jersey.params.LongParam. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GroupsResourceTest.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
@Test public void getSpecificIncludesAllTheThings() {
  when(groupDAO.getGroupById(4444)).thenReturn(Optional.of(group));

  SanitizedSecret secret =
      SanitizedSecret.of(1, "name", null, "checksum", now, "creator", now, "creator", null, null,
          null, 1136214245, 125L, now, "creator");
  when(aclDAO.getSanitizedSecretsFor(group)).thenReturn(ImmutableSet.of(secret));

  Client client =
      new Client(1, "client", "desc", null, now, "creator", now, "creator", null, null, true, false
      );
  when(aclDAO.getClientsFor(group)).thenReturn(ImmutableSet.of(client));

  GroupDetailResponse response = resource.getGroup(user, new LongParam("4444"));

  assertThat(response.getId()).isEqualTo(group.getId());
  assertThat(response.getName()).isEqualTo(group.getName());
  assertThat(response.getDescription()).isEqualTo(group.getDescription());
  assertThat(response.getCreationDate()).isEqualTo(group.getCreatedAt());
  assertThat(response.getCreatedBy()).isEqualTo(group.getCreatedBy());
  assertThat(response.getUpdateDate()).isEqualTo(group.getUpdatedAt());
  assertThat(response.getUpdatedBy()).isEqualTo(group.getUpdatedBy());
  assertThat(response.getSecrets()).containsExactly(secret);
  assertThat(response.getClients()).containsExactly(client);
}
 
Example #2
Source File: ClientsResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Delete Client by ID
 *
 * @param user     the admin user deleting this client
 * @param clientId the ID of the Client to be deleted
 * @return 200 if the deletion was successful, 404 if the client was not found
 * <p>
 * description Deletes a single Client if found. Used by Keywhiz CLI and the web ui.
 * <p>
 * responseMessage 200 Found and deleted Client with given ID
 * <p>
 * responseMessage 404 Client with given ID not Found
 */
@Path("{clientId}")
@Timed @ExceptionMetered
@DELETE
public Response deleteClient(@Auth User user, @PathParam("clientId") LongParam clientId) {
  logger.info("User '{}' deleting client id={}.", user, clientId);

  Optional<Client> client = clientDAO.getClientById(clientId.get());
  if (!client.isPresent()) {
    throw new NotFoundException("Client not found.");
  }

  clientDAO.deleteClient(client.get());

  auditLog.recordEvent(
      new Event(Instant.now(), EventTag.CLIENT_DELETE, user.getName(), client.get().getName()));

  return Response.noContent().build();
}
 
Example #3
Source File: BlobStoreResource1.java    From emodb with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a list of content items in a particular table.
 */
@GET
@Path("{table}")
@RequiresPermissions("blob|read|{table}")
@Timed(name = "bv.emodb.blob.BlobStoreResource1.scanMetadata", absolute = true)
@ApiOperation (value = "Retrieves a list of content items in a particular table.",
        notes = "Retuns BlobMetadata.",
        response = BlobMetadata.class
)
public Iterator<BlobMetadata> scanMetadata(@PathParam("table") String table,
                                           @QueryParam("from") String blobId,
                                           @QueryParam("limit") @DefaultValue("10") LongParam limit,
                                           @Authenticated Subject subject) {
    _scanMetadataRequestsByApiKey.getUnchecked(subject.getId()).mark();
    return streamingIterator(_blobStore.scanMetadata(table, Strings.emptyToNull(blobId), limit.get()));
}
 
Example #4
Source File: DataStoreResource1.java    From emodb with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all recorded history for a piece of content in the data store.
 */
@GET
@Path ("{table}/{key}/timeline")
@RequiresPermissions ("sor|read|{table}")
@Timed (name = "bv.emodb.sor.DataStoreResource1.getTimeline", absolute = true)
@ApiOperation (value = "Retrieves all recorded history for a piece of content in the data store.",
        notes = "Retrieves all recorded history for a piece of content in the data store.",
        response = Iterator.class
)
public Iterator<Change> getTimeline(@PathParam ("table") String table,
                                    @PathParam ("key") String key,
                                    @QueryParam ("data") @DefaultValue ("true") BooleanParam includeContentData,
                                    @QueryParam ("audit") @DefaultValue ("false") BooleanParam includeAuditInformation,
                                    @QueryParam ("start") String startParam,
                                    @QueryParam ("end") String endParam,
                                    @QueryParam ("reversed") @DefaultValue ("true") BooleanParam reversed,
                                    @QueryParam ("limit") @DefaultValue ("10") LongParam limit,
                                    @QueryParam ("consistency") @DefaultValue ("STRONG") ReadConsistencyParam consistency) {
    // For the REST API, start & end may be either UUIDs or ISO 8601 timestamps.  If timestamps, they are inclusive
    // w/granularity of a millisecond so adjust upper endpoints to be the last valid time UUID for the millisecond.
    UUID start = parseUuidOrTimestamp(startParam, reversed.get());
    UUID end = parseUuidOrTimestamp(endParam, !reversed.get());

    return streamingIterator(_dataStore.getTimeline(table, key, includeContentData.get(),
            includeAuditInformation.get(), start, end, reversed.get(), limit.get(), consistency.get()), null);
}
 
Example #5
Source File: DataStoreResource1.java    From emodb with Apache License 2.0 6 votes vote down vote up
@GET
@Path ("_table")
@Timed (name = "bv.emodb.sor.DataStoreResource1.listTables", absolute = true)
@Unbuffered
@ApiOperation (value = "Returns all the existing tables",
        notes = "Returns a Iterator of Table",
        response = Table.class
)
public Object listTables(final @QueryParam ("from") String fromKeyExclusive,
                         final @QueryParam ("limit") @DefaultValue ("10") LongParam limitParam,
                         final @Authenticated Subject subject) {
    Iterator<Table> allTables = _dataStore.listTables(Strings.emptyToNull(fromKeyExclusive), Long.MAX_VALUE);
    return new FilteredJsonStreamingOutput<Table>(allTables, limitParam.get()) {
        @Override
        public boolean include(Table table) {
            return subject.hasPermission(Permissions.readSorTable(new NamedResource(table.getName())));
        }
    };
}
 
Example #6
Source File: DedupQueueResource1.java    From emodb with Apache License 2.0 6 votes vote down vote up
@GET
@Path("{queue}/size")
@RequiresPermissions("queue|get_status|{queue}")
@Timed(name = "bv.emodb.dedupq.DedupQueueResource1.getMessageCount", absolute = true)
@ApiOperation (value = "Gets the messsage count.",
        notes = "Returns a long.",
        response = long.class
)
public long getMessageCount(@QueryParam("partitioned") BooleanParam partitioned,
                            @PathParam("queue") String queue, @QueryParam("limit") LongParam limit,
                            @Authenticated Subject subject) {
    // Call different getMessageCount* methods to collect metrics data that distinguish limited vs. unlimited calls.
    if (limit == null || limit.get() == Long.MAX_VALUE) {
        return getService(partitioned, subject.getAuthenticationId()).getMessageCount(queue);
    } else {
        return getService(partitioned, subject.getAuthenticationId()).getMessageCountUpTo(queue, limit.get());
    }
}
 
Example #7
Source File: QueueResource1.java    From emodb with Apache License 2.0 6 votes vote down vote up
@GET
@Path("{queue}/size")
@RequiresPermissions("queue|get_status|{queue}")
@Timed(name = "bv.emodb.queue.QueueResource1.getMessageCount", absolute = true)
@ApiOperation (value = "gets the Message count.",
        notes = "Returns a long.",
        response = long.class
)
public long getMessageCount(@PathParam("queue") String queue, @QueryParam("limit") LongParam limit) {
    // Not partitioned--any server can count messages in Cassandra.  Claims are ignored.
    // Call different getMessageCount* methods to collect metrics data that distinguish limited vs. unlimited calls.
    if (limit == null || limit.get() == Long.MAX_VALUE) {
        return _queueService.getMessageCount(queue);
    } else {
        return _queueService.getMessageCountUpTo(queue, limit.get());
    }
}
 
Example #8
Source File: DatabusResource1.java    From emodb with Apache License 2.0 6 votes vote down vote up
@GET
@Path ("{subscription}/size")
@RequiresPermissions ("databus|get_status|{subscription}")
@Timed (name = "bv.emodb.databus.DatabusResource1.getEventCount", absolute = true)
@ApiOperation (value = "Gets the event count.",
        notes = "Returns a long.",
        response = long.class
)
public long getEventCount(@QueryParam ("partitioned") BooleanParam partitioned,
                          @PathParam ("subscription") String subscription, @QueryParam ("limit") LongParam limit,
                          @Authenticated Subject subject) {
    // Call different getEventCount* methods to collect metrics data that distinguish limited vs. unlimited calls.
    if (limit == null || limit.get() == Long.MAX_VALUE) {
        return getClient(partitioned).getEventCount(subject, subscription);
    } else {
        return getClient(partitioned).getEventCountUpTo(subject, subscription, limit.get());
    }
}
 
Example #9
Source File: GroupsResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Delete Group by ID
 *
 * @param user the admin user performing this operation
 * @param groupId the ID of the Group to be deleted
 * @return 200 if the deletion succeeded, 404 if the group was not found
 *
 * description Deletes a single Group if found.
 * Used by Keywhiz CLI and the web ui.
 * responseMessage 200 Found and deleted Group with given ID
 * responseMessage 404 Group with given ID not Found
 */
@Path("{groupId}")
@Timed @ExceptionMetered
@DELETE
public Response deleteGroup(@Auth User user, @PathParam("groupId") LongParam groupId) {
  logger.info("User '{}' deleting group id={}.", user, groupId);

  Optional<Group> group = groupDAO.getGroupById(groupId.get());
  if (!group.isPresent()) {
    throw new NotFoundException("Group not found.");
  }

  groupDAO.deleteGroup(group.get());
  auditLog.recordEvent(new Event(Instant.now(), EventTag.GROUP_DELETE, user.getName(), group.get().getName()));
  return Response.noContent().build();
}
 
Example #10
Source File: SecretsResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Rollback to a previous secret version
 *
 * @param user       the admin user performing this operation
 * @param secretName the name of the secret to rollback
 * @param versionId  the ID of the version to return to
 * @return 200 if the rollback was successful, 404 for missing secret or bad input
 * <p>
 * description Returns the previous versions of the secret if found Used by Keywhiz CLI.
 * <p>
 * responseMessage 200 Found and reset the secret to this version
 * <p>
 * responseMessage 404 Secret with given name not found or invalid version provided
 */
@Path("rollback/{secretName}/{versionId}")
@Timed @ExceptionMetered
@POST
public Response resetSecretVersion(@Auth User user, @PathParam("secretName") String secretName,
    @PathParam("versionId") LongParam versionId) {

  logger.info("User '{}' rolling back secret '{}' to version with ID '{}'.", user, secretName,
      versionId);

  secretDAOReadWrite.setCurrentSecretVersionByName(secretName, versionId.get(), user.getName());

  // If the secret wasn't found or the request was misformed, setCurrentSecretVersionByName
  // already threw an exception
  Map<String, String> extraInfo = new HashMap<>();
  extraInfo.put("new version", versionId.toString());
  auditLog.recordEvent(
      new Event(Instant.now(), EventTag.SECRET_CHANGEVERSION, user.getName(), secretName,
          extraInfo));

  // Send the new secret in response
  URI uri = UriBuilder.fromResource(SecretsResource.class)
      .path("rollback/{secretName}/{versionID}")
      .build(secretName, versionId);
  return Response.created(uri).entity(secretDetailResponseFromName(secretName)).build();
}
 
Example #11
Source File: MembershipResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Allow a Group to access this Secret
 *
 * @param user the admin user performing this operation
 * @param secretId ID value of a Secret
 * @param groupId ID value of a Group
 * @return 200 on success, 404 if secret or group is missing
 *
 * description Assigns the Secret specified by the secretID to the Group specified by the groupID
 * Used by Keywhiz CLI and the web ui.
 * responseMessage 200 Successfully enrolled Secret in Group
 * responseMessage 404 Could not find Secret or Group
 */
@Path("/secrets/{secretId}/groups/{groupId}")
@Timed @ExceptionMetered
@PUT
public Response allowAccess(
    @Auth User user,
    @PathParam("secretId") LongParam secretId,
    @PathParam("groupId") LongParam groupId) {

  logger.info("User '{}' allowing groupId {} access to secretId {}", user, groupId, secretId);

  try {
    aclDAO.findAndAllowAccess(secretId.get(), groupId.get(), auditLog, user.getName(), new HashMap<>());
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #12
Source File: MembershipResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Disallow a Group to access this Secret
 *
 * @param user the admin user performing this operation
 * @param secretId ID value of a Secret
 * @param groupId ID value of a Group
 * @return 200 if operation successful, 404 if secret or group not present
 *
 * description Unassigns the Secret specified by the secretID from the Group specified by the groupID
 * Used by Keywhiz CLI and the web ui.
 * responseMessage 200 Successfully removed Secret from Group
 * responseMessage 404 Could not find Secret or Group
 */
@Path("/secrets/{secretId}/groups/{groupId}")
@Timed @ExceptionMetered
@DELETE
public Response disallowAccess(
    @Auth User user,
    @PathParam("secretId") LongParam secretId,
    @PathParam("groupId") LongParam groupId) {

  logger.info("User '{}' disallowing groupId {} access to secretId {}", user, groupId, secretId);

  try {
    aclDAO.findAndRevokeAccess(secretId.get(), groupId.get(), auditLog, user.getName(), new HashMap<>());
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #13
Source File: MembershipResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a Client from a Group
 *
 * @param user the admin user performing this operation
 * @param clientId ID value of a Client
 * @param groupId ID value of a Group
 * @return 200 on success, 404 if client or group not found
 *
 * description Unassigns the Client specified by the clientID from the Group specified by the groupID
 * responseMessage 200 Successfully removed Client from Group
 * responseMessage 404 Could not find Client or Group
 */
@Path("/clients/{clientId}/groups/{groupId}")
@Timed @ExceptionMetered
@DELETE
public Response evictClient(
    @Auth User user,
    @PathParam("clientId") LongParam clientId,
    @PathParam("groupId") LongParam groupId) {
  logger.info("User {} evicting clientId {} from groupId {}.", user.getName(), clientId, groupId);

  try {
    aclDAO.findAndEvictClient(clientId.get(), groupId.get(), auditLog, user.getName(), new HashMap<>());
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #14
Source File: AutomationClientResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve Client by ID
 *
 * @param automationClient the client with automation access performing this operation
 * @param clientId the ID of the Client to retrieve
 * @return the specified client, if found
 *
 * description Returns a single Client if found
 * responseMessage 200 Found and retrieved Client with given ID
 * responseMessage 404 Client with given ID not Found
 */
@Timed @ExceptionMetered
@GET
@Path("{clientId}")
public Response findClientById(
    @Auth AutomationClient automationClient,
    @PathParam("clientId") LongParam clientId) {
  logger.info("Automation ({}) - Looking up an ID {}", automationClient.getName(), clientId);

  Client client = clientDAO.getClientById(clientId.get())
      .orElseThrow(NotFoundException::new);
  ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(client));

  return Response.ok()
      .entity(ClientDetailResponse.fromClient(client, groups, ImmutableList.of()))
      .build();
}
 
Example #15
Source File: AutomationEnrollClientGroupResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Enroll Client in Group
 *
 * @param automationClient the client with automation access performing this operation
 * @param clientId the ID of the Client to assign
 * @param groupId the ID of the Group to be assigned to
 * @return 200 on success, 404 if client or group is missing
 *
 * description Assigns the Client specified by the clientID to the Group specified by the
 * groupID
 * responseMessage 200 Successfully enrolled Client in Group
 * responseMessage 404 Could not find Client or Group
 */
@Timed @ExceptionMetered
@PUT
public Response enrollClientInGroup(
    @Auth AutomationClient automationClient,
    @PathParam("clientId") LongParam clientId,
    @PathParam("groupId") LongParam groupId) {

  try {
    Map<String, String> extraInfo = new HashMap<>();
    extraInfo.put("deprecated", "true");
    aclDAO.findAndEnrollClient(clientId.get(), groupId.get(), auditLog,
        automationClient.getName(), extraInfo);
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #16
Source File: AutomationSecretResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve secret by ID
 *
 * @param automationClient the client with automation access performing this operation
 * @param secretId the ID of the secret to retrieve
 * @return details on the specified secret
 *
 * description Returns a single secret if found
 * responseMessage 200 Found and retrieved secret with given ID
 * responseMessage 404 Secret with given ID not found
 */
@Path("{secretId}")
@Timed @ExceptionMetered
@GET
public AutomationSecretResponse readSecretById(
    @Auth AutomationClient automationClient,
    @PathParam("secretId") LongParam secretId) {

  Optional<Secret> secret = secretController.getSecretById(secretId.get());
  if (!secret.isPresent()) {
    throw new NotFoundException("Secret not found.");
  }

  ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(secret.get()));

  return AutomationSecretResponse.fromSecret(secret.get(), groups);
}
 
Example #17
Source File: AutomationGroupResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes a group
 *
 * @param automationClient the client with automation access performing this operation
 * @param groupId the ID of the group to delete
 * @return 200 if the group was removed successfully, 404 if the group was not found
 *
 * description Deletes a single group by id
 * responseMessage 200 Deleted group
 * responseMessage 404 Group not found by id
 */
@Timed @ExceptionMetered
@DELETE
@Path("{groupId}")
public Response deleteGroup(
    @Auth AutomationClient automationClient,
    @PathParam("groupId") LongParam groupId) {
  Group group = groupDAO.getGroupById(groupId.get()).orElseThrow(NotFoundException::new);
  groupDAO.deleteGroup(group);
  Map<String, String> extraInfo = new HashMap<>();
  extraInfo.put("deprecated", "true");
  auditLog.recordEvent(
      new Event(Instant.now(), EventTag.GROUP_DELETE, automationClient.getName(), group.getName(),
          extraInfo));
  return Response.ok().build();
}
 
Example #18
Source File: AutomationSecretAccessResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Assign Secret to Group
 *
 * @param automationClient the client with automation access performing this operation
 * @param secretId the ID of the Secret to assign
 * @param groupId the ID of the Group to be assigned to
 * @return 200 on success, 404 if the secret or group is absent
 *
 * description Assigns the Secret specified by the secretID to the Group specified by the groupID
 * responseMessage 200 Successfully enrolled Secret in Group
 * responseMessage 404 Could not find Secret or Group
 */
@Timed @ExceptionMetered
@PUT
public Response allowAccess(
    @Auth AutomationClient automationClient,
    @PathParam("secretId") LongParam secretId,
    @PathParam("groupId") LongParam groupId) {
  logger.info("Client '{}' allowing groupId={} access to secretId={}",
      automationClient, secretId, groupId);

  try {
    Map<String, String> extraInfo = new HashMap<>();
    extraInfo.put("deprecated", "true");
    aclDAO.findAndAllowAccess(secretId.get(), groupId.get(), auditLog, automationClient.getName(), extraInfo);
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #19
Source File: AutomationSecretAccessResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Remove Secret from Group
 *
 * @param automationClient the client with automation access performing this operation
 * @param secretId the ID of the Secret to unassign
 * @param groupId the ID of the Group to be removed from
 * @return 200 on success, 404 if the secret or group is absent
 *
 * description Unassigns the Secret specified by the secretID from the Group specified by the groupID
 * responseMessage 200 Successfully removed Secret from Group
 * responseMessage 404 Could not find Secret or Group
 */
@Timed @ExceptionMetered
@DELETE
public Response disallowAccess(
    @Auth AutomationClient automationClient,
    @PathParam("secretId") LongParam secretId,
    @PathParam("groupId") LongParam groupId) {
  logger.info("Client '{}' disallowing groupId={} access to secretId={}",
      automationClient, secretId, groupId);

  try {
    Map<String, String> extraInfo = new HashMap<>();
    extraInfo.put("deprecated", "true");
    aclDAO.findAndRevokeAccess(secretId.get(), groupId.get(), auditLog, automationClient.getName(), extraInfo);
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #20
Source File: ClientsResourceTest.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
@Test public void includesAssociations() {
  Group group1 = new Group(0, "group1", null, null, null, null, null, null);
  Group group2 = new Group(0, "group2", null, null, null, null, null, null);
  Secret secret =
      new Secret(15, "secret", null, () -> "supersecretdata", "checksum", now, "creator", now,
          "updater", null, null, null, 0, 1L, now, "updater");

  when(clientDAO.getClientById(1)).thenReturn(Optional.of(client));
  when(aclDAO.getGroupsFor(client)).thenReturn(Sets.newHashSet(group1, group2));
  when(aclDAO.getSanitizedSecretsFor(client))
      .thenReturn(ImmutableSet.of(SanitizedSecret.fromSecret(secret)));

  ClientDetailResponse response = resource.getClient(user, new LongParam("1"));
  assertThat(response.groups).containsOnly(group1, group2);
  assertThat(response.secrets).containsOnly(SanitizedSecret.fromSecret(secret));
}
 
Example #21
Source File: MembershipResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * Enroll a Client into a Group
 *
 * @param user the admin user performing this operation
 * @param clientId ID value of a Client
 * @param groupId ID value of a Group
 * @return 200 on success, 404 if client or group not found
 *
 * description Assigns the Client specified by the clientID to the Group specified by the groupID
 * responseMessage 200 Successfully enrolled Client in Group
 * responseMessage 404 Could not find Client or Group
 */
@Path("/clients/{clientId}/groups/{groupId}")
@Timed @ExceptionMetered
@PUT
public Response enrollClient(
  @Auth User user,
  @PathParam("clientId") LongParam clientId,
  @PathParam("groupId") LongParam groupId) {

  logger.info("User {} enrolling clientId {} in groupId {}.", user.getName(), clientId, groupId);

  try {
    aclDAO.findAndEnrollClient(clientId.get(), groupId.get(), auditLog, user.getName(), new HashMap<>());
  } catch (IllegalStateException e) {
    throw new NotFoundException();
  }

  return Response.ok().build();
}
 
Example #22
Source File: SecretsResourceTest.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
@Test
public void includesTheSecret() {
  when(secretController.getSecretById(22)).thenReturn(Optional.of(secret));
  when(aclDAO.getGroupsFor(secret)).thenReturn(Collections.emptySet());
  when(aclDAO.getClientsFor(secret)).thenReturn(Collections.emptySet());

  SecretDetailResponse response = resource.retrieveSecret(user, new LongParam("22"));

  assertThat(response.id).isEqualTo(secret.getId());
  assertThat(response.name).isEqualTo(secret.getName());
  assertThat(response.description).isEqualTo(secret.getDescription());
  assertThat(response.createdAt).isEqualTo(secret.getCreatedAt());
  assertThat(response.createdBy).isEqualTo(secret.getCreatedBy());
  assertThat(response.updatedAt).isEqualTo(secret.getUpdatedAt());
  assertThat(response.updatedBy).isEqualTo(secret.getUpdatedBy());
  assertThat(response.metadata).isEqualTo(secret.getMetadata());
}
 
Example #23
Source File: BlobStoreResource1.java    From emodb with Apache License 2.0 6 votes vote down vote up
@GET
@Path("_table")
@Timed(name = "bv.emodb.blob.BlobStoreResource1.listTables", absolute = true)
@ApiOperation (value = "List all the tables.",
        notes = "Returns a list of tables.",
        response = Table.class
)
public Iterator<Table> listTables(@QueryParam("from") final String fromKeyExclusive,
                                  @QueryParam("limit") @DefaultValue("10") LongParam limit,
                                  @Authenticated Subject subject) {
    _listTableRequestsByApiKey.getUnchecked(subject.getId()).mark();
    return streamingIterator(
        StreamSupport.stream(Spliterators.spliteratorUnknownSize(_blobStore.listTables(Strings.emptyToNull(fromKeyExclusive), Long.MAX_VALUE), 0), false)
            .filter(input -> subject.hasPermission(Permissions.readBlobTable(new NamedResource(input.getName()))))
            .limit(limit.get())
            .iterator()
    );
}
 
Example #24
Source File: SecretsResourceTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Test public void canDelete() {
  when(secretController.getSecretById(0xdeadbeef)).thenReturn(Optional.of(secret));
  HashSet<Group> groups = new HashSet<>();
  groups.add(new Group(0, "group1", "", NOW, null, NOW, null, null));
  groups.add(new Group(0, "group2", "", NOW, null, NOW, null, null));
  when(aclDAO.getGroupsFor(secret)).thenReturn(groups);

  Response response = resource.deleteSecret(user, new LongParam(Long.toString(0xdeadbeef)));
  verify(secretDAO).deleteSecretsByName("name");
  assertThat(response.getStatus()).isEqualTo(204);
}
 
Example #25
Source File: SecretsResourceTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Test
public void includesAssociations() {
  Client client = new Client(0, "client", null, null, null, null, null, null, null, null, false, false
  );
  Group group1 = new Group(0, "group1", null, null, null, null, null, null);
  Group group2 = new Group(0, "group2", null, null, null, null, null, null);

  when(secretController.getSecretById(22)).thenReturn(Optional.of(secret));
  when(aclDAO.getGroupsFor(secret)).thenReturn(Sets.newHashSet(group1, group2));
  when(aclDAO.getClientsFor(secret)).thenReturn(Sets.newHashSet(client));

  SecretDetailResponse response = resource.retrieveSecret(user, new LongParam("22"));
  assertThat(response.groups).containsOnly(group1, group2);
  assertThat(response.clients).containsOnly(client);
}
 
Example #26
Source File: CompactionControlResource1.java    From emodb with Apache License 2.0 5 votes vote down vote up
@POST
@Path ("/stash-time/{id}")
@RequiresPermissions ("system|comp_control")
public SuccessResponse updateStashTime(@PathParam ("id") String id,
                                       @QueryParam ("timestamp") LongParam timestampInMillisParam,
                                       @QueryParam ("placement") List<String> placements,
                                       @QueryParam ("expiredTimestamp") LongParam expiredTimestampInMillisParam,
                                       @QueryParam ("dataCenter") String dataCenter) {
    checkArgument(timestampInMillisParam != null, "timestamp is required");
    checkArgument(!placements.isEmpty(), "Placement is required");
    checkArgument(expiredTimestampInMillisParam != null, "expired timestamp is required.");

    _compactionControlSource.updateStashTime(id, timestampInMillisParam.get(), placements, expiredTimestampInMillisParam.get(), dataCenter);
    return SuccessResponse.instance();
}
 
Example #27
Source File: SecretsResourceTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Test
public void handlesNoAssociations() {
  when(secretController.getSecretById(22)).thenReturn(Optional.of(secret));
  when(aclDAO.getGroupsFor(secret)).thenReturn(Collections.emptySet());
  when(aclDAO.getClientsFor(secret)).thenReturn(Collections.emptySet());

  SecretDetailResponse response = resource.retrieveSecret(user, new LongParam("22"));
  assertThat(response.groups).isEmpty();
  assertThat(response.clients).isEmpty();
}
 
Example #28
Source File: PirateResource.java    From dropwizard-xml with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("{pirateId}")
@UnitOfWork
public void deletePirate(@PathParam("pirateId") LongParam pirateId) {
    Optional<Pirate> pirateOptional = pirateDAO.findById(pirateId.get());
    if (pirateOptional.isPresent()) {
        pirateDAO.delete(pirateOptional.get());
    }
}
 
Example #29
Source File: PersonResource.java    From dropwizard-java8 with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/view_mustache")
@UnitOfWork
@Produces(MediaType.TEXT_HTML)
public PersonView getPersonViewMustache(@PathParam("personId") LongParam personId) {
    return new PersonView(PersonView.Template.MUSTACHE, findSafely(personId.get()));
}
 
Example #30
Source File: SecretsResourceTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Test
public void rollbackSuccess() {
  Secret secret1 = new Secret(1, "name1", "desc", () -> "secret",
      "checksum", NOW, "user", NOW, "user", emptyMap, null,
      null, 1136214245, 125L, NOW, "user");

  when(secretController.getSecretByName("name1")).thenReturn(Optional.of(secret1));

  Response response = resource.resetSecretVersion(user, "name1", new LongParam("125"));
  assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_CREATED);
}