play.mvc.Results Java Examples

The following examples show how to use play.mvc.Results. 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: PortfolioController.java    From reactive-stock-trader with Apache License 2.0 6 votes vote down vote up
public CompletionStage<Result> openPortfolio() {
    Form<OpenPortfolioForm> form = openPortfolioForm.bindFromRequest();
    if (form.hasErrors()) {
        return CompletableFuture.completedFuture(badRequest(form.errorsAsJson()));
    } else {
        OpenPortfolioDetails openRequest = form.get().toRequest();
        return portfolioService
                .openPortfolio()
                .invoke(openRequest)
                .thenApply(portfolioId -> {
                    val jsonResult = Json.newObject()
                            .put("portfolioId", portfolioId.getId());
                    return Results.created(jsonResult);
                });
    }
}
 
Example #2
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> addEdge() {
  return CompletableFuture.supplyAsync(
    () -> {
      JsonNode json = request().body().asJson();
      Edge edge = Json.fromJson(json, Edge.class);

      try {
        edge = this.postgresEdgeDao.create(edge);
      } catch (GroundException e) {
        throw new CompletionException(e);
      }

      return Json.toJson(edge);
    },
    PostgresUtils.getDbSourceHttpContext(this.actorSystem))
           .thenApply(Results::created)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
Example #3
Source File: RegionController.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
public Result getUpdateTime(String region, double std) throws SQLException {
	Connection conn = null;
	int regionId = this.getDatabase().getRegionId(region);
	if (regionId == -1) {
		return Results.badRequest();
	}
	try {
		conn = getConnection();
		JsonNode updateTime = getUpdateTime(conn, regionId, std);
		Result result = Utils.handleDefaultGetHeaders(request(), response(), String.valueOf(updateTime.hashCode()), "60");
		if (result != null) {
			return result;
		}
		return ok(Json.toJson(updateTime)).as("application/json");
	} finally {
		DbUtils.closeQuietly(conn);
	}
}
 
Example #4
Source File: ErrorHandler.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
public CompletionStage<Result> onClientError(RequestHeader request, int statusCode, String message) {
    String errorMessage;
    switch (statusCode) {
        case 400:
            errorMessage = "BadRequest";
            break;
        case 403:
            errorMessage = "Forbidden";
            break;
        case 404:
            errorMessage = "NotFound";
            break;
        default:
            errorMessage = "OtherClientError";
    }
    HashMap<String, Object> errorResult = new HashMap<String, Object>() {
        {
            put("Message", "Client error occurred.");
            put("ExceptionMessage", errorMessage);
        }
    };
    return CompletableFuture.completedFuture(
            Results.status(statusCode, toJson(errorResult))
    );
}
 
Example #5
Source File: GraphController.java    From ground with Apache License 2.0 6 votes vote down vote up
public final CompletionStage<Result> getHistory(String sourceKey) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "graph_history." + sourceKey,
          () -> Json.toJson(this.postgresGraphDao.getHistory(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
@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addNode() {
  return CompletableFuture.supplyAsync(
    () -> {
      JsonNode json = request().body().asJson();
      Node node = Json.fromJson(json, Node.class);
      try {
        node = this.postgresNodeDao.create(node);
      } catch (GroundException e) {
        throw new CompletionException(e);
      }
      return Json.toJson(node);
    },
    PostgresUtils.getDbSourceHttpContext(this.actorSystem))
           .thenApply(Results::created)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
Example #7
Source File: NodeController.java    From ground with Apache License 2.0 6 votes vote down vote up
@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addNodeVersion() {
  return CompletableFuture.supplyAsync(
    () -> {
      JsonNode json = request().body().asJson();

      List<Long> parentIds = GroundUtils.getListFromJson(json, "parentIds");
      ((ObjectNode) json).remove("parentIds");
      NodeVersion nodeVersion = Json.fromJson(json, NodeVersion.class);

      try {
        nodeVersion = this.postgresNodeVersionDao.create(nodeVersion, parentIds);
      } catch (GroundException e) {
        e.printStackTrace();
        throw new CompletionException(e);
      }
      return Json.toJson(nodeVersion);
    },
    PostgresUtils.getDbSourceHttpContext(this.actorSystem))
           .thenApply(Results::created)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
Example #8
Source File: NodeController.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(
          "node_leaves." + sourceKey,
          () -> Json.toJson(this.postgresNodeDao.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 #9
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 #10
Source File: ErrorHandler.java    From activator-lagom-cargotracker with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked in dev mode when a server error occurs.
 *
 * @param request The request that triggered the error.
 * @param exception The exception.
 */
protected CompletionStage<Result> onDevServerError(Http.RequestHeader request, UsefulException exception) {

    ObjectNode jsonError = Json.newObject();

    final Throwable cause = exception.cause;
    final String description = exception.description;
    final String id = exception.id;
    final String title = exception.title;

    jsonError.put("description", description);
    jsonError.put("title", title);
    jsonError.put("id", id);
    jsonError.put("message", exception.getMessage());
    jsonError.set("cause", causesToJson(cause));

    return CompletableFuture.completedFuture(Results.internalServerError(jsonError));
}
 
Example #11
Source File: NationController.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
public Result retrieveForumSettings(String name) throws SQLException, ExecutionException {
	Utils.handleDefaultPostHeaders(request(), response());
	final int nationId = getDatabase().getNationId(name);
	if (nationId == -1) {
		return Results.badRequest();
	}
	NationSettings settings = getDatabase().getNationSettings(name, false);
	Map<String, Object> json = Maps.newHashMap();
	json.put("post_ids", settings.getValue("post_ids", true, Boolean.class));
	json.put("egosearch_ignore", settings.getValue("egosearch_ignore", true, Boolean.class));
	json.put("highlight_op_posts", settings.getValue("highlight_op_posts", true, Boolean.class));
	json.put("highlight_color_transparency", settings.getValue("highlight_color_transparency", 0.1, Double.class));
	json.put("highlight_color", settings.getValue("highlight_color", "#39EE00", String.class));
	json.put("floating_sidepanel", settings.getValue("floating_sidepanel", true, Boolean.class));
	return Results.ok(Json.toJson(json)).as("application/json");
}
 
Example #12
Source File: EdgeController.java    From ground with Apache License 2.0 6 votes vote down vote up
public final CompletionStage<Result> getHistory(String sourceKey) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "edge_history." + sourceKey,
          () -> Json.toJson(this.postgresEdgeDao.getHistory(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 #13
Source File: GraphController.java    From ground with Apache License 2.0 6 votes vote down vote up
@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addGraph() {
  return CompletableFuture.supplyAsync(
    () -> {
      JsonNode json = request().body().asJson();
      Graph graph = Json.fromJson(json, Graph.class);

      try {
        graph = this.postgresGraphDao.create(graph);
      } catch (GroundException e) {
        throw new CompletionException(e);
      }

      return Json.toJson(graph);
    },
    PostgresUtils.getDbSourceHttpContext(actorSystem))
           .thenApply(Results::created)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
Example #14
Source File: LineageGraphController.java    From ground with Apache License 2.0 6 votes vote down vote up
public final CompletionStage<Result> getHistory(String sourceKey) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "lineage_graph_history." + sourceKey,
          () -> Json.toJson(this.postgresLineageGraphDao.getHistory(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 #15
Source File: PortfolioController.java    From reactive-stock-trader with Apache License 2.0 6 votes vote down vote up
public CompletionStage<Result> getPortfolio(String portfolioId) {
    val portfolioView = portfolioService
            .getPortfolio(new PortfolioId(portfolioId))
            .invoke();

    val pricedView = portfolioView
            .thenCompose(view ->
                    quoteService.priceHoldings(view.getHoldings())
                            .thenApply(pricedHoldings ->
                                    Portfolio.builder()
                                            .portfolioId(view.getPortfolioId().getId())
                                            .name(view.getName())
                                            .funds(view.getFunds())
                                            .holdings(pricedHoldings)
                                            .build()
                            )
            );

    return pricedView
            .thenApply(Json::toJson)
            .thenApply(Results::ok);
}
 
Example #16
Source File: GraphController.java    From ground with Apache License 2.0 6 votes vote down vote up
@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addGraphVersion() {
  return CompletableFuture.supplyAsync(
    () -> {
      JsonNode json = request().body().asJson();
      List<Long> parentIds = GroundUtils.getListFromJson(json, "parentIds");
      ((ObjectNode) json).remove("parentIds");
      GraphVersion graphVersion = Json.fromJson(json, GraphVersion.class);

      try {
        graphVersion = this.postgresGraphVersionDao.create(graphVersion, parentIds);
      } catch (GroundException e) {
        throw new CompletionException(e);
      }
      return Json.toJson(graphVersion);
    },
    PostgresUtils.getDbSourceHttpContext(actorSystem))
           .thenApply(Results::ok)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
Example #17
Source File: ErrorHandler.java    From htwplus with MIT License 6 votes vote down vote up
protected CompletionStage<Result> onOtherClientError(Http.RequestHeader request, int errorCode, String message) {
    jpaApi.withTransaction(() -> {
        Group group = groupManager.findByTitle(configuration.getString("htwplus.admin.group"));
        if (group != null) {
            Post post = new Post();
            post.content = "Request: " + request + "\nError: " + errorCode + " - " + message;
            post.owner = accountManager.findByEmail(configuration.getString("htwplus.admin.mail"));
            post.group = group;
            postManager.createWithoutIndex(post);
        }
    });

    if (errorCode == Http.Status.REQUEST_ENTITY_TOO_LARGE) {
        return CompletableFuture.completedFuture(Results.status(errorCode, "Es sind maximal "+ MAX_FILESIZE + " MByte pro Datei möglich."));
    }

    return CompletableFuture.completedFuture(Results.status(errorCode, badRequest.render(request.method(), request.uri(), message)));
}
 
Example #18
Source File: RMBController.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
public Result ratePost(int rmbPost, int rating) throws SQLException {
	Result ret = Utils.validateRequest(request(), response(), getAPI(), getDatabase());
	if (ret != null) {
		return ret;
	}
	if (rmbPost < 12 || rating > 1) {
		return Results.badRequest();
	}
	final String nation = Utils.sanitizeName(Utils.getPostValue(request(), "nation"));
	final int nationId = getDatabase().getNationId(nation);
	if (nationId == -1) {
		return Results.badRequest();
	}
	try (Connection conn = getConnection()) {
		JsonNode ratings = rateRMBPost(getDatabase(), conn, nation, nationId, rmbPost, rating);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("rmb_post_id", rmbPost);
		getDatabase().getWebsocketManager().onUpdate(PageType.REGION, RequestType.RMB_RATINGS, new DataRequest(RequestType.RMB_RATINGS, data), ratings);
	} 
	Utils.handleDefaultPostHeaders(request(), response());
	return Results.ok();
}
 
Example #19
Source File: LineageGraphController.java    From ground with Apache License 2.0 6 votes vote down vote up
@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> createLineageGraph() {
  return CompletableFuture.supplyAsync(
    () -> {
      JsonNode json = request().body().asJson();
      LineageGraph lineageGraph = Json.fromJson(json, LineageGraph.class);
      try {
        lineageGraph = this.postgresLineageGraphDao.create(lineageGraph);
      } catch (GroundException e) {
        throw new CompletionException(e);
      }
      return Json.toJson(lineageGraph);
    },
    PostgresUtils.getDbSourceHttpContext(this.actorSystem))
           .thenApply(Results::created)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
Example #20
Source File: LineageGraphController.java    From ground with Apache License 2.0 6 votes vote down vote up
public final CompletionStage<Result> getLineageGraphVersion(Long id) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "lineage_graph_versions." + id,
          () -> Json.toJson(this.postgresLineageGraphVersionDao.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 #21
Source File: BaseController.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * This method will create data for success response.
 *
 * @param request play.mvc.Http.Request
 * @param response Response
 * @return Response
 */
public static Result createSuccessResponse(Request request, Response response) {
  if (request != null) {
    response.setVer(getApiVersion(request.path()));
  } else {
    response.setVer("");
  }

  response.setId(getApiResponseId(request));
  response.setTs(ProjectUtil.getFormattedDate());
  ResponseCode code = ResponseCode.getResponse(ResponseCode.success.getErrorCode());
  code.setResponseCode(ResponseCode.OK.getResponseCode());
  response.setParams(createResponseParamObj(code, null, request.flash().get(JsonKey.REQUEST_ID)));
  String value = null;
  try {
    if (response.getResult() != null) {
      String json = new ObjectMapper().writeValueAsString(response.getResult());
      value = getResponseSize(json);
    }
  } catch (Exception e) {
    value = "0.0";
  }

  return Results.ok(Json.toJson(response))
      .withHeader(HeaderParam.X_Response_Length.getName(), value);
}
 
Example #22
Source File: IRCController.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
public Result getIRCNetwork(String region) throws SQLException {
	Utils.handleDefaultPostHeaders(request(), response());
	int regionId = getDatabase().getRegionId(region);
	if (regionId == -1) {
		return Results.badRequest("Invalid region");
	}
	try (Connection conn = this.getConnection()) {
		try (PreparedStatement select = conn.prepareStatement("SELECT irc_network, irc_channel, irc_port FROM assembly.irc_networks WHERE region = ?")) {
			select.setInt(1, regionId);
			try (ResultSet result = select.executeQuery()) {
				if (result.next()) {
					HashMap<String, Object> ircNetwork = new HashMap<>();
					ircNetwork.put("irc_network", result.getString(1));
					ircNetwork.put("irc_channel", result.getString(2));
					ircNetwork.put("irc_port", result.getInt(3));
					return Results.ok(Json.toJson(ircNetwork)).as("application/json");
				}
			}
		}
	}
	return Results.noContent();
}
 
Example #23
Source File: BaseController.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * Common exception response handler method.
 *
 * @param e Exception
 * @param request play.mvc.Http.Request
 * @return Result
 */
public Result createCommonExceptionResponse(Exception e, Request request) {
  Request req = request;
  ProjectCommonException exception = null;
  if (e instanceof ProjectCommonException) {
    exception = (ProjectCommonException) e;
  } else {
    exception =
        new ProjectCommonException(
            ResponseCode.internalError.getErrorCode(),
            ResponseCode.internalError.getErrorMessage(),
            ResponseCode.SERVER_ERROR.getResponseCode());
  }
  generateExceptionTelemetry(request, exception);
  // cleaning request info ...
  return Results.status(
      exception.getResponseCode(), Json.toJson(createResponseOnException(req, exception)));
}
 
Example #24
Source File: LineageEdgeController.java    From ground with Apache License 2.0 6 votes vote down vote up
public final CompletionStage<Result> getHistory(String sourceKey) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "lineage_edge_history." + sourceKey,
          () -> Json.toJson(this.postgresLineageEdgeDao.getHistory(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 #25
Source File: LineageEdgeController.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(
          "lineage_edge_leaves." + sourceKey,
          () -> Json.toJson(this.postgresLineageEdgeDao.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 #26
Source File: StructureController.java    From ground with Apache License 2.0 6 votes vote down vote up
@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addStructure() {
  return CompletableFuture.supplyAsync(
    () -> {
      JsonNode json = request().body().asJson();
      Structure structure = Json.fromJson(json, Structure.class);

      try {
        structure = this.postgresStructureDao.create(structure);
      } catch (GroundException e) {
        throw new CompletionException(e);
      }
      return Json.toJson(structure);
    },

    PostgresUtils.getDbSourceHttpContext(this.actorSystem))
           .thenApply(Results::created)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
Example #27
Source File: LineageEdgeController.java    From ground with Apache License 2.0 6 votes vote down vote up
@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> createLineageEdge() {
  return CompletableFuture.supplyAsync(
    () -> {
      JsonNode json = request().body().asJson();
      LineageEdge lineageEdge = Json.fromJson(json, LineageEdge.class);
      try {
        lineageEdge = this.postgresLineageEdgeDao.create(lineageEdge);
      } catch (GroundException e) {
        throw new CompletionException(e);
      }
      return Json.toJson(lineageEdge);
    },
    PostgresUtils.getDbSourceHttpContext(this.actorSystem))
           .thenApply(Results::created)
           .exceptionally(e -> GroundUtils.handleException(e, request()));
}
 
Example #28
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 #29
Source File: LineageEdgeController.java    From ground with Apache License 2.0 6 votes vote down vote up
public final CompletionStage<Result> getLineageEdgeVersion(Long id) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "lineage_edge_versions." + id,
          () -> Json.toJson(this.postgresLineageEdgeVersionDao.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 #30
Source File: LineageEdgeController.java    From ground with Apache License 2.0 6 votes vote down vote up
public final CompletionStage<Result> getLineageEdge(String sourceKey) {
  return CompletableFuture.supplyAsync(
    () -> {
      try {
        return this.cache.getOrElse(
          "lineage_edges." + sourceKey,
          () -> Json.toJson(this.postgresLineageEdgeDao.retrieveFromDatabase(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()));
}