io.vertx.core.VertxException Java Examples

The following examples show how to use io.vertx.core.VertxException. 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: EventBusBridgeVisitor.java    From nubes with Apache License 2.0 6 votes vote down vote up
public void visit() {
  sockJSHandler = SockJSHandler.create(config.getVertx(), config.getSockJSOptions());
  try {
    instance = clazz.newInstance();
    injectServices();
  } catch (Exception e) {
    throw new VertxException("Could not instanciate socket controller : " + clazz.getName(), e);
  }
  EventBusBridge annot = clazz.getAnnotation(EventBusBridge.class);
  path = annot.value();
  BridgeOptions bridge = createBridgeOptions(clazz);
  Map<BridgeEventType, Method> handlers = BridgeEventFactory.createFromController(clazz);
  sockJSHandler.bridge(bridge, be -> {
    Method method = handlers.get(be.type());
    if (method != null) {
      tryToInvoke(instance, method, be);
    } else {
      be.complete(true);
    }
  });
  normalizePath();
  router.route(path).handler(sockJSHandler);
}
 
Example #2
Source File: Sync.java    From vertx-vaadin with MIT License 6 votes vote down vote up
public static <T> T await(Consumer<Handler<AsyncResult<T>>> task) {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    try {
        Promise<T> p = Promise.promise();
        Future<T> f = p.future();
        f.setHandler(ar -> {
            countDownLatch.countDown();
            if (ar.failed()) {
                throw new VertxException(ar.cause());
            }
        });
        task.accept(p);
        countDownLatch.await();
        return f.result();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new VertxException(e);
    }
}
 
Example #3
Source File: VertxVaadin.java    From vertx-vaadin with MIT License 6 votes vote down vote up
private VertxVaadin(Vertx vertx, Optional<ExtendedSessionStore> sessionStore, JsonObject config) {
    this.vertx = Objects.requireNonNull(vertx);
    this.config = Objects.requireNonNull(config);
    this.service = createVaadinService();
    try {
        service.init();
    } catch (Exception ex) {
        throw new VertxException("Cannot initialize Vaadin service", ex);
    }

    //SessionStore adaptedSessionStore = SessionStoreAdapter.adapt(service, sessionStore.orElseGet(this::createSessionStore));
    this.sessionStore = withSessionExpirationHandler(
        this.service, sessionStore.orElseGet(this::createSessionStore)
    );
    configureSessionStore();
    this.router = initRouter();
}
 
Example #4
Source File: VertxVaadinService.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Override
public InputStream getThemeResourceAsStream(UI uI, String themeName, String resource) {
    String filename = VaadinServlet.THEME_DIR_PATH + '/' + themeName
        + "/" + resource;

    String normalized = Paths.get(filename).normalize().toString();
    if (!normalized.startsWith("VAADIN/")
        || normalized.contains("/../")) {
        throw new VertxException(String.format(
            "Requested resource [%s] not accessible in the VAADIN directory or access to it is forbidden.",
            filename));
    }
    FileSystem fileSystem = getVertx().fileSystem();
    if (fileSystem.existsBlocking(filename)) {

        return new ByteArrayInputStream(fileSystem.readFileBlocking(filename).getBytes());
    }
    return null;
}
 
Example #5
Source File: Sync.java    From vertx-vaadin with MIT License 6 votes vote down vote up
public static <T> T await(Consumer<Handler<AsyncResult<T>>> task) {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    try {
        Future<T> f = Future.<T>future().setHandler(ar -> {
            countDownLatch.countDown();
            if (ar.failed()) {
                throw new VertxException(ar.cause());
            }
        });
        task.accept(f.completer());
        countDownLatch.await();
        return f.result();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new VertxException(e);
    }

}
 
Example #6
Source File: KeyStoreHelper.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
private static X509Certificate[] loadCerts(Buffer buffer) throws Exception {
    if (buffer == null) {
        throw new RuntimeException("Missing X.509 certificate path");
    }
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    List<X509Certificate> certs = loadPems(buffer, (delimiter, content) -> {
        try {
            switch (delimiter) {
                case "CERTIFICATE":
                    return (Collection<X509Certificate>) certFactory.generateCertificates(new ByteArrayInputStream(content));
                default:
                    return Collections.emptyList();
            }
        } catch (CertificateException e) {
            throw new VertxException(e);
        }
    });
    if (certs.isEmpty()) {
        throw new RuntimeException("Missing -----BEGIN CERTIFICATE----- delimiter");
    }
    return certs.toArray(new X509Certificate[0]);
}
 
Example #7
Source File: SHA512Strategy.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Override
public String computeHash(String password, String salt, int version) {

  String concat =
    (salt == null ? "" : salt) +
      password;

  if (version >= 0) {
    if (nonces == null) {
      // the nonce version is not a number
      throw new VertxException("nonces are not available");
    }
    if (version < nonces.size()) {
      concat += nonces.getString(version);
    }
  }

  byte[] bHash = md.digest(concat.getBytes(StandardCharsets.UTF_8));
  if (version >= 0) {
    return bytesToHex(bHash) + '$' + version;
  } else {
    return bytesToHex(bHash);
  }
}
 
Example #8
Source File: HazelcastClusterManager.java    From vertx-hazelcast with Apache License 2.0 6 votes vote down vote up
@Override
public void getLockWithTimeout(String name, long timeout, Promise<Lock> promise) {
  vertx.executeBlocking(prom -> {
    ISemaphore iSemaphore = hazelcast.getCPSubsystem().getSemaphore(LOCK_SEMAPHORE_PREFIX + name);
    boolean locked = false;
    long remaining = timeout;
    do {
      long start = System.nanoTime();
      try {
        locked = iSemaphore.tryAcquire(remaining, TimeUnit.MILLISECONDS);
      } catch (InterruptedException e) {
        // OK continue
      }
      remaining = remaining - MILLISECONDS.convert(System.nanoTime() - start, NANOSECONDS);
    } while (!locked && remaining > 0);
    if (locked) {
      prom.complete(new HazelcastLock(iSemaphore, lockReleaseExec));
    } else {
      throw new VertxException("Timed out waiting to get lock " + name);
    }
  }, false, promise);
}
 
Example #9
Source File: KeyStoreHelper.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
private static KeyStore loadKeyCert(List<Buffer> keyValue, List<Buffer> certValue) throws Exception {
    if (keyValue.size() < certValue.size()) {
        throw new VertxException("Missing private key");
    } else if (keyValue.size() > certValue.size()) {
        throw new VertxException("Missing X.509 certificate");
    }
    final KeyStore keyStore = createEmptyKeyStore();
    Iterator<Buffer> keyValueIt = keyValue.iterator();
    Iterator<Buffer> certValueIt = certValue.iterator();
    int index = 0;
    while (keyValueIt.hasNext() && certValueIt.hasNext()) {
        Certificate[] chain = loadCerts(certValueIt.next());
        PrivateKey key = loadPrivateKey(keyValueIt.next());
        keyStore.setEntry("dummy-entry-" + index++, new KeyStore.PrivateKeyEntry(key, chain), new KeyStore.PasswordProtection(DUMMY_PASSWORD.toCharArray()));
    }
    return keyStore;
}
 
Example #10
Source File: SocketConnectionBase.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
protected <R> void doSchedule(CommandBase<R> cmd, Handler<AsyncResult<R>> handler) {
  if (handler == null) {
    throw new IllegalArgumentException();
  }
  Context context = Vertx.currentContext();
  if (context != this.context) {
    throw new IllegalStateException();
  }
  cmd.handler = handler;
  if (status == Status.CONNECTED) {
    pending.add(cmd);
    checkPending();
  } else {
    cmd.fail(new VertxException("Connection not open " + status));
  }
}
 
Example #11
Source File: VertxParameterProvider.java    From vertx-junit5 with Apache License 2.0 6 votes vote down vote up
@Override
public ParameterClosingConsumer<Vertx> parameterClosingConsumer() {
  return vertx -> {
    CountDownLatch latch = new CountDownLatch(1);
    AtomicReference<Throwable> errorBox = new AtomicReference<>();
    vertx.close(ar -> {
      if (ar.failed()) {
        errorBox.set(ar.cause());
      }
      latch.countDown();
    });
    if (!latch.await(DEFAULT_TIMEOUT_DURATION, DEFAULT_TIMEOUT_UNIT)) {
      throw new TimeoutException("Closing the Vertx context timed out");
    }
    Throwable throwable = errorBox.get();
    if (throwable != null) {
      if (throwable instanceof Exception) {
        throw (Exception) throwable;
      } else {
        throw new VertxException(throwable);
      }
    }
  };
}
 
Example #12
Source File: SocketConnectionBase.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
protected void handleClose(Throwable t) {
  if (status != Status.CLOSED) {
    status = Status.CLOSED;
    if (t != null) {
      synchronized (this) {
        if (holder != null) {
          holder.handleException(t);
        }
      }
    }
    Throwable cause = t == null ? new VertxException("closed") : t;
    CommandBase<?> cmd;
    while ((cmd = pending.poll()) != null) {
      CommandBase<?> c = cmd;
      context.runOnContext(v -> c.fail(cause));
    }
    if (holder != null) {
      holder.handleClosed();
    }
  }
}
 
Example #13
Source File: VertxParameterProvider.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
@Override
public ParameterClosingConsumer<Vertx> parameterClosingConsumer() {
  return vertx -> {
    try {
      if (!vertx.rxClose().blockingAwait(DEFAULT_TIMEOUT_DURATION, DEFAULT_TIMEOUT_UNIT)) {
        throw new TimeoutException("Closing the Vertx context timed out");
      }
    } catch (Throwable err) {
      if (err instanceof RuntimeException) {
        throw new VertxException(err.getCause());
      } else if (err instanceof Exception) {
        throw err;
      } else {
        throw new VertxException(err);
      }
    }
  };
}
 
Example #14
Source File: VertxParameterProvider.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
@Override
public ParameterClosingConsumer<Vertx> parameterClosingConsumer() {
  return vertx -> {
    try {
      if (!vertx.rxClose().toCompletable().await(DEFAULT_TIMEOUT_DURATION, DEFAULT_TIMEOUT_UNIT)) {
        throw new TimeoutException("Closing the Vertx context timed out");
      }
    } catch (Throwable err) {
      if (err instanceof RuntimeException) {
        throw new VertxException(err.getCause());
      } else if (err instanceof Exception) {
        throw err;
      } else {
        throw new VertxException(err);
      }
    }
  };
}
 
Example #15
Source File: ConsulClientOptions.java    From vertx-consul-client with Apache License 2.0 6 votes vote down vote up
private static Map<String, List<String>> params(URI uri) {
  if (uri.getQuery() == null || uri.getQuery().isEmpty()) {
    return Collections.emptyMap();
  }
  final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
  final String[] pairs = uri.getQuery().split("&");
  for (String pair : pairs) {
    try {
      final int idx = pair.indexOf("=");
      final String key = idx > 0
        ? URLDecoder.decode(pair.substring(0, idx), "UTF-8")
        : pair;
      final String value = idx > 0 && pair.length() > idx + 1
        ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8")
        : null;
      List<String> list = queryPairs.computeIfAbsent(key, k -> new ArrayList<>());
      list.add(value);
    } catch (Exception e) {
      throw new VertxException(e);
    }
  }
  return queryPairs;
}
 
Example #16
Source File: AtomixClusterManager.java    From atomix-vertx with Apache License 2.0 6 votes vote down vote up
@Override
public void getLockWithTimeout(String name, long timeout, Handler<AsyncResult<Lock>> handler) {
  Context context = vertx.getOrCreateContext();
  lockCache.getUnchecked(name).whenComplete((lock, error) -> {
    if (error == null) {
      lock.async().tryLock(Duration.ofMillis(timeout)).whenComplete((lockResult, lockError) -> {
        if (lockError == null) {
          if (lockResult.isPresent()) {
            context.runOnContext(v -> Future.<Lock>succeededFuture(new AtomixLock(vertx, lock)).setHandler(handler));
          } else {
            context.runOnContext(v -> Future.<Lock>failedFuture(new VertxException("Timed out waiting to get lock " + name)).setHandler(handler));
          }
        } else {
          context.runOnContext(v -> Future.<Lock>failedFuture(lockError).setHandler(handler));
        }
      });
    } else {
      context.runOnContext(v -> Future.<Lock>failedFuture(error).setHandler(handler));
    }
  });
}
 
Example #17
Source File: ShellAuth.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
static AuthProvider load(Vertx vertx, JsonObject config) {
  ServiceLoader<ShellAuth> loader = ServiceLoader.load(ShellAuth.class);

  Iterator<ShellAuth> factories = loader.iterator();

  while (factories.hasNext()) {
    try {
      // might fail to start (missing classes for example...
      ShellAuth auth = factories.next();
      if (auth != null) {
        if (auth.provider().equals(config.getString("provider", ""))) {
          return auth.create(vertx, config);
        }
      }
    } catch (RuntimeException e) {
      // continue...
    }
  }
  throw new VertxException("Provider not found [" + config.getString("provider", "") + "] / check your classpath");
}
 
Example #18
Source File: SockJSVisitor.java    From nubes with Apache License 2.0 6 votes vote down vote up
public void visit() {
  sockJSHandler = SockJSHandler.create(config.getVertx(), config.getSockJSOptions());
  try {
    instance = clazz.newInstance();
    injectServices();
  } catch (Exception e) {
    throw new VertxException("Could not instanciate socket controller : " + clazz.getName(), e);
  }
  createHandlers();
  sockJSHandler.socketHandler(ws -> {
    openHandlers.forEach(handler -> tryToInvoke(instance, handler, ws, null));
    ws.handler(buff -> messageHandlers.forEach(messageHandler -> tryToInvoke(instance, messageHandler, ws, buff)));
    ws.endHandler(voidz -> closeHandlers.forEach(closeHandler -> tryToInvoke(instance, closeHandler, ws, null)));
  });
  normalizePath();
  router.route(path).handler(sockJSHandler);
}
 
Example #19
Source File: ControllerVisitor.java    From nubes with Apache License 2.0 6 votes vote down vote up
public List<MVCRoute> visit() throws IllegalAccessException, InstantiationException {
  instance = clazz.newInstance();
  List<MVCRoute> routes = new ArrayList<>();
  try {
    injectServices();
  } catch (IllegalAccessException iae) {
    throw new VertxException(iae);
  }
  extractFilters();
  for (Method method : methods) {
    MethodVisitor<T> visitor = new MethodVisitor<>(this, method);
    routes.addAll(visitor.visit());
  }
  for (MVCRoute route : routes) {
    route.addProcessorsFirst(processors);
    route.addBeforeFilters(beforeFilters);
    route.addAfterFilters(afterFilters);
  }
  return routes;
}
 
Example #20
Source File: AsyncMapImpl.java    From vertx-ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param ttl Time to live in ms.
 */
private <T> Future<T> executeWithTtl(Function<IgniteCache<K, V>, IgniteFuture<T>> cacheOp, long ttl) {
  ContextInternal ctx = vertx.getOrCreateContext();
  Promise<T> promise = ctx.promise();
  IgniteCache<K, V> cache0 = ttl > 0 ?
    cache.withExpiryPolicy(new CreatedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS, ttl))) : cache;

  IgniteFuture<T> future = cacheOp.apply(cache0);
  future.listen(fut -> {
    try {
      promise.complete(unmarshal(future.get()));
    } catch (IgniteException e) {
      promise.fail(new VertxException(e));
    }
  });
  return promise.future();
}
 
Example #21
Source File: UserHolder.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public int readFromBuffer(int pos, Buffer buffer) {
  byte b = buffer.getByte(pos++);
  if (b == (byte)1) {
    int len = buffer.getInt(pos);
    pos += 4;
    byte[] bytes = buffer.getBytes(pos, pos + len);
    pos += len;
    String className = new String(bytes, StandardCharsets.UTF_8);
    try {
      Class<?> clazz = Utils.getClassLoader().loadClass(className);
      if (!ClusterSerializable.class.isAssignableFrom(clazz)) {
        throw new ClassCastException(className + " is not ClusterSerializable");
      }
      ClusterSerializable obj = (ClusterSerializable) clazz.getDeclaredConstructor().newInstance();
      pos = obj.readFromBuffer(pos, buffer);
      synchronized (this) {
        user = (User) obj;
        context = null;
      }
    } catch (Exception e) {
      throw new VertxException(e);
    }
  } else {
    synchronized (this) {
      user = null;
      context = null;
    }
  }
  return pos;
}
 
Example #22
Source File: ServiceRegistry.java    From nubes with Apache License 2.0 5 votes vote down vote up
private void createConsumer(Object service, Consumer consumes, Method method) {
  Class<?>[] parameterTypes = method.getParameterTypes();
  if (parameterTypes.length != 1 || !parameterTypes[0].equals(Message.class)) {
    String msg = "Cannot register consumer on method : " + getFullName(service, method);
    msg += " .Method should only declare one parameter of io.vertx.core.eventbus.Message type.";
    throw new VertxException(msg);
  }
  vertx.eventBus().consumer(consumes.value(), message -> {
    try {
      method.invoke(service, message);
    } catch (Exception e) {
      LOG.error("Exception happened during message handling on method : " + getFullName(service, method), e);
    }
  });
}
 
Example #23
Source File: JacksonPayloadMarshaller.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public String marshallPayload(Object payload) {
  if (payload instanceof JsonObject) {
    return payload.toString();
  } else if (payload instanceof JsonArray) {
    return payload.toString();
  }
  try {
    return mapper.writeValueAsString(payload);
  } catch(IOException ioe) {
    throw new VertxException(ioe);
  }
}
 
Example #24
Source File: JacksonPayloadMarshaller.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T unmarshallPayload(String body, Class<T> clazz) {
  if (clazz.equals(JsonObject.class)) {
    return (T) new JsonObject(body);
  } else if (clazz.equals(JsonArray.class)) {
    return (T) new JsonArray(body);
  }
  try {
    return mapper.readValue(body, clazz);
  } catch(IOException ioe) {
    throw new VertxException(ioe);
  }
}
 
Example #25
Source File: PlainTextMarshaller.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public String marshallPayload(Object payload) {
  if (payload instanceof String) {
    return payload.toString();
  } else {
    throw new VertxException("text/plain should only be used to marshall Strings");
  }
}
 
Example #26
Source File: PlainTextMarshaller.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T unmarshallPayload(String body, Class<T> clazz) {
  if (!String.class.isAssignableFrom(clazz)) {
    throw new VertxException("text/plain should only be used to marshall Strings");
  }
  return (T) body;
}
 
Example #27
Source File: JAXBPayloadMarshaller.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public String marshallPayload(Object payload) {
  StringWriter writer = new StringWriter();
  try {
    marshaller.marshal(payload, writer);
  } catch (JAXBException je) {
    throw new VertxException(je);
  }
  return writer.toString();
}
 
Example #28
Source File: JAXBPayloadMarshaller.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T unmarshallPayload(String body, Class<T> clazz) {
  try {
    return unmarshaller.unmarshal(loadXMLFromString(body), clazz).getValue();
  } catch (MarshallingException | JAXBException e) {
    throw new VertxException(e);
  }
}
 
Example #29
Source File: RouteFactory.java    From nubes with Apache License 2.0 5 votes vote down vote up
private List<MVCRoute> extractRoutesFromController(Class<?> controller) {
  try {
    ControllerVisitor<?> visitor = new ControllerVisitor<>(controller, config, router, authFactory, routeRegistry, returnHandlers);
    return visitor.visit();
  } catch (IllegalAccessException | InstantiationException e) {
    throw new VertxException(e);
  }
}
 
Example #30
Source File: ServiceRegistry.java    From nubes with Apache License 2.0 5 votes vote down vote up
public Object createEbProxyClass(Class<?> serviceInterface, String address) {
  String name = serviceInterface.getName() + "VertxEBProxy";
  try {
    return Class.forName(name).getConstructor(Vertx.class, String.class).newInstance(vertx, address);
  } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) {
    throw new VertxException("Could not create your service proxy for class : " + serviceInterface, e);
  }
}