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); } }
@Override public boolean containsValue(Object value) { try { return curator.getChildren().forPath(mapPath).stream().anyMatch(k -> { try { byte[] bytes = curator.getData().forPath(keyPath((K) k)); KeyValue<K, V> keyValue = asObject(bytes); return keyValue.getValue().equals(value); } catch (Exception ex) { throw new VertxException(ex); } }); } catch (Exception e) { throw new VertxException(e); } }
@Override public V get(Object key) { try { String keyPath = keyPath((K) key); if (null == curator.checkExists().forPath(keyPath)) { return null; } else { KeyValue<K, V> keyValue = asObject(curator.getData().forPath(keyPath)); return keyValue.getValue(); } } catch (Exception e) { if (!(e instanceof KeeperException.NodeExistsException)) { throw new VertxException(e); } } return null; }
@Override public V put(K key, V value) { try { String keyPath = keyPath(key); KeyValue<K, V> keyValue = new KeyValue<>(key, value); byte[] valueBytes = asByte(keyValue); if (get(key) != null) { curator.setData().forPath(keyPath, valueBytes); } else { curator.create().creatingParentsIfNeeded().forPath(keyPath, valueBytes); } return value; } catch (Exception e) { throw new VertxException(e); } }
@Override public void getLockWithTimeout(String name, long timeout, Handler<AsyncResult<Lock>> resultHandler) { ContextImpl context = (ContextImpl) vertx.getOrCreateContext(); // Ordered on the internal blocking executor context.executeBlocking(() -> { java.util.concurrent.locks.Lock lock = lockService.getLock(name); try { if (lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { return new JGroupsLock(vertx, lock); } else { throw new VertxException("Timed out waiting to get lock " + name); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new VertxException(e); } }, resultHandler); }
@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)); } }); }
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { boolean isClusterSerializable = in.readBoolean(); if (isClusterSerializable) { String className = in.readUTF(); Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className); try { data = (T) clazz.newInstance(); byte[] bytes = new byte[in.read()]; in.read(bytes); ((ClusterSerializable) data).readFromBuffer(0, Buffer.buffer(bytes)); } catch (InstantiationException | IllegalAccessException e) { throw new VertxException(e); } } else { data = (T) in.readObject(); } }
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; }
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); }
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); }
@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); ClusterSerializable obj = (ClusterSerializable) clazz.newInstance(); pos = obj.readFromBuffer(pos, buffer); user = (User) obj; } catch (Exception e) { throw new VertxException(e); } } else { user = null; } return pos; }
private synchronized void init() { if (gateway == null) { boolean connected = false; while (!connected) { try { gateway = new GatewayServer(this, port); client = gateway.getCallbackClient().getPort(); gateway.start(); connected = true; } catch (Exception e) { port++; } if (port > 25340) { throw new VertxException("Failed to bind to port"); } } } }
@Override public void getLockWithTimeout(String name, long timeout, Handler<AsyncResult<Lock>> resultHandler) { ContextImpl context = (ContextImpl) vertx.getOrCreateContext(); // Ordered on the internal blocking executor context.executeBlocking(() -> { ISemaphore iSemaphore = hazelcast.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) { return new HazelcastLock(iSemaphore); } else { throw new VertxException("Timed out waiting to get lock " + name); } }, resultHandler); }
@Override public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) { vertx.executeBlocking(fut -> { SubjectContext subjectContext = new DefaultSubjectContext(); Subject subject = securityManager.createSubject(subjectContext); String username = authInfo.getString("username"); String password = authInfo.getString("password"); AuthenticationToken token = new UsernamePasswordToken(username, password); try { subject.login(token); } catch (AuthenticationException e) { throw new VertxException(e); } fut.complete(new ShiroUser(vertx, securityManager, subject, rolePrefix)); }, resultHandler); }
@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); } }
public Future<ApplicationTest> applicationTest() { return gradleProperties.version().map(version -> { try { return new ApplicationTest(hostname(), version); } catch (final IOException e) { throw new VertxException(e); } }); }
public static SessionStore adapt(Vertx vertx, SessionStore sessionStore) { MessageProducer<String> sessionMessageProducer = vertx.eventBus().sender(VAADIN_SESSION_EXPIRED_ADDRESS); if (sessionStore instanceof LocalSessionStoreImpl) { return LocalSessionStoreAdapter.of(sessionMessageProducer, (LocalSessionStoreImpl) sessionStore); } if (sessionStore instanceof ClusteredSessionStoreImpl) { return new ClusteredSessionStoreAdapter(sessionMessageProducer, (ClusteredSessionStoreImpl) sessionStore); } throw new VertxException("Cannot adapt session store of type " + sessionStore.getClass().getName()); }
private VertxVaadin(Vertx vertx, Optional<SessionStore> 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(vertx, sessionStore.orElseGet(this::createSessionStore)); this.router = initRouter(adaptedSessionStore); this.webSocketHandler = initWebSocketHandler(this.router, adaptedSessionStore); }
@Override public int size() { try { return curator.getChildren().forPath(mapPath).size(); } catch (Exception e) { throw new VertxException(e); } }
@Override public boolean isEmpty() { try { return curator.getChildren().forPath(mapPath).isEmpty(); } catch (Exception e) { throw new VertxException(e); } }
@Override public boolean containsKey(Object key) { try { return curator.checkExists().forPath(keyPath((K) key)) != null; } catch (Exception e) { throw new VertxException(e); } }
@Override public V remove(Object key) { try { V result = get(key); if (result != null) curator.delete().deletingChildrenIfNeeded().forPath(keyPath((K) key)); return result; } catch (Exception e) { throw new VertxException(e); } }
@Override public void clear() { try { curator.delete().deletingChildrenIfNeeded().forPath(mapPath); curator.create().creatingParentsIfNeeded().forPath(mapPath); } catch (Exception e) { throw new VertxException(e); } }
public Buffer encode() { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); Bson.encode(map, os); os.flush(); return Buffer.buffer(os.toByteArray()); } catch (IOException e) { throw new VertxException(e); } }
/** * Encode the BSON object as a buffer * * @return the buffer */ public Buffer encode() { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); Bson.encode(list, os); os.flush(); return Buffer.buffer(os.toByteArray()); } catch (IOException e) { throw new VertxException(e); } }
@Override public void getLockWithTimeout(String name, long timeout, Handler<AsyncResult<Lock>> handler) { ContextImpl context = (ContextImpl) vertx.getOrCreateContext(); // Ordered on the internal blocking executor context.executeBlocking(() -> { boolean locked; try { IgniteQueue<String> queue = getQueue(name, true); pendingLocks.offer(name); locked = queue.offer(getNodeID(), timeout, TimeUnit.MILLISECONDS); if (!locked) { // EVT_NODE_LEFT/EVT_NODE_FAILED event might be already handled, so trying get lock again if // node left topology. // Use IgniteSempahore when it will be fixed. String ownerId = queue.peek(); ClusterNode ownerNode = ignite.cluster().forNodeId(UUID.fromString(ownerId)).node(); if (ownerNode == null) { queue.remove(ownerId); locked = queue.offer(getNodeID(), timeout, TimeUnit.MILLISECONDS); } } } catch (Exception e) { throw new VertxException("Error during getting lock " + name, e); } finally { pendingLocks.remove(name); } if (locked) { return new LockImpl(name); } else { throw new VertxException("Timed out waiting to get lock " + name); } }, handler); }
@Override public void release() { vertx.executeBlocking(future -> { IgniteQueue<String> queue = getQueue(name, true); String ownerId = queue.poll(); if (ownerId == null) { throw new VertxException("Inconsistent lock state " + name); } future.complete(); }, false, null); }
@Override public T read(Kryo kryo, Input input, Class<T> type) { try { byte[] bytes = input.readBytes(input.readVarInt(true)); Buffer buffer = Buffer.buffer(bytes); T object = type.newInstance(); object.readFromBuffer(0, buffer); return object; } catch (InstantiationException | IllegalAccessException e) { throw new VertxException("failed to instantiate serializable type: " + type); } }
/** * Try to create a process from the command line tokens. * * @param line the command line tokens * @return the created process */ public Process createProcess(List<CliToken> line) { try { return makeRequest(line); } catch (Exception e) { throw new VertxException(e); } }
@Test public void testNoAuthenticationConfigured() throws Exception { try { startShell(new SSHTermOptions().setPort(5000).setHost("localhost").setKeyPairOptions( new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")) ); fail(); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof VertxException); assertEquals("No authenticator", e.getCause().getMessage()); } }
@Test public void testNoKeyPairConfigured() throws Exception { try { startShell(new SSHTermOptions().setPort(5000).setHost("localhost"). setAuthOptions(new ShiroAuthOptions().setType(ShiroAuthRealmType.PROPERTIES).setConfig( new JsonObject().put("properties_path", "classpath:test-auth.properties"))) ); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof VertxException); assertEquals("No key pair store configured", e.getCause().getMessage()); } }
public void start() { try { channel.getState(null, 10000); } catch (Exception e) { throw new VertxException(e); } }
private void createServices() { JsonObject services = json.getJsonObject("services", new JsonObject()); this.serviceRegistry = new ServiceRegistry(vertx, this); services.forEach(entry -> { String name = entry.getKey(); String className = (String) entry.getValue(); try { Class<?> clazz = Class.forName(className); this.serviceRegistry.registerService(name, clazz.newInstance()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new VertxException(e); } }); }
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); } }
@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); } }
@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(); }
@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; }
@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"); } }
@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); } }
@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); } }