@Override public Response run(JerseyResourceDelegateContext context) { JerseyResourceDelegateContextKey<String> queryIdKey = JerseyResourceDelegateContextKey.valueOf(queryIdKeyName, String.class); String queryId = context.get(queryIdKey); JerseyResourceDelegateContextKey<String> printTypeKey = JerseyResourceDelegateContextKey.valueOf(printTypeKeyName, String.class); String printType = context.get(printTypeKey); JerseyResourceDelegateContextKey<MasterContext> masterContextKey = JerseyResourceDelegateContextKey.valueOf( JerseyResourceDelegateUtil.MasterContextKey, MasterContext.class); MasterContext masterContext = context.get(masterContextKey); QueryId queryIdObj = TajoIdUtils.parseQueryId(queryId); QueryManager queryManager = masterContext.getQueryJobManager(); QueryInProgress queryInProgress = queryManager.getQueryInProgress(queryIdObj); QueryInfo queryInfo = null; if (queryInProgress == null) { queryInfo = queryManager.getFinishedQuery(queryIdObj); } else { queryInfo = queryInProgress.getQueryInfo(); } if (queryInfo != null) { if (briefPrint.equalsIgnoreCase(printType)) { queryInfo = getBriefQueryInfo(queryInfo); } return Response.ok(queryInfo).build(); } else { return Response.status(Status.NOT_FOUND).build(); } }
@POST public Response add(final String body) { logger.debug("Adding a new user with body {}", body); User user = userJsonConverter.convertFrom(body); if (user.getUserType().equals(User.UserType.EMPLOYEE)) { return Response.status(HttpCode.FORBIDDEN.getCode()).build(); } HttpCode httpCode = HttpCode.CREATED; OperationResult result; try { user = userService.add(user); result = OperationResult.success(JsonUtils.getJsonElementWithId(user.getId())); } catch (final FieldNotValidException e) { httpCode = HttpCode.VALIDATION_ERROR; logger.error("One of the fields of the user is not valid", e); result = getOperationResultInvalidField(RESOURCE_MESSAGE, e); } catch (final UserExistException e) { httpCode = HttpCode.VALIDATION_ERROR; logger.error("There is already an user for the given email", e); result = getOperationResultExists(RESOURCE_MESSAGE, "email"); } logger.debug("Returning the operation result after adding user: {}", result); return Response.status(httpCode.getCode()) .entity(OperationResultJsonWriter.toJson(result)) .build(); }
@PUT @Path("/{id}/password") @PermitAll public Response updatePassword(@PathParam("id") final Long id, final String body) { logger.debug("Updating the password for user {}", id); if (!securityContext.isUserInRole(Roles.ADMINISTRATOR.name())) { if (!isLoggedUser(id)) { return Response.status(HttpCode.FORBIDDEN.getCode()).build(); } } HttpCode httpCode = HttpCode.OK; OperationResult result; try { userService.updatePassword(id, getPasswordFromJson(body)); result = OperationResult.success(); } catch (UserNotFoundException e) { httpCode = HttpCode.NOT_FOUND; logger.error("No user found for the given id", e); result = getOperationResultNotFound(RESOURCE_MESSAGE); } logger.debug("Returning the operation result after updating user password: {}", result); return Response.status(httpCode.getCode()) .entity(OperationResultJsonWriter.toJson(result)) .build(); }
@Path("devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}/{serialNumber}") @DELETE public Response unregisterDevice( @PathParam("deviceLibraryIdentifier") String deviceLibraryIdentifier, @PathParam("passTypeIdentifier") String passTypeIdentifier, @PathParam("serialNumber") String serialNumber, @HeaderParam("Authorization") @DefaultValue("") String authorization) { PassDAO pass = new PassDAO(passTypeIdentifier, serialNumber); if (!pass.retrieve()) { // pass not found // response is UNAUTHORIZED in order to prevent trial/error/guessing for passes log.warn("pass does not exist: {}", serialNumber); return Response.status(Response.Status.UNAUTHORIZED).build(); } if (!AuthUtil.isAuthorized(authorization, pass.getAuthenticationToken())) { log.warn("invalid authorization: {}", authorization); return Response.status(Response.Status.UNAUTHORIZED).build(); } DeviceDAO device = new DeviceDAO(deviceLibraryIdentifier); if (device.retrieve()) { device.removeRegistration(passTypeIdentifier, serialNumber); if (device.store()) { return Response.status(Response.Status.OK).build(); } else { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } return Response.status(Response.Status.NOT_FOUND).build(); }
@PUT @Path("/{id}") public Response update(@PathParam("id") int id) { // Update the User resource UserDao.update(UserDao.get(id).get()); return Response.status(200).build(); }
@Override public Response run(JerseyResourceDelegateContext context) { JerseyResourceDelegateContextKey<String> sessionIdKey = JerseyResourceDelegateContextKey.valueOf(sessionIdKeyName, String.class); String sessionId = context.get(sessionIdKey); JerseyResourceDelegateContextKey<SubmitQueryRequest> submitQueryRequestKey = JerseyResourceDelegateContextKey.valueOf( submitQueryRequestKeyName, SubmitQueryRequest.class); SubmitQueryRequest request = context.get(submitQueryRequestKey); JerseyResourceDelegateContextKey<MasterContext> masterContextKey = JerseyResourceDelegateContextKey.valueOf( JerseyResourceDelegateUtil.MasterContextKey, MasterContext.class); MasterContext masterContext = context.get(masterContextKey); if (sessionId == null || sessionId.isEmpty()) { return ResourcesUtil.createBadRequestResponse(LOG, "Session Id is null or empty string."); } if (request == null || request.getQuery() == null || request.getQuery().isEmpty()) { return ResourcesUtil.createBadRequestResponse(LOG, "query is null or emptry string."); } Session session; try { session = masterContext.getSessionManager().getSession(sessionId); } catch (InvalidSessionException e) { return ResourcesUtil.createBadRequestResponse( LOG, "Provided session id (" + sessionId + ") is invalid."); } SubmitQueryResponse response = masterContext.getGlobalEngine().executeQuery(session, request.getQuery(), false); if (ReturnStateUtil.isError(response.getState())) { return ResourcesUtil.createExceptionResponse(LOG, response.getState().getMessage()); } else { JerseyResourceDelegateContextKey<UriInfo> uriInfoKey = JerseyResourceDelegateContextKey.valueOf( JerseyResourceDelegateUtil.UriInfoKey, UriInfo.class); UriInfo uriInfo = context.get(uriInfoKey); QueryId queryId = new QueryId(response.getQueryId()); URI queryURI = uriInfo .getBaseUriBuilder() .path(QueryResource.class) .path(QueryResource.class, "getQuery") .build(queryId.toString()); GetSubmitQueryResponse queryResponse = new GetSubmitQueryResponse(); if (queryId.isNull() == false) { queryResponse.setUri(queryURI); } queryResponse.setResultCode(response.getState().getReturnCode()); queryResponse.setQuery(request.getQuery()); return Response.status(Status.OK).entity(queryResponse).build(); } }
@GET @Path("/{id}") @RolesAllowed({"ADMINISTRATOR"}) public Response find(@PathParam("id") final Long id) { logger.debug("Find user by id: {}", id); Response.ResponseBuilder responseBuilder; try { User user = userService.find(id); OperationResult result = OperationResult.success(userJsonConverter.convertToJsonElement(user)); responseBuilder = Response.status(HttpCode.OK.getCode()).entity(OperationResultJsonWriter.toJson(result)); logger.debug("User found by id: {}", user); } catch (UserNotFoundException e) { logger.error("No user found for id", id); responseBuilder = Response.status(HttpCode.NOT_FOUND.getCode()); } return responseBuilder.build(); }
@Path("devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}") @GET public Response getSerialNumbersOfPassesAssociatedWithDevice( @PathParam("deviceLibraryIdentifier") String deviceLibraryIdentifier, @PathParam("passTypeIdentifier") String passTypeIdentifier, @QueryParam("passesUpdatedSince") @DefaultValue("") String passesUpdatedSince) { DeviceDAO device = new DeviceDAO(deviceLibraryIdentifier); ListOfPasses passes = new ListOfPasses(); passes.setLastUpdated(DateUtil.getTimeStamp()); if (device.retrieve()) { for (Registration reg : device.getRegistrations()) { if (passTypeIdentifier.equals(reg.getPassTypeIdentifier())) { passes.addSerialNumber(reg.getSerialNumber()); } } } if (passes.getSerialNumbers().size() > 0) { return Response.status(Response.Status.OK).entity(passes.toJson(Pass.PRETTY)).build(); } return Response.status(Response.Status.NO_CONTENT).build(); }
@Path("version") @GET @Produces(MediaType.APPLICATION_JSON) public Response getServiceVersion() { return Response.status(Response.Status.OK) .entity( "mobile-passes service version " + String.valueOf(ServiceConst.MAJOR_VERSION) + "." + String.valueOf(ServiceConst.MINOR_VERSION)) .build(); }
@PUT @Path("/{id}") @PermitAll public Response update(@PathParam("id") final Long id, final String body) { logger.debug("Updating the user {} with body {}", id, body); if (!securityContext.isUserInRole(Roles.ADMINISTRATOR.name())) { if (!isLoggedUser(id)) { return Response.status(HttpCode.FORBIDDEN.getCode()).build(); } } final User user = userJsonConverter.convertFrom(body); user.setId(id); HttpCode httpCode = HttpCode.OK; OperationResult result; try { userService.update(user); result = OperationResult.success(); } catch (FieldNotValidException e) { httpCode = HttpCode.VALIDATION_ERROR; logger.error("One of the fields of the user is not valid", e); result = getOperationResultInvalidField(RESOURCE_MESSAGE, e); } catch (UserExistException e) { httpCode = HttpCode.VALIDATION_ERROR; logger.error("There is already an user for the given email", e); result = getOperationResultExists(RESOURCE_MESSAGE, "email"); } catch (UserNotFoundException e) { httpCode = HttpCode.NOT_FOUND; logger.error("No user found for the given id", e); result = getOperationResultNotFound(RESOURCE_MESSAGE); } logger.debug("Returning the operation result after updating user: {}", result); return Response.status(httpCode.getCode()) .entity(OperationResultJsonWriter.toJson(result)) .build(); }
@Path("passes/{passTypeIdentifier}/{serialNumber}") @GET public Response getLatestVersionOfPass( @PathParam("passTypeIdentifier") String passTypeIdentifier, @PathParam("serialNumber") String serialNumber, @HeaderParam("Authorization") @DefaultValue("") String authorization, @HeaderParam("If-Modified-Since") @DefaultValue("") String ifModifedSince) { PassDAO pass = new PassDAO(serialNumber); if (!pass.retrieve()) { // pass not found // response is UNAUTHORIZED in order to prevent trial/error/guessing for passes log.warn("pass does not exist: {}", serialNumber); return Response.status(Response.Status.UNAUTHORIZED).build(); } if (!AuthUtil.isAuthorized(authorization, pass.getAuthenticationToken())) { log.warn("invalid authorization: {}", authorization); return Response.status(Response.Status.UNAUTHORIZED).build(); } return Response.status(Response.Status.OK).entity(pass.toJson()).build(); }
@GET @Path("/{upi}") @ApiOperation( value = "Get person by upi", notes = "Use pck123 as upi. Use 20 as api_key (or 123 to test FORBIDDEN with message)", response = Profile.class) @ApiResponses( value = { @ApiResponse(code = 400, message = "Invalid upi value"), @ApiResponse(code = 401, message = "Invalid api_key"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Person not found") }) @Produces(MediaType.APPLICATION_JSON) public Response getByUpi( @HeaderParam("api_key") String api_key, @ApiParam(value = "upi of a person", required = true, allowMultiple = true) @PathParam("upi") String upi) throws NotFoundException { if (api_key == null || api_key.charAt(api_key.length() - 1) != '0') { return Response.status(Response.Status.FORBIDDEN) .build(); // .entity("Invalid api key '"+api_key+"'").build(); } else if (api_key.equals("123")) { return Response.status(Response.Status.FORBIDDEN) .entity("Invalid api key '" + api_key + "'") .build(); } // return Response.status(Status.OK).entity(dto).type(request.getContentType()).build(); Profile result = PersonData.get(upi); if (result != null) return Response.ok().entity(result).build(); if (upi != null && upi.equals("pck123")) return Response.ok().entity(new Profile("Patrick", "pck123")).build(); else // throw new NotFoundException(400, "Invalid upi key"); return Response.status(Response.Status.NOT_FOUND).build(); }
@POST @Path("/authenticate") @PermitAll public Response findByEmailAndPassword(final String body) { logger.debug("Find user by email and password"); Response.ResponseBuilder responseBuilder; try { User userWithEmailAndPassword = getUserWithEmailAndPasswordFromJson(body); User user = userService.find( userWithEmailAndPassword.getEmail(), userWithEmailAndPassword.getPassword()); OperationResult result = OperationResult.success(userJsonConverter.convertToJsonElement(user)); responseBuilder = Response.status(HttpCode.OK.getCode()).entity(OperationResultJsonWriter.toJson(result)); logger.debug("User found by email/password: {}", user); } catch (UserNotFoundException e) { logger.error("No user found for email/password"); responseBuilder = Response.status(HttpCode.NOT_FOUND.getCode()); } return responseBuilder.build(); }
@Path("log") @POST @Consumes(MediaType.APPLICATION_JSON) public Response doLog(String logsAsJson) { ServiceLogs logs = ServiceLogs.fromJson(logsAsJson); LogDAO logger = new LogDAO(); log.info("Apple wants to tell us something:"); for (String line : logs.getLogs()) { logger.store(line); log.info("{}", line); } return Response.status(Response.Status.OK).build(); }
@Path("/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}/{serialNumber}") @POST public Response registerDeviceForPassPushNotifications( @PathParam("deviceLibraryIdentifier") String deviceLibraryIdentifier, @PathParam("passTypeIdentifier") String passTypeIdentifier, @PathParam("serialNumber") String serialNumber, @HeaderParam("Authorization") @DefaultValue("") String authorization, String jsonDictionaryWithPushToken) { PassDAO pass = new PassDAO(serialNumber); if (!pass.retrieve()) { // pass not found // response is UNAUTHORIZED in order to prevent trial/error/guessing for passes log.warn("pass does not exist: {}", serialNumber); return Response.status(Response.Status.UNAUTHORIZED).build(); } if (!AuthUtil.isAuthorized(authorization, pass.getAuthenticationToken())) { log.warn("invalid authorization: {}", authorization); return Response.status(Response.Status.UNAUTHORIZED).build(); } String pushToken = ServiceUtil.getPushTokenFromBody(jsonDictionaryWithPushToken); DeviceDAO device = new DeviceDAO(deviceLibraryIdentifier); device.retrieve(); if (device.addRegistration(passTypeIdentifier, serialNumber, pushToken) == 1) { // really added a new record if (device.store()) { return Response.status(Response.Status.CREATED).build(); } } else { // nothing added, was already in list return Response.status(Response.Status.OK).build(); } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); }
@GET @RolesAllowed({"ADMINISTRATOR"}) public Response findByFilter() { final UserFilter userFilter = new UserUrlFilterExtractor(uriInfo).getFilter(); logger.debug("Finding users using filter: {}", userFilter); final PaginatedData<User> users = userService.find(userFilter); logger.debug("Found {} users", users.getNumberOfRows()); final JsonElement jsonWithPagingAndEntries = JsonUtils.getJsonElementWithPagingAndEntries(users, userJsonConverter); return Response.status(HttpCode.OK.getCode()) .entity(JsonWriter.writeToString(jsonWithPagingAndEntries)) .build(); }
@POST @Path("/update") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response update(String jsonString) { ObjectMapper mapper = new ObjectMapper(); UpdateResult result = null; try { result = mapper.readValue(jsonString, UpdateResult.class); DAOManager.getInstance().getResultDAO().updateResult(result); } catch (Exception e) { System.out.println(e.getMessage()); } return Response.status(200).build(); }
@GET @Path("/person/login") @ApiOperation( value = "Sets a currently logged in person from the token", response = String.class, produces = MediaType.TEXT_PLAIN) @ApiResponses( value = { @ApiResponse(code = 400, message = "Invalid upi value"), @ApiResponse(code = 401, message = "Absent or incorect authentication information"), @ApiResponse(code = 404, message = "Person not found") }) public Response login( @ApiParam(value = "toke received from AS") @QueryParam("token") String token) { // TODO verify token // TODO extract user information from the token return Response.status(Response.Status.FORBIDDEN).build(); }
private Response sendErrorResponse(String error, String description, Status status) { if (status == Status.UNAUTHORIZED) { return Response.status(Status.UNAUTHORIZED).header(WWW_AUTHENTICATE, BASIC_REALM).build(); } return Response.status(status).entity(new ErrorResponse(error, description)).build(); }
@POST @Path("/cluster/resize") @Consumes(MediaType.APPLICATION_JSON) public Response clusterResize(final ClusterResizeRequest data) { int desired = data.getInstances(); if (desired == 0) { return Response.status(Response.Status.FORBIDDEN) .entity( new GenericAPIResponse() { @Override public int getStatus() { return Response.Status.FORBIDDEN.getStatusCode(); } @Override public Object getMessage() { return "Could not change the number of instances. Scaling down to zero instances is not allowed. Please use '/cluster/shutdown' instead."; } }) .build(); } CrateClient client = client(); if (desired < store.state().crateInstances().size() && client != null) { int maxReplicas = 0; try { SQLResponse response = client .sql( "select number_of_replicas from information_schema.tables group by number_of_replicas") .actionGet(); for (Object[] objects : response.rows()) { List<String> replicas = Splitter.on("-").splitToList((String) objects[0]); String val = replicas.get(replicas.size() - 1); if (replicas.size() == 2 && val.equals("all")) { val = replicas.get(0); } maxReplicas = Math.max(maxReplicas, Integer.parseInt(val)); } } catch (NoNodeAvailableException e) { // since we do not have a crate node to connect to we can accept the request to start up / // shut down nodes. LOGGER.error("No Crate node available.", e); } LOGGER.debug("max replicas = {} desired instances = {}", maxReplicas, desired); client.close(); if (maxReplicas > 0 && desired < maxReplicas + 1) { return Response.status(Response.Status.FORBIDDEN) .entity( new GenericAPIResponse() { @Override public int getStatus() { return Response.Status.FORBIDDEN.getStatusCode(); } @Override public Object getMessage() { return "Could not change the number of instances. The number of desired instances is lower than the number of replicas + 1."; } }) .build(); } } store.state().desiredInstances(desired); return Response.ok(new GenericAPIResponse() {}).build(); }