下面列出了io.vertx.core.json.JsonObject#getInteger ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public DataObjectWithValues(JsonObject json) {
booleanValue = json.getBoolean("booleanValue", false);
shortValue = (short)(int)json.getInteger("shortValue", -1);
intValue = json.getInteger("intValue", -1);
longValue = json.getLong("longValue", -1L);
floatValue = json.getFloat("floatValue", -1f);
doubleValue = json.getDouble("doubleValue", -1d);
boxedBooleanValue = json.getBoolean("boxedBooleanValue", null);
boxedShortValue = json.getInteger("boxedShortValue") != null ? (short)(int)json.getInteger("boxedShortValue") : null;
boxedIntValue = json.getInteger("boxedIntValue", null);
boxedLongValue = json.getLong("boxedLongValue", null);
boxedFloatValue = json.getFloat("boxedFloatValue", null);
boxedDoubleValue = json.getDouble("boxedDoubleValue", null);
stringValue = json.getString("stringValue");
instantValue = json.getInstant("instantValue");
jsonObjectValue = json.getJsonObject("jsonObjectValue");
jsonArrayValue = json.getJsonArray("jsonArrayValue");
dataObjectValue = json.getJsonObject("dataObjectValue") != null ? new TestDataObject(json.getJsonObject("dataObjectValue")) : null;
enumValue = json.getString("enumValue") != null ? TestEnum.valueOf(json.getString("enumValue")) : null;
genEnumValue = json.getString("genEnumValue") != null ? TestGenEnum.valueOf(json.getString("genEnumValue")) : null;
}
/**
* 申请微信授权
* /awp/wxOauth/apply/{body}
* web服务需要授权时,向用户发送重定向,重定向到当前接口
* 参数只有一个,内容为JSON,请用http://localhost:8083/awp/base64.html进行加密
* {
* "eid":web项目使用的公众号在本项目中的用户ID
* "type":0=静默授权,只能获取OpenID,1=正常授权,会弹出授权确认页面,可以获取到用户信息
* "callback":授权成功后调用的web项目回调接口地址,请使用完整地址,
* 回调时会使用GET方法,加上rs参数,
* 如果静默授权,rs参数内容就是openid
* 如果正常授权,rs参数内容是turingBase64加密的授权结果(JSON)
* }
*
* @param rc Vertx的RoutingContext对象
* @author Leibniz.Hu
*/
private void applyForOauth(RoutingContext rc) {
HttpServerResponse resp = rc.response();
String decodedBody = TuringBase64Util.decode(rc.request().getParam("body"));
JsonObject reqJson = new JsonObject(decodedBody);
Integer eid = reqJson.getInteger("eid");
int type = reqJson.getInteger("type");
String callback = TuringBase64Util.encode(reqJson.getString("callback"));//授权后回调方法
vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
if (ar.succeeded()) {
JsonObject account = ar.result().body();
String redirectAfterUrl = PROJ_URL + "oauth/wx/" + (type == 0 ? "baseCb" : "infoCb") + "?eid=" + eid + "&visitUrl=" + callback;
String returnUrl = null;
try {
returnUrl = String.format((type == 0 ? OAUTH_BASE_API : OAUTH_INFO_API)
, account.getString(WXAPPID), URLEncoder.encode(redirectAfterUrl, "UTF-8"));
} catch (UnsupportedEncodingException ignored) { //不可能出现的
}
resp.setStatusCode(302).putHeader("Location", returnUrl).end();
} else {
log.error("EventBus消息响应错误", ar.cause());
resp.setStatusCode(500).end("EventBus error!");
}
});
}
@SuppressWarnings("unchecked")
public UpdateOptions(JsonObject json) {
super(json);
script = json.getString(FIELD_SCRIPT);
scriptLang = json.getString(FIELD_SCRIPT_LANG);
scriptParams = json.getJsonObject(FIELD_SCRIPT_PARAMS);
//noinspection unchecked
fields = json.getJsonArray(FIELD_FIELDS, new JsonArray()).getList();
retryOnConflict = json.getInteger(FIELD_RETRY_ON_CONFLICT);
doc = json.getJsonObject(FIELD_DOC);
upsert = json.getJsonObject(FIELD_UPSERT);
docAsUpsert = json.getBoolean(FIELD_DOC_AS_UPSERT);
detectNoop = json.getBoolean(FIELD_DETECT_NOOP);
scriptedUpsert = json.getBoolean(FIELD_SCRIPTED_UPSERT);
scriptType = Optional.ofNullable(json.getString(FIELD_SCRIPT_TYPE)).map(ScriptType::valueOf).orElse(null);
}
protected void initTransportAddresses(JsonObject config) {
try {
JsonArray jsonArray = config.getJsonArray(CONFIG_TRANSPORT_ADDRESSES);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject transportAddress = jsonArray.getJsonObject(i);
String hostname = transportAddress.getString(CONFIG_HOSTNAME);
if (hostname != null && !hostname.isEmpty()) {
int port = transportAddress.getInteger(CONFIG_PORT, 9300);
transportAddresses.add(new TransportAddress(InetAddress.getByName(hostname), port));
}
}
}
// If no addresses are configured, add local host on the default port
if (transportAddresses.size() == 0) {
transportAddresses.add(new TransportAddress(new InetSocketAddress("localhost", 9300)));
}
} catch (Exception e) {
throw new IllegalStateException("Can't create transport client", e);
}
}
/**
* Returns an Integer configuration value by key or return default value
*
* @param config, the configuration object
* @param propertyName the property name to look for
* @param defaultValue the fallback value
* @return the Integer configuration value
*/
public static Integer getIntegerConfiguration(final JsonObject config, String propertyName,
int defaultValue) {
String env = System.getenv(propertyName.toUpperCase());
if (env != null && !env.isEmpty()) {
return Integer.valueOf(env);
}
return config.getInteger(propertyName, defaultValue);
}
private void initConfiguration(JsonObject config) {
expiration_age = config.getLong("expiration", DEFAULT_EXPIRATION_AGE);
ping_time = config.getLong("ping", DEFAULT_PING_TIME);
sweep_time = config.getLong("sweep", DEFAULT_SWEEP_TIME);
timeout_time = config.getLong("timeout", DEFAULT_TIMEOUT);
serviceRegisterPath = config.getString("serviceRegisterPath", GlobalKeyHolder.SERVICE_REGISTER_HANDLER);
serviceUnRegisterPath = config.getString("serviceUnRegisterPath", GlobalKeyHolder.SERVICE_UNREGISTER_HANDLER);
host = config.getString("host", HOST);
port = config.getInteger("port", PORT);
mainURL = host.concat(":").concat(Integer.valueOf(port).toString());
debug = config.getBoolean("debug",false);
}
/**
* Construct Proxy service.
* @param vertx Vert.x handle
* @param modules module manager
* @param tm tenant manager
* @param dm discovery manager
* @param im internal module
* @param okapiUrl Okapi URL
* @param config configuration
*/
public ProxyService(Vertx vertx, ModuleManager modules, TenantManager tm,
DiscoveryManager dm, InternalModule im, String okapiUrl, JsonObject config) {
this.vertx = vertx;
this.moduleManager = modules;
this.tenantManager = tm;
this.internalModule = im;
this.discoveryManager = dm;
this.okapiUrl = okapiUrl;
this.waitMs = config.getInteger("logWaitMs", 0);
HttpClientOptions opt = new HttpClientOptions();
opt.setMaxPoolSize(1000);
httpClient = vertx.createHttpClient(opt);
}
/**
* Creates an instance of {@link SlimVaultClient}.
*
* @param vertx the vert.x instance
* @param configuration the configuration. This configuration can contain the underlying Web Client configuration.
*/
public SlimVaultClient(Vertx vertx, JsonObject configuration) {
String host = configuration.getString("host");
Integer port = configuration.getInteger("port", 8200);
Objects.requireNonNull(host, "The Vault host must be set");
client = WebClient.create(vertx, new WebClientOptions(configuration)
.setDefaultPort(port).setDefaultHost(host)
);
setToken(configuration.getString("token"));
}
public ZookeeperConfigStore(Vertx vertx, JsonObject configuration) {
String connection = Objects.requireNonNull(configuration.getString("connection"));
path = Objects.requireNonNull(configuration.getString("path"));
this.vertx = Objects.requireNonNull(vertx);
int maxRetries = configuration.getInteger("maxRetries", 3);
int baseGraceBetweenRetries = configuration.getInteger("baseSleepTimeBetweenRetries", 1000);
client = CuratorFrameworkFactory.newClient(connection,
new ExponentialBackoffRetry(baseGraceBetweenRetries, maxRetries));
client.start();
}
static PgConnectOptions createPgConnectOptions(JsonObject sqlConfig) {
PgConnectOptions pgConnectOptions = new PgConnectOptions();
String host = sqlConfig.getString(HOST);
if (host != null) {
pgConnectOptions.setHost(host);
}
Integer port = sqlConfig.getInteger(PORT);
if (port != null) {
pgConnectOptions.setPort(port);
}
String username = sqlConfig.getString(_USERNAME);
if (username != null) {
pgConnectOptions.setUser(username);
}
String password = sqlConfig.getString(_PASSWORD);
if (password != null) {
pgConnectOptions.setPassword(password);
}
String database = sqlConfig.getString(DATABASE);
if (database != null) {
pgConnectOptions.setDatabase(database);
}
Integer connectionReleaseDelay = sqlConfig.getInteger(CONNECTION_RELEASE_DELAY, DEFAULT_CONNECTION_RELEASE_DELAY);
pgConnectOptions.setIdleTimeout(connectionReleaseDelay);
pgConnectOptions.setIdleTimeoutUnit(TimeUnit.MILLISECONDS);
return pgConnectOptions;
}
/**
* Checks if the given json is a valid LoRa gateway.
*
* @param gateway the gateway as json
* @return {@code true} if the input is in a valid format
*/
public static boolean isValidLoraGateway(final JsonObject gateway) {
final JsonObject data = gateway.getJsonObject(RegistrationConstants.FIELD_DATA);
if (data == null) {
return false;
}
final JsonObject loraConfig = data.getJsonObject(LoraConstants.FIELD_LORA_CONFIG);
if (loraConfig == null) {
return false;
}
try {
final String provider = loraConfig.getString(LoraConstants.FIELD_LORA_PROVIDER);
if (isBlank(provider)) {
return false;
}
final String authId = loraConfig.getString(LoraConstants.FIELD_AUTH_ID);
if (isBlank(authId)) {
return false;
}
final int port = loraConfig.getInteger(LoraConstants.FIELD_LORA_DEVICE_PORT);
if (port < 0 || port > 65535) {
return false;
}
final String url = loraConfig.getString(LoraConstants.FIELD_LORA_URL);
if (isBlank(url)) {
return false;
}
} catch (final ClassCastException | DecodeException e) {
return false;
}
return true;
}
/**
* 支付宝支付,直接向响应写入支付宝返回的内容
*
* @author Leibniz
*/
private void alipayOrder(RoutingContext rc) {
//请求json解码,获取订单参数
JsonObject reqJson = new JsonObject(TuringBase64Util.decode(rc.request().getParam("body")));
log.debug("接收到支付宝下单请求,下单参数:{}", reqJson);
int eid = reqJson.getInteger(EID);
String orderId = reqJson.getString(ORDERID);//orderId 本地订单ID
int price = reqJson.getInteger("price");
String name = reqJson.getString("name");
String callback = reqJson.getString(CALLBACK);
String successUrl = reqJson.getString("success");
HttpServerResponse response = rc.response();
//记录eid和orderId、callback关系
JsonObject order = new JsonObject().put(ORDERID, orderId).put(CALLBACK, callback).put(EID, eid).put(TYPE, 1);
vertx.eventBus().<JsonObject>send(ADDR_ORDER_DB.get(), makeMessage(COMMAND_INSERT_ORDER, order), ar -> {
if (ar.failed()) {
log.error("EventBus消息响应错误", ar.cause());
response.setStatusCode(500).end("EventBus error!");
}
});
vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
if (ar.succeeded()) {
JsonObject acc = ar.result().body();
payServ.alipayOrder(name, price, orderId, acc, successUrl, response);
} else {
log.error("EventBus消息响应错误", ar.cause());
response.setStatusCode(500).end("EventBus error!");
}
});
}
/**
* 发送客服消息
*/
private void sendCustomerServiceMessage(RoutingContext rc) {
if (refuseNonLanAccess(rc)) return;
JsonObject params = rc.getBodyAsJson();
String openId = params.getString("openId");
String content = params.getString("content");
int eid = params.getInteger("eid");
vertx.eventBus().<JsonObject>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_GET_ACCOUNT_BY_ID, eid), ar -> {
HttpServerResponse response = rc.response();
if (ar.succeeded()) {
JsonObject acc = ar.result().body();
vertx.executeBlocking(future -> {
future.complete(null);//TODO 支付宝客服消息的实现
}, res -> {
if (res.succeeded()) {
response.putHeader("content-type", "application/json;charset=UTF-8").end(res.result().toString());
} else {
log.error("向公众号" + acc.getString(NAME) + "的粉丝" + openId + "发送客服消息时抛出异常", res.cause());
response.setStatusCode(500).end(res.cause().getMessage());
}
});
} else {
log.error("EventBus消息响应错误", ar.cause());
response.setStatusCode(500).end("EventBus error!");
}
});
}
static String discoveryType(JsonObject service, Record record) {
JsonObject spec = service.getJsonObject("spec");
JsonArray ports = spec.getJsonArray("ports");
if (ports == null || ports.isEmpty()) {
return ServiceType.UNKNOWN;
}
if (ports.size() > 1) {
LOGGER.warn("More than one ports has been found for " + record.getName() + " - taking the " +
"first one to build the record location");
}
JsonObject port = ports.getJsonObject(0);
int p = port.getInteger("port");
// Http
if (p == 80 || p == 443 || p >= 8080 && p <= 9000) {
return HttpEndpoint.TYPE;
}
// PostGreSQL
if (p == 5432 || p == 5433) {
return JDBCDataSource.TYPE;
}
// MySQL
if (p == 3306 || p == 13306) {
return JDBCDataSource.TYPE;
}
// Redis
if (p == 6379) {
return RedisDataSource.TYPE;
}
// Mongo
if (p == 27017 || p == 27018 || p == 27019) {
return MongoDataSource.TYPE;
}
return ServiceType.UNKNOWN;
}
public static AccountFans syncAccountFans(String openId, Account mpAccount){
String accessToken = getAccessToken(mpAccount);
String url = WxApi.getFansInfoUrl(accessToken, openId);
JsonObject jsonObj = WxApi.httpsRequest(url, "GET", null);
if (null != jsonObj) {
if(jsonObj.containsKey("errcode")){
int errorCode = jsonObj.getInteger("errcode");
System.out.println(String.format("获取用户信息失败 errcode:{} errmsg:{}", errorCode, ErrCode.errMsg(errorCode)));
return null;
}else{
AccountFans fans = new AccountFans();
fans.setOpenId(jsonObj.getString("openid"));// 用户的标识
fans.setSubscribeStatus(new Integer(jsonObj.getInteger("subscribe")));// 关注状态(1是关注,0是未关注),未关注时获取不到其余信息
if(jsonObj.containsKey("subscribe_time")){
fans.setSubscribeTime(jsonObj.getString("subscribe_time"));// 用户关注时间
}
if(jsonObj.containsKey("nickname")){// 昵称
try {
String nickname = jsonObj.getString("nickname");
fans.setNickname(nickname.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
if(jsonObj.containsKey("sex")){// 用户的性别(1是男性,2是女性,0是未知)
fans.setGender(jsonObj.getInteger("sex"));
}
if(jsonObj.containsKey("language")){// 用户的语言,简体中文为zh_CN
fans.setLanguage(jsonObj.getString("language"));
}
if(jsonObj.containsKey("country")){// 用户所在国家
fans.setCountry(jsonObj.getString("country"));
}
if(jsonObj.containsKey("province")){// 用户所在省份
fans.setProvince(jsonObj.getString("province"));
}
if(jsonObj.containsKey("city")){// 用户所在城市
fans.setCity(jsonObj.getString("city"));
}
if(jsonObj.containsKey("headimgurl")){// 用户头像
fans.setHeadimgurl(jsonObj.getString("headimgurl"));
}
if(jsonObj.containsKey("remark")){
fans.setRemark(jsonObj.getString("remark"));
}
fans.setStatus(1);
fans.setCreatetime(new Date());
return fans;
}
}
return null;
}
@Override
public void start() throws Exception {
address = MQTTSession.ADDRESS;
JsonObject conf = config();
localBridgePort = conf.getInteger("local_bridge_port", 7007);
idleTimeout = conf.getInteger("socket_idle_timeout", 120);
ssl_cert_key = conf.getString("ssl_cert_key");
ssl_cert = conf.getString("ssl_cert");
ssl_trust = conf.getString("ssl_trust");
// [WebSocket -> BUS] listen WebSocket publish to BUS
HttpServerOptions opt = new HttpServerOptions()
.setTcpKeepAlive(true)
.setIdleTimeout(idleTimeout)
.setPort(localBridgePort)
;
if(ssl_cert_key != null && ssl_cert != null && ssl_trust != null) {
opt.setSsl(true).setClientAuth(ClientAuth.REQUIRED)
.setPemKeyCertOptions(new PemKeyCertOptions()
.setKeyPath(ssl_cert_key)
.setCertPath(ssl_cert)
)
.setPemTrustOptions(new PemTrustOptions()
.addCertPath(ssl_trust)
)
;
}
netServer = vertx.createHttpServer(opt);
netServer.requestHandler(httpServerRequest -> httpServerRequest.response().end() );
netServer.websocketHandler(sock -> {
final EventBusWebsocketBridge ebnb = new EventBusWebsocketBridge(sock, vertx.eventBus(), address);
sock.closeHandler(aVoid -> {
logger.info("Bridge Server - closed connection from client ip: " + sock.remoteAddress());
ebnb.stop();
});
sock.exceptionHandler(throwable -> {
logger.error("Bridge Server - Exception: " + throwable.getMessage(), throwable);
ebnb.stop();
});
logger.info("Bridge Server - new connection from client ip: " + sock.remoteAddress());
RecordParser parser = ebnb.initialHandhakeProtocolParser();
sock.handler(parser::handle);
}).listen();
}
@Override
public void start() throws Exception {
address = MQTTSession.ADDRESS;
JsonObject conf = config();
localBridgePort = conf.getInteger("local_bridge_port", 7007);
idleTimeout = conf.getInteger("socket_idle_timeout", 120);
ssl_cert_key = conf.getString("ssl_cert_key");
ssl_cert = conf.getString("ssl_cert");
ssl_trust = conf.getString("ssl_trust");
// [TCP -> BUS] listen TCP publish to BUS
NetServerOptions opt = new NetServerOptions()
.setTcpKeepAlive(true)
.setIdleTimeout(idleTimeout)
.setPort(localBridgePort)
;
if(ssl_cert_key != null && ssl_cert != null && ssl_trust != null) {
opt.setSsl(true).setClientAuth(ClientAuth.REQUIRED)
.setPemKeyCertOptions(new PemKeyCertOptions()
.setKeyPath(ssl_cert_key)
.setCertPath(ssl_cert)
)
.setPemTrustOptions(new PemTrustOptions()
.addCertPath(ssl_trust)
)
;
}
netServer = vertx.createNetServer(opt);
netServer.connectHandler(sock -> {
final EventBusNetBridge ebnb = new EventBusNetBridge(sock, vertx.eventBus(), address);
sock.closeHandler(aVoid -> {
logger.info("Bridge Server - closed connection from client ip: " + sock.remoteAddress());
ebnb.stop();
});
sock.exceptionHandler(throwable -> {
logger.error("Bridge Server - Exception: " + throwable.getMessage(), throwable);
ebnb.stop();
});
logger.info("Bridge Server - new connection from client ip: " + sock.remoteAddress());
RecordParser parser = ebnb.initialHandhakeProtocolParser();
sock.handler(parser::handle);
}).listen();
}
@Override
public void start() throws Exception {
JsonObject restServerConf = config().getJsonObject("rest_server", new JsonObject());
int httpPort = restServerConf.getInteger("port", 2883);
String mqttAddress = MQTTSession.ADDRESS;
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
long size1mb = 1024*1024 ; //bytes
router.route().handler(BodyHandler.create().setBodyLimit(size1mb));
// http://<host:port>/pubsub/publish?channel=<channel1>&qos=0&retained=0
// qos: MOST_ONE, LEAST_ONE, EXACTLY_ONC
router.post("/pubsub/publish").handler( req -> {
MultiMap headers = req.request().headers();
MultiMap params = req.request().params();
String tenant;
if(headers.contains("tenant")) {
tenant = headers.get("tenant");
} else {
tenant = params.get("tenant");
}
String topic;
if(params.contains("topic")) {
topic = req.request().params().get("topic");
} else if (params.contains("channel")) {
topic = req.request().params().get("channel");
} else {
throw new IllegalArgumentException("parameter 'topic' is required");
}
String qos = req.request().params().get("qos");
String retained = req.request().params().get("retained");
PublishMessage msg = new PublishMessage();
msg.setMessageID(1);
msg.setTopicName(topic);
if ( qos != null) {
AbstractMessage.QOSType theqos =
AbstractMessage.QOSType.valueOf(qos);
msg.setQos(theqos);
}
if (retained != null)
msg.setRetainFlag(true);
try {
Buffer body = req.getBody();
byte[] payload = body.getBytes();
msg.setPayload(ByteBuffer.wrap(payload));
MQTTEncoder enc = new MQTTEncoder();
DeliveryOptions opt = new DeliveryOptions()
.addHeader(MQTTSession.TENANT_HEADER, tenant);
vertx.eventBus().publish(mqttAddress, enc.enc(msg), opt);
req.response().setStatusCode(200);
} catch (Throwable e) {
logger.error(e.getMessage(), e);
req.response().setStatusCode(500);
req.response().setStatusMessage(e.getMessage());
}
req.response().end();
});
router.exceptionHandler(event -> {
logger.error(event.getMessage(), event.getCause());
});
// JWT AUTH
SPAuthHandler spAuthHandler = SPAuthHandler.create(vertx);
Router mainRouter = Router.router(vertx);
mainRouter.route("/sp/*")
.handler(spAuthHandler::validateJWTToken)
// .handler(spAuthHandler::validateTenant)
;
mainRouter.route("/api/v2/*")
.handler(spAuthHandler::validateJWTToken)
// .handler(spAuthHandler::validateTenant)
;
// retrocompatilità con vecchie api
mainRouter.mountSubRouter("/sp", router);
// nuovi path per le nuove api
mainRouter.mountSubRouter("/api/v2", router);
mainRouter.mountSubRouter("/", router);
mainRouter.mountSubRouter("/api/1.2", router);
mainRouter.route().handler( ctx -> ctx.response().end() );
// JWT AUTH END
server.requestHandler(mainRouter::accept).listen(httpPort, event -> {
if (event.succeeded()) {
logger.info("RestApiVerticle http server started on http://<host>:" + server.actualPort());
} else {
logger.info("RestApiVerticle http server NOT started !");
}
});
logger.info("RestApiVerticle started" );
}
public ErrorLocation(JsonObject json) {
this.line = json.getInteger("line", 0);
this.column = json.getInteger("column", 0);
}
protected void validateJsonVersion(JsonObject json) {
if (json.getInteger("version") != 1) {
throw new RuntimeException("Failed to validate the user JSON. The version is missing or has an invalid value.");
}
}