当前位置: 首页>>代码示例>>Java>>正文


Java Http类代码示例

本文整理汇总了Java中play.mvc.Http的典型用法代码示例。如果您正苦于以下问题:Java Http类的具体用法?Java Http怎么用?Java Http使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Http类属于play.mvc包,在下文中一共展示了Http类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: setUp

import play.mvc.Http; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
    Map<String, String> flashData = Collections.emptyMap();
    Map<String, Object> argData = Collections.emptyMap();
    Long id = 2L;
    play.api.mvc.RequestHeader header = mock(play.api.mvc.RequestHeader.class);
    Http.Context context = new Http.Context(id, header, request, flashData, flashData, argData);
    Http.Context.current.set(context);
}
 
开发者ID:thomas-young-2013,项目名称:wherehowsX,代码行数:10,代码来源:DatasetControllerTest.java

示例2: getUsername

import play.mvc.Http; //导入依赖的package包/类
@Override
public String getUsername(Http.Context context) {
    System.out.println("auth_service   ====/   getUserName called @ @ @");
    try {
        JsonNode params = context.request().body().asJson();
        String token = params.get("token").asText();
        UserSessionModel model = UserSessionDao.getInstance().getUserSession(token);
        if (model != null) {
            return model.getToken();
        } else {
            return super.getUsername(context);
        }
    } catch (Exception e) {
        LogUtil.printLogMessage("Auth service", "params error", e.getMessage());
        e.printStackTrace();
        return super.getUsername(context);
    }
}
 
开发者ID:shuza,项目名称:Simple-RestFull-API,代码行数:19,代码来源:AuthService.java

示例3: callback

import play.mvc.Http; //导入依赖的package包/类
/**
 * Function called by the GitHub authentication flow which takes the resulting code as a parameter.
 * This function will take the code passed and exchange it for a client access token used to make
 * GitHub api requests.
 * @param code
 * @return
 */
public CompletionStage<Result> callback(String code) {

    final Http.Context context = Http.Context.current();

    return wsClient.url("https://github.com/login/oauth/access_token")
            .setQueryParameter("client_id", configuration.getString("gh.id"))
            .setQueryParameter("client_secret", configuration.getString("gh.secret"))
            .setQueryParameter("code", code)
            .setHeader("accept", "application/json")
            .setRequestTimeout(10 * 1000)
            .post("")
            .thenApply(response -> {
                String accessToken = response.asJson().get("access_token").asText();

                context.session().put(TOKEN_KEY, accessToken);

                return redirect("/configHelper");
            });
}
 
开发者ID:btkelly,项目名称:gnag-website,代码行数:27,代码来源:GitHubAuthController.java

示例4: getSubject

import play.mvc.Http; //导入依赖的package包/类
@Override
public CompletionStage<Optional<? extends Subject>> getSubject(final Http.Context context) {
    String token = BaseController.getToken(context).orElse("");
    Session session = cache.get(BaseController.SITNET_CACHE_KEY + token);
    User user = session == null ? null : Ebean.find(User.class, session.getUserId());
    // filter out roles not found in session
    if (user != null) {
        if (session.isTemporalStudent()) {
            user.getRoles().clear();
            user.getRoles().add(Ebean.find(Role.class).where().eq("name", Role.Name.STUDENT.toString()).findUnique());
        } else {
            user.setRoles(user.getRoles().stream()
                    .filter((r) -> r.getName().equals(session.getLoginRole()))
                    .collect(Collectors.toList()));
        }
    }
    return CompletableFuture.supplyAsync(() -> Optional.ofNullable(user));
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:19,代码来源:AuthorizationHandler.java

示例5: isAllowed

import play.mvc.Http; //导入依赖的package包/类
@Override
public CompletionStage<Boolean> isAllowed(String name, Optional<String> meta, DeadboltHandler deadboltHandler, Http.Context ctx) {
    if (meta.isPresent() && meta.get().matches("pattern=.+,role=.+,anyMatch=(true|false)")) {
        String[] config = meta.get().split(",");
        String pattern = config[0].substring(config[0].indexOf('=') + 1);
        String[] roles = {config[1].substring(config[1].indexOf('=') + 1)};
        Boolean anyMatch = Boolean.valueOf(config[2].substring(config[2].indexOf('=') + 1));
        return deadboltHandler.getSubject(ctx).thenApplyAsync(s -> {
            DeadboltAnalyzer da = new DeadboltAnalyzer();
            if (anyMatch) {
                return da.checkPatternEquality(s, Optional.of(pattern)) ||
                        da.checkRole(s, roles);
            } else {
                return da.checkPatternEquality(s, Optional.of(pattern)) &&
                        da.checkRole(s, roles);
            }
        });
    } else {
        return CompletableFuture.completedFuture(false);
    }
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:22,代码来源:CombinedRoleAndPermissionHandler.java

示例6: importGrades

import play.mvc.Http; //导入依赖的package包/类
@Restrict({@Group("ADMIN"), @Group("TEACHER")})
public Result importGrades() {
    Http.MultipartFormData<File> body = request().body().asMultipartFormData();
    Http.MultipartFormData.FilePart<File> filePart = body.getFile("file");
    if (filePart == null) {
        return notFound();
    }
    File file = filePart.getFile();
    User user = getLoggedUser();
    boolean isAdmin = user.hasRole(Role.Name.ADMIN.toString(), getSession());
    try {
        CsvBuilder.parseGrades(file, user, isAdmin ? Role.Name.ADMIN : Role.Name.TEACHER);
    } catch (IOException e) {
        Logger.error("Failed to parse CSV file. Stack trace follows");
        e.printStackTrace();
        return internalServerError("sitnet_internal_error");
    }
    return ok();
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:20,代码来源:ReviewController.java

示例7: createAction

import play.mvc.Http; //导入依赖的package包/类
@Override
public Action createAction(Http.Request request, Method actionMethod) {
    String token = BaseController.getToken(request).orElse("");
    Session session = cache.get(BaseController.SITNET_CACHE_KEY + token);
    boolean temporalStudent = session != null && session.isTemporalStudent();
    User user = session == null ? null : Ebean.find(User.class, session.getUserId());
    AuditLogger.log(request, user);

    // logout, no further processing
    if (request.path().equals("/app/logout")) {
        return propagateAction();
    }

    return validateSession(session, token).orElseGet(() -> {
        updateSession(request, session, token);
        if ((user == null || !user.hasRole("STUDENT", session)) && !temporalStudent) {
            // propagate further right away
            return propagateAction();
        } else {
            // requests are candidates for extra processing
            return propagateAction(getReservationHeaders(request, user));
        }
    });
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:25,代码来源:SystemRequestHandler.java

示例8: validateSession

import play.mvc.Http; //导入依赖的package包/类
private Optional<Action> validateSession(Session session, String token) {
    if (session == null) {
        if (token == null) {
            Logger.debug("User not logged in");
        } else {
            Logger.info("Session with token {} not found", token);
        }
        return Optional.of(propagateAction());
    } else if (!session.getValid()) {
        Logger.warn("Session #{} is marked as invalid", token);
        return Optional.of(new Action.Simple() {
            @Override
            public CompletionStage<Result> call(final Http.Context ctx) {
                return CompletableFuture.supplyAsync(() -> {
                            ctx.response().getHeaders().put(SITNET_FAILURE_HEADER_KEY, "Invalid token");
                            return Action.badRequest("Token has expired / You have logged out, please close all browser windows and login again.");
                        }
                );
            }
        });
    } else {
        return Optional.empty();
    }
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:25,代码来源:SystemRequestHandler.java

示例9: getReservationHeaders

import play.mvc.Http; //导入依赖的package包/类
private Map<String, String> getReservationHeaders(Http.RequestHeader request, User user) {
    Map<String, String> headers = new HashMap<>();
    Optional<ExamEnrolment> ongoingEnrolment = getNextEnrolment(user.getId(), 0);
    if (ongoingEnrolment.isPresent()) {
        handleOngoingEnrolment(ongoingEnrolment.get(), request, headers);
    } else {
        DateTime now = new DateTime();
        int lookAheadMinutes = Minutes.minutesBetween(now, now.plusDays(1).withMillisOfDay(0)).getMinutes();
        Optional<ExamEnrolment> upcomingEnrolment = getNextEnrolment(user.getId(), lookAheadMinutes);
        if (upcomingEnrolment.isPresent()) {
            handleUpcomingEnrolment(upcomingEnrolment.get(), request, headers);
        } else if (isOnExamMachine(request)) {
            // User is logged on an exam machine but has no exams for today
            headers.put("x-exam-upcoming-exam", "none");
        }
    }
    return headers;
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:19,代码来源:SystemRequestHandler.java

示例10: onClientError

import play.mvc.Http; //导入依赖的package包/类
@Override
public CompletionStage<Result> onClientError(Http.RequestHeader request, int statusCode, String message) {
    return CompletableFuture.supplyAsync(() -> {
        Logger.warn("onClientError: URL: {}, status: {}, msg: {}", request.uri(), statusCode, message);
        if (statusCode == play.mvc.Http.Status.BAD_REQUEST) {
            return Results.badRequest(Json.toJson(new ApiError(message)));
        }
        if (statusCode == play.mvc.Http.Status.NOT_FOUND) {
            return Results.notFound(Json.toJson(new ApiError(message)));
        }
        if (statusCode == Http.Status.UNAUTHORIZED || statusCode == Http.Status.FORBIDDEN) {
            return Results.unauthorized(Json.toJson(new ApiError(message)));
        }
        return Results.internalServerError(Json.toJson(new ApiError(message)));
    });
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:17,代码来源:SystemErrorHandler.java

示例11: onServerError

import play.mvc.Http; //导入依赖的package包/类
@Override
public CompletionStage<Result> onServerError(Http.RequestHeader request, Throwable exception) {
    return CompletableFuture.supplyAsync(() -> {
        Throwable cause = exception.getCause();
        String errorMessage = cause == null ? exception.getMessage() : cause.getMessage();
        Logger.error("onServerError: URL: {}, msg: {}", request.uri(), errorMessage);
        exception.printStackTrace();
        if (cause != null) {
            if (cause instanceof MalformedDataException) {
                return Results.badRequest(Json.toJson(errorMessage));
            }
            if (cause instanceof IllegalArgumentException) {
                return Results.badRequest(Json.toJson(new ApiError(errorMessage)));
            }
            if (cause instanceof OptimisticLockException) {
                return Results.badRequest("sitnet_error_data_has_changed");
            }
        }
        return Results.internalServerError(Json.toJson(new ApiError(errorMessage)));
    });
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:22,代码来源:SystemErrorHandler.java

示例12: call

import play.mvc.Http; //导入依赖的package包/类
@Override
public CompletionStage<Result> call(Http.Context ctx) {
    return delegate.call(ctx).thenApply(result -> {
        if (result.status() <= HTTP_CREATED &&
                result.body().contentType().orElse("").equals("application/json")) {
            result.body().consumeData(materializer).thenApplyAsync(body -> {
                JsonNode bodyJson = Json.parse(body.decodeString("UTF-8"));
                if (searchForSensitiveContent(bodyJson) != null) {
                    Logger.error("!!!Sensitive data returned by action!!!");
                    throw new SecurityException();
                }
                return result;
            });
        }
        return result;
    });
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:18,代码来源:SensitiveDataAction.java

示例13: call

import play.mvc.Http; //导入依赖的package包/类
public CompletionStage<Result> call(final Http.Context ctx) {
    String username = ctx.session().get("username");
    Long postId = Long.parseLong(ctx.request().getQueryString("id"));
    Optional<PostDTO> optionalPost = postService.getPost(postId);
    if (!optionalPost.isPresent()) {
        // Post doesn't exists, return notFound
        return CompletableFuture.completedFuture(notFound());
    } else if (!optionalPost.get().username.equals(username)) {
        // User is not the owner of Post, show him Login form
        Result login = unauthorized(views.html.login.render(
                loginDTOForm.withGlobalError("Please login with proper credentials to modify this post")));
        return CompletableFuture.completedFuture(login);
    } else {
        // Post exists and User is the owner of Post, call delegate
        return delegate.call(ctx);
    }
}
 
开发者ID:reljicd,项目名称:play-framework-blog,代码行数:18,代码来源:PostExistsAndUserIsOwnerAction.java

示例14: apply

import play.mvc.Http; //导入依赖的package包/类
@Override
public CompletionStage<Result> apply(
        Function<Http.RequestHeader, CompletionStage<Result>> nextFilter,
        Http.RequestHeader requestHeader) {
    long startTime = System.currentTimeMillis();
    return nextFilter.apply(requestHeader).thenApply(result -> {
        long endTime = System.currentTimeMillis();
        long requestTime = endTime - startTime;

        if (!requestHeader.uri().contains("assets")) {
            Logger.info("{} {} from {} took {}ms and returned {}",
                    requestHeader.method(), requestHeader.uri(), requestHeader.remoteAddress(), requestTime, result.status());
        }

        return result;
    });

}
 
开发者ID:reljicd,项目名称:play-framework-blog,代码行数:19,代码来源:LoggingFilter.java

示例15: fetchAndSaveLastViewedProducts

import play.mvc.Http; //导入依赖的package包/类
/**
 * Fetches the list of viewed products according to what is stored in session
 * and saves it in {@code lastViewedProducts} class field.
 */
private CompletionStage<?> fetchAndSaveLastViewedProducts() {
    final List<String> skuList = findLastViewedProductsSkuInSession(Http.Context.current().session());
    if (!skuList.isEmpty()) {
        final ProductProjectionSearch request = ProductProjectionSearch.ofCurrent()
                .withQueryFilters(product -> product.allVariants().sku().isIn(skuList))
                .withPriceSelection(priceSelection);
        return sphereClient.execute(request)
                .thenApply(result -> {
                    this.lastViewedProducts = sortProductsBySkuList(result.getResults(), skuList);
                    return null;
                }).exceptionally(throwable -> {
                    LOGGER.error("Could not fetch last viewed products", throwable);
                    return null;
                });
    }
    return completedFuture(null);
}
 
开发者ID:commercetools,项目名称:commercetools-sunrise-java-training,代码行数:22,代码来源:LastViewedProductsViewerControllerComponent.java


注:本文中的play.mvc.Http类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。