Java 类io.vertx.core.json.DecodeException 实例源码

项目:okapi    文件:BeanTest.java   
@Test
public void testDeploymentDescriptor1() {
  int fail = 0;
  final String docSampleDeployment = "{" + LS
    + "  \"srvcId\" : \"sample-module-1\"," + LS
    + "  \"descriptor\" : {" + LS
    + "    \"exec\" : "
    + "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"," + LS
    + "    \"env\" : [ {" + LS
    + "      \"name\" : \"helloGreeting\"," + LS
    + "      \"value\" : \"hej\"" + LS
    + "    } ]" + LS
    + "  }" + LS
    + "}";

  try {
    final DeploymentDescriptor md = Json.decodeValue(docSampleDeployment,
      DeploymentDescriptor.class);
    String pretty = Json.encodePrettily(md);
    assertEquals(docSampleDeployment, pretty);
  } catch (DecodeException ex) {
    ex.printStackTrace();
    fail = 400;
  }
  assertEquals(0, fail);
}
项目:vertx-zero    文件:JsonSaber.java   
@Override
public Object from(final Class<?> paramType,
                   final String literal) {
    return Fn.get(() ->
                    Fn.getSemi(this.isValid(paramType), this.getLogger(),
                            () -> {
                                try {
                                    return this.getFun().apply(literal);
                                } catch (final DecodeException ex) {
                                    // Do not do anything
                                    // getLogger().jvm(ex);
                                    throw new _400ParameterFromStringException(this.getClass(), paramType, literal);
                                }
                            }, Fn::nil),
            paramType, literal);
}
项目:vertx-postgresql-starter    文件:RestApiUtil.java   
public static <T> T decodeBodyToObject(RoutingContext routingContext, Class<T> clazz) {
  try {
    return Json.decodeValue(routingContext.getBodyAsString("UTF-8"), clazz);
  } catch (DecodeException exception) {
    routingContext.fail(exception);
    return null;
  }
}
项目:vertx-web-problem    文件:ExampleVerticle.java   
@Override
public void start(Future<Void> startFuture) throws Exception {
    configureJsonMapper();
    Router router = Router.router(vertx);

    router.route().handler(BodyHandler.create());
    router.route().failureHandler(one.valuelogic.vertx.web.problem.reactivex.ProblemHandler.create());
    router.get("/test-get").handler(context -> context.response().end("ok"));
    router.get("/test-error").handler(context -> { throw new DecodeException("testing decode error"); });
    router.route().last().handler(one.valuelogic.vertx.web.problem.reactivex.NotFoundHandler.create());

    vertx.createHttpServer()
            .requestHandler(router::accept)
            .rxListen(HTTP_PORT)
            .subscribe(s -> startFuture.complete(), startFuture::fail);
}
项目:chili-core    文件:RequestMock.java   
@Override
public void reply(Object message) {
    JsonObject data = new JsonObject();

    if (message instanceof JsonObject) {
        data = (JsonObject) message;
    } else if (message instanceof Buffer) {
        // normally buffers passed directly, for testing purposes
        // its wrapped in a json object.
        try {
            data = ((Buffer) message).toJsonObject();

            if (!data.containsKey(PROTOCOL_STATUS)) {
                data.put(PROTOCOL_STATUS, ACCEPTED);
            }
        } catch (DecodeException e) {
            data.put(ID_BUFFER, message.toString());
            data.put(PROTOCOL_STATUS, ACCEPTED);
        }
    }
    listener.handle(data, responseStatusFromJson(data));
}
项目:vertx-swagger    文件:BodyParameterExtractor.java   
@Override
public Object extract(String name, Parameter parameter, RoutingContext context) {
    BodyParameter bodyParam = (BodyParameter) parameter;
    if ("".equals(context.getBodyAsString())) {
        if (bodyParam.getRequired())
            throw new IllegalArgumentException("Missing required parameter: " + name);
        else
            return null;
    }

    try {
        if(bodyParam.getSchema() instanceof ArrayModel) {
            return context.getBodyAsJsonArray();
        } else {
            return context.getBodyAsJson();
        }
    } catch (DecodeException e) {
        return context.getBodyAsString();  
    }
}
项目:okapi    文件:Auth.java   
public void login(RoutingContext ctx) {
  final String json = ctx.getBodyAsString();
  if (json.length() == 0) {
    logger.debug("test-auth: accept OK in login");
    responseText(ctx, 202).end("Auth accept in /authn/login");
    return;
  }
  LoginParameters p;
  try {
    p = Json.decodeValue(json, LoginParameters.class);
  } catch (DecodeException ex) {
    responseText(ctx, 400).end("Error in decoding parameters: " + ex);
    return;
  }

  // Simple password validation: "peter" has a password "peter-password", etc.
  String u = p.getUsername();
  String correctpw = u + "-password";
  if (!p.getPassword().equals(correctpw)) {
    logger.warn("test-auth: Bad passwd for '" + u + "'. "
            + "Got '" + p.getPassword() + "' expected '" + correctpw + "'");
    responseText(ctx, 401).end("Wrong username or password");
    return;
  }
  String tok;
  tok = token(p.getTenant(), p.getUsername());
  logger.info("test-auth: Ok login for " + u + ": " + tok);
  responseJson(ctx, 200).putHeader(XOkapiHeaders.TOKEN, tok).end(json);
}
项目:okapi    文件:InternalModule.java   
private void createTenant(ProxyContext pc, String body,
  Handler<ExtendedAsyncResult<String>> fut) {
  try {
    final TenantDescriptor td = Json.decodeValue(body, TenantDescriptor.class);
    if (td.getId() == null || td.getId().isEmpty()) {
      td.setId(UUID.randomUUID().toString());
    }
    final String id = td.getId();
    if (!id.matches("^[a-z0-9_-]+$")) {
      fut.handle(new Failure<>(USER, "Invalid tenant id '" + id + "'"));
      return;
    }
    Tenant t = new Tenant(td);
    tenantManager.insert(t, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
        return;
      }
      location(pc, id, null, Json.encodePrettily(t.getDescriptor()), fut);
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void updateTenant(String id, String body,
  Handler<ExtendedAsyncResult<String>> fut) {
  try {
    final TenantDescriptor td = Json.decodeValue(body, TenantDescriptor.class);
    if (!id.equals(td.getId())) {
      fut.handle(new Failure<>(USER, "Tenant.id=" + td.getId() + " id=" + id));
      return;
    }
    Tenant t = new Tenant(td);
    tenantManager.updateDescriptor(td, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
        return;
      }
      final String s = Json.encodePrettily(t.getDescriptor());
      fut.handle(new Success<>(s));
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void enableModuleForTenant(ProxyContext pc, String id, String body,
  Handler<ExtendedAsyncResult<String>> fut) {
  try {
    final TenantModuleDescriptor td = Json.decodeValue(body,
      TenantModuleDescriptor.class);
    String moduleTo = td.getId();
    tenantManager.enableAndDisableModule(id, null, moduleTo, pc, eres -> {
      if (eres.failed()) {
        fut.handle(new Failure<>(eres.getType(), eres.cause()));
        return;
      }
      td.setId(eres.result());
      location(pc, td.getId(), null, Json.encodePrettily(td), fut);
    });

  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void installModulesForTenant(ProxyContext pc, String id,
  String body, Handler<ExtendedAsyncResult<String>> fut) {

  try {
    TenantInstallOptions options = createTenantOptions(pc.getCtx());

    final TenantModuleDescriptor[] tml = Json.decodeValue(body,
      TenantModuleDescriptor[].class);
    List<TenantModuleDescriptor> tm = new LinkedList<>();
    Collections.addAll(tm, tml);
    tenantManager.installUpgradeModules(id, pc, options, tm, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
      } else {
        logger.info("installUpgradeModules returns:\n" + Json.encodePrettily(res.result()));
        fut.handle(new Success<>(Json.encodePrettily(res.result())));
      }
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void upgradeModulesForTenant(ProxyContext pc, String id,
  Handler<ExtendedAsyncResult<String>> fut) {

  try {
    TenantInstallOptions options = createTenantOptions(pc.getCtx());

    tenantManager.installUpgradeModules(id, pc, options, null, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
      } else {
        logger.info("installUpgradeModules returns:\n" + Json.encodePrettily(res.result()));
        fut.handle(new Success<>(Json.encodePrettily(res.result())));
      }
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void upgradeModuleForTenant(ProxyContext pc, String id, String mod,
  String body, Handler<ExtendedAsyncResult<String>> fut) {
  try {
    final String module_from = mod;
    final TenantModuleDescriptor td = Json.decodeValue(body,
      TenantModuleDescriptor.class);
    final String module_to = td.getId();
    tenantManager.enableAndDisableModule(id, module_from, module_to, pc, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
        return;
      }
      td.setId(res.result());
      final String uri = pc.getCtx().request().uri();
      final String regex = "^(.*)/" + module_from + "$";
      final String newuri = uri.replaceAll(regex, "$1");
      location(pc, td.getId(), newuri, Json.encodePrettily(td), fut);
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void createModule(ProxyContext pc, String body,
  Handler<ExtendedAsyncResult<String>> fut) {
  try {
    final ModuleDescriptor md = Json.decodeValue(body, ModuleDescriptor.class);
    String validerr = md.validate(pc);
    if (!validerr.isEmpty()) {
      fut.handle(new Failure<>(USER, validerr));
      return;
    }
    moduleManager.create(md, cres -> {
      if (cres.failed()) {
        fut.handle(new Failure<>(cres.getType(), cres.cause()));
        return;
      }
      location(pc, md.getId(), null, Json.encodePrettily(md), fut);
    });
  } catch (DecodeException ex) {
    pc.debug("Failed to decode md: " + pc.getCtx().getBodyAsString());
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void updateModule(ProxyContext pc, String id, String body,
  Handler<ExtendedAsyncResult<String>> fut) {
  try {
    final ModuleDescriptor md = Json.decodeValue(body, ModuleDescriptor.class);
    if (!id.equals(md.getId())) {
      fut.handle(new Failure<>(USER, "Module.id=" + md.getId() + " id=" + id));
      return;
    }
    String validerr = md.validate(pc);
    if (!validerr.isEmpty()) {
      fut.handle(new Failure<>(USER, validerr));
      return;
    }
    moduleManager.update(md, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
        return;
      }
      final String s = Json.encodePrettily(md);
      fut.handle(new Success<>(s));
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void createDeployment(ProxyContext pc, String body,
  Handler<ExtendedAsyncResult<String>> fut) {
  try {
    final DeploymentDescriptor pmd = Json.decodeValue(body,
      DeploymentDescriptor.class);
    deploymentManager.deploy(pmd, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
        return;
      }
      final String s = Json.encodePrettily(res.result());
      location(pc, res.result().getInstId(), null, s, fut);
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void discoveryDeploy(ProxyContext pc, String body,
  Handler<ExtendedAsyncResult<String>> fut) {
  try {
    final DeploymentDescriptor pmd = Json.decodeValue(body,
      DeploymentDescriptor.class);
    discoveryManager.addAndDeploy(pmd, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
        return;
      }
      DeploymentDescriptor md = res.result();
      final String s = Json.encodePrettily(md);
      final String baseuri = pc.getCtx().request().uri()
        + "/" + md.getSrvcId();
      location(pc, md.getInstId(), baseuri, s, fut);
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void createEnv(ProxyContext pc, String body,
  Handler<ExtendedAsyncResult<String>> fut) {

  try {
    final EnvEntry pmd = Json.decodeValue(body, EnvEntry.class);
    envManager.add(pmd, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
        return;
      }
      final String js = Json.encodePrettily(pmd);
      location(pc, pmd.getName(), null, js, fut);
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:InternalModule.java   
private void pullModules(String body,
  Handler<ExtendedAsyncResult<String>> fut) {

  try {
    final PullDescriptor pmd = Json.decodeValue(body, PullDescriptor.class);
    pullManager.pull(pmd, res -> {
      if (res.failed()) {
        fut.handle(new Failure<>(res.getType(), res.cause()));
        return;
      }
      fut.handle(new Success<>(Json.encodePrettily(res.result())));
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(USER, ex));
  }
}
项目:okapi    文件:RoutingEntry.java   
public void setType(String type) {
  if ("request-response".equals(type)) {
    proxyType = ProxyType.REQUEST_RESPONSE;
  } else if ("request-only".equals(type)) {
    proxyType = ProxyType.REQUEST_ONLY;
  } else if ("headers".equals(type)) {
    proxyType = ProxyType.HEADERS;
  } else if ("redirect".equals(type)) {
    proxyType = ProxyType.REDIRECT;
  } else if ("system".equals(type)) {
    proxyType = ProxyType.REQUEST_RESPONSE;
  } else if ("internal".equals(type)) {
    proxyType = ProxyType.INTERNAL;
  } else if ("request-response-1.0".equals(type)) {
    proxyType = ProxyType.REQUEST_RESPONSE_1_0;
  } else {
    throw new DecodeException("Invalid entry type: " + type);
  }
  this.type = type;
}
项目:okapi    文件:RoutingEntry.java   
public void setPathPattern(String pathPattern) {
  this.pathPattern = pathPattern;
  StringBuilder b = new StringBuilder();
  b.append("^");
  int i = 0;
  while (i < pathPattern.length()) {
    char c = pathPattern.charAt(i);
    if (c == '{') {
      b.append("[^/?#]+");
      i = skipNamedPattern(pathPattern, i, c);
    } else if (c == '*') {
      b.append(".*");
    } else if (INVALID_PATH_CHARS.indexOf(c) != -1) {
      throw new DecodeException("Invalid character " + c + " for pathPattern");
    } else {
      b.append(c);
    }
    i++;
  }
  b.append("$");
  this.pathRegex = b.toString();
}
项目:okapi    文件:BeanTest.java   
@Test
public void testDeploymentDescriptor2() {
  int fail = 0;
  final String docSampleDeployment = "{" + LS
    + "  \"srvcId\" : \"sample-module-1\"," + LS
    + "  \"descriptor\" : {" + LS
    + "    \"exec\" : "
    + "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"," + LS
    + "    \"env\" : [ {" + LS
    + "      \"name\" : \"helloGreeting\"" + LS
    + "    } ]" + LS
    + "  }" + LS
    + "}";

  try {
    final DeploymentDescriptor md = Json.decodeValue(docSampleDeployment,
      DeploymentDescriptor.class);
    String pretty = Json.encodePrettily(md);
    assertEquals(docSampleDeployment, pretty);
  } catch (DecodeException ex) {
    ex.printStackTrace();
    fail = 400;
  }
  assertEquals(0, fail);
}
项目:okapi    文件:BeanTest.java   
@Test
public void testDeploymentDescriptor3() {
  int fail = 0;
  final String docSampleDeployment = "{" + LS
    + "  \"srvcId\" : \"sample-module-1\"," + LS
    + "  \"descriptor\" : {" + LS
    + "    \"exec\" : "
    + "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
    + "  }" + LS
    + "}";

  try {
    final DeploymentDescriptor md = Json.decodeValue(docSampleDeployment,
      DeploymentDescriptor.class);
    String pretty = Json.encodePrettily(md);
    assertEquals(docSampleDeployment, pretty);
  } catch (DecodeException ex) {
    ex.printStackTrace();
    fail = 400;
  }
  assertEquals(0, fail);
}
项目:okapi    文件:BeanTest.java   
@Test
public void testDeploymentDescriptor4() {
  int fail = 0;
  final String docSampleDeployment = "{" + LS
    + "  \"srvcId\" : \"sample-module-1\"," + LS
    + "  \"descriptor\" : {" + LS
    + "    \"dockerImage\" : \"my-image\"," + LS
    + "    \"dockerArgs\" : {" + LS
    + "      \"Hostname\" : \"localhost\"," + LS
    + "      \"User\" : \"nobody\"" + LS
    + "    }" + LS
    + "  }" + LS
    + "}";

  try {
    final DeploymentDescriptor md = Json.decodeValue(docSampleDeployment,
      DeploymentDescriptor.class);
    String pretty = Json.encodePrettily(md);
    assertEquals(docSampleDeployment, pretty);
  } catch (DecodeException ex) {
    ex.printStackTrace();
    fail = 400;
  }
  assertEquals(0, fail);
}
项目:vertx-configuration-service    文件:DirectoryConfigurationStoreTest.java   
@Test
public void testWithAFileSetMatching2FilesOneNotBeingAJsonFile(TestContext context) {
  Async async = context.async();
  retriever = ConfigurationRetriever.create(vertx, new ConfigurationRetrieverOptions()
      .addStore(new ConfigurationStoreOptions()
          .setType("directory")
          .setConfig(new JsonObject().put("path", "src/test/resources")
              .put("filesets", new JsonArray()
                  .add(new JsonObject().put("pattern", "dir/a?*.json"))
              ))));
  retriever.getConfiguration(ar -> {
    assertThat(ar.failed());
    assertThat(ar.cause()).isInstanceOf(DecodeException.class);
    async.complete();
  });
}
项目:vertx-configuration-service    文件:GitConfigurationStoreTest.java   
@Test
public void testWithAFileSetMatching2FilesOneNotBeingAJsonFile(TestContext tc) throws GitAPIException, IOException {
  Async async = tc.async();
  add(git, root, new File("src/test/resources/files/a-bad.json"), "dir");
  add(git, root, new File("src/test/resources/files/a.json"), "dir");
  push(git);

  retriever = ConfigurationRetriever.create(vertx, new ConfigurationRetrieverOptions().addStore(new
      ConfigurationStoreOptions().setType("git").setConfig(new JsonObject()
      .put("url", bareRoot.getAbsolutePath())
      .put("path", "target/junk/work")
      .put("filesets", new JsonArray()
          .add(new JsonObject().put("pattern", "dir/a?*.*son"))
      ))));

  retriever.getConfiguration(ar -> {
    assertThat(ar.failed());
    assertThat(ar.cause()).isInstanceOf(DecodeException.class);
    async.complete();
  });

}
项目:vertx-configuration-service    文件:YamlProcessorTest.java   
@Test
public void testWithTextFile(TestContext tc) {
  Async async = tc.async();
  retriever = ConfigurationRetriever.create(vertx,
      new ConfigurationRetrieverOptions().addStore(
          new ConfigurationStoreOptions()
              .setType("file")
              .setFormat("yaml")
              .setConfig(new JsonObject().put("path", "src/test/resources/some-text.txt"))));

  retriever.getConfiguration(ar -> {
    assertThat(ar.failed()).isTrue();
    assertThat(ar.cause()).isNotNull().isInstanceOf(DecodeException.class);
    async.complete();
  });
}
项目:hono    文件:FileBasedCredentialsService.java   
private Future<Void> addAll(final Buffer credentials) {
    Future<Void> result = Future.future();
    try {
        int credentialsCount = 0;
        JsonArray allObjects = credentials.toJsonArray();
        log.debug("trying to load credentials for {} tenants", allObjects.size());
        for (Object obj : allObjects) {
            if (JsonObject.class.isInstance(obj)) {
                credentialsCount += addCredentialsForTenant((JsonObject) obj);
            }
        }
        log.info("successfully loaded {} credentials from file [{}]", credentialsCount, getConfig().getCredentialsFilename());
        result.complete();
    } catch (DecodeException e) {
        log.warn("cannot read malformed JSON from credentials file [{}]", getConfig().getCredentialsFilename());
        result.fail(e);
    }
    return result;
}
项目:hono    文件:FileBasedRegistrationService.java   
private Future<Void> addAll(final Buffer deviceIdentities) {

        Future<Void> result = Future.future();
        try {
            int deviceCount = 0;
            JsonArray allObjects = deviceIdentities.toJsonArray();
            for (Object obj : allObjects) {
                if (JsonObject.class.isInstance(obj)) {
                    deviceCount += addDevicesForTenant((JsonObject) obj);
                }
            }
            log.info("successfully loaded {} device identities from file [{}]", deviceCount, getConfig().getFilename());
            result.complete();
        } catch (DecodeException e) {
            log.warn("cannot read malformed JSON from device identity file [{}]", getConfig().getFilename());
            result.fail(e);
        }
        return result;
    }
项目:hono    文件:RegistrationRestServerTest.java   
private Future<JsonObject> getRegistrationInfo(final String deviceId) {

        final Future<JsonObject> result = Future.future();
        final String requestUri = String.format("/%s/%s/%s", RegistrationConstants.REGISTRATION_ENDPOINT, TENANT, deviceId);
        vertx.createHttpClient()
            .get(getPort(), HOST, requestUri)
            .handler(response -> {
                if (response.statusCode() != HttpURLConnection.HTTP_OK) {
                    result.fail(new ClientErrorException(response.statusCode()));
                } else {
                    response.bodyHandler(totalBuffer -> {
                        try {
                            result.complete(totalBuffer.toJsonObject());
                        } catch (DecodeException ex) {
                            result.fail(ex);
                        }
                    });
                }
            }).exceptionHandler(result::fail)
            .end();

        return result;
    }
项目:hono    文件:CredentialsHttpEndpoint.java   
/**
 * 
 * @param ctx The routing context to retrieve the JSON request body from.
 */
private void extractRequiredJsonPayload(final RoutingContext ctx) {

    final MIMEHeader contentType = ctx.parsedHeaders().contentType();
    if (contentType == null) {
        ctx.response().setStatusMessage("Missing Content-Type header");
        ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
    } else if (!HttpUtils.CONTENT_TYPE_JSON.equalsIgnoreCase(contentType.value())) {
        ctx.response().setStatusMessage("Unsupported Content-Type");
        ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
    } else {
        try {
            if (ctx.getBody() != null) {
                ctx.put(KEY_REQUEST_BODY, ctx.getBodyAsJson());
                ctx.next();
            } else {
                ctx.response().setStatusMessage("Empty body");
                ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (DecodeException e) {
            ctx.response().setStatusMessage("Invalid JSON");
            ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
        }
    }
}
项目:vertx-config    文件:GitConfigStoreTest.java   
@Test
public void testWithAFileSetMatching2FilesOneNotBeingAJsonFile(TestContext tc) throws GitAPIException, IOException {
  Async async = tc.async();
  add(git, root, new File("src/test/resources/files/a-bad.json"), "dir");
  add(git, root, new File("src/test/resources/files/a.json"), "dir");
  push(git);

  retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(new
      ConfigStoreOptions().setType("git").setConfig(new JsonObject()
      .put("url", bareRoot.getAbsolutePath())
      .put("path", "target/junk/work")
      .put("filesets", new JsonArray()
          .add(new JsonObject().put("pattern", "dir/a?*.*son"))
      ))));

  retriever.getConfig(ar -> {
    assertThat(ar.failed());
    assertThat(ar.cause()).isInstanceOf(DecodeException.class);
    async.complete();
  });

}
项目:vertx-config    文件:YamlProcessorTest.java   
@Test
public void testWithTextFile(TestContext tc) {
  Async async = tc.async();
  retriever = ConfigRetriever.create(vertx,
      new ConfigRetrieverOptions().addStore(
          new ConfigStoreOptions()
              .setType("file")
              .setFormat("yaml")
              .setConfig(new JsonObject().put("path", "src/test/resources/some-text.txt"))));

  retriever.getConfig(ar -> {
    assertThat(ar.failed()).isTrue();
    assertThat(ar.cause()).isNotNull().isInstanceOf(DecodeException.class);
    async.complete();
  });
}
项目:vertx-config    文件:DirectoryConfigStoreTest.java   
@Test
public void testWithAFileSetMatching2FilesOneNotBeingAJsonFile(TestContext context) {
  Async async = context.async();
  retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions()
      .addStore(new ConfigStoreOptions()
          .setType("directory")
          .setConfig(new JsonObject().put("path", "src/test/resources")
              .put("filesets", new JsonArray()
                  .add(new JsonObject().put("pattern", "dir/a?*.json"))
              ))));
  retriever.getConfig(ar -> {
    assertThat(ar.failed());
    assertThat(ar.cause()).isInstanceOf(DecodeException.class);
    async.complete();
  });
}
项目:raml-module-builder    文件:HTTPJsonResponseHandler.java   
private void handleSuccess(Buffer bh, Response r) {
  if(r.code == 204 || bh.length() == 0) {
    r.body = null;
    cf.complete(r);
  } else  {
    try {
      r.body = bh.toJsonObject();
      cf.complete(r);
    } catch (DecodeException decodeException) {
      if("text/plain".equals(r.getHeaders().get("Accept"))){
        //currently only support json responses
        //best effort to wrap text
        try {
          r.body = new JsonObject("{\"wrapped_text\": "+bh.getByteBuf().toString(Charset.defaultCharset())+"}");
          cf.complete(r);
        } catch (Exception e) {
          cf.completeExceptionally(decodeException);
        }
      }
      else{
        cf.completeExceptionally(decodeException);
      }
    }
  }
}
项目:vertx3-deployer    文件:ConfigLoader.java   
/**
 * Load the global application configuration. The global application state
 * is merged with the external configuration. The external configuration
 * takes precedence.
 *
 * @return The configuration for the deployer
 */
public static JsonObject loadConfiguration() {
    JsonObject result = null;

    // read file by convention
    LOG.info("Looking for the deployer configuration");
    URL appConf = loadURL();

    if (appConf != null) {
        LOG.info("Deployer configuration found");
        try {
            URI uri = appConf.toURI();
            initFileSystemIfNeeded(uri);

            byte[] readAllBytes = Files.readAllBytes(Paths.get(appConf.toURI()));
            result = new JsonObject(new String(readAllBytes, "UTF-8"));
            LOG.info("Deployer configuration loaded");

        } catch (IOException | URISyntaxException | DecodeException e) {
            LOG.log(Level.SEVERE, "Global application configuration invalid", e);
        }
    } else {
        LOG.info("Global application configuration not found.");
    }
    return result;
}
项目:vertx-web    文件:SockJSSession.java   
private String[] parseMessageString(String msgs) {
  try {
    String[] parts;
    if (msgs.startsWith("[")) {
      //JSON array
      parts = (String[])JsonCodec.decodeValue(msgs, String[].class);
    } else {
      //JSON string
      String str = (String)JsonCodec.decodeValue(msgs, String.class);
      parts = new String[] { str };
    }
    return parts;
  } catch (DecodeException e) {
    return null;
  }
}
项目:apiman    文件:URILoadingRegistry.java   
private void processData() {
    if (rawData.length() == 0) {
        log.warn("File loaded into registry was empty. No entities created.");
        dataProcessed = true;
        allRegistries.stream().forEach(this::checkSuccess);
        return;
    }
    try {
        JsonObject json = new JsonObject(rawData.toString("UTF-8").trim());
        log.trace("Processing JSON: {0}", json);
        clients = requireJsonArray("clients", json, Client.class);
        apis = requireJsonArray("apis", json, Api.class);
        dataProcessed = true;
        checkQueue();
    } catch (DecodeException e) {
        failAll(e);
    }
}
项目:apiman    文件:PolicyConfigLoader.java   
private void processData() {
    if (rawData.length() == 0) {
        log.warn("Remote file at {0} was empty.", uri);
        return;
    }
    try {
        JsonObject json = new JsonObject(rawData.toString("UTF-8").trim());
        log.trace("Processing JSON: {0}", json);
        if (clientResultHandler != null)
            clients = requireJsonArray("clients", json, Client.class);
        if (apiResultHandler != null)
            apis = requireJsonArray("apis", json, Api.class);
    } catch (DecodeException e) {
        exceptionHandler.handle(e);
    }
}
项目:spring-vertx-tcp    文件:FrameParser.java   
@Override
public void handle(Buffer buffer) {
  append(buffer);

  int offset;

  while (true) {
    // set a rewind point. if a failure occurs,
    // wait for the next handle()/append() and try again
    offset = _offset;

    // how many bytes are in the buffer
    int remainingBytes = bytesRemaining();

    // at least 4 bytes
    if (remainingBytes < 4) {
      break;
    }

    // what is the length of the message
    int length = _buffer.getInt(_offset);
    _offset += 4;

    if (remainingBytes - 4 >= length) {
      // we have a complete message
      try {
        client.handle(Future.succeededFuture(_buffer.getBytes(_offset, _offset + length)));
      } catch (DecodeException e) {
        // bad json
        client.handle(Future.failedFuture(e));
      }
      _offset += length;
    } else {
      // not enough data: rewind, and wait
      // for the next packet to appear
      _offset = offset;
      break;
    }
  }
}