Ejemplo n.º 1
1
    @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();
      }
    }
  @GET
  @Path("/{id}")
  public Response get(@PathParam("id") int id, @Context Request request) {
    // Create cache control header
    CacheControl cc = new CacheControl();
    // Set max age to one day
    cc.setMaxAge(86400);

    Response.ResponseBuilder rb = null;

    // Calculate the ETag on last modified date of user resource
    EntityTag etag = new EntityTag(UserDao.getLastModifiedById(id).hashCode() + "");

    // Verify if it matched with etag available in http request
    rb = request.evaluatePreconditions(etag);

    // If ETag matches the rb will be non-null;
    // Use the rb to return the response without any further processing
    if (rb != null) {
      return rb.cacheControl(cc).tag(etag).build();
    }

    // If rb is null then either it is first time request; or resource is modified
    // Get the updated representation and return with Etag attached to it
    rb = Response.ok(UserDao.get(id).get()).cacheControl(cc).tag(etag);
    return rb.build();
  }
Ejemplo n.º 3
0
  @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();
  }
Ejemplo n.º 4
0
 @PUT
 @Consumes(MediaType.APPLICATION_XML)
 public Response putTaskData(String value) {
   Response res = null;
   // add your code here
   // first check if the Entity exists in the datastore
   DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
   MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
   syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
   Key entKey = KeyFactory.createKey("TaskData", keyname);
   Date date = new Date();
   try {
     // if it is, signal that we updated the entity
     Entity ts = datastore.get(entKey);
     ts.setProperty("value", value);
     ts.setProperty("date", date);
     datastore.put(ts);
     res = Response.noContent().build();
   } catch (EntityNotFoundException e) {
     // if it is not, create it and
     // signal that we created the entity in the datastore
     Entity taskdata = new Entity("TaskData", keyname);
     taskdata.setProperty("value", value);
     taskdata.setProperty("date", date);
     datastore.put(taskdata);
     res = Response.created(uriInfo.getAbsolutePath()).build();
   }
   TaskData td = new TaskData(keyname, value, date);
   syncCache.put(keyname, td);
   return res;
 }
  @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();
  }
Ejemplo n.º 6
0
  @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();
  }
 @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();
 }
 @POST
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 @Produces(BeeterMediaType.BEETER_AUTH_TOKEN)
 public Response registerUser(
     @FormParam("loginid") String loginid,
     @FormParam("password") String password,
     @FormParam("email") String email,
     @FormParam("fullname") String fullname,
     @Context UriInfo uriInfo)
     throws URISyntaxException {
   if (loginid == null || password == null || email == null || fullname == null)
     throw new BadRequestException("all parameters are mandatory");
   UserDAO userDAO = new UserDAOImpl();
   User user = null;
   AuthToken authToken = null;
   try {
     user = userDAO.createUser(loginid, password, email, fullname);
     authToken = (new AuthTokenDAOImpl()).createAuthToken(user.getId());
   } catch (UserAlreadyExistsException e) {
     throw new WebApplicationException("loginid already exists", Response.Status.CONFLICT);
   } catch (SQLException e) {
     throw new InternalServerErrorException();
   }
   URI uri = new URI(uriInfo.getAbsolutePath().toString() + "/" + user.getId());
   return Response.created(uri).type(BeeterMediaType.BEETER_AUTH_TOKEN).entity(authToken).build();
 }
Ejemplo n.º 9
0
  @Path(("/registrar"))
  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces(MusicloudMediaType.MUSICLOUD_AUTH_TOKEN)
  public Response registerUser(
      @FormParam("login") String login,
      @FormParam("nombre") String nombre,
      @FormParam("apellidos") String apellidos,
      @FormParam("email") String email,
      @FormParam("password") String password,
      @Context UriInfo uriInfo)
      throws URISyntaxException {
    if (login == null || nombre == null || apellidos == null || password == null || email == null)
      throw new BadRequestException("Se necesitan todos los parametros");
    UserDAO userDAO = new UserDAOImpl();
    User user = null;

    try {
      user = userDAO.crear_usuario_registrado(login, nombre, apellidos, email, password);

    } catch (UserAlreadyExistsException e) {
      throw new WebApplicationException("Este login ya existe ", Response.Status.CONFLICT);
    } catch (SQLException e) {
      throw new InternalServerErrorException();
    }
    URI uri = new URI(uriInfo.getAbsolutePath().toString() + "/" + user.getId());
    return Response.ok().build();
  }
Ejemplo n.º 10
0
 @POST
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 @Produces(GrouptalkMediaType.GROUPTALK_AUTH_TOKEN)
 public Response createJoinGroup(
     @FormParam("userid") String userid,
     @FormParam("groupid") String groupid,
     @Context UriInfo uriInfo)
     throws URISyntaxException {
   if (userid == null || groupid == null)
     throw new BadRequestException("all parameters are mandatory");
   JoinGroupDAO joinGroupDAO = new JoinGroupDAOImpl();
   JoinGroup joinGroup = null;
   AuthToken authenticationToken = null;
   try {
     joinGroup =
         joinGroupDAO.createJoinGroup(securityContext.getUserPrincipal().getName(), groupid);
   } catch (SQLException e) {
     throw new InternalServerErrorException();
   }
   URI uri = new URI(uriInfo.getAbsolutePath().toString() + "/" + joinGroup.getUserid());
   return Response.created(uri)
       .type(GrouptalkMediaType.GROUPTALK_InterestGroups)
       .entity(joinGroup)
       .build();
 }
Ejemplo n.º 11
0
    @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("/cluster")
 public Response clusterIndex(@Context UriInfo uriInfo) {
   final int desired = store.state().desiredInstances().getValue();
   final int running = store.state().crateInstances().size();
   final HashMap<String, List<String>> excluded = store.state().excludedSlaves();
   return Response.ok()
       .entity(
           new GenericAPIResponse() {
             @Override
             public Object getMessage() {
               return new HashMap<String, Object>() {
                 {
                   put("mesosMaster", conf.mesosMaster());
                   put(
                       "instances",
                       new HashMap<String, Integer>() {
                         {
                           put("desired", desired);
                           put("running", running);
                         }
                       });
                   put("excludedSlaves", excluded);
                   put(
                       "cluster",
                       new HashMap<String, Object>() {
                         {
                           put("version", conf.version);
                           put("name", conf.clusterName);
                           put("httpPort", conf.httpPort);
                           put("nodeCount", conf.nodeCount);
                         }
                       });
                   put(
                       "resources",
                       new HashMap<String, Double>() {
                         {
                           put("memory", conf.resMemory);
                           put("heap", conf.resHeap);
                           put("cpus", conf.resCpus);
                           put("disk", conf.resDisk);
                         }
                       });
                   put(
                       "api",
                       new HashMap<String, Integer>() {
                         {
                           put("apiPort", conf.apiPort);
                         }
                       });
                 }
               };
             }
           })
       .build();
 }
Ejemplo n.º 13
0
 private Response sendAuthorizationCodeResponse(AuthorizationRequest authReq) {
   String uri = authReq.getRedirectUri();
   String authorizationCode = getAuthorizationCodeValue();
   authReq.setAuthorizationCode(authorizationCode);
   authorizationRequestRepository.save(authReq);
   uri = uri + appendQueryMark(uri) + "code=" + authorizationCode + appendStateParameter(authReq);
   return Response.seeOther(UriBuilder.fromUri(uri).build())
       .cacheControl(cacheControlNoStore())
       .header("Pragma", "no-cache")
       .build();
 }
Ejemplo n.º 14
0
  @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();
 }
  @GET
  @Path("/setOperatorToKen")
  @ApiOperation(
      value = "A quick way to sets value of operator to Ken profile",
      notes = "For testing purposes",
      response = String.class,
      produces = MediaType.TEXT_PLAIN)
  public Response setOperatorToKen() throws NotFoundException {
    if (PersonData.get(PersonData.KEN.getUpi()) == null) PersonData.replace(PersonData.KEN);

    return Response.ok().entity(PersonData.setOperator(PersonData.KEN.getUpi())).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();
 }
Ejemplo n.º 18
0
  /**
   * The "token endpoint" as described in <a
   * href="http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-3.2">Section 3.2</a> of the
   * OAuth spec.
   *
   * @param authorization the HTTP Basic auth header.
   * @param formParameters the request parameters
   * @return the response
   */
  @POST
  @Path("/token")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes("application/x-www-form-urlencoded")
  public Response token(
      @HeaderParam("Authorization") String authorization,
      final MultivaluedMap<String, String> formParameters) {
    // Convert incoming parameters into internal form and validate them
    AccessTokenRequest accessTokenRequest =
        AccessTokenRequest.fromMultiValuedFormParameters(formParameters);
    BasicAuthCredentials credentials =
        BasicAuthCredentials.createCredentialsFromHeader(authorization);

    ValidationResponse vr = oAuth2Validator.validate(accessTokenRequest, credentials);
    if (!vr.valid()) {
      return sendErrorResponse(vr);
    }

    // The request looks valid, attempt to process
    String grantType = accessTokenRequest.getGrantType();
    AuthorizationRequest request;
    try {
      if (GRANT_TYPE_AUTHORIZATION_CODE.equals(grantType)) {
        request = authorizationCodeToken(accessTokenRequest);
      } else if (GRANT_TYPE_REFRESH_TOKEN.equals(grantType)) {
        request = refreshTokenToken(accessTokenRequest);
      } else if (GRANT_TYPE_CLIENT_CREDENTIALS.equals(grantType)) {
        request = clientCredentialToken(accessTokenRequest);
      } else if (GRANT_TYPE_PASSWORD.equals(grantType)) {
        request = passwordToken(accessTokenRequest);
      } else {
        return sendErrorResponse(ValidationResponse.UNSUPPORTED_GRANT_TYPE);
      }
    } catch (ValidationResponseException e) {
      return sendErrorResponse(e.v);
    }
    AccessToken token = createAccessToken(request, false);

    AccessTokenResponse response =
        new AccessTokenResponse(
            token.getToken(),
            BEARER,
            token.getExpiresIn(),
            token.getRefreshToken(),
            StringUtils.join(token.getScopes(), ' '));

    return Response.ok()
        .entity(response)
        .cacheControl(cacheControlNoStore())
        .header("Pragma", "no-cache")
        .build();
  }
Ejemplo n.º 19
0
 @GET
 @Path("/{type}")
 @Produces(MediaType.APPLICATION_JSON)
 public Response getItemsByType(@PathParam("type") String type) {
   System.out.println("get item by type = " + type);
   List<Item> items = ItemDao.getItemsByType(type);
   final GenericEntity<List<Item>> entity = new GenericEntity<List<Item>>(items) {};
   return Response.ok()
       .entity(entity)
       .header("Access-Control-Allow-Origin", "*")
       .header("Access-Control-Allow-Methods", "POST, GET")
       .build();
 }
Ejemplo n.º 20
0
  @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();
  }
Ejemplo n.º 21
0
 @GET
 @Path("/")
 @Produces(MediaType.APPLICATION_JSON)
 public Response getItems() {
   System.out.println("get all items ");
   List<Item> items = ItemDao.getItems();
   final GenericEntity<List<Item>> entity = new GenericEntity<List<Item>>(items) {};
   return Response.ok()
       .entity(entity)
       .header("Access-Control-Allow-Origin", "*")
       .header("Access-Control-Allow-Methods", "POST, GET")
       .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();
  }
Ejemplo n.º 24
0
  @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();
  }
Ejemplo n.º 26
0
    @Override
    public Response run(JerseyResourceDelegateContext context) {
      JerseyResourceDelegateContextKey<String> stateKey =
          JerseyResourceDelegateContextKey.valueOf(stateKeyName, String.class);
      String state = context.get(stateKey);
      JerseyResourceDelegateContextKey<Long> startTimeKey =
          JerseyResourceDelegateContextKey.valueOf(startTimeKeyName, Long.class);
      long startTime = context.get(startTimeKey);
      JerseyResourceDelegateContextKey<Long> endTimeKey =
          JerseyResourceDelegateContextKey.valueOf(endTimeKeyName, Long.class);
      long endTime = context.get(endTimeKey);
      JerseyResourceDelegateContextKey<MasterContext> masterContextKey =
          JerseyResourceDelegateContextKey.valueOf(
              JerseyResourceDelegateUtil.MasterContextKey, MasterContext.class);
      MasterContext masterContext = context.get(masterContextKey);

      TajoProtos.QueryState queryState = null;
      try {
        if (state != null && !state.isEmpty()) {
          queryState = TajoProtos.QueryState.valueOf(state);
        }
      } catch (Exception e) {
        return ResourcesUtil.createBadRequestResponse(LOG, state + " is not a valid query state.");
      }

      Map<String, List<QueryInfo>> queriesMap = new HashMap<>();
      List<QueryInfo> queriesInfo = new ArrayList<>();

      QueryManager queryManager = masterContext.getQueryJobManager();
      for (QueryInProgress queryInProgress : queryManager.getSubmittedQueries()) {
        queriesInfo.add(queryInProgress.getQueryInfo());
      }

      for (QueryInProgress queryInProgress : queryManager.getRunningQueries()) {
        queriesInfo.add(queryInProgress.getQueryInfo());
      }

      queriesInfo.addAll(queryManager.getFinishedQueries());

      if (state != null) {
        queriesInfo = selectQueriesInfoByState(queriesInfo, queryState);
      }

      if (startTime > 0 || endTime > 0) {
        queriesInfo = selectQueriesInfoByTime(queriesInfo, startTime, endTime);
      }
      queriesMap.put("queries", queriesInfo);

      return Response.ok(queriesMap).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();
  }
Ejemplo n.º 28
0
  @RolesAllowed({"administrador", "registrado"})
  @Path("/modificarPASSWORD/{login}")
  @POST
  public Response modificarPASSWORD(
      @FormParam("password") String password, @PathParam("login") String login)
      throws SQLException {

    UserDAO userdao = new UserDAOImpl();
    try {
      userdao.insertarPASWWORD(login, password);
    } catch (SQLException e) {
      throw new InternalServerErrorException();
    }
    return Response.ok().build();
  }
 @PUT
 @Path("/person/me/{myUpi}")
 @ApiOperation(
     value = "Currently logged person. This is what is returned me call to /me",
     notes = "This is a mockup",
     response = String.class,
     produces = MediaType.TEXT_PLAIN)
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Previous upi"),
       @ApiResponse(code = 400, message = "Unexpected error")
     })
 public Response setMe(@ApiParam(value = "my upi") @PathParam("myUpi") String newUpi) {
   return Response.ok().entity(PersonData.setMe(newUpi)).build();
 }
Ejemplo n.º 30
0
  @RolesAllowed({"administrador", "registrado"})
  @Path("/eliminar/{login}")
  @DELETE
  public Response eliminarUser(@PathParam("login") String login) throws UserNoExisteException {

    UserDAO userdao = new UserDAOImpl();
    try {

      if (!userdao.eliminar_Usuario(login))
        throw new WebApplicationException("Este usuario no existe ", Response.Status.CONFLICT);
    } catch (SQLException e) {
      throw new InternalServerErrorException();
    }
    return Response.ok().build();
  }