Java Code Examples for play.mvc.Http#Context

The following examples show how to use play.mvc.Http#Context . 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: 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 2
Source File: GSNDeadboltHandler.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Promise<Result> beforeAuthCheck(final Http.Context context) {
	if (PlayAuthenticate.isLoggedIn(context.session())) {
		// user is logged in
		return F.Promise.pure(null);
	} else {
		// user is not logged in

		// call this if you want to redirect your visitor to the page that
		// was requested before sending him to the login page
		// if you don't call this, the user will get redirected to the page
		// defined by your resolver
		final String originalUrl = PlayAuthenticate.storeOriginalUrl(context);
		
		System.out.println("-----------------"+originalUrl);

		context.flash().put("error",
				"You need to log in first, to view '" + originalUrl + "'");
           return F.Promise.promise(new F.Function0<Result>()
           {
               @Override
               public Result apply() throws Throwable
               {
                   return redirect(PlayAuthenticate.getResolver().login());
               }
           });
	}
}
 
Example 3
Source File: FormSettingsWithOptions.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all selected valid options for this form in the HTTP request.
 * @param httpContext current HTTP context
 * @return a list of valid selected options for this form
 */
default List<T> getAllSelectedOptions(final Http.Context httpContext) {
    final List<String> selectedValues = getSelectedValuesAsRawList(httpContext);
    return getOptions().stream()
            .filter(option -> selectedValues.contains(option.getFieldValue()))
            .collect(toList());
}
 
Example 4
Source File: TestUtils.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
public static Http.Response setRequest(String body) {
    Http.Request mockRequest = mock(Http.Request.class);
    when(mockRequest.body()).thenReturn(new Http.RequestBody(Json.parse(body)));
    Http.Response mockResponse = mock(Http.Response.class);
    doNothing().when(mockResponse).setHeader(
            any(String.class), any(String.class));
    Http.Context mockContext = mock(Http.Context.class);
    when(mockContext.request()).thenReturn(mockRequest);
    when(mockContext.response()).thenReturn(mockResponse);
    Http.Context.current.set(mockContext);
    return mockResponse;
}
 
Example 5
Source File: GSNDeadboltHandler.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
@Override
public F.Promise<Result> onAuthFailure(final Http.Context context,
		final String content) {
	// if the user has a cookie with a valid user and the local user has
	// been deactivated/deleted in between, it is possible that this gets
	// shown. You might want to consider to sign the user out in this case.
       return F.Promise.promise(new F.Function0<Result>()
       {
           @Override
           public Result apply() throws Throwable
           {
               return forbidden("Forbidden");
           }
       });
}
 
Example 6
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 7
Source File: MyDeadboltHandler.java    From thunderbit with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Promise<Result> onAuthFailure(final Http.Context context, final String content) {
       if (context.session().get("username") != null && !context.session().get("username").isEmpty()) {
           return Promise.promise(() -> forbidden("Forbidden"));
       } else {
           return Promise.promise(() -> redirect(routes.Authentication.login()));
       }
}
 
Example 8
Source File: MetricsLogger.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Result> call(final Http.Context ctx) {
    if (LOGGER.isDebugEnabled()) {
        if (sphereClient instanceof SimpleMetricsSphereClient) {
            return callWithMetrics((SimpleMetricsSphereClient) sphereClient, ctx);
        } else {
            LOGGER.warn(ctx.request() + " enabled logging via @LogMetrics annotation without a SimpleMetricsSphereClient");
        }
    }
    return delegate.call(ctx);
}
 
Example 9
Source File: TestUtils.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
public static void setRequest(String body) {
    Http.Request mockRequest = mock(Http.Request.class);
    when(mockRequest.body()).thenReturn(new Http.RequestBody(Json.parse(body)));
    Http.Response mockResponse = mock(Http.Response.class);
    doNothing().when(mockResponse).setHeader(
            any(String.class), any(String.class));
    Http.Context mockContext = mock(Http.Context.class);
    when(mockContext.request()).thenReturn(mockRequest);
    when(mockContext.response()).thenReturn(mockResponse);
    Http.Context.current.set(mockContext);
}
 
Example 10
Source File: ComponentsRegisterer.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Result> call(final Http.Context ctx) {
    if (configuration.value().length > 0) {
        // On creation of this action there isn't any HTTP context, necessary to initialize the ComponentRegistry
        final ComponentRegistry componentRegistry = injector.instanceOf(ComponentRegistry.class);
        Arrays.stream(configuration.value())
                .forEach(componentClass -> registerComponent(componentRegistry, componentClass));
    }
    return delegate.call(ctx);
}
 
Example 11
Source File: MetricsLogger.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
private static void logRequestData(final List<ObservedTotalDuration> metrics, final Http.Context ctx, final long totalDuration) {
    if (LOGGER.isTraceEnabled()) {
        logTraceRequestData(metrics);
    } else {
        logDebugRequestData(metrics, ctx, totalDuration);
    }
}
 
Example 12
Source File: RequestScope.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
private T provideFromContext(final Http.Context currentContext) {
    final boolean providerTypeIsHttpContext = key.getTypeLiteral().equals(CONTEXT_TYPE_LITERAL);
    if (providerTypeIsHttpContext) {
        return castToProviderType(currentContext);
    } else {
        final Cache cache = new HttpContextCache(currentContext);
        return provideFromCache(cache);
    }
}
 
Example 13
Source File: EntriesPerPageFormSettings.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
default long getLimit(final Http.Context httpContext) {
    return getSelectedOption(httpContext)
            .map(FormOption::getValue)
            .orElse(DEFAULT_LIMIT);
}
 
Example 14
Source File: BucketRangeFacetedSearchFormSettings.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
@Override
default RangeFacetedSearchExpression<T> buildFacetedSearchExpression(final Http.Context httpContext) {
    final RangeFacetExpression<T> facetExpression = buildFacetExpression();
    final List<FilterExpression<T>> filterExpressions = buildFilterExpressions(httpContext);
    return RangeFacetedSearchExpression.of(facetExpression, filterExpressions);
}
 
Example 15
Source File: PaginationSettings.java    From commercetools-sunrise-java with Apache License 2.0 4 votes vote down vote up
default long getOffset(final Http.Context httpContext, final long limit) {
    return (getSelectedValueOrDefault(httpContext) - 1) * limit;
}
 
Example 16
Source File: Authorizer.java    From remote-monitoring-services-java with MIT License 2 votes vote down vote up
/**
 * Retrieves user allowed actions
 *
 * @param ctx the current request context
 * @return a list of allowed actions
 */
public List<String> getAllowedActions(Http.Context ctx) {
    return ctx.request().attrs().get(ALLOWED_ACTIONS_TYPED_KEY);
}
 
Example 17
Source File: Authorizer.java    From remote-monitoring-services-java with MIT License 2 votes vote down vote up
/**
 * Retrieves the configuration of auth
 *
 * @param ctx the current request context
 * @return a list of allowed actions
 */
public Boolean isAuthRequired(Http.Context ctx) {
    return ctx.request().attrs().get(AUTH_REQUIRED_TYPED_KEY);
}
 
Example 18
Source File: Authorizer.java    From remote-monitoring-services-java with MIT License 2 votes vote down vote up
/**
 * Retrieves the configuration of auth
 *
 * @param ctx the current request context
 * @return a list of allowed actions
 */
public Boolean isAuthRequired(Http.Context ctx) {
    return ctx.request().attrs().get(AUTH_REQUIRED_TYPED_KEY);
}
 
Example 19
Source File: FakeApplicationTest.java    From htwplus with MIT License 2 votes vote down vote up
/**
 * Returns the current HTTP context.
 *
 * @return Context instance
 */
protected Http.Context getContext() {
    return Http.Context.current();
}
 
Example 20
Source File: FacetedSearchFormSettings.java    From commercetools-sunrise-java with Apache License 2.0 votes vote down vote up
FacetedSearchExpression<T> buildFacetedSearchExpression(Http.Context httpContext);