com.alibaba.fastjson.serializer.PropertyFilter#play.mvc.Result源码实例Demo

下面列出了com.alibaba.fastjson.serializer.PropertyFilter#play.mvc.Result 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

public CompletionStage<Result> placeOrder(String portfolioId) {
    Form<PlaceOrderForm> form = placeOrderForm.bindFromRequest();
    if (form.hasErrors()) {
        return CompletableFuture.completedFuture(badRequest(form.errorsAsJson()));
    } else {
        PlaceOrderForm orderForm = form.get();

        OrderDetails order = OrderDetails.builder()
                .tradeType(orderForm.getOrder().toTradeType())
                .symbol(orderForm.getSymbol())
                .shares(orderForm.getShares())
                .orderType(OrderType.Market.INSTANCE)
                .build();
        return portfolioService
                .placeOrder(new PortfolioId(portfolioId))
                .invoke(order)
                .thenApply(orderId -> {
                    val jsonResult = Json.newObject()
                            .put("orderId", orderId.getId());
                    return Results.status(Http.Status.ACCEPTED, jsonResult);
                });

    }
}
 
源代码2 项目: play-mpc   文件: Application.java
/**
 * Performs GET /toggleRandome
 * @return an action result
 */
public static Result toggleShuffle()
{
	try
	{
		MPD mpd = MpdMonitor.getInstance().getMPD();
		MPDPlayer player = mpd.getMPDPlayer();
		player.setRandom(!player.isRandom());

		Logger.info("Setting shuffle: " + player.isRandom());
	}
	catch (MPDException e)
	{
		Logger.error("MPD error", e);
		flash("error", "Command failed! " + e.getMessage());
	}
	
	return ok("");
}
 
源代码3 项目: ground   文件: NodeController.java
public final CompletionStage<Result> getAdjacentLineage(Long id) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "node_version_adj_lineage." + id,
          () -> Json.toJson(this.postgresNodeVersionDao.retrieveAdjacentLineageEdgeVersion(id)),
          Integer.parseInt(System.getProperty("ground.cache.expire.secs")));
      } catch (Exception e) {
        throw new CompletionException(e);
      }
    },
    PostgresUtils.getDbSourceHttpContext(actorSystem))
           .thenApply(Results::ok)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
/**
 * This method will add badges to user profile.
 *
 * @return CompletionStage<Result>
 */
public CompletionStage<Result> getBadgeIssuer(String issuerId, Http.Request httpRequest) {
  try {
    Request reqObj = new Request();
    reqObj =
        setExtraParam(
            reqObj,
            httpRequest.flash().get(JsonKey.REQUEST_ID),
            BadgeOperations.getBadgeIssuer.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));
  }
}
 
private CompletionStage<Result> getAlarmCountByRuleHelper(String from, String to, String order, int skip,
                                        int limit, String[] deviceIds) throws Exception {
    // TODO: move this logic to the storage engine, depending on the
    // storage type the limit will be different. DEVICE_LIMIT is CosmosDb
    // limit for the IN clause.
    if (deviceIds.length > DEVICE_LIMIT) {
        log.warn("The client requested too many devices: {}", deviceIds.length);
        return CompletableFuture.completedFuture(
                badRequest("The number of devices cannot exceed " + DEVICE_LIMIT));
    }

    return this.rulesService.getAlarmCountForList(
            DateHelper.parseDate(from),
            DateHelper.parseDate(to),
            order,
            skip,
            limit,
            deviceIds)
            .thenApply(alarmByRuleList -> ok(toJson(
                    new AlarmByRuleListApiModel(alarmByRuleList))));
}
 
源代码6 项目: ground   文件: EdgeController.java
@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addEdgeVersion() {
  return CompletableFuture.supplyAsync(
    () -> {
      JsonNode json = request().body().asJson();
      List<Long> parentIds = GroundUtils.getListFromJson(json, "parentIds");

      ((ObjectNode) json).remove("parentIds");
      EdgeVersion edgeVersion = Json.fromJson(json, EdgeVersion.class);

      try {
        edgeVersion = this.postgresEdgeVersionDao.create(edgeVersion, parentIds);
      } catch (GroundException e) {
        throw new CompletionException(e);
      }

      return Json.toJson(edgeVersion);
    },
    PostgresUtils.getDbSourceHttpContext(actorSystem))
           .thenApply(Results::created)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
源代码7 项目: sunbird-lms-service   文件: UserController.java
public CompletionStage<Result> getUserByKey(String idType, String id, Http.Request httpRequest) {

    HashMap<String, Object> map = new HashMap<>();
    map.put(JsonKey.KEY, JsonKey.LOGIN_ID.equalsIgnoreCase(idType) ? JsonKey.LOGIN_ID : idType);
    map.put(JsonKey.VALUE, ProjectUtil.getLmsUserId(id));
    return handleRequest(
        ActorOperations.GET_USER_BY_KEY.getValue(),
        null,
        req -> {
          Request request = (Request) req;
          request.setRequest(map);
          new UserGetRequestValidator().validateGetUserByKeyRequest(request);
          return null;
        },
        null,
        null,
        false,
            httpRequest);
  }
 
源代码8 项目: ground   文件: EdgeController.java
public final CompletionStage<Result> getEdgeVersion(Long id) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "edge_versions." + id,
          () -> Json.toJson(this.postgresEdgeVersionDao.retrieveFromDatabase(id)),
          Integer.parseInt(System.getProperty("ground.cache.expire.secs")));
      } catch (Exception e) {
        throw new CompletionException(e);
      }
    },
    PostgresUtils.getDbSourceHttpContext(actorSystem))
           .thenApply(Results::ok)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
@Test
public void testgetMetrics() {
  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(ENTITY_NAME, entityName);
  List<String> requiredFields = new ArrayList<>();
  requiredFields.add("userid");
  innerMap.put(REQUIRED_FIELDS, requiredFields);
  Map<String, Object> filters = new HashMap<>();
  filters.put(JsonKey.USER_ID, "usergt78y4ry85464");
  innerMap.put(JsonKey.FILTERS, filters);
  innerMap.put(JsonKey.ID, "ggudy8d8ydyy8ddy9");
  requestMap.put(JsonKey.REQUEST, innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req =
      new RequestBuilder().bodyJson(json).uri("/v1/object/metrics").method("POST");
  //req.headers(headerMap);
  Result result = Helpers.route(application,req);
  assertEquals(200, result.status());
}
 
源代码10 项目: ground   文件: GraphController.java
public final CompletionStage<Result> getGraph(String sourceKey) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "graphs." + sourceKey,
          () -> Json.toJson(this.postgresGraphDao.retrieveFromDatabase(sourceKey)),
          Integer.parseInt(System.getProperty("ground.cache.expire.secs")));
      } catch (Exception e) {
        throw new CompletionException(e);
      }
    },
    PostgresUtils.getDbSourceHttpContext(this.actorSystem))
           .thenApply(Results::ok)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
源代码11 项目: judgels   文件: LessonVersionController.java
@Transactional(readOnly = true)
public Result editVersionLocalChanges(long lessonId) throws LessonNotFoundException {
    Lesson lesson = lessonService.findLessonById(lessonId);

    if (!LessonControllerUtils.isPartnerOrAbove(lessonService, lesson)) {
        return notFound();
    }

    lessonService.fetchUserClone(IdentityUtils.getUserJid(), lesson.getJid());

    if (!lessonService.updateUserClone(IdentityUtils.getUserJid(), lesson.getJid())) {
        flash("localChangesError", Messages.get("lesson.version.local.cantMerge"));
    }

    return redirect(routes.LessonVersionController.viewVersionLocalChanges(lesson.getId()));
}
 
源代码12 项目: judgels   文件: ProblemStatementController.java
@Transactional(readOnly = true)
public Result enableStatementLanguage(long problemId, String languageCode) throws ProblemNotFoundException {
    Problem problem = problemService.findProblemById(problemId);

    if (!ProblemControllerUtils.isAllowedToManageStatementLanguages(problemService, problem)) {
        return notFound();
    }

    problemService.createUserCloneIfNotExists(IdentityUtils.getUserJid(), problem.getJid());

    try {
        // TODO should check if language has been enabled
        if (!WorldLanguageRegistry.getInstance().getLanguages().containsKey(languageCode)) {
            return notFound();
        }

        problemService.enableLanguage(IdentityUtils.getUserJid(), problem.getJid(), languageCode);
    } catch (IOException e) {
        throw new IllegalStateException("Statement language probably hasn't been added.", e);
    }

    return redirect(routes.ProblemStatementController.listStatementLanguages(problem.getId()));
}
 
源代码13 项目: openapi-generator   文件: PetApiController.java
@ApiAction
public Result findPetsByStatus() throws Exception {
    String[] statusArray = request().queryString().get("status");
    if (statusArray == null) {
        throw new IllegalArgumentException("'status' parameter is required");
    }
    List<String> statusList = OpenAPIUtils.parametersToList("csv", statusArray);
    List<String> status = new ArrayList<>();
    for (String curParam : statusList) {
        if (!curParam.isEmpty()) {
            //noinspection UseBulkOperation
            status.add(curParam);
        }
    }
    List<Pet> obj = imp.findPetsByStatus(status);
    if (configuration.getBoolean("useOutputBeanValidation")) {
        for (Pet curItem : obj) {
            OpenAPIUtils.validate(curItem);
        }
    }
    JsonNode result = mapper.valueToTree(obj);
    return ok(result);
}
 
源代码14 项目: openapi-generator   文件: PetApiController.java
@ApiAction
public Result updatePetWithForm(Long petId) throws Exception {
    String valuename = (request().body().asMultipartFormData().asFormUrlEncoded().get("name"))[0];
    String name;
    if (valuename != null) {
        name = valuename;
    } else {
        name = null;
    }
    String valuestatus = (request().body().asMultipartFormData().asFormUrlEncoded().get("status"))[0];
    String status;
    if (valuestatus != null) {
        status = valuestatus;
    } else {
        status = null;
    }
    imp.updatePetWithForm(petId, name, status);
    return ok();
}
 
源代码15 项目: judgels   文件: ProblemPartnerController.java
@Transactional(readOnly = true)
public Result editPartner(long problemId, long partnerId) throws ProblemNotFoundException {
    Problem problem = problemService.findProblemById(problemId);

    if (!ProblemControllerUtils.isAuthorOrAbove(problem)) {
        return notFound();
    }

    switch (problem.getType()) {
        case PROGRAMMING:
            return redirect(org.iatoki.judgels.sandalphon.problem.programming.partner.routes.ProgrammingProblemPartnerController.editPartner(problem.getId(), partnerId));
        case BUNDLE:
            return redirect(org.iatoki.judgels.sandalphon.problem.bundle.partner.routes.BundleProblemPartnerController.editPartner(problem.getId(), partnerId));
        default:
            return badRequest();
    }
}
 
源代码16 项目: htwplus   文件: GroupController.java
@Transactional
public Result edit(Long id) {
    Group group = groupManager.findById(id);

    if (group == null) {
        flash("error", messagesApi.get(Lang.defaultLang(), "group.group_not_found"));
        return redirect(controllers.routes.GroupController.index());
    }

    // Check rights
    if (!Secured.editGroup(group)) {
        return redirect(controllers.routes.GroupController.view(id));
    }

    Navigation.set(Level.GROUPS, "Bearbeiten", group.title, controllers.routes.GroupController.stream(group.id, PAGE, false));
    Form<Group> groupForm = formFactory.form(Group.class).fill(group);
    groupForm.data().put("type", String.valueOf(group.groupType.ordinal()));
    return ok(edit.render(group, groupForm));

}
 
源代码17 项目: openapi-generator   文件: PetApiController.java
@ApiAction
public Result findPetsByTags() throws Exception {
    String[] tagsArray = request().queryString().get("tags");
    if (tagsArray == null) {
        throw new IllegalArgumentException("'tags' parameter is required");
    }
    List<String> tagsList = OpenAPIUtils.parametersToList("csv", tagsArray);
    List<String> tags = new ArrayList<>();
    for (String curParam : tagsList) {
        if (!curParam.isEmpty()) {
            //noinspection UseBulkOperation
            tags.add(curParam);
        }
    }
    List<Pet> obj = imp.findPetsByTags(tags);
    if (configuration.getBoolean("useOutputBeanValidation")) {
        for (Pet curItem : obj) {
            OpenAPIUtils.validate(curItem);
        }
    }
    JsonNode result = mapper.valueToTree(obj);
    return ok(result);
}
 
源代码18 项目: judgels   文件: ProblemPartnerController.java
@Transactional(readOnly = true)
public Result listPartners(long problemId, long pageIndex, String orderBy, String orderDir) throws ProblemNotFoundException {
    Problem problem = problemService.findProblemById(problemId);

    if (!ProblemControllerUtils.isAuthorOrAbove(problem)) {
        return notFound();
    }

    Page<ProblemPartner> pageOfProblemPartners = problemService.getPageOfProblemPartners(problem.getJid(), pageIndex, PAGE_SIZE, orderBy, orderDir);

    HtmlTemplate template = getBaseHtmlTemplate();
    template.setContent(listPartnersView.render(problem.getId(), pageOfProblemPartners, orderBy, orderDir));
    template.setSecondaryTitle(Messages.get("problem.partner.list"));
    template.addSecondaryButton(Messages.get("problem.partner.add"), routes.ProblemPartnerController.addPartner(problem.getId()));
    template.setPageTitle("Problem - Partners");

    return renderPartnerTemplate(template, problemService, problem);
}
 
源代码19 项目: ground   文件: StructureController.java
public final CompletionStage<Result> getLatest(String sourceKey) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "structure_leaves." + sourceKey,
          () -> Json.toJson(this.postgresStructureDao.getLeaves(sourceKey)),
          Integer.parseInt(System.getProperty("ground.cache.expire.secs")));
      } catch (Exception e) {
        throw new CompletionException(e);
      }
    },
    PostgresUtils.getDbSourceHttpContext(actorSystem))
           .thenApply(Results::ok)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
@Test
public void testUpdateLocationWithType() {

  Map<String, Object> requestMap = new HashMap<>();
  Map<String, Object> requestBody = new HashMap<>();
  requestBody.put(GeoLocationJsonKey.LOCATION_TYPE, LOCATION_TYPE);
  requestBody.put(JsonKey.ID, LOCATION_ID);
  requestMap.put(JsonKey.REQUEST, requestBody);
  String data = TestUtil.mapToJson(requestMap);
  JsonNode json = Json.parse(data);
  RequestBuilder req =
      new RequestBuilder().bodyJson(json).uri(UPDATE_LOCATION_URL).method("PATCH");
  //req.headers(headerMap);
  Result result = Helpers.route(application,req);
  assertEquals(400, result.status());
}
 
源代码21 项目: swagger-aem   文件: SlingApiController.java
@ApiAction
public Result postTruststorePKCS12() throws Exception {
    Http.MultipartFormData.FilePart truststoreP12 = request().body().asMultipartFormData().getFile("truststore.p12");
    String obj = imp.postTruststorePKCS12(truststoreP12);
    JsonNode result = mapper.valueToTree(obj);
    return ok(result);
}
 
@Test
public void loginWithDifferentCaseUsername() {
    DemoData demoData = app.injector().instanceOf(DemoData.class);
    ObjectNode loginJson = Json.newObject();
    loginJson.put("emailAddress", demoData.user1.getEmailAddress().toUpperCase());
    loginJson.put("password", demoData.user1.getPassword());

    Result result = route(fakeRequest(controllers.routes.SecurityController.login()).bodyJson(loginJson));

    assertEquals(OK, result.status());
}
 
源代码23 项目: commercetools-sunrise-java   文件: WithFormFlow.java
default CompletionStage<Result> handleFailedAction(final I input, final Form<? extends F> form, final Throwable throwable) {
    final Throwable causeThrowable = throwable.getCause();
    if (causeThrowable instanceof ClientErrorException) {
        return handleClientErrorFailedAction(input, form, (ClientErrorException) causeThrowable);
    }
    return handleGeneralFailedAction(throwable);
}
 
源代码24 项目: swaggy-jenkins   文件: BlueOceanApiController.java
@ApiAction
public Result getAuthenticatedUser(String organization) throws Exception {
    User obj = imp.getAuthenticatedUser(organization);
    if (configuration.getBoolean("useOutputBeanValidation")) {
        OpenAPIUtils.validate(obj);
    }
    JsonNode result = mapper.valueToTree(obj);
    return ok(result);
}
 
源代码25 项目: glowroot   文件: StreamController.java
public static Result stream() {
    Chunks<String> chunks = new StringChunks() {
        public void onReady(Chunks.Out<String> out) {
            registerOutChannelSomewhere(out);
        }
    };
    return ok(chunks);
}
 
源代码26 项目: sunbird-lms-service   文件: UserRoleController.java
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);
}
 
@Test
public void testGetSystemSettingSuccess() {
  RequestBuilder req = new RequestBuilder().uri("/v1/system/settings/get/isRootOrgInitialised").method("GET");
  //req.headers(headerMap);
  Result result = Helpers.route(application,req);
  assertEquals(200, result.status());
}
 
源代码28 项目: pfe-samples   文件: OAuth.java
public F.Promise<Result> callback() {
    String code = request().getQueryString("code");
    if (code != null) {
        String state = request().getQueryString("state");
        String returnTo = state != null ? state : configuration.defaultReturnUrl;
        return ws.url(configuration.tokenEndpoint)
                .setContentType(Http.MimeTypes.FORM)
                .post(URL.encode(Scala.varargs(
                        param("code", code),
                        param("client_id", configuration.clientId),
                        param("client_secret", configuration.clientSecret),
                        param("redirect_uri", routes.OAuth.callback().absoluteURL(request())),
                        param("grant_type", "authorization_code")
                ))).map(response -> {
                    JsonNode accessTokenJson = response.asJson().get("access_token");
                    if (accessTokenJson == null || !accessTokenJson.isTextual()) {
                        return internalServerError();
                    } else {
                        String accessToken = accessTokenJson.asText();
                        session().put(configuration.tokenKey, accessToken);
                        return redirect(returnTo);
                    }
                });
    } else {
        return F.Promise.pure(internalServerError());
    }
}
 
源代码29 项目: tutorials   文件: StudentControllerUnitTest.java
@Test
public void givenUrlToListStudents_whenListingStudents_ThenShouldReturnStudentList() {
    Http.RequestBuilder request = new Http.RequestBuilder()
            .method(GET)
            .uri("/");

    Result result = route(app, request);
    assertEquals(OK, result.status());
    assertTrue(result.contentType().isPresent());
    assertEquals("application/json", result.contentType().get());
}
 
源代码30 项目: sunbird-lms-service   文件: ErrorHandler.java
@Override
public CompletionStage<Result> onServerError(Http.RequestHeader request, Throwable t) {
  ProjectLogger.log(
      "Global: onError called for path = "
          + request.path()
          + ", headers = "
          + request.getHeaders().toMap(),
      t);
  Response response = null;
  ProjectCommonException commonException = null;
  if (t instanceof ProjectCommonException) {
    commonException = (ProjectCommonException) t;
    response =
        BaseController.createResponseOnException(
            request.path(), request.method(), (ProjectCommonException) t);
  } else if (t instanceof akka.pattern.AskTimeoutException) {
    commonException =
        new ProjectCommonException(
            ResponseCode.actorConnectionError.getErrorCode(),
            ResponseCode.actorConnectionError.getErrorMessage(),
            ResponseCode.SERVER_ERROR.getResponseCode());
  } else {
    commonException =
        new ProjectCommonException(
            ResponseCode.internalError.getErrorCode(),
            ResponseCode.internalError.getErrorMessage(),
            ResponseCode.SERVER_ERROR.getResponseCode());
  }
  response =
      BaseController.createResponseOnException(request.path(), request.method(), commonException);
  return CompletableFuture.completedFuture(Results.internalServerError(Json.toJson(response)));
}