play.mvc.Http Java Examples

The following examples show how to use play.mvc.Http. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserSkillControllerTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testGetSkill() {

  Map<String, Object> requestMap = new HashMap<>();
  Map<String, Object> innerMap = new HashMap<>();
  innerMap.put(JsonKey.USER_ID, "7687584");
  requestMap.put(JsonKey.REQUEST, innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  Http.RequestBuilder req =
      new Http.RequestBuilder().bodyJson(json).uri("/v1/user/skill/read").method("POST");
  //req.headers(headerMap);
  Result result = Helpers.route(application,req);
  assertEquals(200, result.status());
}
 
Example #2
Source File: BadgeAssertionController.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * This method will be called to issue a badge either on content or user. Request Param
 * {"issuerSlug":"unique String","badgeSlug" : "unique string",
 * "recipientEmail":"email","evidence":"url , basically it is badge class public url"
 * ,"notify":boolean}
 *
 * @return CompletionStage<Result>
 */
public CompletionStage<Result> issueBadge(Http.Request httpRequest) {
  try {
    JsonNode requestData = httpRequest.body().asJson();
    ProjectLogger.log(" Issue badge method called = " + requestData, LoggerEnum.DEBUG.name());
    Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class);
    BadgeAssertionValidator.validateBadgeAssertion(reqObj);
    reqObj =
        setExtraParam(
            reqObj,
            httpRequest.flash().get(JsonKey.REQUEST_ID),
            BadgingActorOperations.CREATE_BADGE_ASSERTION.getValue(),
            httpRequest.flash().get(JsonKey.USER_ID),
            getEnvironment());
    return actorResponseHandler(getActorRef(), reqObj, timeout, null, httpRequest);
  } catch (Exception e) {
    return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
  }
}
 
Example #3
Source File: OrganisationMetricsController.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public CompletionStage<Result> orgConsumption(String orgId, Http.Request httpRequest) {
  ProjectLogger.log("Start Org Metrics Consumption Contoller");
  try {
    String periodStr = httpRequest.getQueryString(JsonKey.PERIOD);
    Map<String, Object> map = new HashMap<>();
    map.put(JsonKey.ORG_ID, orgId);
    map.put(JsonKey.PERIOD, periodStr);
    Request request = new Request();
    request.setEnv(getEnvironment());
    request.setRequest(map);
    request.setOperation(ActorOperations.ORG_CONSUMPTION_METRICS.getValue());
    request.setRequest(map);
    request.setRequestId(httpRequest.flash().get(JsonKey.REQUEST_ID));
    ProjectLogger.log("Return from Org Metrics Consumption Contoller");
    return actorResponseHandler(getActorRef(), request, timeout, null, httpRequest);
  } catch (Exception e) {
    return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
  }
}
 
Example #4
Source File: RequestInterceptor.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
private static String getUserRequestedFor(Http.Request request) {
  String requestedForUserID = null;
  JsonNode jsonBody = request.body().asJson();
  if (!(jsonBody == null)) { // for search and update and create_mui api's
    if (!(jsonBody.get(JsonKey.REQUEST).get(JsonKey.USER_ID) == null)) {
      requestedForUserID = jsonBody.get(JsonKey.REQUEST).get(JsonKey.USER_ID).asText();
    }
  } else { // for read-api
    String uuidSegment = null;
    Path path = Paths.get(request.uri());
    if (request.queryString().isEmpty()) {
      uuidSegment = path.getFileName().toString();
    } else {
      String[] queryPath = path.getFileName().toString().split("\\?");
      uuidSegment = queryPath[0];
    }
    try {
      requestedForUserID = UUID.fromString(uuidSegment).toString();
    } catch (IllegalArgumentException iae) {
      ProjectLogger.log("Perhaps this is another API, like search that doesn't carry user id.");
    }
  }
  return requestedForUserID;
}
 
Example #5
Source File: CategoryTreeFacetedSearchFormSettingsImpl.java    From commercetools-sunrise-java with Apache License 2.0 6 votes vote down vote up
@Override
public List<FilterExpression<ProductProjection>> buildFilterExpressions(final Http.Context httpContext) {
    final List<SpecialCategorySettings> specialCategories = categoriesSettings.specialCategories();
    if (!specialCategories.isEmpty()) {
        final Optional<Category> selectedCategory = getSelectedValue(httpContext);
        if (selectedCategory.isPresent()) {
            return specialCategories.stream()
                    .filter(config -> config.externalId().equals(selectedCategory.get().getExternalId()))
                    .findAny()
                    .map(config -> config.productFilterExpressions().stream()
                            .map(expression -> SearchUtils.replaceCategoryExternalId(expression, categoryTree))
                            .map(FilterExpression::<ProductProjection>of)
                            .collect(toList()))
                    .orElseGet(() -> CategoryTreeFacetedSearchFormSettings.super.buildFilterExpressions(httpContext));
        }
    }
    return CategoryTreeFacetedSearchFormSettings.super.buildFilterExpressions(httpContext);
}
 
Example #6
Source File: UserSkillEndorsementControllerTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testAddSkillEndorsement() {
  PowerMockito.mockStatic(RequestInterceptor.class);
  when(RequestInterceptor.verifyRequestData(Mockito.anyObject()))
      .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh");
  Map<String, Object> requestMap = new HashMap();
  Map<String, Object> innerMap = new HashMap<>();
  innerMap.put(JsonKey.USER_ID, "{userId} uuiuhcf784508 8y8c79-fhh");
  innerMap.put(JsonKey.ENDORSED_USER_ID, "1223");
  innerMap.put(JsonKey.SKILL_NAME, "C");

  requestMap.put(JsonKey.REQUEST, innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  Http.RequestBuilder req =
      new Http.RequestBuilder().bodyJson(json).uri("/v1/user/skill/endorse/add").method("POST");
  //req.headers(headerMap);
  Result result = Helpers.route(application,req);
  assertEquals(200, result.status());
}
 
Example #7
Source File: BadgeAssertionController.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * This controller will provide list of assertions based on issuerSlug,badgeSlug and assertionSlug
 *
 * @return CompletionStage<Result>
 */
public CompletionStage<Result> getAssertionList(Http.Request httpRequest) {
  try {
    JsonNode requestData = httpRequest.body().asJson();
    ProjectLogger.log(" get assertion list api called = " + requestData, LoggerEnum.DEBUG.name());
    Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class);
    BadgeAssertionValidator.validateGetAssertionList(reqObj);
    reqObj =
        setExtraParam(
            reqObj,
            httpRequest.flash().get(JsonKey.REQUEST_ID),
            BadgingActorOperations.GET_BADGE_ASSERTION_LIST.getValue(),
            httpRequest.flash().get(JsonKey.USER_ID),
            getEnvironment());
    return actorResponseHandler(getActorRef(), reqObj, timeout, null, httpRequest);
  } catch (Exception e) {
    return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
  }
}
 
Example #8
Source File: SlingApiController.java    From swagger-aem with Apache License 2.0 6 votes vote down vote up
@ApiAction
public Result postNode(String path,String name) throws Exception {
    String valuecolonOperation = request().getQueryString(":operation");
    String colonOperation;
    if (valuecolonOperation != null) {
        colonOperation = valuecolonOperation;
    } else {
        colonOperation = null;
    }
    String valuedeleteAuthorizable = request().getQueryString("deleteAuthorizable");
    String deleteAuthorizable;
    if (valuedeleteAuthorizable != null) {
        deleteAuthorizable = valuedeleteAuthorizable;
    } else {
        deleteAuthorizable = null;
    }
    Http.MultipartFormData.FilePart file = request().body().asMultipartFormData().getFile("file");
    imp.postNode(path, name, colonOperation, deleteAuthorizable, file);
    return ok();
}
 
Example #9
Source File: BadgeIssuerController.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * This method will add badges to user profile.
 *
 * @return CompletionStage<Result>
 */
public CompletionStage<Result> deleteBadgeIssuer(String issuerId, Http.Request httpRequest) {
  try {
    Request reqObj = new Request();
    reqObj =
        setExtraParam(
            reqObj,
            httpRequest.flash().get(JsonKey.REQUEST_ID),
            BadgeOperations.deleteIssuer.name(),
            httpRequest.flash().get(JsonKey.USER_ID),
            getEnvironment());
    reqObj.getRequest().put(JsonKey.SLUG, issuerId);
    new BadgeIssuerRequestValidator().validateGetBadgeIssuerDetail(reqObj);
    return actorResponseHandler(getActorRef(), reqObj, timeout, null, httpRequest);
  } catch (Exception e) {
    return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
  }
}
 
Example #10
Source File: TenantPreferenceController.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public CompletionStage<Result> updateTenantPreference(Http.Request httpRequest) {
  try {
    JsonNode requestData = httpRequest.body().asJson();
    ProjectLogger.log("Update tenant preferences: " + requestData, LoggerEnum.INFO.name());
    Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class);
    reqObj.setOperation(ActorOperations.UPDATE_TENANT_PREFERENCE.getValue());
    reqObj.setRequestId(httpRequest.flash().get(JsonKey.REQUEST_ID));
    reqObj.setEnv(getEnvironment());
    Map<String, Object> innerMap = reqObj.getRequest();
    innerMap.put(JsonKey.REQUESTED_BY, httpRequest.flash().get(JsonKey.USER_ID));
    reqObj.setRequest(innerMap);
    return actorResponseHandler(getActorRef(), reqObj, timeout, null, httpRequest);
  } catch (Exception e) {
    return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
  }
}
 
Example #11
Source File: OrgMemberController.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public CompletionStage<Result> removeMemberFromOrganisation(Http.Request httpRequest) {
  return handleRequest(
      ActorOperations.REMOVE_MEMBER_ORGANISATION.getValue(),
      httpRequest.body().asJson(),
      orgRequest -> {
        new OrgMemberRequestValidator().validateCommon((Request) orgRequest);
        return null;
      },
      getAllRequestHeaders(request()), httpRequest);
}
 
Example #12
Source File: NotesController.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
/**
 * Method to get the note details
 *
 * @param noteId
 * @return CompletionStage<Result>
 */
public CompletionStage<Result> getNote(String noteId, Http.Request httpRequest) {
  return handleRequest(
      ActorOperations.GET_NOTE.getValue(),
      (request) -> {
        new NoteRequestValidator().validateNoteId(noteId);
        return null;
      },
      noteId,
      JsonKey.NOTE_ID,
          httpRequest);
}
 
Example #13
Source File: BasicHttpAuthenticationFilterTest.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Test
public void unauthorizedWhenEnabledAndWrongCredentialsProvided() throws Exception {
    try (WSClient wsClient = WS.newClient(testServer.port())) {
        final WSResponse response = wsClient
                .url(URI)
                .setAuth(USERNAME, "wrong", WSAuthScheme.BASIC)
                .get().toCompletableFuture().get();
        assertThat(response.getStatus()).isEqualTo(Http.Status.UNAUTHORIZED);
        assertThat(response.getHeader(Http.HeaderNames.WWW_AUTHENTICATE)).isNull();
    }
}
 
Example #14
Source File: ThreadDumpController.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public CompletionStage<Result> threaddump(Http.Request httpRequest) {
  final StringBuilder dump = new StringBuilder();
  final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  final ThreadInfo[] threadInfos =
      threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);
  for (ThreadInfo threadInfo : threadInfos) {
    dump.append('"');
    dump.append(threadInfo.getThreadName());
    dump.append("\" ");
    final Thread.State state = threadInfo.getThreadState();
    dump.append("\n   java.lang.Thread.State: ");
    dump.append(state);
    final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
    for (final StackTraceElement stackTraceElement : stackTraceElements) {
      dump.append("\n        at ");
      dump.append(stackTraceElement);
    }
    dump.append("\n\n");
  }
  System.out.println("=== thread-dump start ===");
  System.out.println(dump.toString());
  System.out.println("=== thread-dump end ===");
  Request request = new Request();
  request.setOperation("takeThreadDump");
  request.setEnv(getEnvironment());
  if ("off".equalsIgnoreCase(BackgroundRequestRouter.getMode())) {
    actorResponseHandler(
        SunbirdMWService.getBackgroundRequestRouter(), request, timeout, null, httpRequest);
  }
  return CompletableFuture.supplyAsync(() -> ok("successful"));
}
 
Example #15
Source File: OnRequestHandler.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
/**
 * This method will do request data validation for GET method only. As a GET request user must
 * send some key in header.
 *
 * @param request Request
 * @param errorMessage String
 * @return CompletionStage<Result>
 */
public CompletionStage<Result> onDataValidationError(
    Http.Request request, String errorMessage, int responseCode) {
  ProjectLogger.log("Data error found--" + errorMessage);
  ResponseCode code = ResponseCode.getResponse(errorMessage);
  ResponseCode headerCode = ResponseCode.CLIENT_ERROR;
  Response resp = BaseController.createFailureResponse(request, code, headerCode);
  return CompletableFuture.completedFuture(Results.status(responseCode, Json.toJson(resp)));
}
 
Example #16
Source File: CustomGzipFilter.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Inject
public CustomGzipFilter(Materializer materializer) {
    GzipFilterConfig gzipFilterConfig = new GzipFilterConfig();
    gzipFilter = new GzipFilter(
            gzipFilterConfig.withBufferSize(BUFFER_SIZE)
                    .withChunkedThreshold(CHUNKED_THRESHOLD)
                    .withShouldGzip((BiFunction<Http.RequestHeader, Result, Object>)
                            (req, res) -> shouldGzipFunction(req, res)),
            materializer
    );
}
 
Example #17
Source File: MetricsLogger.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
private static void logDebugRequestData(final List<ObservedTotalDuration> metrics, final Http.Context ctx, final long totalDuration) {
    String report = metrics.stream()
            .map(data -> String.format("(%dms) %s",
                    data.getDurationInMilliseconds(),
                    CtpLogUtils.printableRequest(data.getRequest())))
            .collect(joining("\n"));
    if (!report.isEmpty()) {
        report = ":\n" + report;
    }
    LOGGER.debug("({}ms) {} used {} CTP request(s){}",
            totalDuration,
            ctx.request(),
            metrics.size(),
            report);
}
 
Example #18
Source File: ApiCall.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public CompletionStage<Result> call(Http.Context ctx) {
    try {
        //TODO: Do stuff you want to handle with each API call (metrics, logging, etc..)
        return delegate.call(ctx);
    } catch (Throwable t) {
        //TODO: log the error in your metric

        //We rethrow this error so it will be caught in the ErrorHandler
        throw t;
    }
}
 
Example #19
Source File: TermFacetedSearchFormSettings.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
default List<FilterExpression<T>> buildFilterExpressions(final Http.Context httpContext) {
    final List<String> selectedValues = getAllSelectedValues(httpContext);
    final FacetedSearchSearchModel<T> searchModel = TermFacetedSearchSearchModel.of(getAttributePath());
    final TermFacetedSearchExpression<T> facetedSearchExpr;
    if (selectedValues.isEmpty()) {
        facetedSearchExpr = searchModel.allTerms();
    } else if (isMatchingAll()) {
        facetedSearchExpr = searchModel.containsAll(selectedValues);
    } else {
        facetedSearchExpr = searchModel.containsAny(selectedValues);
    }
    return facetedSearchExpr.filterExpressions();
}
 
Example #20
Source File: UserSkillController.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public CompletionStage<Result> updateSkill(Http.Request httpRequest) {
  try {
    JsonNode bodyJson = httpRequest.body().asJson();
    Request reqObj = createAndInitRequest(ActorOperations.UPDATE_SKILL.getValue(), bodyJson, httpRequest);
    new UserSkillRequestValidator().validateUpdateSkillRequest(reqObj);
    return actorResponseHandler(getActorRef(), reqObj, timeout, null, httpRequest);
  } catch (Exception e) {
    return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
  }
}
 
Example #21
Source File: UserDataEncryptionController.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public CompletionStage<Result> decrypt(Http.Request httpRequest) {
  return handleRequest(
      ActorOperations.DECRYPT_USER_DATA.getValue(),
      httpRequest.body().asJson(),
      (request) -> {
        new UserDataEncryptionRequestValidator().validateDecryptRequest((Request) request);
        return null;
      },
      getAllRequestHeaders(httpRequest),
          httpRequest);
}
 
Example #22
Source File: SortFormSettings.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
default List<QuerySort<T>> buildQueryExpressions(final Http.Context httpContext) {
    return getSelectedOption(httpContext)
            .map(option -> option.getValue().stream()
                    .map(QuerySort::<T>of)
                    .collect(toList()))
            .orElseGet(Collections::emptyList);
}
 
Example #23
Source File: SunriseControllerTest.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Test
public void savesLastMessageOfSameTypeInFlash() throws Exception {
    final String message1 = "foo";
    final String message2 = "bar";
    invokeWithContext(fakeRequest(), () -> {
        assertThat(Http.Context.current().flash()).isEmpty();
        testController.saveMessage(SUCCESS, message1);
        testController.saveMessage(SUCCESS, message2);
        assertThat(Http.Context.current().flash())
                .doesNotContainEntry(SUCCESS.name(), message1)
                .containsEntry(SUCCESS.name(), message2);
        return null;
    });
}
 
Example #24
Source File: UserTypeControllerTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public Result performTest(String url, String method, Map map) {
  String data = mapToJson(map);
  Http.RequestBuilder req;
  if (StringUtils.isNotBlank(data)) {
    JsonNode json = Json.parse(data);
    req = new Http.RequestBuilder().bodyJson(json).uri(url).method(method);
  } else {
    req = new Http.RequestBuilder().uri(url).method(method);
  }
  //req.headers(new Http.Headers(headerMap));
  Result result = Helpers.route(application, req);
  return result;
}
 
Example #25
Source File: ProductPaginationControllerComponent.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
public ProductProjectionSearch onProductProjectionSearch(final ProductProjectionSearch search) {
    final Http.Context context = Http.Context.current();
    final long limit = getEntriesPerPageSettings().getLimit(context);
    final long offset = getPaginationSettings().getOffset(context, limit);
    return search
            .withOffset(offset)
            .withLimit(limit);
}
 
Example #26
Source File: Authentication.java    From pfe-samples with MIT License 5 votes vote down vote up
public static <A> A authenticated(Http.Context ctx, F.Function<String, A> f, F.Function0<A> g) throws Throwable {
    String username = ctx.session().get(USER_KEY);
    if (username != null) {
        return f.apply(username);
    } else {
        return g.apply();
    }
}
 
Example #27
Source File: UserDataEncryptionController.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public CompletionStage<Result> encrypt(Http.Request httpRequest) {
  return handleRequest(
      ActorOperations.ENCRYPT_USER_DATA.getValue(),
      httpRequest.body().asJson(),
      (request) -> {
        new UserDataEncryptionRequestValidator().validateEncryptRequest((Request) request);
        return null;
      },
      getAllRequestHeaders(httpRequest),
          httpRequest);
}
 
Example #28
Source File: HomeControllerUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenRequest_whenBadRequest_ThenStatusBadRequest() {
    Http.RequestBuilder request = new Http.RequestBuilder()
            .method(GET)
            .uri("/baeldung/bad-req");

    Result result = route(app, request);
    assertEquals(BAD_REQUEST, result.status());
}
 
Example #29
Source File: CertificateController.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public CompletionStage<Result> getSignUrl(Http.Request httpRequest) {
	return handleRequest(ActorOperations.GET_SIGN_URL.getValue(), httpRequest.body().asJson(), req -> {
		Request request = (Request) req;
		CertAddRequestValidator.getInstance(request).validateDownlaodFileData();
		return null;
	}, null, null, true,
           httpRequest);
}
 
Example #30
Source File: UserRoleController.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public CompletionStage<Result> assignRoles(Http.Request httpRequest) {
   final boolean isPrivate = httpRequest.path().contains(JsonKey.PRIVATE)?true:false;

  return handleRequest(
      ActorOperations.ASSIGN_ROLES.getValue(),
      httpRequest.body().asJson(),
      (request) -> {
        Request req = (Request) request;
        req.getContext().put(JsonKey.PRIVATE, isPrivate);
        new UserRoleRequestValidator().validateAssignRolesRequest(req);
        return null;
      },
          httpRequest);
}