Java 类io.dropwizard.hibernate.UnitOfWork 实例源码

项目: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());
}
项目:SECP    文件:ChatSocketCreator.java   
@Override
@UnitOfWork
public Object createWebSocket(
    ServletUpgradeRequest servletUpgradeRequest,
    ServletUpgradeResponse servletUpgradeResponse) {

    String path = servletUpgradeRequest.getRequestPath();

    if(!StringUtils.isEmpty(path)) {
        String[] paths = servletUpgradeRequest.getRequestPath().split("/");

        String userID = paths[paths.length - 1];
        try {
            long id = Long.parseLong(userID);
            Optional<User> optionalUser = userRepository.getUserWithGroups(id);
            if (optionalUser.isPresent())
                return new ChatSocketListener(optionalUser.get(), this.messageHandler);
            log.error("Invalid user id was passed in");
        } catch (NumberFormatException exception) {
            log.error("Value passed in for user id is not a number", exception);
        }
    }

    return null;
}
项目:SECP    文件:SECPAuthenticator.java   
@Override
@UnitOfWork
public Optional<User> authenticate(String token) throws AuthenticationException {
    String username;

    try {
        username = tokenController.getUsernameFromToken(token);
    } catch (InvalidJwtException e) {
        throw new AuthenticationException(e);
    }

    if (StringUtils.isBlank(username)) {
        LOG.error("Username is blank.");
        return Optional.empty();
    } else {
        User user = userDAO.findByUserName(username);
        return Optional.ofNullable(user);
    }
}
项目:AugumentedSzczecin_java    文件:SearchResource.java   
@GET
@UnitOfWork
@Timed
@ExceptionMetered
@JsonView(Views.Public.class)
public SearchResults getByRegion(@BeanParam SearchCriteria searchCriteria) throws IOException {
    boolean shouldGetDataFromOpendataServer = !searchCriteria.getUser().isPresent();
    if (shouldGetDataFromOpendataServer) {
        return getFromOpendata(searchCriteria);
    }

    validateBean(searchCriteria);

    // TODO add sorting
    return searchService.searchByCriteria(searchCriteria);
}
项目:amos-ss15-proj2    文件:TripsResource.java   
/**
 * Find all offers that belong to a particular driver.
 * @param showActiveAndNotFullOnly if false this method will return all offers that belong to a driver,
 *                                 otherwise only those which are active (not disable due to timeouts etc.)
 *                                 and are not full (passengers can still join). Default is true.
 */
@GET
@Path(PATH_OFFERS)
@UnitOfWork
public List<TripOffer> getOffers(@Auth User driver, @DefaultValue("true") @QueryParam("active") boolean showActiveAndNotFullOnly) {
    List<TripOffer> offers = new ArrayList<>(tripsManager.findOffersByDriver(driver));
    if (!showActiveAndNotFullOnly) return offers;

    // filter by active status
    Iterator<TripOffer> iterator = offers.iterator();
    while (iterator.hasNext()) {
        TripOffer offer = iterator.next();
        if (!offer.getStatus().equals(TripOfferStatus.ACTIVE)) iterator.remove();
        else if (tripsUtils.getActivePassengerCountForOffer(offer) >= offer.getVehicle().getCapacity()) iterator.remove();
    }

    return offers;
}
项目:AugumentedSzczecin_java    文件:BasicAuthenticator.java   
@UnitOfWork
public Optional<User> authenticate(final BasicCredentials basicCredentials) throws AuthenticationException {

    String email = basicCredentials.getUsername();
    String plaintextPassword = basicCredentials.getPassword();

    final Optional<User> user = userDao.findByEmail(email);
    if (user.isPresent()) {
        final User existingUser = user.get();
        checkState(existingUser.getPassword() != null, "Cannot authenticate: user with id: %s (email: %s) without password",
                existingUser.getId(), existingUser.getEmail());

        if (isMatched(plaintextPassword, existingUser.getPassword())) {
            return user;
        }
    }
    return Optional.absent();
}
项目:amos-ss15-proj2    文件:TripsResource.java   
@PUT
@UnitOfWork
@Path(PATH_SUPER_TRIP + "/cancel")
public void cancelActiveSuperTrips( @Auth User passenger ){
    List<SuperTrip> superTrips = tripsManager.findAllActiveTrips(passenger);
    for( SuperTrip superTrip : superTrips ) {
        for( JoinTripRequest request : superTrip.getJoinRequests() ) {
            JoinTripStatus status = request.getStatus();
            if (status.equals(JoinTripStatus.PASSENGER_IN_CAR) || status.equals(JoinTripStatus.PASSENGER_AT_DESTINATION))
                throw RestUtils.createJsonFormattedException("cannot cancel when in car or at destination", 409);
            assertUserIsPassenger(request, passenger);
        }

        tripsManager.updateSuperTripPassengerCancel(superTrip);
    }
}
项目:coner-core    文件:EventRunsResource.java   
@GET
@Path("/{runId}")
@UnitOfWork
@ApiOperation(value = "Get a specific run")
@ApiResponses({
        @ApiResponse(code = HttpStatus.OK_200, response = RunApiEntity.class, message = "OK"),
        @ApiResponse(code = HttpStatus.NOT_FOUND_404, response = ErrorMessage.class, message = "Not found"),
        @ApiResponse(
                code = HttpStatus.CONFLICT_409,
                response = ErrorMessage.class,
                message = "Event ID and Run ID are mismatched"
        )
})
public RunApiEntity getRun(
        @PathParam("eventId") @ApiParam(value = "Event ID", required = true) String eventId,
        @PathParam("runId") @ApiParam(value = "Run ID", required = true) String runId
) throws EntityMismatchException, EntityNotFoundException {
    Run domainRun = runEntityService.getByEventIdAndRunId(eventId, runId);
    return runMapper.toApiEntity(domainRun);
}
项目:coner-core    文件:HandicapGroupSetsResource.java   
@POST
@Path("/{handicapGroupSetId}/handicapGroups/{handicapGroupId}")
@UnitOfWork
@ApiOperation(value = "Add a Handicap Group to a Handicap Group Set", response = HandicapGroupSetApiEntity.class)
@ApiResponses({
        @ApiResponse(code = HttpStatus.OK_200, response = HandicapGroupSetApiEntity.class, message = "OK"),
        @ApiResponse(code = HttpStatus.NOT_FOUND_404, response = ErrorMessage.class, message = "Not found"),
})
public HandicapGroupSetApiEntity addHandicapGroupToHandicapGroupSet(
        @PathParam("handicapGroupSetId") @ApiParam(value = "Handicap Group Set ID", required = true)
                String handicapGroupSetId,
        @PathParam("handicapGroupId") @ApiParam(value = "Handicap Group ID", required = true)
                String handicapGroupId
) throws EntityNotFoundException {
    HandicapGroupSet domainSetEntity = handicapGroupSetService.getById(handicapGroupSetId);
    HandicapGroup domainEntity = handicapGroupEntityService.getById(handicapGroupId);
    handicapGroupSetService.addToHandicapGroups(domainSetEntity, domainEntity);
    return handicapGroupSetMapper.toApiEntity(domainSetEntity);
}
项目:amos-ss15-proj2    文件:TripsResource.java   
/**
 * Get the {@link org.croudtrip.api.directions.NavigationResult} for an offer containing a not
 * yet accepted additionally provided {@link JoinTripRequest}. The result will contain a complete
 * route visiting all the passengers pick-up and destination locations as well as a list of all
 * the waypoints in the correct order of the current trip.
 * @param offerId The offer the navigation result should be computed for
 * @param joinRequestId the not yet accepted join trip request ({@link JoinTripStatus#PASSENGER_ACCEPTED})
 *                      which should be included into the navigation result.
 * @return A navigation result that contains the route and waypoints for all the passengers
 * especially of the additionally provided request.
 */
@GET
@Path(PATH_OFFERS + "/{offerId}/navigation/{joinRequestId}")
@UnitOfWork
public NavigationResult computePendingNavigationResultForOffer(@PathParam("offerId") long offerId, @PathParam("joinRequestId") long joinRequestId) throws RouteNotFoundException {
    TripOffer offer = assertIsValidOfferId( offerId );

    Optional<JoinTripRequest> request = tripsManager.findJoinRequest(joinRequestId);
    if (!request.isPresent()) throw RestUtils.createNotFoundException();

    if( request.get().getStatus() != JoinTripStatus.PASSENGER_ACCEPTED )
        throw RestUtils.createJsonFormattedException("Request must have status PASSENGER_ACCEPTED.", 409);

    SuperTripSubQuery subQuery = request.get().getSubQuery();
    TripQuery origQuery = request.get().getSuperTrip().getQuery();

    TripQuery query = new TripQuery( null, subQuery.getStartLocation(), subQuery.getDestinationLocation(), origQuery.getMaxWaitingTimeInSeconds(), origQuery.getCreationTimestamp(), origQuery.getPassenger() );

    return tripsNavigationManager.getNavigationResultForOffer( offer, query );
}
项目:Pinot    文件:AnomalyFunctionRelationResource.java   
@GET
@UnitOfWork
@Path("/{parentId}")
public List<Long> findByParent(@PathParam("parentId") Long parentId) {
  List<AnomalyFunctionRelation> result = dao.findByParent(parentId);
  if (result.isEmpty()) {
    throw new NotFoundException();
  }

  List<Long> childIds = new ArrayList<>();
  for (AnomalyFunctionRelation relation : result) {
    childIds.add(relation.getChildId());
  }

  return childIds;
}
项目:biblio-server    文件:UserResource.java   
@PUT
@Timed
@UnitOfWork
@ExceptionMetered
public User put(@Auth User existingUser, User user) {
    if (user.getPassword() != null) {
        final PasswordHashed passwordHashed = PasswordEncoder.encode(user.getPassword());
        existingUser.setSalt(passwordHashed.salt());
        existingUser.setPassword(passwordHashed.encodedPassword());
    }
    if (user.getRole() != null) {
        existingUser.setRole(user.getRole());
    }
    if (user.getUsername() != null) {
        throw new IllegalArgumentException("You cannot update username");
    }
    _userDao.save(existingUser);

    return existingUser;
}
项目:biblio-server    文件:BookResource.java   
@POST
@Timed
@UnitOfWork
public Response createBook(@Auth User user, @Context UriInfo info, Book book) {
    final Book persistedBook;
    try {
        book.setUser(user);
        persistedBook = _bookDao.save(book);
        String uri = String.format("%s/%s", info.getAbsolutePath().getPath(), persistedBook.getId());
        return Response.created(URI.create(uri)).build();
    } catch (Exception e) {
        LOGGER.error("Error on creating book.", e);
        formatAndThrow(LOGGER, Response.Status.CONFLICT, String.format("Book with isbn %s already exists", book.getIsbn()));
        return null;
    }
}
项目:metadict    文件:SessionResource.java   
@POST
@UnitOfWork
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response login(@Context ContainerRequestContext requestContext, @NotNull @Valid Credentials credentials) {
    JwtCookiePrincipal principal = sessionService.startSession(credentials, requestContext);

    try {
        // Sleep for a while to avoid brute-force attacks
        Thread.sleep(500);
    } catch (InterruptedException e) {
        LOGGER.debug("Unexpected interruption while sleeping", e);
    }

    if (principal == null) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    } else {
        return Response.ok(ResponseContainer.fromSuccessful(principal)).build();
    }
}
项目:metadict    文件:RegistrationResource.java   
/**
 * Register a new user account. The given {@link RegistrationRequestData} must be valid, i.e. matching bean
 * constraints or the registration will be blocked.
 *
 * @param registrationRequestData
 *         The registration request.
 * @return Either a response with {@link javax.ws.rs.core.Response.Status#ACCEPTED} if the registration was
 * successful or either 422 if any validation errors occurred or {@link javax.ws.rs.core.Response.Status#CONFLICT}
 * if the user already exists. If the registration was successful, the user will also be logged in automatically.
 */
@POST
@UnitOfWork
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response register(@Valid @NotNull RegistrationRequestData registrationRequestData) {
    Optional<User> newUser = this.userService.createNewUser(registrationRequestData.getName(), registrationRequestData.getPassword());
    Response.ResponseBuilder responseBuilder;

    if (!newUser.isPresent()) {
        responseBuilder = Response.status(Response.Status.CONFLICT).entity(ResponseContainer.withStatus(ResponseStatus.DUPLICATE));
    } else {
        Optional<User> user = this.userService.authenticateWithPassword(registrationRequestData.getName(),
                registrationRequestData.getPassword());
        if (user.isPresent() && Objects.equals(newUser.get(), user.get())) {
            responseBuilder = Response.accepted(ResponseContainer.withStatus(ResponseStatus.OK));
        } else {
            // This should never happen
            responseBuilder = Response.serverError();
            LOGGER.error("User authentication after registration failed");
        }
    }
    return responseBuilder.build();
}
项目:metadict    文件:QueryLoggingService.java   
/**
 * Returns the logged queries for the currently authenticated user.
 *
 * @param offset
 *         The offset for logged queries.
 * @param size
 *         The total size of queries to return. If zero, all entries will be returned.
 * @return A list containing the logged queries. If no user is currently authenticated, the list will be empty.
 */
@NotNull
@UnitOfWork
public List<QueryLogEntry> getLoggedQueries(@NotNull Principal principal, int offset, int size) {
    checkArgument(offset >= 0, "Offset must be greater than zero or equal");
    checkArgument(size > 0, "Size must be greater than zero");

    List<QueryLogEntry> result;

    Optional<PersistedUser> user = userService.findPersistedUserByName(principal.getName());
    if (user.isPresent()) {
        result = readQueryLog(user.get(), offset, size);
    } else {
        LOGGER.warn("User {} doesn't exist", principal.getName());
        result = new ArrayList<>();
    }
    return result;
}
项目:SECP    文件:ChatSocketHandler.java   
@Override
@UnitOfWork
public void notifySession(MessageDTO message, IMessageReceiver receiver) {
    long groupID = message.getGroupId();
    long senderID = receiver.getUser().getId();
    MessageDTO savedMessage = saveMessage(message, receiver);
    for(IMessageReceiver messageReceiver: activeGroups.get(groupID)) {
        long receiverID = messageReceiver.getUser().getId();
        if (receiverID != senderID)
            messageReceiver.updateUser(savedMessage);
    }
}
项目:SECP    文件:AdminResource.java   
@POST
@Path("{id}")
@UnitOfWork
public Response registerAdmin(@PathParam("id") String id) {
    adminController.registerAdmin(id);
    return Response.status(Response.Status.OK).build();
}
项目:SECP    文件:AdminResource.java   
@DELETE
@Path("{id}")
@UnitOfWork
public Response removeAdmin(@Auth @PathParam("id") String id) {
    adminController.removeAdmin(id);
    return Response.status(Response.Status.OK).build();
}
项目:SECP    文件:AdminResource.java   
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
@Path("/register")
public Response create(UserRegistrationRequest request) {
    return userRegistrationController.registerUser(request);
}
项目:SECP    文件:AdminResource.java   
@POST
@Timed
@UnitOfWork
@Path("/roles")
public Response createRoles(@Auth AppCreateDTO request) {
    return adminController.registerRoles(request);
}
项目:SECP    文件:AdminResource.java   
@POST
@Timed
@UnitOfWork
@Path("/permissions")
public Response createPermissions(AppCreateDTO request) {
    return adminController.registerPermissions(request);
}
项目:SECP    文件:AdminResource.java   
@POST
@Timed
@UnitOfWork
@Path("/roles/id/{id}")
public Response updateRole(@Auth RolesOrPermissionDTO request, @PathParam("id") String id) {
    return adminController.updateRoles(request,id);
}
项目:SECP    文件:AdminResource.java   
@POST
@Timed
@UnitOfWork
@Path("/permissions/id/{id}")
public Response updatePermissions(@Auth RolesOrPermissionDTO request, @PathParam("id") String id) {
    return adminController.updatePermissions(request,id);
}
项目:SECP    文件:MessageResource.java   
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
@Path("/group/{groupID}")
public Response getMessagesForGroup(
    @Auth @PathParam("groupID") long id,
    @QueryParam("offset") int offset,
    @QueryParam("limit") int limit)
{
    return messageController.getMessagesForGroup(id,offset,limit);
}
项目:SECP    文件:GroupResource.java   
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
public Response createPublicGroup(@Auth GroupCreateRequest request) {
    return groupController.createPublicGroup(request);
}
项目:SECP    文件:GroupResource.java   
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
@RolesAllowed({"ADMIN","NORMAL"})
@Path("/private")
public Response createPrivateGroup(@Auth User user, UserDTO userDTO) {
    return groupController.createPrivateGroup(user, userDTO);
}
项目:SECP    文件:GroupResource.java   
@GET
@Produces(MediaType.APPLICATION_JSON)
@UnitOfWork
@RolesAllowed({"ADMIN", "NORMAL"})
@Path("/user")
public Response getGroupForUser(@Auth User user)
{
    return groupController.getGroupsForUser(user);
}
项目:SECP    文件:GroupResource.java   
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
@Path("/modify")
public Response modifyGroup(@Auth GroupDTO request)
{
    return  groupController.modifyGroup(request);
}
项目:SECP    文件:GroupResource.java   
@DELETE
@UnitOfWork
@Path("/{id}")
public Response deleteGroup(@Auth @PathParam("id") int id)
{
    return  groupController.deleteGroup(id);
}
项目:SECP    文件:GroupResource.java   
@GET
@Path("/id/{id}")
@RolesAllowed({"ADMIN", "NORMAL"})
@UnitOfWork
public Response getGroup(@Auth @PathParam("id") String id) {
    return groupController.getGroupGivenId(id);
}
项目:SECP    文件:UserResource.java   
@GET
@Path("/verify/admin/id/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
public Response isUserAnAdmin(@Auth @PathParam("id") String id) {

    if(!StringUtils.isBlank(id) && userController.isUserAnAdmin(id)) {
        return Response.status(Response.Status.OK).build();
    }

    return Response.status(Response.Status.NO_CONTENT).build();
}
项目:SECP    文件:UserResource.java   
@GET
@Path("/verify/username/{username}")
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
public Response verifyUsername(@Auth @PathParam("username") String username) {

    if(!StringUtils.isBlank(username) && userRegistrationController.isUsernameValid(username)) {
        return Response.status(Response.Status.OK).build();
    }

    return Response.status(Response.Status.NO_CONTENT).build();
}
项目:SECP    文件:UserResource.java   
@GET
@Path("/verify/email/{email}")
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
public Response verifyEmailAddress(@Auth @PathParam("email") String email) {

    if(!StringUtils.isBlank(email) && userRegistrationController.isEmailValid(email)) {
        return Response.status(Response.Status.OK).build();
    }

    return Response.status(Response.Status.NO_CONTENT).build();
}
项目:SECP    文件:UserResource.java   
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@UnitOfWork
@Path("/device")
public Response addDevice(@Auth DeviceDTO deviceDTO) {
    return userController.addDevice(deviceDTO);
}
项目:SECP    文件:UserResource.java   
@GET
@Path("/id/{id}/device/name/{name}")
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
public Response verifyDevice(@Auth @PathParam("name") String deviceName, @PathParam("id") long id) {

    if(!StringUtils.isBlank(deviceName) && userController.isDeviceRegisteredForUser(id, deviceName)) {
        return Response.status(Response.Status.OK).build();
    }

    return Response.status(Response.Status.NO_CONTENT).build();
}
项目:SECP    文件:UserResource.java   
@GET
@Path("/id/{id}/publicKey")
@Produces(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
public Response getUsersPublicKeys(@Auth @PathParam("id") long id) {
    return userController.getUsersPublicKeys(id);
}
项目:SECP    文件:UserResource.java   
@DELETE
@Path("/id/{id}")
@UnitOfWork
@RolesAllowed({ "ADMIN"})
public Response deleteUser(@Auth @PathParam("id") String id) {
    return userController.deleteUser(id);
}
项目:SECP    文件:UserResource.java   
@POST
@Path("/modify")
@UnitOfWork
@RolesAllowed("ADMIN")
public Response modifyUser(@Auth UserDTO userDTO) {
    return userController.modifyUser(userDTO);
}
项目:SECP    文件:EntryResource.java   
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@UnitOfWork
@Path("/login")
public Response login(LoginRequestDTO loginRequestDTO) {
    return loginRequestController.login(loginRequestDTO);
}