Java Code Examples for io.vertx.core.eventbus.Message#body()

The following examples show how to use io.vertx.core.eventbus.Message#body() . 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: SensorDataServiceVertxProxyHandler.java    From vertx-in-action with MIT License 6 votes vote down vote up
public void handle(Message<JsonObject> msg) {
  try{
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) throw new IllegalStateException("action not specified");
    accessed();
    switch (action) {
      case "valueFor": {
        service.valueFor((java.lang.String)json.getValue("sensorId"),
                      HelperUtils.createHandler(msg, includeDebugInfo));
        break;
      }
      case "average": {
        service.average(HelperUtils.createHandler(msg, includeDebugInfo));
        break;
      }
      default: throw new IllegalStateException("Invalid action: " + action);
    }
  } catch (Throwable t) {
    if (includeDebugInfo) msg.reply(new ServiceException(500, t.getMessage(), HelperUtils.generateDebugInfo(t)));
    else msg.reply(new ServiceException(500, t.getMessage()));
    throw t;
  }
}
 
Example 2
Source File: GeneratorVerticle.java    From vertx-starter with Apache License 2.0 6 votes vote down vote up
private void onProjectRequested(Message<VertxProject> msg) {
  VertxProject project = msg.body();
  vertx.executeBlocking(fut -> {
    try {
      fut.complete(generatorService.onProjectRequested(project));
    } catch (Exception e) {
      fut.fail(e);
    }
  }, false, ar -> {
    if (ar.succeeded()) {
      msg.reply(ar.result());
    } else {
      log.error("Failed to generate project " + project.getId(), ar.cause());
      msg.fail(-1, ar.cause().getMessage());
    }
  });
}
 
Example 3
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 更新一个路由
 * 
 * @param msg
 */
public void updtRoute(Message<JsonObject> msg) {
	if (msg.body() == null) {
		msg.fail(1400, "参数不能为空");
		return;
	}
	VxApisDTO dto = VxApisDTO.fromJson(msg.body());
	if (dto == null) {
		msg.fail(1405, "参数不能为空");
		return;
	}
	String apiName = dto.getApiName();
	if (httpRouteMaps.get(apiName) != null) {
		httpRouteMaps.get(apiName).forEach(r -> r.disable().remove());
	}
	if (httpsRouteMaps.get(apiName) != null) {
		httpsRouteMaps.get(apiName).forEach(r -> r.disable().remove());
	}
	addRoute(msg);
}
 
Example 4
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 删除一个路由
 * 
 * @param msg
 */
public void delRoute(Message<String> msg) {
	if (StrUtil.isNullOrEmpty(msg.body())) {
		msg.fail(1400, "参数:API名字不能为空");
		return;
	}
	String apiName = msg.body();
	if (httpRouteMaps.get(apiName) != null) {
		httpRouteMaps.get(apiName).forEach(r -> r.disable().remove());
	}
	if (httpsRouteMaps.get(apiName) != null) {
		httpsRouteMaps.get(apiName).forEach(r -> r.disable().remove());
	}
	msg.reply(1);
}
 
Example 5
Source File: CheckoutServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
public void handle(Message<JsonObject> msg) {
  try {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
      throw new IllegalStateException("action not specified");
    }
    accessed();
    switch (action) {

      case "checkout": {
        service.checkout((java.lang.String)json.getValue("userId"), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      default: {
        throw new IllegalStateException("Invalid action: " + action);
      }
    }
  } catch (Throwable t) {
    msg.reply(new ServiceException(500, t.getMessage()));
    throw t;
  }
}
 
Example 6
Source File: ProtocolAdapterCommandConsumerFactoryImpl.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void handleTenantTimeout(final Message<String> msg) {
    final String tenantId = msg.body();
    final MessageConsumer consumer = mappingAndDelegatingCommandConsumerFactory.getClient(tenantId);
    if (consumer != null) {
        log.info("timeout of tenant {}: closing and removing command consumer", tenantId);
        consumer.close(v -> mappingAndDelegatingCommandConsumerFactory.removeClient(tenantId));
    }
    final List<CommandHandlerWrapper> handlersToRemove = adapterInstanceCommandHandler
            .getDeviceSpecificCommandHandlers().stream().filter(handler -> handler.getTenantId().equals(tenantId))
            .collect(Collectors.toList());
    handlersToRemove.forEach(handler -> {
        log.info("timeout of tenant {}: removing command handler for device {}", tenantId, handler.getDeviceId());
        adapterInstanceCommandHandler.removeDeviceSpecificCommandHandler(handler.getTenantId(), handler.getDeviceId());
    });
}
 
Example 7
Source File: SysVerticle.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 添加异常的数量
 * 
 * @param msg
 */
public void PlusError(Message<JsonObject> msg) {
	errorCount += 1;
	if (msg.body() != null) {
		VxApiTrackInfos infos = VxApiTrackInfos.fromJson(msg.body());
		LOG.error(MessageFormat.format("应用:{0} , API:{1} ,在执行的过程中发生了异常:{2} ,堆栈信息{3}", infos.getAppName(), infos.getApiName(),
				infos.getErrMsg(), infos.getErrStackTrace()));
	}
}
 
Example 8
Source File: BaseAuthenticationService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void processMessage(final Message<JsonObject> message) {
    final JsonObject body = message.body();
    authenticate(body, validation -> {
        if (validation.succeeded()) {
            message.reply(AuthenticationConstants.getAuthenticationReply(validation.result().getToken()));
        } else {
            if (validation.cause() instanceof ServiceInvocationException) {
                message.fail(((ServiceInvocationException) validation.cause()).getErrorCode(), validation.cause().getMessage());
            } else {
                LOG.debug("unable to get status code from non-ServiceInvocationException", validation.cause());
                message.fail(HttpURLConnection.HTTP_INTERNAL_ERROR, validation.cause().getMessage());
            }
        }
    });
}
 
Example 9
Source File: PaymentQueryServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
public void handle(Message<JsonObject> msg) {
  try {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
      throw new IllegalStateException("action not specified");
    }
    accessed();
    switch (action) {
      case "initializePersistence": {
        service.initializePersistence(createHandler(msg));
        break;
      }
      case "addPaymentRecord": {
        service.addPaymentRecord(json.getJsonObject("payment") == null ? null : new io.vertx.blueprint.microservice.payment.Payment(json.getJsonObject("payment")), createHandler(msg));
        break;
      }
      case "retrievePaymentRecord": {
        service.retrievePaymentRecord((java.lang.String)json.getValue("payId"), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      default: {
        throw new IllegalStateException("Invalid action: " + action);
      }
    }
  } catch (Throwable t) {
    msg.reply(new ServiceException(500, t.getMessage()));
    throw t;
  }
}
 
Example 10
Source File: DATAVerticle.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 查看所有API
 * 
 * @param msg
 */
public void findAPI(Message<JsonObject> msg) {
	if (msg.body() == null || msg.body().getString("appName") == null) {
		msg.fail(411, "the application name is null");
	} else {
		String sql = MessageFormat.format("select {0} AS {1},{2} AS {3},{4} AS {5} from {6} where {2} = ? ", APIIC, APIIN, API_APPIC,
				API_APPIN, APICC, APICN, APITN);
		// 添加从请求中获取添加值并添加到查询条件中
		JsonArray params = new JsonArray();
		params.add(msg.body().getString("appName"));
		jdbcClient.queryWithParams(sql, params, res -> {
			if (res.succeeded()) {
				List<JsonObject> rows = res.result().getRows();
				JsonArray array = new JsonArray();
				rows.forEach(va -> {
					if (va.getValue(APICN) instanceof String) {
						array.add(new JsonObject(va.getString(APICN)));
					} else if (va.getValue(APICN) instanceof JsonObject) {
						array.add(va.getJsonObject(APICN));
					}
				});
				msg.reply(array);
			} else {
				msg.fail(500, res.cause().toString());
				LOG.error("执行查看所有API-->失败:" + res.cause().toString());
			}
		});
	}
}
 
Example 11
Source File: CounterServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
public void handle(Message<JsonObject> msg) {
  try {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
      throw new IllegalStateException("action not specified");
    }
    accessed();
    switch (action) {
      case "addThenRetrieve": {
        service.addThenRetrieve((java.lang.String)json.getValue("key"), createHandler(msg));
        break;
      }
      case "addThenRetrieveBy": {
        service.addThenRetrieveBy((java.lang.String)json.getValue("key"), json.getValue("increment") == null ? null : (json.getLong("increment").longValue()), createHandler(msg));
        break;
      }
      case "retrieveThenAdd": {
        service.retrieveThenAdd((java.lang.String)json.getValue("key"), createHandler(msg));
        break;
      }
      case "reset": {
        service.reset((java.lang.String)json.getValue("key"), createHandler(msg));
        break;
      }
      default: {
        throw new IllegalStateException("Invalid action: " + action);
      }
    }
  } catch (Throwable t) {
    msg.reply(new ServiceException(500, t.getMessage()));
    throw t;
  }
}
 
Example 12
Source File: OperLogMessageHandler.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Message<OperLogMessage> event) {
    OperLogMessage operLogMsg = event.body();
    if (operLogMsg == null ) {
        return;
    }
    operLogService.add(operLogMsg);
}
 
Example 13
Source File: ShoppingCartServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
public void handle(Message<JsonObject> msg) {
  try {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
      throw new IllegalStateException("action not specified");
    }
    accessed();
    switch (action) {
      case "addCartEvent": {
        service.addCartEvent(json.getJsonObject("event") == null ? null : new io.vertx.blueprint.microservice.cart.CartEvent(json.getJsonObject("event")), createHandler(msg));
        break;
      }
      case "getShoppingCart": {
        service.getShoppingCart((java.lang.String)json.getValue("userId"), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      default: {
        throw new IllegalStateException("Invalid action: " + action);
      }
    }
  } catch (Throwable t) {
    msg.reply(new ServiceException(500, t.getMessage()));
    throw t;
  }
}
 
Example 14
Source File: QueryableVertxProxyHandler.java    From vertx-graphql-service-discovery with Apache License 2.0 4 votes vote down vote up
public void handle(Message<JsonObject> msg) {
  try {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
      throw new IllegalStateException("action not specified");
    }
    accessed();
    switch (action) {

      case "query": {
        service.query((java.lang.String)json.getValue("graphqlQuery"), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      case "queryWithVariables": {
        service.queryWithVariables((java.lang.String)json.getValue("graphqlQuery"), (io.vertx.core.json.JsonObject)json.getValue("variables"), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      case "close": {
        service.close();
        close();
        break;
      }
      default: {
        throw new IllegalStateException("Invalid action: " + action);
      }
    }
  } catch (Throwable t) {
    msg.reply(new ServiceException(500, t.getMessage()));
    throw t;
  }
}
 
Example 15
Source File: SysVerticle.java    From VX-API-Gateway with MIT License 4 votes vote down vote up
/**
 * 添加API追踪信息
 * 
 * @param msg
 */
public void plusTrackInfos(Message<JsonObject> msg) {
	if (msg.body() != null) {
		VxApiTrackInfos infos = VxApiTrackInfos.fromJson(msg.body());
		if (LOG.isDebugEnabled()) {
			LOG.debug(MessageFormat.format("应用:{0} , API:{1} ,执行结果{2}", infos.getAppName(), infos.getApiName(), infos));
		}
		// map的key
		String key = infos.getAppName() + "-" + infos.getApiName();
		// 记录API相关信息
		if (!infos.isSuccessful()) {
			// 记录异常
			errorCount += 1;
			if (requstFailedCount.get(key) == null) {
				requstFailedCount.put(key, 0L);
			}
			requstFailedCount.put(key, requstFailedCount.get(key) + 1);
			LOG.error(MessageFormat.format("应用:{0} , API:{1} ,在执行的过程中发生了异常:{2} ,堆栈信息{3}", infos.getAppName(), infos.getApiName(),
					infos.getErrMsg(), infos.getErrStackTrace()));
		} else {
			JsonObject json = new JsonObject();
			Duration proc = Duration.between(infos.getStartTime(), infos.getEndTime());
			json.put("time", infos.getStartTime());
			json.put("overallTime", proc.toMillis());
			Duration reqs = Duration.between(infos.getRequestTime(), infos.getResponseTime());
			json.put("requestTime", reqs.toMillis());
			json.put("requestBodyLen", infos.getRequestBufferLen());
			json.put("responseBodyLen", infos.getResponseBufferLen());
			if (trackSucceededMap.get(key) == null) {
				trackSucceededMap.put(key, new LinkedList<>());
			} else {
				if (trackSucceededMap.get(key).size() > 100) {
					trackSucceededMap.get(key).pollFirst();
				}
			}
			trackSucceededMap.get(key).add(json);
		}
		// 添加请求数量统计
		if (requstCount.get(key) == null) {
			requstCount.put(key, 0L);
		}
		requstCount.put(key, requstCount.get(key) + 1);
	}
}
 
Example 16
Source File: CLIVerticle.java    From VX-API-Gateway with MIT License 4 votes vote down vote up
/**
 * 启动指定网关应用并启动所有的API
 * 
 * @param msg
 */
public void startAPPEverything(Message<JsonArray> msg) {
	LOG.info("cli->执行启动指定网关应用并启动所有的API...");
	JsonArray body = msg.body();
	if (body == null || body.size() < 1) {
		msg.reply("1400");
		if (LOG.isDebugEnabled()) {
			LOG.debug("cli->执行启动指定网关应用并启动所有的API-->失败:缺少参数,系统接收到信息:" + body);
		}
		return;
	}
	vertx.executeBlocking(futrue -> {
		vertx.eventBus().<JsonArray>send(thisVertxName + VxApiEventBusAddressConstant.FIND_APP, null, reply -> {
			if (reply.succeeded()) {
				JsonArray allAPP = reply.result().body();
				if (allAPP != null && allAPP.size() > 0) {
					JsonArray apps = new JsonArray();
					allAPP.forEach(va -> {
						JsonObject json = (JsonObject) va;
						String key = json.getString("appName", "");
						if (body.contains(key)) {
							apps.add(json);
						}
					});
					if (apps.size() < 1) {
						LOG.info("cli->执行启动指定网关应用并启动所有的API-->结果:没有查询到应用网关,请查看是否输入了不存在的网关应用名字或者是否存在空格或者大小写");
						futrue.complete();
					} else {
						startAppService(apps, 0, 0, true, handler -> {
							Integer success = handler.result().getInteger("success", 0);
							Integer fail = handler.result().getInteger("fail", 0);
							LOG.info("cli->执行启动指定网关应用并启动所有的API-->结果:成功数量:" + success + ",失败数量:" + fail);
							futrue.complete();
						});
					}
				} else {
					futrue.complete();
					LOG.info("cli->执行启动指定网关应用并启动所有的API-->失败:没有查询到应用网关");
				}
			} else {
				futrue.fail(reply.cause());
				LOG.error("cli->执行启动指定网关应用并启动所有的API-->失败:" + reply.cause());
			}
		});
	}, result -> {
		if (result.succeeded()) {
			msg.reply("ok");
		} else {
			msg.reply("500");
			LOG.error("cli->执行启动指定网关应用并启动所有的API-->失败:" + result.cause());
		}
	});
}
 
Example 17
Source File: CLIVerticle.java    From VX-API-Gateway with MIT License 4 votes vote down vote up
/**
 * 启动指定网关应用
 * 
 * @param msg
 */
public void startAPP(Message<JsonArray> msg) {
	LOG.info("cli->执行启动指定网关应用...");
	JsonArray body = msg.body();
	if (body == null || body.size() < 1) {
		msg.reply("1400");
		if (LOG.isDebugEnabled()) {
			LOG.debug("cli->执行启动指定网关应用-->失败:缺少参数,系统接收到信息:" + body);
		}
		return;
	}
	vertx.executeBlocking(futrue -> {
		vertx.eventBus().<JsonArray>send(thisVertxName + VxApiEventBusAddressConstant.FIND_APP, null, reply -> {
			if (reply.succeeded()) {
				JsonArray allAPP = reply.result().body();
				if (allAPP != null && allAPP.size() > 0) {
					JsonArray apps = new JsonArray();
					allAPP.forEach(va -> {
						JsonObject json = (JsonObject) va;
						String key = json.getString("appName", "");
						if (body.contains(key)) {
							apps.add(json);
						}
					});
					if (apps.size() < 1) {
						LOG.info("cli->执行启动指定网关应用-->结果:没有查询到应用网关,请查看是否输入了不存在的APP名字或者是否存在空格或者大小写");
						futrue.complete();
					} else {
						startAppService(apps, 0, 0, false, handler -> {
							Integer success = handler.result().getInteger("success", 0);
							Integer fail = handler.result().getInteger("fail", 0);
							LOG.info("cli->执行启动指定网关应用-->结果:成功数量:" + success + ",失败数量:" + fail);
							futrue.complete();
						});
					}
				} else {
					futrue.complete();
					LOG.info("cli->执行启动指定网关应用-->失败:没有查询到应用网关");
				}
			} else {
				futrue.fail(reply.cause());
				LOG.error("cli->执行启动指定网关应用-->失败:" + reply.cause());
			}
		});
	}, result -> {
		if (result.succeeded()) {
			msg.reply("ok");
		} else {
			msg.reply("500");
			LOG.error("cli->执行启动指定网关应用-->失败:" + result.cause());
		}
	});
}
 
Example 18
Source File: ProductServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 4 votes vote down vote up
public void handle(Message<JsonObject> msg) {
  try {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
      throw new IllegalStateException("action not specified");
    }
    accessed();
    switch (action) {
      case "initializePersistence": {
        service.initializePersistence(createHandler(msg));
        break;
      }
      case "addProduct": {
        service.addProduct(json.getJsonObject("product") == null ? null : new io.vertx.blueprint.microservice.product.Product(json.getJsonObject("product")), createHandler(msg));
        break;
      }
      case "retrieveProduct": {
        service.retrieveProduct((java.lang.String)json.getValue("productId"), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      case "retrieveProductPrice": {
        service.retrieveProductPrice((java.lang.String)json.getValue("productId"), createHandler(msg));
        break;
      }
      case "retrieveAllProducts": {
        service.retrieveAllProducts(res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(new JsonArray(res.result().stream().map(Product::toJson).collect(Collectors.toList())));
          }
       });
        break;
      }
      case "retrieveProductsByPage": {
        service.retrieveProductsByPage(json.getValue("page") == null ? null : (json.getLong("page").intValue()), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(new JsonArray(res.result().stream().map(Product::toJson).collect(Collectors.toList())));
          }
       });
        break;
      }
      case "deleteProduct": {
        service.deleteProduct((java.lang.String)json.getValue("productId"), createHandler(msg));
        break;
      }
      case "deleteAllProducts": {
        service.deleteAllProducts(createHandler(msg));
        break;
      }
      default: {
        throw new IllegalStateException("Invalid action: " + action);
      }
    }
  } catch (Throwable t) {
    msg.reply(new ServiceException(500, t.getMessage()));
    throw t;
  }
}
 
Example 19
Source File: OrderServiceVertxProxyHandler.java    From vertx-blueprint-microservice with Apache License 2.0 4 votes vote down vote up
public void handle(Message<JsonObject> msg) {
  try {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
      throw new IllegalStateException("action not specified");
    }
    accessed();
    switch (action) {
      case "initializePersistence": {
        service.initializePersistence(createHandler(msg));
        break;
      }
      case "retrieveOrdersForAccount": {
        service.retrieveOrdersForAccount((java.lang.String)json.getValue("accountId"), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(new JsonArray(res.result().stream().map(Order::toJson).collect(Collectors.toList())));
          }
       });
        break;
      }
      case "createOrder": {
        service.createOrder(json.getJsonObject("order") == null ? null : new io.vertx.blueprint.microservice.order.Order(json.getJsonObject("order")), createHandler(msg));
        break;
      }
      case "retrieveOrder": {
        service.retrieveOrder(json.getValue("orderId") == null ? null : (json.getLong("orderId").longValue()), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      default: {
        throw new IllegalStateException("Invalid action: " + action);
      }
    }
  } catch (Throwable t) {
    msg.reply(new ServiceException(500, t.getMessage()));
    throw t;
  }
}
 
Example 20
Source File: PortfolioServiceVertxProxyHandler.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
public void handle(Message<JsonObject> msg) {
  try {
    JsonObject json = msg.body();
    String action = msg.headers().get("action");
    if (action == null) {
      throw new IllegalStateException("action not specified");
    }
    accessed();
    switch (action) {
      case "getPortfolio": {
        service.getPortfolio(res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      case "buy": {
        service.buy(json.getValue("amount") == null ? null : (json.getLong("amount").intValue()), (io.vertx.core.json.JsonObject)json.getValue("quote"), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      case "sell": {
        service.sell(json.getValue("amount") == null ? null : (json.getLong("amount").intValue()), (io.vertx.core.json.JsonObject)json.getValue("quote"), res -> {
          if (res.failed()) {
            if (res.cause() instanceof ServiceException) {
              msg.reply(res.cause());
            } else {
              msg.reply(new ServiceException(-1, res.cause().getMessage()));
            }
          } else {
            msg.reply(res.result() == null ? null : res.result().toJson());
          }
       });
        break;
      }
      case "evaluate": {
        service.evaluate(createHandler(msg));
        break;
      }
      default: {
        throw new IllegalStateException("Invalid action: " + action);
      }
    }
  } catch (Throwable t) {
    msg.reply(new ServiceException(500, t.getMessage()));
    throw t;
  }
}