play.mvc.Result Java Examples

The following examples show how to use play.mvc.Result. 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: LessonVersionController.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@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()));
}
 
Example #2
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> 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));
  }
}
 
Example #3
Source File: ProblemPartnerController.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: Application.java    From play-mpc with MIT License 6 votes vote down vote up
/**
 * 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("");
}
 
Example #5
Source File: StructureController.java    From ground with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example #6
Source File: NodeController.java    From ground with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example #7
Source File: PortfolioController.java    From reactive-stock-trader with Apache License 2.0 6 votes vote down vote up
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);
                });

    }
}
 
Example #8
Source File: LocationControllerTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@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());
}
 
Example #9
Source File: AlarmsByRuleController.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
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))));
}
 
Example #10
Source File: EdgeController.java    From ground with Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example #11
Source File: UserController.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
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);
  }
 
Example #12
Source File: PetApiController.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: GraphController.java    From ground with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example #14
Source File: ProblemStatementController.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@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()));
}
 
Example #15
Source File: PetApiController.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: DbOperationControllerTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@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());
}
 
Example #17
Source File: EdgeController.java    From ground with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example #18
Source File: PetApiController.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #19
Source File: ProblemPartnerController.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@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();
    }
}
 
Example #20
Source File: GroupController.java    From htwplus with MIT License 6 votes vote down vote up
@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));

}
 
Example #21
Source File: MyDeadboltHandler.java    From thunderbit with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Promise<Optional<Result>> beforeAuthCheck(final Http.Context context) {
       if (context.session().get("username") != null && !context.session().get("username").isEmpty()) {
		// user is logged in
		return Promise.pure(Optional.empty());
	} else {
		// user is not logged in
           return Promise.promise(() -> Optional.of(redirect(routes.Authentication.login())));
	}
}
 
Example #22
Source File: SlingApiController.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #23
Source File: SitemapControllerTest.java    From play-sitemap-module.edulify.com with Apache License 2.0 5 votes vote down vote up
@Test @SuppressWarnings("rawtypes")
public void should_return_sitemap_file_root() {
  Call action = routes.Sitemaps.sitemap("");
  Http.RequestBuilder request = Helpers.fakeRequest(action);
  Result result = Helpers.route(request);
  Assertions.assertThat(result.status()).isEqualTo(Helpers.OK);
}
 
Example #24
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 #25
Source File: PetApiController.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public Result getPetById(Long petId) throws Exception {
    Pet obj = imp.getPetById(petId);
    if (configuration.getBoolean("useOutputBeanValidation")) {
        OpenAPIUtils.validate(obj);
    }
    JsonNode result = mapper.valueToTree(obj);
    return ok(result);
}
 
Example #26
Source File: UserMetricsControllerTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Test
public void testuserCreation() {
  PowerMockito.mockStatic(RequestInterceptor.class);
  when(RequestInterceptor.verifyRequestData(Mockito.anyObject()))
      .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh");
  RequestBuilder req =
      new RequestBuilder().uri("/v1/dashboard/creation/user/userId").method("GET");
  //req.headers(headerMap);
  Result result = Helpers.route(application,req);
  assertEquals(200, result.status());
}
 
Example #27
Source File: StudentController.java    From tutorials with MIT License 5 votes vote down vote up
public CompletionStage<Result> delete(int id) {
    return supplyAsync(() -> {
        boolean status = studentStore.deleteStudent(id);
        if (!status) {
            return notFound(Util.createResponse("Student with id:" + id + " not found", false));
        }
        return ok(Util.createResponse("Student with id:" + id + " deleted", true));
    }, ec.current());
}
 
Example #28
Source File: Application.java    From htwplus with MIT License 5 votes vote down vote up
@Security.Authenticated(Secured.class)
public Result searchSuggestions(String query) throws ExecutionException, InterruptedException {
    Account currentAccount = Component.currentAccount();
    if (currentAccount == null) {
        return forbidden();
    }
    SearchResponse response = elasticsearchService.doSearch("searchSuggestions", query, "all", null, 1, currentAccount.id.toString(), asList("name", "title", "filename"), asList("friends", "member", "viewable"));
    return ok(response.toString());
}
 
Example #29
Source File: Storage.java    From thunderbit with GNU Affero General Public License v3.0 5 votes vote down vote up
public F.Promise<Result> download(Long id) {
    // Retrieves the item from the database
    Item item = Item.find.byId(id);
    if (item == null) {
        // If there is no item with the provided id returns a 404 Result
        return F.Promise.pure(notFound());
    } else {
        // Returns a promise of retrieving a download URL for the stored file
        return storage.getDownload(item.storageKey, item.name)
                // If an error occurs when retrieving the download URL returns a 500 Result
                .recover(throwable -> internalServerError(error.render()));
    }
}
 
Example #30
Source File: NSWikiController.java    From NationStatesPlusPlus with MIT License 5 votes vote down vote up
public Result verifyNationLogin() throws IOException, SQLException {
	Utils.handleDefaultPostHeaders(request(), response());
	Result ret = Utils.validateRequest(request(), response(), getAPI(), getDatabase(), false);
	if (ret != null) {
		return ret;
	}
	String nation = Utils.getPostValue(request(), "nation");
	String password = Utils.getPostValue(request(), "password");
	if (password == null || password.isEmpty() || password.length() < 8) {
		Logger.warn("NSWiki User [" + nation + "] attempted an invalid password: [" + password + "]");
		return Results.badRequest("Invalid password");
	}
	Logger.info("Attempting NSWiki login for " + nation);
	final String title;
	Connection conn = null;
	PreparedStatement select = null;
	ResultSet set = null;
	try {
		conn = getConnection();
		select = conn.prepareStatement("SELECT title FROM assembly.nation WHERE name = ?");
		select.setString(1, Utils.sanitizeName(nation));
		set = select.executeQuery();
		set.next();
		title = set.getString(1);
		
		if (doesNSWikiUserExist(title)) {
			Logger.info("NSWiki Updating password for " + title);
			if (changePassword(conn, title, password)) {
				return Results.ok();
			}
			return Results.internalServerError("Unable to change password for " + title);
		}
	} finally {
		DbUtils.closeQuietly(conn);
		DbUtils.closeQuietly(select);
		DbUtils.closeQuietly(set);
	}
	return createNSWikiUser(title, password);
}