io.vertx.core.json.DecodeException Java Examples

The following examples show how to use io.vertx.core.json.DecodeException. 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: RawProcessorTest.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithBrokenJson(TestContext tc) {
  Async async = tc.async();
  retriever = ConfigRetriever.create(vertx,
      new ConfigRetrieverOptions()
          .addStore(
              new ConfigStoreOptions()
                  .setType("file")
                  .setFormat("raw")
                  .setConfig(
                      new JsonObject()
                          .put("path", "src/test/resources/raw/username")
                          .put("raw.type", "json-object")
                          .put("raw.key", "some-json")))
  );

  retriever.getConfig(ar -> {
    assertThat(ar.failed());
    assertThat(ar.cause())
      .isInstanceOf(DecodeException.class)
      .hasRootCauseInstanceOf(JsonParseException.class);
    async.complete();
  });
}
 
Example #2
Source File: DynamicClientRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
protected Single<DynamicClientRegistrationRequest> extractRequest(RoutingContext context) {
    try{
        if(context.getBodyAsJson()==null) {
            throw new InvalidClientMetadataException("no content");
        }
        return Single.just(context.getBodyAsJson().mapTo(DynamicClientRegistrationRequest.class));
    }catch (Exception ex) {
        if(ex instanceof DecodeException) {
            return Single.error(new InvalidClientMetadataException(ex.getMessage()));
        }
        //Jackson mapper Replace Customs exception by an IllegalArgumentException
        if(ex instanceof IllegalArgumentException && ex.getMessage().startsWith(JWKSetDeserializer.PARSE_ERROR_MESSAGE)) {
            String sanitizedMessage = ex.getMessage().substring(0,ex.getMessage().indexOf(" (through reference chain:"));
            return Single.error(new InvalidClientMetadataException(sanitizedMessage));
        }
        return Single.error(ex);
    }
}
 
Example #3
Source File: HTTPJsonResponseHandler.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
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);
      }
    }
  }
}
 
Example #4
Source File: InternalModule.java    From okapi with Apache License 2.0 6 votes vote down vote up
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<>(ErrorType.USER, messages.getMessage("11601", 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<>(ErrorType.USER, ex));
  }
}
 
Example #5
Source File: InternalModule.java    From okapi with Apache License 2.0 6 votes vote down vote up
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<>(ErrorType.USER, messages.getMessage("11602", td.getId(), 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<>(ErrorType.USER, ex));
  }
}
 
Example #6
Source File: InternalModule.java    From okapi with Apache License 2.0 6 votes vote down vote up
private void enableModuleForTenant(ProxyContext pc, String id, String body,
                                   Handler<ExtendedAsyncResult<String>> fut) {
  try {
    TenantInstallOptions options = ModuleUtil.createTenantOptions(pc.getCtx().request());

    final TenantModuleDescriptor td = Json.decodeValue(body,
        TenantModuleDescriptor.class);
    tenantManager.enableAndDisableModule(id, options, null, td, 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<>(ErrorType.USER, ex));
  }
}
 
Example #7
Source File: InternalModule.java    From okapi with Apache License 2.0 6 votes vote down vote up
private void upgradeModuleForTenant(ProxyContext pc, String id, String mod,
                                    String body, Handler<ExtendedAsyncResult<String>> fut) {
  TenantInstallOptions options = ModuleUtil.createTenantOptions(pc.getCtx().request());
  try {
    final String module_from = mod;
    final TenantModuleDescriptor td = Json.decodeValue(body,
        TenantModuleDescriptor.class);
    tenantManager.enableAndDisableModule(id, options, module_from, td, 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<>(ErrorType.USER, ex));
  }
}
 
Example #8
Source File: InternalModule.java    From okapi with Apache License 2.0 6 votes vote down vote up
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<>(ErrorType.USER, ex));
  }
}
 
Example #9
Source File: InternalModule.java    From okapi with Apache License 2.0 6 votes vote down vote up
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();
      String[] ids = new String [2];
      ids[0] = md.getSrvcId();
      ids[1] = md.getInstId();
      location(pc, ids, baseuri, s, fut);
    });
  } catch (DecodeException ex) {
    fut.handle(new Failure<>(ErrorType.USER, ex));
  }
}
 
Example #10
Source File: InternalModule.java    From okapi with Apache License 2.0 6 votes vote down vote up
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<>(ErrorType.USER, ex));
  }
}
 
Example #11
Source File: InternalModule.java    From okapi with Apache License 2.0 6 votes vote down vote up
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<>(ErrorType.USER, ex));
  }
}
 
Example #12
Source File: RoutingEntry.java    From okapi with Apache License 2.0 6 votes vote down vote up
/**
 * Set routing entry type.
 * @param type routing entry type
 */
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 if ("request-log".equals(type)) {
    proxyType = ProxyType.REQUEST_LOG;
  } else {
    throw new DecodeException("Invalid entry type: " + type);
  }
  this.type = type;
}
 
Example #13
Source File: RoutingEntry.java    From okapi with Apache License 2.0 6 votes vote down vote up
/**
 * Set routing entry phrase.
 * @param phase such as "auth", "pre", ..
 */
public void setPhase(String phase) {
  if (phase != null) {
    switch (phase) {
      case "auth":
        phaseLevel = "10";
        break;
      case "pre":
        phaseLevel = "40";
        break;
      case "post":
        phaseLevel = "60";
        break;
      default:
        throw new DecodeException("Invalid phase " + phase);
    }
  }
  this.phase = phase;
}
 
Example #14
Source File: BeanTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source File: BeanTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: BeanTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #17
Source File: URILoadingRegistry.java    From apiman with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #18
Source File: DelegatingDeviceManagementHttpEndpoint.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets the device from the request body.
 *
 * @param ctx The context to retrieve the request body from.
 * @return A future indicating the outcome of the operation.
 *         The future will be succeeded if the request body is either empty or contains a JSON
 *         object that complies with the Device Registry Management API's Device object definition.
 *         Otherwise, the future will be failed with a {@link org.eclipse.hono.client.ClientErrorException}
 *         containing a corresponding status code.
 * @throws NullPointerException If the context is {@code null}.
 */
private static Future<Device> fromPayload(final RoutingContext ctx) {

    Objects.requireNonNull(ctx);

    final Promise<Device> result = Promise.promise();
    Optional.ofNullable(ctx.get(KEY_REQUEST_BODY))
        .map(JsonObject.class::cast)
        .ifPresentOrElse(
                // validate payload
                json -> {
                    try {
                        result.complete(json.mapTo(Device.class));
                    } catch (final DecodeException | IllegalArgumentException e) {
                        result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                                "request does not contain a valid Device object", e));
                    }
                },
                // payload was empty
                () -> result.complete(new Device()));
    return result.future();
}
 
Example #19
Source File: DelegatingCredentialsManagementHttpEndpoint.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Decodes a list of secrets from a request body.
 *
 * @param ctx The request to retrieve the updated credentials from.
 * @return The list of decoded secrets.
 * @throws NullPointerException if context is {@code null}.
 * @throws IllegalArgumentException If a credentials object is invalid.
 */
private static Future<List<CommonCredential>> fromPayload(final RoutingContext ctx) {

    Objects.requireNonNull(ctx);
    final Promise<List<CommonCredential>> result = Promise.promise();
    Optional.ofNullable(ctx.get(KEY_REQUEST_BODY))
        .map(JsonArray.class::cast)
        .ifPresentOrElse(
                // deserialize & validate payload
                array -> {
                    try {
                        result.complete(decodeCredentials(array));
                    } catch (final IllegalArgumentException | DecodeException e) {
                        result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                                "request body does not contain valid Credentials objects"));
                    }
                },
                () -> result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                        "request body does not contain JSON array")));
    return result.future();

}
 
Example #20
Source File: FileBasedRegistrationService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Void> addAll(final Buffer deviceIdentities) {

        final Promise<Void> result = Promise.promise();
        try {
            int deviceCount = 0;
            final JsonArray allObjects = deviceIdentities.toJsonArray();
            for (final Object obj : allObjects) {
                if (obj instanceof JsonObject) {
                    deviceCount += addDevicesForTenant((JsonObject) obj);
                }
            }
            LOG.info("successfully loaded {} device identities from file [{}]", deviceCount, getConfig().getFilename());
            result.complete();
        } catch (final DecodeException e) {
            LOG.warn("cannot read malformed JSON from device identity file [{}]", getConfig().getFilename());
            result.fail(e);
        }
        return result.future();
    }
 
Example #21
Source File: RegistrationClientImpl.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected final RegistrationResult getResult(
        final int status,
        final String contentType,
        final Buffer payload,
        final CacheDirective cacheDirective,
        final ApplicationProperties applicationProperties) {

    if (isSuccessResponse(status, contentType, payload)) {
        try {
            return RegistrationResult.from(status, new JsonObject(payload), cacheDirective, applicationProperties);
        } catch (final DecodeException e) {
            LOG.warn("received malformed payload from Device Registration service", e);
            return RegistrationResult.from(HttpURLConnection.HTTP_INTERNAL_ERROR, null, null, applicationProperties);
        }
    } else {
        return RegistrationResult.from(status, null, null, applicationProperties);
    }
}
 
Example #22
Source File: DeviceConnectionClientImpl.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected final DeviceConnectionResult getResult(
        final int status,
        final String contentType,
        final Buffer payload,
        final CacheDirective cacheDirective,
        final ApplicationProperties applicationProperties) {

    if (payload == null) {
        return DeviceConnectionResult.from(status, null, null, applicationProperties);
    } else {
        try {
            // ignoring given cacheDirective param here - device connection results shall not be cached
            return DeviceConnectionResult.from(status, new JsonObject(payload), CacheDirective.noCacheDirective(), applicationProperties);
        } catch (final DecodeException e) {
            LOG.warn("received malformed payload from Device Connection service", e);
            return DeviceConnectionResult.from(HttpURLConnection.HTTP_INTERNAL_ERROR, null, null, applicationProperties);
        }
    }
}
 
Example #23
Source File: JmsBasedTenantClient.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected TenantResult<TenantObject> getResult(final int status, final Buffer payload, final CacheDirective cacheDirective) {

    if (payload == null) {
        return TenantResult.from(status);
    } else {
        try {
            final JsonObject json = payload.toJsonObject();
            final TenantObject tenant = json.mapTo(TenantObject.class);
            return TenantResult.from(status, tenant, cacheDirective);
        } catch (DecodeException e) {
            LOGGER.warn("Tenant service returned malformed payload", e);
            throw new ServiceInvocationException(
                    HttpURLConnection.HTTP_INTERNAL_ERROR,
                    "Tenant service returned malformed payload");
        }
    }
}
 
Example #24
Source File: JmsBasedRegistrationClient.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected RegistrationResult getResult(final int status, final Buffer payload, final CacheDirective cacheDirective) {

    if (payload == null) {
        return RegistrationResult.from(status);
    } else {
        try {
            final JsonObject json = payload.toJsonObject();
            return RegistrationResult.from(status, json, cacheDirective);
        } catch (DecodeException e) {
            LOGGER.warn("Device Registration service returned malformed payload", e);
            throw new ServiceInvocationException(
                    HttpURLConnection.HTTP_INTERNAL_ERROR,
                    "Device Registration service returned malformed payload");
        }
    }
}
 
Example #25
Source File: JmsBasedCredentialsClient.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected CredentialsResult<CredentialsObject> getResult(final int status, final Buffer payload, final CacheDirective cacheDirective) {

    if (payload == null) {
        return CredentialsResult.from(status);
    } else {
        try {
            final JsonObject json = payload.toJsonObject();
            final CredentialsObject credentials = json.mapTo(CredentialsObject.class);
            return CredentialsResult.from(status, credentials, cacheDirective);
        } catch (DecodeException e) {
            LOGGER.warn("Credentials service returned malformed payload", e);
            throw new ServiceInvocationException(
                    HttpURLConnection.HTTP_INTERNAL_ERROR,
                    "Credentials service returned malformed payload");
        }
    }
}
 
Example #26
Source File: DirectoryConfigStoreTest.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
@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();
  });
}
 
Example #27
Source File: CBOR.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
private static Object parseAny(JsonParser parser) throws IOException, DecodeException {
  switch (parser.getCurrentTokenId()) {
    case JsonTokenId.ID_START_OBJECT:
      return parseObject(parser);
    case JsonTokenId.ID_START_ARRAY:
      return parseArray(parser);
    case JsonTokenId.ID_EMBEDDED_OBJECT:
      return B64ENC.encodeToString(parser.getBinaryValue(Base64Variants.MODIFIED_FOR_URL));
    case JsonTokenId.ID_STRING:
      return parser.getText();
    case JsonTokenId.ID_NUMBER_FLOAT:
    case JsonTokenId.ID_NUMBER_INT:
      return parser.getNumberValue();
    case JsonTokenId.ID_TRUE:
      return Boolean.TRUE;
    case JsonTokenId.ID_FALSE:
      return Boolean.FALSE;
    case JsonTokenId.ID_NULL:
      return null;
    default:
      throw new DecodeException("Unexpected token"/*, parser.getCurrentLocation()*/);
  }
}
 
Example #28
Source File: LoraUtils.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source File: JsonRpcHttpService.java    From besu with Apache License 2.0 5 votes vote down vote up
private void handleJsonRPCRequest(final RoutingContext routingContext) {
  // first check token if authentication is required
  final String token = getAuthToken(routingContext);
  if (authenticationService.isPresent() && token == null) {
    // no auth token when auth required
    handleJsonRpcUnauthorizedError(routingContext, null, JsonRpcError.UNAUTHORIZED);
  } else {
    // Parse json
    try {
      final String json = routingContext.getBodyAsString().trim();
      if (!json.isEmpty() && json.charAt(0) == '{') {
        final JsonObject requestBodyJsonObject =
            ContextKey.REQUEST_BODY_AS_JSON_OBJECT.extractFrom(
                routingContext, () -> new JsonObject(json));
        AuthenticationUtils.getUser(
            authenticationService,
            token,
            user -> handleJsonSingleRequest(routingContext, requestBodyJsonObject, user));
      } else {
        final JsonArray array = new JsonArray(json);
        if (array.size() < 1) {
          handleJsonRpcError(routingContext, null, JsonRpcError.INVALID_REQUEST);
          return;
        }
        AuthenticationUtils.getUser(
            authenticationService,
            token,
            user -> handleJsonBatchRequest(routingContext, array, user));
      }
    } catch (final DecodeException ex) {
      handleJsonRpcError(routingContext, null, JsonRpcError.PARSE_ERROR);
    }
  }
}
 
Example #30
Source File: EeaSendTransactionJsonParametersTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Test
public void transactionWithInvalidPrivateForThrowsIllegalArgumentException() {
  final JsonObject parameters = validEeaTransactionParameters();
  parameters.put("privateFor", singletonList("invalidThirtyTwoByteData="));

  final JsonRpcRequest request = wrapParametersInRequest(parameters);

  assertThatExceptionOfType(DecodeException.class)
      .isThrownBy(
          () ->
              factory.fromRpcRequestToJsonParam(EeaSendTransactionJsonParameters.class, request));
}