Java 类io.dropwizard.auth.Auth 实例源码

项目:SAPNetworkMonitor    文件:MonitorResource.java   
/**
 * Agent和Server之间的心跳,可以1分钟或更长时间一次,传回Monitor的信息,返回MonitorJob信息
 *
 * @param monitorId
 * @param monitor
 * @return
 */
@POST
@Path("/monitor/{monitorId}/heartbeat")
public RestfulReturnResult heartbeat(@Auth OAuthUser user, @PathParam("monitorId") String monitorId, @NotNull @Valid Monitor monitor) {
    if (!monitorId.equals(monitor.getMonitorId())) {
        log.error("monitor id in path {} and json {} and parameter not match error.", monitorId, monitor.getMonitorId());
        return new RestfulReturnResult(new NiPingException(MonitoridNotMatchError), null);
    }

    monitor.setMonitorId(monitorId);
    monitor.setAccountId(user.getAccountId());

    log.info("user {} monitorId {} send heartbeat {}", user, monitorId, monitor);
    monitorService.heartbeat(monitor);
    Optional<MonitorJob> job = Optional.empty();
    try {
        monitorService.saveMonitor(monitor);
        job = taskService.getNextJob(monitorId, monitor.getRunningTaskIds());
        if (log.isInfoEnabled() && job.isPresent()) {
            log.info("user {} monitorId {} get next job {}", user, monitorId, job.get());
        }
    } catch (NiPingException e) {
        return new RestfulReturnResult(e, job.orElse(null));
    }
    return new RestfulReturnResult(SUCCESS, job.orElse(null));
}
项目:SAPNetworkMonitor    文件:DatabusResource.java   
@POST
@Path("/monitor/{monitorId}/result")
public RestfulReturnResult result(@Auth OAuthUser user, @PathParam("monitorId") String monitorId, @NotNull @Valid MonitorNiPingResult
        monitorNiPingResult) {
    if (!monitorId.equals(monitorNiPingResult.getMonitorId())) {
        log.error("monitor id in path {} and json {} and parameter not match error.", monitorId, monitorNiPingResult.getMonitorId());
        return new RestfulReturnResult(new NiPingException(MonitoridNotMatchError), null);
    }

    monitorNiPingResult.setAccountId(user.getAccountId());
    monitorNiPingResult.setMonitorId(monitorId);
    try {
        log.info("user {} save monitor NiPing result {}", user, monitorNiPingResult);
        taskService.saveMonitorNiPingResult(monitorNiPingResult);
    } catch (NiPingException e) {
        return new RestfulReturnResult(e, null);
    }
    return new RestfulReturnResult(SUCCESS, null);
}
项目:stroom-stats    文件:QueryResource.java   
@POST
@Path(SEARCH_ENDPOINT)
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Timed
@UnitOfWork
public Response search(
        @NotNull @Auth User user,
        @NotNull @Valid SearchRequest searchRequest) {
    LOGGER.debug("Received search request");

    return performWithAuthorisation(
            user,
            searchRequest.getQuery().getDataSource(),
            () -> Response.ok(hBaseClient.query(searchRequest)).build());
}
项目:amigo-chatbot    文件:UserResource.java   
@Override
@GET
@Produces(MediaType.APPLICATION_JSON)
/*@ApiOperation(httpMethod = "GET",
        value = "list all users",
        response = User.class,
        responseContainer = "List",
        nickname="list")*/
public List<User> list(@Auth PrincipalUser user, @QueryParam("filter") String filter) throws InternalErrorException {
    try {
        if(filter == null) {
            return userDAO.fetchById(null);
        } else {
            return userDAO.fetch(filter, User.class);
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error in getting users", e);
        throw new BadRequestException(e);
    }
}
项目:amigo-chatbot    文件:UserResource.java   
@Override
@DELETE
@Path("/{id}")
/*@ApiOperation(httpMethod = "DELETE",
        value = "delete a user",
        response = Response.class,
        nickname="delete")*/
@Produces(MediaType.APPLICATION_JSON)
public Response delete(@Auth PrincipalUser user, @PathParam("id") String id) throws ResourceNotFoundException, InternalErrorException {
    try {
        userDAO.deleteById(id);
        return Response.ok()
                .entity(Entity.json(id))
                .build();
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error in getting users", e);
        throw new BadRequestException(e);
    }
}
项目:outland    文件:GroupResource.java   
@GET
@Path("/{group}")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "getByKey")
public Response getByKey(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String group
) throws AuthenticationException {

  final long start = System.currentTimeMillis();
  final Optional<Group> maybe = findGroup(group);

  if (maybe.isPresent()) {
    accessControlSupport.throwUnlessGrantedFor(authPrincipal, maybe.get());
    return headers.enrich(Response.ok(maybe.get()), start).build();
  }

  return headers.enrich(Response.status(404).entity(
      Problem.clientProblem(GroupResource.TITLE_NOT_FOUND, "", 404)), start).build();
}
项目:outland    文件:GroupResource.java   
@DELETE
@Path("/{group}/access/services/{service_key}")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "removeService")
public Response removeService(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String groupKey,
    @PathParam("service_key") String serviceKey
) throws AuthenticationException {
  final long start = System.currentTimeMillis();

  final Optional<Group> maybe = findGroup(groupKey);

  if (maybe.isPresent()) {
    final Group group = maybe.get();
    accessControlSupport.throwUnlessGrantedFor(authPrincipal, group);
    final Group updated = groupService.removeServiceAccess(group, serviceKey);

    return headers.enrich(Response.ok(updated), start).build();
  }

  return headers.enrich(Response.status(404).entity(
      Problem.clientProblem(TITLE_NOT_FOUND, "", 404)), start).build();
}
项目:outland    文件:GroupResource.java   
@DELETE
@Path("/{group}/access/members/{member_key}")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "removeMember")
public Response removeMember(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String groupKey,
    @PathParam("member_key") String memberKey
) throws AuthenticationException {
  final long start = System.currentTimeMillis();

  final Optional<Group> maybe = findGroup(groupKey);

  if (maybe.isPresent()) {
    final Group group = maybe.get();
    accessControlSupport.throwUnlessGrantedFor(authPrincipal, group);
    final Group updated = groupService.removeMemberAccess(group, memberKey);

    return headers.enrich(Response.ok(updated), start).build();
  }

  return headers.enrich(Response.status(404).entity(
      Problem.clientProblem(TITLE_NOT_FOUND, "", 404)), start).build();
}
项目:outland    文件:FeatureResource.java   
@POST
@Path("/{group}/{feature_key}")
@PermitAll
@Timed(name = "updateFeature")
public Response updateFeature(
    @Auth AuthPrincipal principal,
    @PathParam("group") String group,
    @PathParam("feature_key") String featureKey,
    Feature feature,
    @Context HttpHeaders httpHeaders
) throws AuthenticationException {

  final long start = System.currentTimeMillis();

  grantedGuard(principal, group);
  groupValidGuard(group, featureKey, feature);

  final Optional<String> maybeSeen = idempotencyChecker.extractKey(httpHeaders);
  if (maybeSeen.isPresent() && idempotencyChecker.seen(maybeSeen.get())) {
    return alreadyUpdated(feature, start, maybeSeen);
  }

  return headers.enrich(Response.ok(update(group, feature)), start).build();
}
项目:outland    文件:FeatureResource.java   
@GET
@Path("/{group}/{feature_key}")
@PermitAll
@Timed(name = "getFeatureByKey")
public Response getFeatureByKey(
    @Auth AuthPrincipal principal,
    @PathParam("group") String group,
    @PathParam("feature_key") String featureKey
) throws AuthenticationException {

  final long start = System.currentTimeMillis();
  grantedGuard(principal, group);
  return headers.enrich(
      featureService.loadFeatureByKey(group, featureKey)
          .map(Response::ok)
          .orElseGet(this::featureNotFound), start).build();
}
项目:j1st-mqtt    文件:MqttSubscribeResource.java   
@PermitAll
@GET
/**
 * Handle MQTT Subscribe Request in RESTful style
 * Granted QoS Levels will send back to client.
 * Retain Messages matched the subscriptions will NOT send back to client.
 */
public ResultEntity<List<Subscription>> subscribe(@PathParam("clientId") String clientId, @Auth UserPrincipal user) {
    List<Subscription> subscriptions = new ArrayList<>();

    // HTTP interface require valid Client Id
    if (!this.validator.isClientIdValid(clientId)) {
        logger.debug("Protocol violation: Client id {} not valid based on configuration", clientId);
        throw new ValidateException(new ErrorEntity(ErrorCode.INVALID));
    }

    // Read client's subscriptions from storage
    Map<String, MqttQoS> map = this.redis.getClientSubscriptions(clientId);
    map.forEach((topic, qos) -> subscriptions.add(new Subscription(topic, qos.value())));

    return new ResultEntity<>(subscriptions);
}
项目:rufus    文件:ArticleResource.java   
@Path("/tagStubs")
@GET
public Response tagStubs(@Auth Optional<User> user) {
    List<Source> sources;
    if (user.isPresent()) {
        User present = user.get();
        if (!articleDao.hasSubscriptions(present.getId())) {
            return Response.status(Response.Status.OK)
                .type(MediaType.APPLICATION_JSON_TYPE)
                .entity(Collections.EMPTY_LIST)
                .build();
        } else {
            sources = articleDao.getSources(userDao.findByEmail(present.getEmail()).getId());
        }
    } else {
        sources = articleDao.getPublicSources();
    }

    Set<String> tags = sources.stream()
            .map(Source::getTags)
            .filter(Objects::nonNull)
            .flatMap(List::stream)
            .collect(Collectors.toSet());

    return Response.ok(tags).build();
}
项目:dust-api    文件:ProfileResource.java   
@GET
@Path("/watches")
public Collection<Watch> profileWatches(@Auth final User authUser) {
    return userRepo.findWatchesOfUser(authUser.getId()).stream()
            .map(Watch::new)
            .collect(toList());
}
项目:dust-api    文件:ProfileResource.java   
@DELETE
@Path("/watches/{deviceId}")
public void removeProfileWatch(
        @Auth final User authUser,
        @PathParam("deviceId") final long deviceId
) {
    userRepo.removeWatch(deviceId, authUser.getId());
}
项目:dust-api    文件:DeviceClaimResource.java   
@POST
@Path("{deviceId:\\d+}/claims")
public Claim claimDevice(
        @PathParam("deviceId") final long deviceId,
        @Auth User user
) {
    final Device device = deviceRepo.findById(deviceId);
    final Claim newClaim = Claim.startingNow(device, user);
    return claimRepo.create(newClaim);
}
项目:dust-api    文件:DeviceClaimResource.java   
@POST
@Path("{nickname}/claims")
public Claim claimDevice(
        @PathParam("nickname") final String nickname,
        @Auth User user
) {
    final Device device = deviceRepo.findByName(nickname);
    final Claim newClaim = Claim.startingNow(device, user);
    return claimRepo.create(newClaim);
}
项目:dust-api    文件:DeviceClaimResource.java   
@DELETE
@Path("{deviceId:\\d+}/claims")
public Claim unclaimDevice(
        @PathParam("deviceId") final Long deviceId,
        @Auth User user
) {
    return claimRepo.delete(claimRepo.findActive(deviceId, user.getId()).id);
}
项目:dust-api    文件:DeviceClaimResource.java   
@DELETE
@Path("{nickname}/claims")
public Claim unclaimDevice(
        @PathParam("nickname") final String nickname,
        @Auth User user
) {
    final Device device = deviceRepo.findByName(nickname);
    return unclaimDevice(device.getId(), user);
}
项目:stroom-stats    文件:QueryResource.java   
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path(DATA_SOURCE_ENDPOINT)
@Timed
public Response getDataSource(
        @Auth User user,
        @NotNull @Valid final DocRef docRef) {
    return performWithAuthorisation(
            user,
            docRef,
            () -> dataSourceService.getDatasource(docRef)
                    .map(dataSource -> Response.ok(dataSource).build())
                    .orElse(Response.noContent().build()));
}
项目:amigo-chatbot    文件:UserResource.java   
@Override
@PUT
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
/*@ApiOperation(httpMethod = "PUT",
        value = "update a user",
        response = User.class,
        nickname="update")*/
public User update(@Auth PrincipalUser user, @PathParam("id") String id, @Valid String entity) throws ResourceNotFoundException, InternalErrorException, IOException {
    try {
        User u = JsonUtils.convertJsonToObject(entity, User.class);
        u.isValid();
        userDAO.update(new ArrayList<User>() {{
            add(u);
        }});
        List<User> users = userDAO.fetchById(new ArrayList<String>() {{
            add(id);
        }});
        if (users != null && !users.isEmpty()) {
            return users.get(0);
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error in getting user ID [" + id +  "]", e);
        throw new BadRequestException(e);
    }
    return null;
}
项目:outland    文件:GroupResource.java   
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Timed(name = "register")
public Response register(
    @Auth AuthPrincipal authPrincipal,
    Group group,
    @Context HttpHeaders httpHeaders
) throws AuthenticationException {

  final long start = System.currentTimeMillis();

  // no further acl check; if you are an authenticated AuthPrincipal, you can create

  final URI loc = locationHeader(group);
  final Optional<String> optional = idempotencyChecker.extractKey(httpHeaders);
  final boolean seen = optional.isPresent() && idempotencyChecker.seen(optional.get());
  if (seen) {
    return headers.enrich(
        Response.ok(groupService.loadByKey(group.getKey()))
            .header(IdempotencyChecker.RES_HEADER, "key=" + optional.get()), start).build();
  }

  final Group registered = groupService.register(group)
      .orElseThrow(() -> new RuntimeException("todo"));

  return headers.enrich(Response.created(loc).entity(registered), start).build();
}
项目:outland    文件:GroupResource.java   
@POST
@Path("/{group}/owners")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "addOwner")
public Response addOwner(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String group,
    Owner owner
) throws AuthenticationException {
  return postUpdate(authPrincipal, group, ns -> groupService.add(ns, owner));
}
项目:outland    文件:GroupResource.java   
@POST
@Path("/{group}/access/services")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "addService")
public Response addService(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String group,
    ServiceAccess serviceAccess
) throws AuthenticationException {
  return postUpdate(authPrincipal, group, ns -> groupService.add(ns, serviceAccess));
}
项目:outland    文件:GroupResource.java   
@POST
@Path("/{group}/access/members")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "addService")
public Response addService(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String group,
    MemberAccess memberAccess
) throws AuthenticationException {
  return postUpdate(authPrincipal, group, ns -> groupService.add(ns, memberAccess));
}
项目:outland    文件:GroupResource.java   
@DELETE
@Path("/{group}/owners/{owner_key}")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "removeOwner")
public Response removeOwner(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String groupKey,
    @PathParam("owner_key") String ownerKey
) throws AuthenticationException {
  final long start = System.currentTimeMillis();

  if (Strings.isNullOrEmpty(ownerKey)) {
    return headers.enrich(Response.status(404).entity(
        Problem.clientProblem("param_not_found", "", 404)), start).build();
  }

  final Optional<Group> maybe = findGroup(groupKey);

  if (maybe.isPresent()) {
    final Group group = maybe.get();
    accessControlSupport.throwUnlessGrantedFor(authPrincipal, group);
    final Group updated = groupService.removeOwner(group, ownerKey);
    return headers.enrich(Response.ok(updated), start).build();
  }

  return headers.enrich(Response.status(404).entity(
      Problem.clientProblem(GroupResource.TITLE_NOT_FOUND, "", 404)), start).build();
}
项目:outland    文件:FeatureResource.java   
@POST
@Path("/{group}")
@PermitAll
@Timed(name = "registerFeature")
public Response registerFeature(
    @Auth AuthPrincipal principal,
    Feature feature,
    @Context HttpHeaders httpHeaders
) throws AuthenticationException {

  final long start = System.currentTimeMillis();

  final Optional<Group> maybe = groupService.loadByKey(feature.getGroup());
  if (!maybe.isPresent()) {
    return notFound(start);
  }

  accessControlSupport.throwUnlessGrantedFor(principal, maybe.get());

  final URI loc = locationUrl(feature);

  final Optional<String> maybeSeen = idempotencyChecker.extractKey(httpHeaders);
  if (maybeSeen.isPresent() && idempotencyChecker.seen(maybeSeen.get())) {
    return respondAlreadyCreated(feature, start, loc, maybeSeen);
  }

  return headers.enrich(
      Response.created(loc).entity(featureService.registerFeature(feature)), start).build();
}
项目:outland    文件:FeatureResource.java   
@GET
@Path("/{group}")
@PermitAll
@Timed(name = "getFeatures")
public Response getFeatures(
    @Auth AuthPrincipal principal,
    @PathParam("group") String group
) throws AuthenticationException {

  final long start = System.currentTimeMillis();
  grantedGuard(principal, group);
  return this.headers.enrich(Response.ok(featureService.loadFeatures(group)), start).build();
}
项目:outland    文件:FeatureResource.java   
@GET
@Path("/{group}/feed")
@PermitAll
@Timed(name = "getFeaturesSince")
public Response getFeaturesSince(
    @Auth AuthPrincipal principal,
    @PathParam("group") String group,
    @QueryParam("since") long since
) throws AuthenticationException {

  final long start = System.currentTimeMillis();
  grantedGuard(principal, group);
  return this.headers.enrich(
      Response.ok(featureService.loadChangedSince(group, toOffset(since))), start).build();
}
项目:outland    文件:FeatureResource.java   
@POST
@Path("/{group}/{feature_key}/namespaces")
@PermitAll
@Timed(name = "addNamespaceFeature")
public Response addNamespaceFeature(
    @Auth AuthPrincipal principal,
    @PathParam("group") String group,
    @PathParam("feature_key") String featureKey,
    NamespaceFeature namespaceFeature
) throws AuthenticationException {

  return postUpdate(principal, group, featureKey, f -> featureService.add(f, namespaceFeature));
}
项目:outland    文件:FeatureResource.java   
@POST
@Path("/{group}/{feature_key}/namespaces/{namespace}")
@PermitAll
@Timed(name = "updateNamespaceFeature")
public Response updateNamespaceFeature(
    @Auth AuthPrincipal principal,
    @PathParam("group") String group,
    @PathParam("feature_key") String featureKey,
    @PathParam("namespace") String namespace,
    NamespaceFeature namespaceFeature
) throws AuthenticationException {

  return postUpdate(principal, group, featureKey,
      f -> featureService.updateNamespaceFeature(f, namespaceFeature));
}
项目:outland    文件:FeatureResource.java   
@DELETE
@Path("/{group}/{feature_key}/namespaces/{namespace}")
@PermitAll
@Timed(name = "removeNamespaceFeature")
public Response removeNamespaceFeature(
    @Auth AuthPrincipal principal,
    @PathParam("group") String group,
    @PathParam("feature_key") String featureKey,
    @PathParam("namespace") String namespace
) throws AuthenticationException {

  return postUpdate(principal, group, featureKey,
      f -> featureService.removeNamespaceFeature(f.getGroup(), f.getKey(), namespace));
}
项目:oacc-example-securetodo    文件:TodoItemResource.java   
@Path("/{id}/")
@PUT
public void shareItem(@Auth OaccPrincipal oaccPrincipal,
                      @PathParam("id") LongParam todoItemId,
                      @QueryParam("share_with") String email) {

   todoItemService.shareItem(oaccPrincipal.getAccessControlContext(), todoItemId.get(), email);
}
项目:oacc-example-securetodo    文件:TodoItemResource.java   
@Path("/{id}")
@PATCH
// @Consumes(MediaType.APPLICATION_MERGE_PATCH_JSON)
public TodoItem updateItem(@Auth OaccPrincipal oaccPrincipal,
                           @PathParam("id") LongParam todoItemId,
                           TodoItem patchItem) {

   return todoItemService.updateItem(oaccPrincipal.getAccessControlContext(), todoItemId.get(), patchItem);
}
项目:rufus    文件:ArticleResource.java   
@Path("/frontpage")
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
@GET
public Response frontPage(@Auth Optional<User> user) {
    return user.isPresent()
        ? articleView(() -> processor.buildFrontpageCollection(user.get()))
        : articleView(processor::buildFrontpageCollection);
}
项目:rufus    文件:ArticleResource.java   
@Path("/all")
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
@GET
public Response all(@Auth Optional<User> user) {
    return  user.isPresent()
        ? articleView(() -> processor.buildArticleCollection(user.get()))
        : articleView(processor::buildArticleCollection);
}
项目:rufus    文件:ArticleResource.java   
@Path("/tagged")
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
@GET
public Response byTag(@Auth Optional<User> user, @QueryParam("tag") String tag) {
    return user.isPresent()
        ? articleView(() -> processor.buildTagCollection(user.get(), tag))
        : articleView(() -> processor.buildTagCollection(tag));
}
项目:rufus    文件:ArticleResource.java   
@Path("/bookmark")
@Consumes(MediaType.APPLICATION_JSON)
@POST
public Response bookmark(@Auth User user, Article article) {
    user = userDao.findByEmail(user.getEmail());
    if (articleDao.getBookmarked(user.getId()).contains(article)) {
        return ResourceUtils.badRequest("Article is already bookmarked.");
    }
    articleDao.bookmarkArticle(user.getId(), article);
    return Response.ok().build();
}
项目:rufus    文件:ArticleResource.java   
@Path("/removeBookmark")
@Consumes(MediaType.APPLICATION_JSON)
@PUT
public Response removeBookmark(@Auth User user, Article article) {
    user = userDao.findByEmail(user.getEmail());
    articleDao.removeArticle(user.getId(), article.getUrl());
    return Response.ok().build();
}
项目:rufus    文件:ArticleResource.java   
@Path("/bookmarked")
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
@GET
public Response bookmarked(@Auth User user) {
    final User u = userDao.findByEmail(user.getEmail());
    return articleView(() -> articleDao.getBookmarked(u.getId()));
}
项目:rufus    文件:ArticleResource.java   
@Path("/new")
@Consumes(MediaType.APPLICATION_JSON)
@POST
public Response addFeed(@Auth User user, List<String> feeds) {
    if (feeds.isEmpty()) {
        return ResourceUtils.badRequest("No feeds provided.");
    }
    return Response.ok(FeedResponse.formatMessage(parser.parse(user, feeds))).build();
}