Search in sources :

Example 26 with DecodeException

use of io.vertx.core.json.DecodeException in project hono by eclipse.

the class RequestResponseEndpoint method handleMessage.

/**
 * Handles a request message received from a client.
 * <p>
 * The message gets rejected if
 * <ul>
 * <li>the message does not pass {@linkplain #passesFormalVerification(ResourceIdentifier, Message) formal verification}
 * or</li>
 * <li>the client is not {@linkplain #isAuthorized(HonoUser, ResourceIdentifier, Message) authorized to execute the operation}
 * indicated by the message's <em>subject</em> or</li>
 * <li>its payload cannot be parsed</li>
 * </ul>
 *
 * @param con The connection with the client.
 * @param receiver The link over which the message has been received.
 * @param targetAddress The address the message is sent to.
 * @param delivery The message's delivery status.
 * @param message The message.
 */
protected final void handleMessage(final ProtonConnection con, final ProtonReceiver receiver, final ResourceIdentifier targetAddress, ProtonDelivery delivery, Message message) {
    final Future<Void> formalCheck = Future.future();
    if (passesFormalVerification(targetAddress, message)) {
        formalCheck.complete();
    } else {
        formalCheck.fail(new AmqpErrorException(AmqpError.DECODE_ERROR, "malformed payload"));
    }
    final HonoUser clientPrincipal = Constants.getClientPrincipal(con);
    formalCheck.compose(ok -> isAuthorized(clientPrincipal, targetAddress, message)).compose(authorized -> {
        logger.debug("client [{}] is {}authorized to {}:{}", clientPrincipal.getName(), authorized ? "" : "not ", targetAddress, message.getSubject());
        if (authorized) {
            try {
                processRequest(message, targetAddress, clientPrincipal);
                ProtonHelper.accepted(delivery, true);
                return Future.succeededFuture();
            } catch (DecodeException e) {
                return Future.failedFuture(new AmqpErrorException(AmqpError.DECODE_ERROR, "malformed payload"));
            }
        } else {
            return Future.failedFuture(new AmqpErrorException(AmqpError.UNAUTHORIZED_ACCESS, "unauthorized"));
        }
    }).otherwise(t -> {
        if (t instanceof AmqpErrorException) {
            AmqpErrorException cause = (AmqpErrorException) t;
            MessageHelper.rejected(delivery, cause.asErrorCondition());
        } else {
            logger.debug("error processing request [resource: {}, op: {}]: {}", targetAddress, message.getSubject(), t.getMessage());
            MessageHelper.rejected(delivery, ProtonHelper.condition(AmqpError.INTERNAL_ERROR, "internal error"));
        }
        return null;
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) AmqpErrorException(org.eclipse.hono.util.AmqpErrorException) ProtonDelivery(io.vertx.proton.ProtonDelivery) DecodeException(io.vertx.core.json.DecodeException) Autowired(org.springframework.beans.factory.annotation.Autowired) EventBusMessage(org.eclipse.hono.util.EventBusMessage) HonoUser(org.eclipse.hono.auth.HonoUser) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) Constants(org.eclipse.hono.util.Constants) Message(org.apache.qpid.proton.message.Message) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) Vertx(io.vertx.core.Vertx) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Objects(java.util.Objects) Optional(java.util.Optional) ProtonSender(io.vertx.proton.ProtonSender) ClaimsBasedAuthorizationService(org.eclipse.hono.service.auth.ClaimsBasedAuthorizationService) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) AuthorizationService(org.eclipse.hono.service.auth.AuthorizationService) HonoUser(org.eclipse.hono.auth.HonoUser) AmqpErrorException(org.eclipse.hono.util.AmqpErrorException) DecodeException(io.vertx.core.json.DecodeException)

Example 27 with DecodeException

use of io.vertx.core.json.DecodeException in project hono by eclipse.

the class AbstractHttpEndpoint method extractRequiredJsonPayload.

/**
 * Check the Content-Type of the request to be 'application/json' and extract the payload if this check was
 * successful.
 * <p>
 * The payload is parsed to ensure it is valid JSON and is put to the RoutingContext ctx with the
 * key {@link #KEY_REQUEST_BODY}.
 *
 * @param ctx The routing context to retrieve the JSON request body from.
 */
protected 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 (final DecodeException e) {
            ctx.response().setStatusMessage("Invalid JSON");
            ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
        }
    }
}
Also used : MIMEHeader(io.vertx.ext.web.MIMEHeader) DecodeException(io.vertx.core.json.DecodeException)

Example 28 with DecodeException

use of io.vertx.core.json.DecodeException in project georocket by georocket.

the class GeoRocket method main.

/**
 * Runs the server
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    // register schedulers that run Rx operations on the Vert.x event bus
    RxJavaHooks.setOnComputationScheduler(s -> RxHelper.scheduler(vertx));
    RxJavaHooks.setOnIOScheduler(s -> RxHelper.blockingScheduler(vertx));
    RxJavaHooks.setOnNewThreadScheduler(s -> RxHelper.scheduler(vertx));
    DeploymentOptions options = new DeploymentOptions();
    try {
        JsonObject conf = loadGeoRocketConfiguration();
        options.setConfig(conf);
    } catch (IOException ex) {
        log.fatal("Invalid georocket home", ex);
        System.exit(1);
    } catch (DecodeException ex) {
        log.fatal("Failed to decode the GeoRocket (JSON) configuration", ex);
        System.exit(1);
    }
    boolean logConfig = options.getConfig().getBoolean(ConfigConstants.LOG_CONFIG, false);
    if (logConfig) {
        log.info("Configuration:\n" + options.getConfig().encodePrettily());
    }
    // deploy main verticle
    vertx.deployVerticle(GeoRocket.class.getName(), options, ar -> {
        if (ar.failed()) {
            log.fatal("Could not deploy GeoRocket");
            ar.cause().printStackTrace();
            System.exit(1);
        }
    });
}
Also used : DeploymentOptions(io.vertx.core.DeploymentOptions) JsonObject(io.vertx.core.json.JsonObject) IOException(java.io.IOException) Vertx(io.vertx.core.Vertx) DecodeException(io.vertx.core.json.DecodeException)

Example 29 with DecodeException

use of io.vertx.core.json.DecodeException in project rulesservice by genny-project.

the class RuleTest method processFile.

private static List<Tuple2<String, String>> processFile(final Vertx vertx, String inputFileStr) {
    File file = new File(inputFileStr);
    String fileName = inputFileStr.replaceFirst(".*/(\\w+).*", "$1");
    String fileNameExt = inputFileStr.replaceFirst(".*/\\w+\\.(.*)", "$1");
    List<Tuple2<String, String>> rules = new ArrayList<Tuple2<String, String>>();
    if (!file.isFile()) {
        final List<String> filesList = vertx.fileSystem().readDirBlocking(inputFileStr);
        for (final String dirFileStr : filesList) {
            // use directory name as
            List<Tuple2<String, String>> childRules = processFile(vertx, dirFileStr);
            // rulegroup
            rules.addAll(childRules);
        }
        return rules;
    } else {
        Buffer buf = vertx.fileSystem().readFileBlocking(inputFileStr);
        try {
            if ((!fileName.startsWith("XX")) && (fileNameExt.equalsIgnoreCase("drl"))) {
                // ignore files that start
                // with XX
                final String ruleText = buf.toString();
                Tuple2<String, String> rule = (Tuple.of(fileName + "." + fileNameExt, ruleText));
                System.out.println("Loading in Rule:" + rule._1 + " of " + inputFileStr);
                rules.add(rule);
            } else if ((!fileName.startsWith("XX")) && (fileNameExt.equalsIgnoreCase("bpmn"))) {
                // ignore files
                // that start
                // with XX
                final String bpmnText = buf.toString();
                Tuple2<String, String> bpmn = (Tuple.of(fileName + "." + fileNameExt, bpmnText));
                System.out.println("Loading in BPMN:" + bpmn._1 + " of " + inputFileStr);
                rules.add(bpmn);
            }
            return rules;
        } catch (final DecodeException dE) {
        }
    }
    return null;
}
Also used : Buffer(io.vertx.rxjava.core.buffer.Buffer) Tuple2(io.vavr.Tuple2) ArrayList(java.util.ArrayList) File(java.io.File) DecodeException(io.vertx.core.json.DecodeException)

Example 30 with DecodeException

use of io.vertx.core.json.DecodeException in project rulesservice by genny-project.

the class RulesLoader method processFile.

private static List<Tuple2<String, String>> processFile(String inputFileStr) {
    File file = new File(inputFileStr);
    String fileName = inputFileStr.replaceFirst(".*/(\\w+).*", "$1");
    String fileNameExt = inputFileStr.replaceFirst(".*/\\w+\\.(.*)", "$1");
    List<Tuple2<String, String>> rules = new ArrayList<Tuple2<String, String>>();
    if (!file.isFile()) {
        if (!fileName.startsWith("XX")) {
            final List<String> filesList = Vertx.currentContext().owner().fileSystem().readDirBlocking(inputFileStr);
            for (final String dirFileStr : filesList) {
                // use directory name as
                List<Tuple2<String, String>> childRules = processFile(dirFileStr);
                // rulegroup
                rules.addAll(childRules);
            }
        }
        return rules;
    } else {
        Buffer buf = Vertx.currentContext().owner().fileSystem().readFileBlocking(inputFileStr);
        try {
            if ((!fileName.startsWith("XX")) && (fileNameExt.equalsIgnoreCase("drl"))) {
                // ignore files that start
                // with XX
                final String ruleText = buf.toString();
                Tuple2<String, String> rule = (Tuple.of(fileName + "." + fileNameExt, ruleText));
                System.out.println("Loading in Rule:" + rule._1 + " of " + inputFileStr);
                rules.add(rule);
            } else if ((!fileName.startsWith("XX")) && (fileNameExt.equalsIgnoreCase("bpmn"))) {
                // ignore files
                // that start
                // with XX
                final String bpmnText = buf.toString();
                Tuple2<String, String> bpmn = (Tuple.of(fileName + "." + fileNameExt, bpmnText));
                System.out.println("Loading in BPMN:" + bpmn._1 + " of " + inputFileStr);
                rules.add(bpmn);
            } else if ((!fileName.startsWith("XX")) && (fileNameExt.equalsIgnoreCase("xls"))) {
                // ignore files that
                // start with XX
                final String xlsText = buf.toString();
                Tuple2<String, String> xls = (Tuple.of(fileName + "." + fileNameExt, xlsText));
                System.out.println("Loading in XLS:" + xls._1 + " of " + inputFileStr);
                rules.add(xls);
            }
            return rules;
        } catch (final DecodeException dE) {
        }
    }
    return null;
}
Also used : Buffer(io.vertx.rxjava.core.buffer.Buffer) Tuple2(io.vavr.Tuple2) ArrayList(java.util.ArrayList) File(java.io.File) DecodeException(io.vertx.core.json.DecodeException)

Aggregations

DecodeException (io.vertx.core.json.DecodeException)42 JsonObject (io.vertx.core.json.JsonObject)17 Failure (org.folio.okapi.common.Failure)13 Test (org.junit.Test)8 File (java.io.File)6 DeploymentDescriptor (org.folio.okapi.bean.DeploymentDescriptor)6 TenantModuleDescriptor (org.folio.okapi.bean.TenantModuleDescriptor)6 JsonArray (io.vertx.core.json.JsonArray)4 ArrayList (java.util.ArrayList)4 ModuleDescriptor (org.folio.okapi.bean.ModuleDescriptor)4 Buffer (io.vertx.rxjava.core.buffer.Buffer)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 Tuple2 (io.vavr.Tuple2)2 Vertx (io.vertx.core.Vertx)2 Buffer (io.vertx.core.buffer.Buffer)2 FileNotFoundException (java.io.FileNotFoundException)2 ByteBuffer (java.nio.ByteBuffer)2 Scanner (java.util.Scanner)2 AmqpClient (io.enmasse.iot.transport.AmqpClient)1