@Override public RandomStringResponse handleRequest(GetRandomStringQuery request, OrangeContext ctx) throws RpcCallException { new Sleeper().sleepNoException(5000); return RandomStringResponse.getDefaultInstance(); }
public static Class<?> findSubClassParameterType(Object instance, int parameterIndex) throws ClassNotFoundException { if (instance instanceof MockMethodHandler) { if (parameterIndex == 0) { return ((MockMethodHandler) instance).getRequestType(); } else { return ((MockMethodHandler) instance).getResponseType(); } } Class<?> clazz = instance.getClass(); Type[] genericInterfaces = clazz.getGenericInterfaces(); if (genericInterfaces.length > 0) { return retrieveGenericParameterTypes(genericInterfaces, parameterIndex); } else if (clazz.getSuperclass() != null) { return retrieveGenericParameterTypes( clazz.getSuperclass().getGenericInterfaces(), parameterIndex ); } else { return null; } }
public int getExposedPortFromDocker(String serviceName, int internalPort) { Sleeper sleeper = new Sleeper(); String dockerJson = null; List<String> command = of("bash", "-c", "docker inspect `docker ps | grep -w '" + internalPort + "/tcp' | cut -f 1 -d ' '`"); int count = 0; while (count < 60) { dockerJson = processUtil.runProcess(command); if (dockerJson.startsWith("[")) { break; } else { sleeper.sleepNoException(1000); } count++; } int retval = -1; if (dockerJson != null && dockerJson.startsWith("[")) { retval = parseExposedPort(dockerJson, internalPort); } if (retval == -1) { logger.error("Could not determine host port mapping for {}, is it configured " + "for port {} internally, and also exposed?", serviceName, internalPort); } return retval; }
@Test public void test_interceptor() throws ClassNotFoundException { Injector injector = Guice.createInjector((Module) binder -> binder.bindInterceptor( Matchers.identicalTo(TestedRpcHandler.class), Matchers.any(), new RpcHandlerMethodInterceptor() )); TestedRpcHandler methodHandler = injector.getInstance(TestedRpcHandler.class); methodHandler.handleRequest(RpcEnvelope.Request.newBuilder().build(), new OrangeContext()); SameGuiceModuleAssertionOnInterceptorInvokation sameGuiceModuleAssertionOnInterceptorInvokation = injector.getInstance(SameGuiceModuleAssertionOnInterceptorInvokation.class); sameGuiceModuleAssertionOnInterceptorInvokation.test_that_intercepted_rpc_handler_still_verified(); assertThat(ReflectionUtil.findSubClassParameterType(methodHandler, 0)). isEqualTo(RpcEnvelope.Request.class); assertThat(ReflectionUtil.findSubClassParameterType(methodHandler, 1)). isEqualTo(RpcEnvelope.Response.class); }
private static void verifyDefaultCharset() { String charset = Charset.defaultCharset().name(); logger.info("Found charset {}", charset); if (! charset.equals("UTF-8")) { Exception ex = new IllegalStateException("The default character set is not UTF-8.\n" + "Please configure your runtime with the JVM option -Dfile.encoding=UTF8"); logger.error("Bad configuration", ex); try { new Sleeper().sleep(Long.MAX_VALUE); } catch (InterruptedException ignored) { } } }
/** * Converts a proto file name into a class name according to the rules defined by protobuf: * https://developers.google.com/protocol-buffers/docs/reference/java-generated * * The file name will be camel cased (and underscores, hyphens etc. stripped out). * @param protoFileName The file name to process: e.g. my_service.proto * @return The class name: MyService */ public static String toClassName(String protoFileName) { if (protoFileName == null) { return null; } String fileName = FileUtil.stripPath(protoFileName); fileName = FileUtil.stripExtension(fileName); String parts[] = fileName.split("[^A-Za-z0-9]"); StringBuilder classNameBuilder = new StringBuilder(); for (String part : parts) { classNameBuilder.append(StringUtils.capitalize(part)); } return classNameBuilder.toString(); } }
@Override public void run() { if (isRegistered()) { return; } long sleepDuration = 1000; while (! isRegistered.get()) { try { attemptRegistration(); if (isRegistered.get()) { break; } sleeper.sleepNoException(sleepDuration); sleepDuration = (long) (sleepDuration * 1.5); } catch (Exception ex) { logger.warn("Caught exception attempting service registration", ex); } catch (Throwable t) { logger.error("Caught throwable attempting service registration", t); throw t; } } }
@Test public void verifyReflection() throws ClassNotFoundException { TestServiceMethodHandler handler = new TestServiceMethodHandler(); assertThat(ReflectionUtil.findSubClassParameterType(handler, 0)). isEqualTo(RpcEnvelope.Request.class); assertThat(ReflectionUtil.findSubClassParameterType(handler, 1)). isEqualTo(RpcEnvelope.Response.class); assertThat(ReflectionUtil.findSubClassParameterType(handler, 2)).isNull(); }
@Test public void verifyReflectionWorksWithAChild() throws ClassNotFoundException { ChildTestServiceMethodHandler handler = new ChildTestServiceMethodHandler(); assertThat(ReflectionUtil.findSubClassParameterType(handler, 0)). isEqualTo(RpcEnvelope.Request.class); assertThat(ReflectionUtil.findSubClassParameterType(handler, 1)). isEqualTo(RpcEnvelope.Response.class); assertThat(ReflectionUtil.findSubClassParameterType(handler, 2)).isNull(); }
messageType = ReflectionUtil.findSubClassParameterType(callback, 0); if (messageType == null) { throw new IllegalStateException("Could not determine EventReceivedCallback message type");
@Test public void stripExtension() { assertThat(FileUtil.stripExtension("/usr/local/blah/blah/myfileName.txt")).isEqualTo("/usr/local/blah/blah/myfileName"); assertThat(FileUtil.stripExtension("C:/Program\\ Files/Applications/SomeFile.app")).isEqualTo("C:/Program\\ Files/Applications/SomeFile"); assertThat(FileUtil.stripExtension("SomeFile.app")).isEqualTo("SomeFile"); assertThat(FileUtil.stripExtension("/home/jbloggs/SomeFile.longfileextension")).isEqualTo("/home/jbloggs/SomeFile"); assertThat(FileUtil.stripExtension("")).isEqualTo(""); assertThat(FileUtil.stripExtension(" ")).isEqualTo(" "); assertThat(FileUtil.stripExtension(null)).isEqualTo(""); }
@Test public void stripPath() { assertThat(FileUtil.stripPath("/usr/local/blah/blah/myfileName.txt")).isEqualTo("myfileName.txt"); assertThat(FileUtil.stripPath("C:/Program\\ Files/Applications/SomeFile.app")).isEqualTo("SomeFile.app"); assertThat(FileUtil.stripPath("SomeFile.app")).isEqualTo("SomeFile.app"); assertThat(FileUtil.stripPath("/home/jbloggs/SomeFile.longfileextension")).isEqualTo("SomeFile.longfileextension"); assertThat(FileUtil.stripPath("")).isEqualTo(""); assertThat(FileUtil.stripPath(" ")).isEqualTo(" "); assertThat(FileUtil.stripPath(null)).isEqualTo(""); }
HealthCheck.Status.FAIL, message)); try { sleeper.sleep(60000L); } catch (InterruptedException e1) {
@SuppressWarnings("unchecked") public <T>T getEvent(String eventName, Class eventClass, Predicate<T> predicate, long timeout){ long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < timeout){ //the reversing is for starting with the newest events List<T> events = Lists.reverse(getEventsOfType(eventName, eventClass)); for (T event: events) { if(predicate.test(event)){ return event; } } new Sleeper().sleepNoException(10); } logger.error("The event {} is not found after {} ms", eventName, timeout); return null; }
@Override public void run() { if (serviceName == null) { throw new IllegalStateException("Service name was not set"); } if (StringUtils.isBlank(serviceProps.getRegistryServer())) { logger.error("registryServer was not specified"); return; } else { logger.info("Will use consul server at {}", serviceProps.getRegistryServer()); } //don't start polling until we are properly initialized, even if the initial result was empty List<ConsulHealthEntry> instances = loadCurrentHealthList(); while (instances.isEmpty()) { sleeper.sleepNoException(1000); instances = loadCurrentHealthList(); logger.debug("Received {} health entries for {}", instances.size(), serviceName); } reportInitialServicesList(instances); //TODO: detect if multiple AZs; if multiple AZs, determine AZ sort order //TODO: instances = sortByAvailabilityZone(instances); while (true) { watchForUpdates(); if (shutdownSemaphore.tryAcquire()) { logger.debug("Shutdown semaphore acquired"); break; } } }
@SuppressWarnings("unchecked") private Message convertJsonToProtobuf(ServiceMethodHandler handler, JsonRpcRequest rpcRequest) throws RpcCallException { try { Class<?> requestKlass = findSubClassParameterType(handler, 0); return ProtobufUtil.jsonToProtobuf(rpcRequest.getParams(), (Class<? extends Message>) requestKlass); } catch (ClassNotFoundException ex) { throw new IllegalStateException("Reflection for handler " + handler.getClass() + " failed"); } catch (RuntimeException ex) { throw new RpcCallException(RpcCallException.Category.BadRequest, "Invalid request"); } }
/** * Publish an event to kafka. We create one publisher per topic. * * @param topic The topic to publish under * @param key The key for the event * @param event The event to publish */ public void publishEventWithKey(String topic, String key, Message event) { KafkaPublisher publisher = topicToPublisher.get(topic); if (publisher == null) { publisher = factory.newBuilder(topic).build(); topicToPublisher.put(topic, publisher); } String jsonEvent = ProtobufUtil.protobufToJson(event).toString(); boolean isPublished = publisher.publishSyncWithKey(key, jsonEvent); if (isPublished){ logger.info("Published event: {}", jsonEvent); new Sleeper().sleepNoException(sleepAfterPublish); } else{ logger.warn("Publishing event message {} to Kafka topic {} failed", jsonEvent, topic); } }
private void initialize() throws Exception { buildMethodHandlers(serviceName.replaceAll("-", "_")); registrationManager.setRegisteredHandlers(methodHandlers.getMethodHandlers()); registrationManager.register(); messageHandler.setServiceName(serviceName); messageHandler.start(); while(! registrationManager.isRegistered()) { logger.info("Waiting for service registration of {}", serviceName); new Sleeper().sleepNoException(100); } healthCheckManager.initialize(); loadBalancerFactory = injector.getInstance(LoadBalancerFactory.class); loadBalancerFactory.getLoadBalancer(serviceName).waitForServiceInstance(); }
@Test public void queue_processingEnded_retryScheduled() { messageQueue = new OffsetBlockingMessageQueue(messageExecutor, 100); ConsumerRecord record1 = new ConsumerRecord<>(topic, 0, 0, defaultKey, defaultValue); messageQueue.add(record1); messageQueue.add(new ConsumerRecord<>(topic, 0, 1, defaultKey, defaultValue)); messageQueue.add(new ConsumerRecord<>(topic, 0, 2, defaultKey, defaultValue)); messageQueue.processingEnded(new KafkaTopicInfo(topic, 0, 0, defaultKey)); new Sleeper().sleepNoException(120); messageQueue.processingEnded(new KafkaTopicInfo(topic, 0, 0, defaultKey)); new Sleeper().sleepNoException(120); ArgumentCaptor<ConsumerRecord> captor = ArgumentCaptor.forClass(ConsumerRecord.class); verify(messageExecutor, times(3)).execute(captor.capture()); assertThat(captor.getAllValues().get(0)).isEqualTo(record1); assertThat(captor.getAllValues().get(1)).isEqualTo(record1); assertThat(captor.getAllValues().get(2)).isEqualTo(record1); }
@Override public void run() { OrangeContext context = new OrangeContext(); Sleeper sleeper = new Sleeper(); try { while (produceMessages.get()) { String key = RandomStringUtils.randomAscii(5); SayHelloToCmd payload = SayHelloToCmd.newBuilder().setName(key).build(); Message request = Messages.requestFor(ping, pong, key, payload, context); producer.send(request); sentMessages.incrementAndGet(); sleeper.sleepNoException(250); } } catch (Throwable t) { logger.error("Exception in producer loop", t); } } });