當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。