focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Node getLastNode() { return parent == null ? null : parent.getCurNode(); }
@Test public void testGetLastNode() { Context context = new NullContext(); CtEntry entry = new CtEntry(new StringResourceWrapper("testGetLastNode", EntryType.IN), null, context); assertNull(entry.parent); assertNull(entry.getLastNode()); Entry parentEntry = mock(Entry.class); Node node = mock(Node.class); when(parentEntry.getCurNode()).thenReturn(node); entry.parent = parentEntry; assertSame(node, entry.getLastNode()); }
@Override public String[] split(String text) { if (splitContraction) { text = WONT_CONTRACTION.matcher(text).replaceAll("$1ill not"); text = SHANT_CONTRACTION.matcher(text).replaceAll("$1ll not"); text = AINT_CONTRACTION.matcher(text).replaceAll("$1m not"); for (Pattern regexp : NOT_CONTRACTIONS) { text = regexp.matcher(text).replaceAll("$1 not"); } for (Pattern regexp : CONTRACTIONS2) { text = regexp.matcher(text).replaceAll("$1 $2"); } for (Pattern regexp : CONTRACTIONS3) { text = regexp.matcher(text).replaceAll("$1 $2 $3"); } } text = DELIMITERS[0].matcher(text).replaceAll(" $1 "); text = DELIMITERS[1].matcher(text).replaceAll(" $1"); text = DELIMITERS[2].matcher(text).replaceAll(" $1"); text = DELIMITERS[3].matcher(text).replaceAll(" . "); text = DELIMITERS[4].matcher(text).replaceAll(" $1 "); String[] words = WHITESPACE.split(text); if (words.length > 1 && words[words.length-1].equals(".")) { if (EnglishAbbreviations.contains(words[words.length-2])) { words[words.length-2] = words[words.length-2] + "."; } } ArrayList<String> result = new ArrayList<>(); for (String token : words) { if (!token.isEmpty()) { result.add(token); } } return result.toArray(new String[0]); }
@Test public void testTokenizeDiacritizedWords() { System.out.println("tokenize words with diacritized chars (both composite and combining)"); String text = "The naïve résumé of Raúl Ibáñez; re\u0301sume\u0301."; String[] expResult = {"The", "naïve", "résumé", "of", "Raúl", "Ibáñez", ";", "re\u0301sume\u0301", "."}; SimpleTokenizer instance = new SimpleTokenizer(); String[] result = instance.split(text); assertEquals(expResult.length, result.length); for (int i = 0; i < result.length; i++) { assertEquals(expResult[i], result[i]); } }
static void populateFirstLevelCache(final Map<EfestoClassKey, List<KieRuntimeService>> toPopulate) { List<KieRuntimeService> discoveredKieRuntimeServices = getDiscoveredKieRuntimeServices(); populateFirstLevelCache(discoveredKieRuntimeServices, toPopulate); }
@Test void populateFirstLevelCache() { List<KieRuntimeService> discoveredKieRuntimeServices = Arrays.asList(kieRuntimeServiceA, kieRuntimeServiceB, kieRuntimeServiceC, kieRuntimeServiceA_cloned); final Map<EfestoClassKey, List<KieRuntimeService>> toPopulate = new HashMap<>(); RuntimeManagerUtils.populateFirstLevelCache(discoveredKieRuntimeServices, toPopulate); assertThat(toPopulate).hasSize(2); assertThat(toPopulate).containsKeys(efestoClassKeyA, efestoClassKeyB, efestoClassKeyC); // efestoClassKeyA and efestoClassKeyB are equals List<KieRuntimeService> servicesA = toPopulate.get(efestoClassKeyA); List<KieRuntimeService> servicesB = toPopulate.get(efestoClassKeyB); assertThat(servicesA).isEqualTo(servicesB); assertThat(servicesA).hasSize(3); assertThat(servicesA).contains(kieRuntimeServiceA, kieRuntimeServiceB, kieRuntimeServiceA_cloned); List<KieRuntimeService> servicesC = toPopulate.get(efestoClassKeyC); assertThat(servicesC).containsExactly(kieRuntimeServiceC); }
@Override public void close(Duration timeout) { long waitTimeMs = timeout.toMillis(); if (waitTimeMs < 0) throw new IllegalArgumentException("The timeout cannot be negative."); waitTimeMs = Math.min(TimeUnit.DAYS.toMillis(365), waitTimeMs); // Limit the timeout to a year. long now = time.milliseconds(); long newHardShutdownTimeMs = now + waitTimeMs; long prev = INVALID_SHUTDOWN_TIME; while (true) { if (hardShutdownTimeMs.compareAndSet(prev, newHardShutdownTimeMs)) { if (prev == INVALID_SHUTDOWN_TIME) { log.debug("Initiating close operation."); } else { log.debug("Moving hard shutdown time forward."); } client.wakeup(); // Wake the thread, if it is blocked inside poll(). break; } prev = hardShutdownTimeMs.get(); if (prev < newHardShutdownTimeMs) { log.debug("Hard shutdown time is already earlier than requested."); newHardShutdownTimeMs = prev; break; } } if (log.isDebugEnabled()) { long deltaMs = Math.max(0, newHardShutdownTimeMs - time.milliseconds()); log.debug("Waiting for the I/O thread to exit. Hard shutdown in {} ms.", deltaMs); } try { // close() can be called by AdminClient thread when it invokes callback. That will // cause deadlock, so check for that condition. if (Thread.currentThread() != thread) { // Wait for the thread to be joined. thread.join(waitTimeMs); } log.debug("Kafka admin client closed."); } catch (InterruptedException e) { log.debug("Interrupted while joining I/O thread", e); Thread.currentThread().interrupt(); } }
@Test @SuppressWarnings("deprecation") public void testDisableJmxReporter() { Properties props = new Properties(); props.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999"); props.setProperty(AdminClientConfig.AUTO_INCLUDE_JMX_REPORTER_CONFIG, "false"); KafkaAdminClient admin = (KafkaAdminClient) AdminClient.create(props); assertTrue(admin.metrics.reporters().isEmpty()); admin.close(); }
public <T extends AbstractMessageListenerContainer> T decorateMessageListenerContainer(T container) { Advice[] advice = prependTracingMessageContainerAdvice(container); if (advice != null) { container.setAdviceChain(advice); } return container; }
@Test void decorateSimpleMessageListenerContainer__adds_by_default() { SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(); assertThat(rabbitTracing.decorateMessageListenerContainer(listenerContainer)) .extracting("adviceChain") .asInstanceOf(array(Advice[].class)) .hasSize(1); }
public void succeededAppsSubmitted(long duration) { totalSucceededAppsSubmitted.add(duration); submitApplicationLatency.add(duration); }
@Test public void testSucceededAppsSubmitted() { long totalGoodBefore = metrics.getNumSucceededAppsSubmitted(); goodSubCluster.submitApplication(100); Assert.assertEquals(totalGoodBefore + 1, metrics.getNumSucceededAppsSubmitted()); Assert.assertEquals(100, metrics.getLatencySucceededAppsSubmitted(), 0); goodSubCluster.submitApplication(200); Assert.assertEquals(totalGoodBefore + 2, metrics.getNumSucceededAppsSubmitted()); Assert.assertEquals(150, metrics.getLatencySucceededAppsSubmitted(), 0); }
protected String getResourceName(String resourceName, /*@NonNull*/ Method method) { // If resource name is present in annotation, use this value. if (StringUtil.isNotBlank(resourceName)) { return resourceName; } // Parse name of target method. return MethodUtil.resolveMethodName(method); }
@Test public void testGetResourceName() throws Exception { Method method = FooService.class.getMethod("random"); String resourceName = "someRandom"; String expectedResolvedName = FooService.class.getName() + ":random()"; assertThat(getResourceName(resourceName, method)).isEqualTo(resourceName); assertThat(getResourceName(null, method)).isEqualTo(expectedResolvedName); assertThat(getResourceName("", method)).isEqualTo(expectedResolvedName); }
@Override public CloseableIterator<ScannerReport.LineCoverage> readComponentCoverage(int fileRef) { ensureInitialized(); return delegate.readComponentCoverage(fileRef); }
@Test public void verify_readComponentCoverage() { writer.writeComponentCoverage(COMPONENT_REF, of(COVERAGE_1, COVERAGE_2)); CloseableIterator<ScannerReport.LineCoverage> res = underTest.readComponentCoverage(COMPONENT_REF); assertThat(res).toIterable().containsExactly(COVERAGE_1, COVERAGE_2); res.close(); }
public static Optional<String> encrypt(String publicKey, String text) { try { Cipher cipher = Cipher.getInstance(RSA_PADDING); byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey.getBytes(DEFAULT_ENCODE)); X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(publicKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generatePublic(encodedKeySpec)); return Optional.ofNullable(new String(Base64.getEncoder().encode(cipher.doFinal( text.getBytes(DEFAULT_ENCODE))), DEFAULT_ENCODE)); } catch (IOException | GeneralSecurityException e) { return Optional.empty(); } }
@Test void encrypt() { Optional<String[]> optional = RsaUtil.generateKey(); Assertions.assertTrue(optional.isPresent()); String[] key = optional.get(); Optional<String> encryptTextOptional = RsaUtil.encrypt(key[1], TEXT); Optional<String> decryptTextOptional = RsaUtil.decrypt(key[0], encryptTextOptional.get()); Assert.assertEquals(decryptTextOptional.get(), TEXT); }
@Override public void write(final MySQLPacketPayload payload, final Object value) { LocalDateTime dateTime = value instanceof LocalDateTime ? (LocalDateTime) value : new Timestamp(((Date) value).getTime()).toLocalDateTime(); int year = dateTime.getYear(); int month = dateTime.getMonthValue(); int dayOfMonth = dateTime.getDayOfMonth(); int hours = dateTime.getHour(); int minutes = dateTime.getMinute(); int seconds = dateTime.getSecond(); int nanos = dateTime.getNano(); boolean isTimeAbsent = 0 == hours && 0 == minutes && 0 == seconds; boolean isNanosAbsent = 0 == nanos; if (isTimeAbsent && isNanosAbsent) { payload.writeInt1(4); writeDate(payload, year, month, dayOfMonth); return; } if (isNanosAbsent) { payload.writeInt1(7); writeDate(payload, year, month, dayOfMonth); writeTime(payload, hours, minutes, seconds); return; } payload.writeInt1(11); writeDate(payload, year, month, dayOfMonth); writeTime(payload, hours, minutes, seconds); writeNanos(payload, nanos); }
@Test void assertWriteLocalDateTimeTypeFourBytes() { MySQLDateBinaryProtocolValue actual = new MySQLDateBinaryProtocolValue(); actual.write(payload, LocalDateTime.of(1970, 1, 14, 0, 0, 0)); verify(payload).writeInt1(4); verify(payload).writeInt2(1970); verify(payload).writeInt1(1); verify(payload).writeInt1(14); }
@VisibleForTesting protected int sizeIncrement(String partitionKey, @Nullable String hashKey, byte[] record) { final int[] size = {0, 0}; // wrapper & record sizeIncrementOfKey(size, partitionKey, partitionKeys); // partition key encoding if (hashKey != null) { sizeIncrementOfKey(size, hashKey, explicitHashKeys); // optional hash key encoding } if (record != null) { size[1] += 1 + VarInt.getLength(record.length) + record.length; // record encoding } // wrapper with partition / hash key table + record with partition / hash key reference return size[0] + 1 + VarInt.getLength(size[1]) + size[1]; }
@Test public void testSizeIncrement() { Random rnd = new Random(); List<String> keys = Stream.generate(() -> randomAscii(1, 256)).limit(3).collect(toList()); List<String> hashKeys = Stream.generate(() -> randomNumeric(1, 38)).limit(3).collect(toList()); hashKeys.add(null); int sizeBytes = BASE_OVERHEAD; int increment = 0; String pk, ehk, data; do { int currentBytes = aggregator.toBytes().length; assertThat(increment).isEqualTo(currentBytes - sizeBytes); assertThat(aggregator.getSizeBytes()).isEqualTo(currentBytes); sizeBytes = currentBytes; pk = keys.get(rnd.nextInt(keys.size())); ehk = hashKeys.get(rnd.nextInt(hashKeys.size())); data = randomAscii(256, 512); increment = aggregator.sizeIncrement(pk, ehk, data.getBytes(UTF_8)); } while (aggregator.addRecord(pk, ehk, data.getBytes(UTF_8))); }
@Override public boolean canRenameTo( FileObject newfile ) { return resolvedFileObject.canRenameTo( newfile ); }
@Test public void testDelegatesCanRenameTo() { FileObject newFile = mock( FileObject.class ); when( resolvedFileObject.canRenameTo( newFile ) ).thenReturn( true ); assertTrue( fileObject.canRenameTo( newFile ) ); when( resolvedFileObject.canRenameTo( newFile ) ).thenReturn( false ); assertFalse( fileObject.canRenameTo( newFile ) ); verify( resolvedFileObject, times( 2 ) ).canRenameTo( newFile ); }
public static <T> Values<T> of(Iterable<T> elems) { return new Values<>(elems, Optional.absent(), Optional.absent(), false); }
@Test public void testCreateRegisteredSchema() { p.getSchemaRegistry() .registerSchemaForClass( String.class, STRING_SCHEMA, s -> Row.withSchema(STRING_SCHEMA).addValue(s).build(), r -> r.getString("field")); PCollection<String> out = p.apply(Create.of("a", "b", "c", "d")); assertThat(out.getCoder(), instanceOf(SchemaCoder.class)); }
@Override public void run() { try { // make sure we call afterRun() even on crashes // and operate countdown latches, else we may hang the parallel runner if (steps == null) { beforeRun(); } if (skipped) { return; } int count = steps.size(); int index = 0; while ((index = nextStepIndex()) < count) { currentStep = steps.get(index); execute(currentStep); if (currentStepResult != null) { // can be null if debug step-back or hook skip result.addStepResult(currentStepResult); } } } catch (Exception e) { if (currentStepResult != null) { result.addStepResult(currentStepResult); } logError("scenario [run] failed\n" + StringUtils.throwableToString(e)); currentStepResult = result.addFakeStepResult("scenario [run] failed", e); } finally { if (!skipped) { afterRun(); if (isFailed() && engine.getConfig().isAbortSuiteOnFailure()) { featureRuntime.suite.abort(); } } if (caller.isNone()) { logAppender.close(); // reclaim memory } } }
@Test void testReplace() { run( "def text = 'words that need to be {replaced}'", "replace text.{replaced} = 'correct'", "match text == 'words that need to be correct'", "match text.toString() == 'words that need to be correct'" ); matchVar("text", "words that need to be correct"); }
@Udf public Map<String, String> splitToMap( @UdfParameter( description = "Separator string and values to join") final String input, @UdfParameter( description = "Separator string and values to join") final String entryDelimiter, @UdfParameter( description = "Separator string and values to join") final String kvDelimiter) { if (input == null || entryDelimiter == null || kvDelimiter == null) { return null; } if (entryDelimiter.isEmpty() || kvDelimiter.isEmpty() || entryDelimiter.equals(kvDelimiter)) { return null; } final Iterable<String> entries = Splitter.on(entryDelimiter).omitEmptyStrings().split(input); return StreamSupport.stream(entries.spliterator(), false) .filter(e -> e.contains(kvDelimiter)) .map(kv -> Splitter.on(kvDelimiter).split(kv).iterator()) .collect(Collectors.toMap( Iterator::next, Iterator::next, (v1, v2) -> v2)); }
@Test public void shouldSplitStringGivenMultiCharDelimiters() { Map<String, String> result = udf.splitToMap("foo:=apple||bar:=cherry", "||", ":="); assertThat(result, hasEntry("foo", "apple")); assertThat(result, hasEntry("bar", "cherry")); assertThat(result.size(), equalTo(2)); }
public PushOffsetVector mergeCopy(final OffsetVector other) { final PushOffsetVector copy = copy(); copy.merge(other); return copy; }
@Test public void shouldMerge() { // Given: PushOffsetVector pushOffsetVector1 = new PushOffsetVector(ImmutableList.of(1L, 2L, 3L)); PushOffsetVector pushOffsetVector2 = new PushOffsetVector(ImmutableList.of(2L, 0L, 9L)); // Then: assertThat(pushOffsetVector1.mergeCopy(pushOffsetVector2), is(new PushOffsetVector(ImmutableList.of(2L, 2L, 9L)))); assertThat(pushOffsetVector2.mergeCopy(pushOffsetVector1), is(new PushOffsetVector(ImmutableList.of(2L, 2L, 9L)))); }
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) { IdentityProvider provider = resolveProviderOrHandleResponse(request, response, CALLBACK_PATH); if (provider != null) { handleProvider(request, response, provider); } }
@Test public void do_filter_with_context_no_log_if_provider_did_not_call_authenticate_on_context() { when(request.getContextPath()).thenReturn("/sonarqube"); when(request.getRequestURI()).thenReturn("/sonarqube/oauth2/callback/" + OAUTH2_PROVIDER_KEY); FakeOAuth2IdentityProvider identityProvider = new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true); identityProviderRepository.addIdentityProvider(identityProvider); underTest.doFilter(request, response, chain); assertCallbackCalled(identityProvider); verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture()); AuthenticationException authenticationException = authenticationExceptionCaptor.getValue(); assertThat(authenticationException).hasMessage("Plugin did not call authenticate"); assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider)); assertThat(authenticationException.getLogin()).isNull(); assertThat(authenticationException.getPublicMessage()).isNull(); }
public FEELFnResult<List<Object>> invoke( @ParameterName( "list" ) List list, @ParameterName( "item" ) Object[] items ) { return invoke((Object) list, items); }
@Test void invokeAppendSomething() { FunctionTestUtil.assertResultList(appendFunction.invoke(Collections.emptyList(), new Object[]{"test"}), List.of("test")); FunctionTestUtil.assertResultList(appendFunction.invoke(List.of("test"), new Object[]{"test2"}), Arrays.asList("test", "test2")); FunctionTestUtil.assertResultList(appendFunction.invoke(List.of("test"), new Object[]{"test2", "test3"}), Arrays.asList("test", "test2", "test3")); }
@Override public String convertTaskConfigToJson(TaskConfig taskConfig) { return new Gson().toJson(configPropertiesAsMap(taskConfig)); }
@Test public void shouldConvertTaskConfigObjectToJson() { TaskConfig taskConfig = new TaskConfig(); TaskConfigProperty p1 = new TaskConfigProperty("k1", "value1"); p1.with(Property.SECURE, true); p1.with(Property.REQUIRED, true); TaskConfigProperty p2 = new TaskConfigProperty("k2", "value2"); p2.with(Property.SECURE, false); p2.with(Property.REQUIRED, true); taskConfig.add(p1); taskConfig.add(p2); String json = new JsonBasedTaskExtensionHandler_V1().convertTaskConfigToJson(taskConfig); Map taskConfigMap = (Map) new GsonBuilder().create().fromJson(json, Object.class); Map property1 = (Map) taskConfigMap.get("k1"); assertThat(property1.get("value").toString(), is("value1")); assertThat(property1.get("secure"), is(true)); assertThat(property1.get("required"), is(true)); Map property2 = (Map) taskConfigMap.get("k2"); assertThat(property2.get("value").toString(), is("value2")); assertThat(property2.get("secure"), is(false)); assertThat(property2.get("required"), is(true)); }
public static RestSettingBuilder get(final String id) { return get(eq(checkId(id))); }
@Test public void should_reply_404_for_unknown_resource() throws Exception { server.resource("targets", get("2").response(with(text("hello")))); running(server, () -> { HttpResponse response = helper.getResponse(remoteUrl("/targets/1")); assertThat(response.getCode(), is(404)); }); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void unpinAllForumTopicMessages() { String name = "edit_thread-" + System.currentTimeMillis(); BaseResponse response = bot.execute(new EditForumTopic(forum, forumEditThread, name, "")); assertTrue(response.isOk()); response = bot.execute(new UnpinAllForumTopicMessages(forum, forumEditThread)); assertTrue(response.isOk()); }
@Override public String toString() { return key + "=" + getValue(); }
@Test public void string() { assertThat(entry.toString()).isEqualTo(Map.entry(1, 2).toString()); }
@Udf public String lpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (padding == null || padding.isEmpty() || targetLen == null || targetLen < 0) { return null; } final StringBuilder sb = new StringBuilder(targetLen + padding.length()); final int padUpTo = Math.max(targetLen - input.length(), 0); for (int i = 0; i < padUpTo; i += padding.length()) { sb.append(padding); } sb.setLength(padUpTo); sb.append(input); sb.setLength(targetLen); return sb.toString(); }
@Test public void shouldAppendPartialPaddingBytes() { final ByteBuffer result = udf.lpad(BYTES_123, 4, BYTES_45); assertThat(BytesUtils.getByteArray(result), is(new byte[]{4,1,2,3})); }
@Override public Host getHost(HostName hostName) throws HostNameNotFoundException { ApplicationInstance applicationInstance = serviceMonitor .getApplicationNarrowedTo(hostName) .orElseThrow(() -> new HostNameNotFoundException(hostName)); List<ServiceInstance> serviceInstances = applicationInstance .serviceClusters().stream() .flatMap(cluster -> cluster.serviceInstances().stream()) .filter(serviceInstance -> hostName.equals(serviceInstance.hostName())) .toList(); HostInfo hostInfo = statusService.getHostInfo(applicationInstance.reference(), hostName); return new Host(hostName, hostInfo, applicationInstance.reference(), serviceInstances); }
@Test public void testGetHost() { ClusterControllerClientFactory clusterControllerClientFactory = new ClusterControllerClientFactoryMock(); StatusService statusService = new ZkStatusService( new MockCurator(), mock(Metric.class), new TestTimer(), new DummyAntiServiceMonitor()); HostName hostName = new HostName("host.yahoo.com"); TenantId tenantId = new TenantId("tenant"); ApplicationInstanceId applicationInstanceId = new ApplicationInstanceId("applicationInstanceId"); ApplicationInstanceReference reference = new ApplicationInstanceReference( tenantId, applicationInstanceId); ApplicationInstance applicationInstance = new ApplicationInstance( tenantId, applicationInstanceId, Set.of(new ServiceCluster( new ClusterId("clusterId"), new ServiceType("serviceType"), Set.of(new ServiceInstance( new ConfigId("configId1"), hostName, ServiceStatus.UP), new ServiceInstance( new ConfigId("configId2"), hostName, ServiceStatus.NOT_CHECKED))))); ServiceMonitor serviceMonitor = () -> new ServiceModel(Map.of(reference, applicationInstance)); orchestrator = new OrchestratorImpl(new HostedVespaPolicy(new HostedVespaClusterPolicy(flagSource, zone), clusterControllerClientFactory, applicationApiFactory, flagSource), clusterControllerClientFactory, statusService, serviceMonitor, 0, new ManualClock(), applicationApiFactory, flagSource); orchestrator.setNodeStatus(hostName, HostStatus.ALLOWED_TO_BE_DOWN); Host host = orchestrator.getHost(hostName); assertEquals(reference, host.getApplicationInstanceReference()); assertEquals(hostName, host.getHostName()); assertEquals(HostStatus.ALLOWED_TO_BE_DOWN, host.getHostInfo().status()); assertTrue(host.getHostInfo().suspendedSince().isPresent()); assertEquals(2, host.getServiceInstances().size()); }
Timer.Context getTimerContextFromExchange(Exchange exchange, String propertyName) { return exchange.getProperty(propertyName, Timer.Context.class); }
@Test public void testGetTimerContextFromExchangeNotFound() { when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(null); assertThat(producer.getTimerContextFromExchange(exchange, PROPERTY_NAME), is(nullValue())); inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class); inOrder.verifyNoMoreInteractions(); }
@Override public int length() { return 2; }
@Test public void testLength() { System.out.println("length"); WeibullDistribution instance = new WeibullDistribution(1.5, 1.0); instance.rand(); assertEquals(2, instance.length()); }
@Override public void set(V value) { get(setAsync(value)); }
@Test public void testOptions() { Config c = createConfig(); c.useSingleServer().setTimeout(10); RedissonClient r = Redisson.create(c); String val = RandomString.make(1048 * 10000); Assertions.assertThrows(RedisResponseTimeoutException.class, () -> { RBucket<String> al = r.getBucket("test"); al.set(val); }); RBucket<String> al = r.getBucket(PlainOptions.name("test") .timeout(Duration.ofSeconds(1))); al.set(val); r.shutdown(); }
public boolean isNewerThan(JavaSpecVersion otherVersion) { return this.compareTo(otherVersion) > 0; }
@Test public void test8newerThan7() throws Exception { // Setup fixture. final JavaSpecVersion seven = new JavaSpecVersion( "1.7" ); final JavaSpecVersion eight = new JavaSpecVersion( "1.8" ); // Execute system under test. final boolean result = eight.isNewerThan( seven ); // Verify results. assertTrue( result ); }
public static Object convert(final Object o) { if (o == null) { return RubyUtil.RUBY.getNil(); } final Class<?> cls = o.getClass(); final Valuefier.Converter converter = CONVERTER_MAP.get(cls); if (converter != null) { return converter.convert(o); } return fallbackConvert(o, cls); }
@Test public void testConcreteJavaProxy() { List<IRubyObject> array = new ArrayList<>(); array.add(RubyString.newString(RubyUtil.RUBY, "foo")); RubyClass proxyClass = (RubyClass) Java.getProxyClass(RubyUtil.RUBY, ArrayList.class); ConcreteJavaProxy cjp = new ConcreteJavaProxy(RubyUtil.RUBY, proxyClass, array); Object result = Valuefier.convert(cjp); assertEquals(ConvertedList.class, result.getClass()); List<Object> a = (ConvertedList) result; }
void allocateCollectionField( Object object, BeanInjectionInfo beanInjectionInfo, String fieldName ) { BeanInjectionInfo.Property property = getProperty( beanInjectionInfo, fieldName ); String groupName = ( property != null ) ? property.getGroupName() : null; if ( groupName == null ) { return; } List<BeanInjectionInfo.Property> groupProperties; groupProperties = getGroupProperties( beanInjectionInfo, groupName ); Integer maxGroupSize = getMaxSize( groupProperties, object ); // not able to get numeric size if ( maxGroupSize == null ) { return; } // guaranteed to get at least one field for constant allocateCollectionField( property, object, Math.max( 1, maxGroupSize ) ); }
@Test public void allocateCollectionField_Property_List_IntiallyNull() { BeanInjector bi = new BeanInjector(null ); BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class ); MetaBeanLevel1 mbl1 = new MetaBeanLevel1(); mbl1.setSub( new MetaBeanLevel2() ); BeanInjectionInfo.Property listProperty = bii.getProperties().values().stream() .filter( p -> p.getName().equals( "ASCENDING_LIST" ) ).findFirst().orElse( null ); assertNull( mbl1.getSub().getAscending() ); bi.allocateCollectionField( listProperty, mbl1.getSub(), 6); assertEquals( 6,mbl1.getSub().getAscending().size() ); }
public Builder toBuilder() { return new Builder(this); }
@Test void toBuilder() { MessagingTracing messagingTracing = MessagingTracing.newBuilder(tracing).build(); assertThat(messagingTracing.toBuilder().build()) .usingRecursiveComparison() .isEqualTo(messagingTracing); assertThat(messagingTracing.toBuilder().producerSampler(neverSample()).build()) .usingRecursiveComparison() .isEqualTo(MessagingTracing.newBuilder(tracing).producerSampler(neverSample()).build()); }
public static <T> boolean isNullOrEmpty(Collection<T> collection) { if (collection == null) return true; return collection.isEmpty(); }
@Test void isNullOrEmptyIsTrueForEmptyCollection() { assertThat(isNullOrEmpty(new ArrayList<>())).isTrue(); }
public RuntimeOptionsBuilder parse(Map<String, String> properties) { return parse(properties::get); }
@Test void should_parse_ansi_colors() { properties.put(Constants.ANSI_COLORS_DISABLED_PROPERTY_NAME, "true"); RuntimeOptions options = cucumberPropertiesParser.parse(properties).build(); assertThat(options.isMonochrome(), equalTo(true)); }
@Override public List<?> deserialize(final String topic, final byte[] bytes) { if (bytes == null) { return null; } try { final String recordCsvString = new String(bytes, StandardCharsets.UTF_8); final List<CSVRecord> csvRecords = CSVParser.parse(recordCsvString, csvFormat) .getRecords(); if (csvRecords.isEmpty()) { throw new SerializationException("No fields in record"); } final CSVRecord csvRecord = csvRecords.get(0); if (csvRecord == null || csvRecord.size() == 0) { throw new SerializationException("No fields in record."); } SerdeUtils.throwOnColumnCountMismatch(parsers.size(), csvRecord.size(), false, topic); final List<Object> values = new ArrayList<>(parsers.size()); final Iterator<Parser> pIt = parsers.iterator(); for (int i = 0; i < csvRecord.size(); i++) { final String value = csvRecord.get(i); final Parser parser = pIt.next(); final Object parsed = value == null || value.isEmpty() ? null : parser.parse(value); values.add(parsed); } return values; } catch (final Exception e) { throw new SerializationException("Error deserializing delimited", e); } }
@Test public void shouldDeserializeNegativeDecimalSerializedAsString() { // Given: final PersistenceSchema schema = persistenceSchema( column("cost", SqlTypes.decimal(4, 2)) ); final KsqlDelimitedDeserializer deserializer = createDeserializer(schema); final byte[] bytes = "\"-01.12\"".getBytes(StandardCharsets.UTF_8); // When: final List<?> result = deserializer.deserialize("", bytes); // Then: assertThat(result, contains(new BigDecimal("-1.12"))); }
@Override public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException { return memoryLimiter.acquire(e, timeout, unit) && super.offer(e, timeout, unit); }
@Test public void testOfferWhenTimeout() throws InterruptedException { MemoryLimitedLinkedBlockingQueue<Runnable> queue = new MemoryLimitedLinkedBlockingQueue<>(1, instrumentation); assertFalse(queue.offer(() -> { }, 2, TimeUnit.SECONDS)); }
@ApiOperation(value = "List of process definitions", tags = { "Process Definitions" }, nickname = "listProcessDefinitions") @ApiImplicitParams({ @ApiImplicitParam(name = "version", dataType = "integer", value = "Only return process definitions with the given version.", paramType = "query"), @ApiImplicitParam(name = "name", dataType = "string", value = "Only return process definitions with the given name.", paramType = "query"), @ApiImplicitParam(name = "nameLike", dataType = "string", value = "Only return process definitions with a name like the given name.", paramType = "query"), @ApiImplicitParam(name = "nameLikeIgnoreCase", dataType = "string", value = "Only return process definitions with a name like the given name ignoring case.", paramType = "query"), @ApiImplicitParam(name = "key", dataType = "string", value = "Only return process definitions with the given key.", paramType = "query"), @ApiImplicitParam(name = "keyLike", dataType = "string", value = "Only return process definitions with a name like the given key.", paramType = "query"), @ApiImplicitParam(name = "resourceName", dataType = "string", value = "Only return process definitions with the given resource name.", paramType = "query"), @ApiImplicitParam(name = "resourceNameLike", dataType = "string", value = "Only return process definitions with a name like the given resource name.", paramType = "query"), @ApiImplicitParam(name = "category", dataType = "string", value = "Only return process definitions with the given category.", paramType = "query"), @ApiImplicitParam(name = "categoryLike", dataType = "string", value = "Only return process definitions with a category like the given name.", paramType = "query"), @ApiImplicitParam(name = "categoryNotEquals", dataType = "string", value = "Only return process definitions which do not have the given category.", paramType = "query"), @ApiImplicitParam(name = "deploymentId", dataType = "string", value = "Only return process definitions which are part of a deployment with the given deployment id.", paramType = "query"), @ApiImplicitParam(name = "parentDeploymentId", dataType = "string", value = "Only return process definitions which are part of a deployment with the given parent deployment id.", paramType = "query"), @ApiImplicitParam(name = "startableByUser", dataType = "string", value = "Only return process definitions which are part of a deployment with the given id.", paramType = "query"), @ApiImplicitParam(name = "latest", dataType = "boolean", value = "Only return the latest process definition versions. Can only be used together with key and keyLike parameters, using any other parameter will result in a 400-response.", paramType = "query"), @ApiImplicitParam(name = "suspended", dataType = "boolean", value = "If true, only returns process definitions which are suspended. If false, only active process definitions (which are not suspended) are returned.", paramType = "query"), @ApiImplicitParam(name = "sort", dataType = "string", value = "Property to sort on, to be used together with the order.", allowableValues = "name,id,key,category,deploymentId,version", paramType = "query"), }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates request was successful and the process-definitions are returned"), @ApiResponse(code = 400, message = "Indicates a parameter was passed in the wrong format or that latest is used with other parameters other than key and keyLike. The status-message contains additional information.") }) @GetMapping(value = "/repository/process-definitions", produces = "application/json") public DataResponse<ProcessDefinitionResponse> getProcessDefinitions(@ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams) { ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery(); // Populate filter-parameters if (allRequestParams.containsKey("category")) { processDefinitionQuery.processDefinitionCategory(allRequestParams.get("category")); } if (allRequestParams.containsKey("categoryLike")) { processDefinitionQuery.processDefinitionCategoryLike(allRequestParams.get("categoryLike")); } if (allRequestParams.containsKey("categoryNotEquals")) { processDefinitionQuery.processDefinitionCategoryNotEquals(allRequestParams.get("categoryNotEquals")); } if (allRequestParams.containsKey("key")) { processDefinitionQuery.processDefinitionKey(allRequestParams.get("key")); } if (allRequestParams.containsKey("keyLike")) { processDefinitionQuery.processDefinitionKeyLike(allRequestParams.get("keyLike")); } if (allRequestParams.containsKey("name")) { processDefinitionQuery.processDefinitionName(allRequestParams.get("name")); } if (allRequestParams.containsKey("nameLike")) { processDefinitionQuery.processDefinitionNameLike(allRequestParams.get("nameLike")); } if (allRequestParams.containsKey("nameLikeIgnoreCase")) { processDefinitionQuery.processDefinitionNameLikeIgnoreCase(allRequestParams.get("nameLikeIgnoreCase")); } if (allRequestParams.containsKey("resourceName")) { processDefinitionQuery.processDefinitionResourceName(allRequestParams.get("resourceName")); } if (allRequestParams.containsKey("resourceNameLike")) { processDefinitionQuery.processDefinitionResourceNameLike(allRequestParams.get("resourceNameLike")); } if (allRequestParams.containsKey("version")) { processDefinitionQuery.processDefinitionVersion(Integer.valueOf(allRequestParams.get("version"))); } if (allRequestParams.containsKey("suspended")) { if (Boolean.parseBoolean(allRequestParams.get("suspended"))) { processDefinitionQuery.suspended(); } else { processDefinitionQuery.active(); } } if (allRequestParams.containsKey("latest")) { if (Boolean.parseBoolean(allRequestParams.get("latest"))) { processDefinitionQuery.latestVersion(); } } if (allRequestParams.containsKey("deploymentId")) { processDefinitionQuery.deploymentId(allRequestParams.get("deploymentId")); } if (allRequestParams.containsKey("parentDeploymentId")) { processDefinitionQuery.parentDeploymentId(allRequestParams.get("parentDeploymentId")); } if (allRequestParams.containsKey("startableByUser")) { processDefinitionQuery.startableByUser(allRequestParams.get("startableByUser")); } if (allRequestParams.containsKey("tenantId")) { processDefinitionQuery.processDefinitionTenantId(allRequestParams.get("tenantId")); } if (allRequestParams.containsKey("tenantIdLike")) { processDefinitionQuery.processDefinitionTenantIdLike(allRequestParams.get("tenantIdLike")); } if (restApiInterceptor != null) { restApiInterceptor.accessProcessDefinitionsWithQuery(processDefinitionQuery); } return paginateList(allRequestParams, processDefinitionQuery, "name", properties, restResponseFactory::createProcessDefinitionResponseList); }
@Test public void testGetProcessDefinitions() throws Exception { try { Deployment firstDeployment = repositoryService.createDeployment() .name("Deployment 1") .parentDeploymentId("parent1") .addClasspathResource("org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml") .deploy(); Deployment secondDeployment = repositoryService.createDeployment().name("Deployment 2") .parentDeploymentId("parent2") .addClasspathResource("org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml") .addClasspathResource("org/flowable/rest/service/api/repository/twoTaskProcess.bpmn20.xml").deploy(); Deployment thirdDeployment = repositoryService.createDeployment().name("Deployment 3").addClasspathResource("org/flowable/rest/service/api/repository/oneTaskProcessWithDi.bpmn20.xml").deploy(); ProcessDefinition oneTaskProcess = repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").deploymentId(firstDeployment.getId()).singleResult(); ProcessDefinition latestOneTaskProcess = repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").deploymentId(secondDeployment.getId()).singleResult(); ProcessDefinition twoTaskprocess = repositoryService.createProcessDefinitionQuery().processDefinitionKey("twoTaskProcess").deploymentId(secondDeployment.getId()).singleResult(); ProcessDefinition oneTaskWithDiProcess = repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcessWithDi").deploymentId(thirdDeployment.getId()).singleResult(); // Test parameterless call String baseUrl = RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_DEFINITION_COLLECTION); assertResultsPresentInDataResponse(baseUrl, oneTaskProcess.getId(), twoTaskprocess.getId(), latestOneTaskProcess.getId(), oneTaskWithDiProcess.getId()); // Verify ACT-2141 Persistent isGraphicalNotation flag for process definitions CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + baseUrl), HttpStatus.SC_OK); JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data"); closeResponse(response); for (int i = 0; i < dataNode.size(); i++) { JsonNode processDefinitionJson = dataNode.get(i); String key = processDefinitionJson.get("key").asText(); JsonNode graphicalNotationNode = processDefinitionJson.get("graphicalNotationDefined"); if ("oneTaskProcessWithDi".equals(key)) { assertThat(graphicalNotationNode.asBoolean()).isTrue(); } else { assertThat(graphicalNotationNode.asBoolean()).isFalse(); } } // Verify // Test name filtering String url = baseUrl + "?name=" + encode("The Two Task Process"); assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test nameLike filtering url = baseUrl + "?nameLike=" + encode("The Two%"); assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test nameLikeIgnoreCase filtering url = baseUrl + "?nameLikeIgnoreCase=" + encode("the Two%"); assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test key filtering url = baseUrl + "?key=twoTaskProcess"; assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test returning multiple versions for the same key url = baseUrl + "?key=oneTaskProcess"; assertResultsPresentInDataResponse(url, oneTaskProcess.getId(), latestOneTaskProcess.getId()); // Test keyLike filtering url = baseUrl + "?keyLike=" + encode("two%"); assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test category filtering url = baseUrl + "?category=TwoTaskCategory"; assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test categoryLike filtering url = baseUrl + "?categoryLike=" + encode("Two%"); assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test categoryNotEquals filtering url = baseUrl + "?categoryNotEquals=OneTaskCategory"; assertResultsPresentInDataResponse(url, twoTaskprocess.getId(), oneTaskWithDiProcess.getId()); // Test resourceName filtering url = baseUrl + "?resourceName=org/flowable/rest/service/api/repository/twoTaskProcess.bpmn20.xml"; assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test resourceNameLike filtering url = baseUrl + "?resourceNameLike=" + encode("%twoTaskProcess%"); assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test version filtering url = baseUrl + "?version=2"; assertResultsPresentInDataResponse(url, latestOneTaskProcess.getId()); // Test latest filtering url = baseUrl + "?latest=true"; assertResultsPresentInDataResponse(url, latestOneTaskProcess.getId(), twoTaskprocess.getId(), oneTaskWithDiProcess.getId()); url = baseUrl + "?latest=false"; assertResultsPresentInDataResponse(url, oneTaskProcess.getId(), twoTaskprocess.getId(), latestOneTaskProcess.getId(), oneTaskWithDiProcess.getId()); // Test deploymentId url = baseUrl + "?deploymentId=" + secondDeployment.getId(); assertResultsPresentInDataResponse(url, twoTaskprocess.getId(), latestOneTaskProcess.getId()); // Test parentDeploymentId url = baseUrl + "?parentDeploymentId=parent2"; assertResultsPresentInDataResponse(url, twoTaskprocess.getId(), latestOneTaskProcess.getId()); // Test parentDeploymentId url = baseUrl + "?parentDeploymentId=parent1"; assertResultsPresentInDataResponse(url, oneTaskProcess.getId()); // Test startableByUser url = baseUrl + "?startableByUser=kermit"; assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); // Test suspended repositoryService.suspendProcessDefinitionById(twoTaskprocess.getId()); url = baseUrl + "?suspended=true"; assertResultsPresentInDataResponse(url, twoTaskprocess.getId()); url = baseUrl + "?suspended=false"; assertResultsPresentInDataResponse(url, latestOneTaskProcess.getId(), oneTaskProcess.getId(), oneTaskWithDiProcess.getId()); } finally { // Always cleanup any created deployments, even if the test failed List<Deployment> deployments = repositoryService.createDeploymentQuery().list(); for (Deployment deployment : deployments) { repositoryService.deleteDeployment(deployment.getId(), true); } } }
public static String from(Path path) { return from(path.toString()); }
@Test void testUnknownContentType() { assertThatThrownBy(() -> ContentType.from(Path.of("un.known"))).isInstanceOf(IllegalArgumentException.class); }
@ScalarOperator(EQUAL) @SqlType(StandardTypes.BOOLEAN) @SqlNullable public static Boolean equal(@SqlType(StandardTypes.BOOLEAN) boolean left, @SqlType(StandardTypes.BOOLEAN) boolean right) { return left == right; }
@Test public void testEqual() { assertFunction("true = true", BOOLEAN, true); assertFunction("true = false", BOOLEAN, false); assertFunction("false = true", BOOLEAN, false); assertFunction("false = false", BOOLEAN, true); }
@Override public int run(String[] args) throws Exception { YarnConfiguration yarnConf = getConf() == null ? new YarnConfiguration() : new YarnConfiguration( getConf()); boolean isHAEnabled = yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED, YarnConfiguration.DEFAULT_RM_HA_ENABLED); if (args.length < 1) { printUsage("", isHAEnabled); return -1; } int exitCode = -1; int i = 0; String cmd = args[i++]; exitCode = 0; if ("-help".equals(cmd)) { if (i < args.length) { printUsage(args[i], isHAEnabled); } else { printHelp("", isHAEnabled); } return exitCode; } if (USAGE.containsKey(cmd)) { if (isHAEnabled) { return super.run(args); } System.out.println("Cannot run " + cmd + " when ResourceManager HA is not enabled"); return -1; } // // verify that we have enough command line parameters // String subClusterId = StringUtils.EMPTY; if ("-refreshAdminAcls".equals(cmd) || "-refreshQueues".equals(cmd) || "-refreshNodesResources".equals(cmd) || "-refreshServiceAcl".equals(cmd) || "-refreshUserToGroupsMappings".equals(cmd) || "-refreshSuperUserGroupsConfiguration".equals(cmd) || "-refreshClusterMaxPriority".equals(cmd)) { subClusterId = parseSubClusterId(args, isHAEnabled); // If we enable Federation mode, the number of args may be either one or three. // Example: -refreshQueues or -refreshQueues -subClusterId SC-1 if (isYarnFederationEnabled(getConf()) && args.length != 1 && args.length != 3) { printUsage(cmd, isHAEnabled); return exitCode; } else if (!isYarnFederationEnabled(getConf()) && args.length != 1) { // If Federation mode is not enabled, then the number of args can only be one. // Example: -refreshQueues printUsage(cmd, isHAEnabled); return exitCode; } } // If it is federation mode, we will print federation mode information if (isYarnFederationEnabled(getConf())) { System.out.println("Using YARN Federation mode."); } try { if ("-refreshQueues".equals(cmd)) { exitCode = refreshQueues(subClusterId); } else if ("-refreshNodes".equals(cmd)) { exitCode = handleRefreshNodes(args, cmd, isHAEnabled); } else if ("-refreshNodesResources".equals(cmd)) { exitCode = refreshNodesResources(subClusterId); } else if ("-refreshUserToGroupsMappings".equals(cmd)) { exitCode = refreshUserToGroupsMappings(subClusterId); } else if ("-refreshSuperUserGroupsConfiguration".equals(cmd)) { exitCode = refreshSuperUserGroupsConfiguration(subClusterId); } else if ("-refreshAdminAcls".equals(cmd)) { exitCode = refreshAdminAcls(subClusterId); } else if ("-refreshServiceAcl".equals(cmd)) { exitCode = refreshServiceAcls(subClusterId); } else if ("-refreshClusterMaxPriority".equals(cmd)) { exitCode = refreshClusterMaxPriority(subClusterId); } else if ("-getGroups".equals(cmd)) { String[] usernames = Arrays.copyOfRange(args, i, args.length); exitCode = getGroups(usernames); } else if ("-updateNodeResource".equals(cmd)) { exitCode = handleUpdateNodeResource(args, cmd, isHAEnabled, subClusterId); } else if ("-addToClusterNodeLabels".equals(cmd)) { exitCode = handleAddToClusterNodeLabels(args, cmd, isHAEnabled); } else if ("-removeFromClusterNodeLabels".equals(cmd)) { exitCode = handleRemoveFromClusterNodeLabels(args, cmd, isHAEnabled); } else if ("-replaceLabelsOnNode".equals(cmd)) { exitCode = handleReplaceLabelsOnNodes(args, cmd, isHAEnabled); } else { exitCode = -1; System.err.println(cmd.substring(1) + ": Unknown command"); printUsage("", isHAEnabled); } } catch (IllegalArgumentException arge) { exitCode = -1; System.err.println(cmd.substring(1) + ": " + arge.getLocalizedMessage()); printUsage(cmd, isHAEnabled); } catch (RemoteException e) { // // This is a error returned by hadoop server. Print // out the first line of the error message, ignore the stack trace. exitCode = -1; try { String[] content; content = e.getLocalizedMessage().split("\n"); System.err.println(cmd.substring(1) + ": " + content[0]); } catch (Exception ex) { System.err.println(cmd.substring(1) + ": " + ex.getLocalizedMessage()); } } catch (Exception e) { exitCode = -1; System.err.println(cmd.substring(1) + ": " + e.getLocalizedMessage()); } if (null != localNodeLabelsManager) { localNodeLabelsManager.stop(); } return exitCode; }
@Test public void testAddToClusterNodeLabelsWithExclusivitySetting() throws Exception { // Parenthese not match String[] args = new String[] { "-addToClusterNodeLabels", "x(" }; assertTrue(0 != rmAdminCLI.run(args)); args = new String[] { "-addToClusterNodeLabels", "x)" }; assertTrue(0 != rmAdminCLI.run(args)); // Not expected key=value specifying inner parentese args = new String[] { "-addToClusterNodeLabels", "x(key=value)" }; assertTrue(0 != rmAdminCLI.run(args)); // Not key is expected, but value not args = new String[] { "-addToClusterNodeLabels", "x(exclusive=)" }; assertTrue(0 != rmAdminCLI.run(args)); // key=value both set args = new String[] { "-addToClusterNodeLabels", "w,x(exclusive=true), y(exclusive=false),z()", "-directlyAccessNodeLabelStore" }; assertTrue(0 == rmAdminCLI.run(args)); assertTrue(dummyNodeLabelsManager.isExclusiveNodeLabel("w")); assertTrue(dummyNodeLabelsManager.isExclusiveNodeLabel("x")); assertFalse(dummyNodeLabelsManager.isExclusiveNodeLabel("y")); assertTrue(dummyNodeLabelsManager.isExclusiveNodeLabel("z")); // key=value both set, and some spaces need to be handled args = new String[] { "-addToClusterNodeLabels", "a (exclusive= true) , b( exclusive =false),c ", "-directlyAccessNodeLabelStore" }; assertTrue(0 == rmAdminCLI.run(args)); assertTrue(dummyNodeLabelsManager.isExclusiveNodeLabel("a")); assertFalse(dummyNodeLabelsManager.isExclusiveNodeLabel("b")); assertTrue(dummyNodeLabelsManager.isExclusiveNodeLabel("c")); }
public static <T> Flattened<T> flattenedSchema() { return new AutoValue_Select_Flattened.Builder<T>() .setNameFn(CONCAT_FIELD_NAMES) .setNameOverrides(Collections.emptyMap()) .build(); }
@Test @Category(NeedsRunner.class) public void testFlattenWithOutputSchema() { List<Row> bottomRow = IntStream.rangeClosed(0, 2) .mapToObj(i -> Row.withSchema(SIMPLE_SCHEMA).addValues(i, Integer.toString(i)).build()) .collect(Collectors.toList()); List<Row> rows = bottomRow.stream() .map(r -> Row.withSchema(NESTED_SCHEMA).addValues(r, r).build()) .collect(Collectors.toList()); PCollection<Row> unnested = pipeline .apply(Create.of(rows).withRowSchema(NESTED_SCHEMA)) .apply(Select.<Row>flattenedSchema().withOutputSchema(CLASHING_NAME_UNNESTED_SCHEMA)); assertEquals(CLASHING_NAME_UNNESTED_SCHEMA, unnested.getSchema()); pipeline.run(); }
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthGetCompilers() throws Exception { web3j.ethGetCompilers().send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getCompilers\"," + "\"params\":[],\"id\":1}"); }
public static Class<?> loadClass(String name) throws UtilException { return loadClass(name, true); }
@Test public void loadClassTest() { String name = ClassLoaderUtil.loadClass("java.lang.Thread.State").getName(); assertEquals("java.lang.Thread$State", name); name = ClassLoaderUtil.loadClass("java.lang.Thread$State").getName(); assertEquals("java.lang.Thread$State", name); }
public static boolean checkLiteralOverflowInDecimalStyle(BigDecimal value, ScalarType scalarType) { int realPrecision = getRealPrecision(value); int realScale = getRealScale(value); BigInteger underlyingInt = value.setScale(scalarType.getScalarScale(), RoundingMode.HALF_UP).unscaledValue(); BigInteger maxDecimal = BigInteger.TEN.pow(scalarType.decimalPrecision()); BigInteger minDecimal = BigInteger.TEN.pow(scalarType.decimalPrecision()).negate(); if (underlyingInt.compareTo(minDecimal) <= 0 || underlyingInt.compareTo(maxDecimal) >= 0) { if (LOG.isDebugEnabled()) { LOG.debug("Typed decimal literal({}) is overflow, value='{}' (precision={}, scale={})", scalarType, value.toPlainString(), realPrecision, realScale); } return false; } return true; }
@Test public void testCheckLiteralOverflowInDecimalStyleSuccess() throws AnalysisException { BigDecimal decimal32Values[] = { new BigDecimal("99999.99994"), new BigDecimal("99999.9999"), new BigDecimal("99999.999"), new BigDecimal("-99999.99994"), new BigDecimal("-99999.9999"), new BigDecimal("-99999.999"), new BigDecimal("0.0001"), new BigDecimal("0.0"), new BigDecimal("-0.0001"), }; ScalarType decimal32p9s4 = ScalarType.createDecimalV3Type(PrimitiveType.DECIMAL32, 9, 4); for (BigDecimal dec32 : decimal32Values) { Assert.assertTrue(DecimalLiteral.checkLiteralOverflowInDecimalStyle(dec32, decimal32p9s4)); } BigDecimal decimal64Values[] = { new BigDecimal("999999999999.9999994"), new BigDecimal("999999999999.999999"), new BigDecimal("999999999999.99999"), new BigDecimal("-999999999999.9999994"), new BigDecimal("-999999999999.999999"), new BigDecimal("-999999999999.99999"), new BigDecimal("-0.000001"), new BigDecimal("0.000001"), new BigDecimal("0.0"), }; ScalarType decimal64p18s6 = ScalarType.createDecimalV3Type(PrimitiveType.DECIMAL64, 18, 6); for (BigDecimal dec64 : decimal64Values) { Assert.assertTrue(DecimalLiteral.checkLiteralOverflowInDecimalStyle(dec64, decimal64p18s6)); } BigDecimal decimal128Values[] = { new BigDecimal("999999999999999999999999999.999999999994"), new BigDecimal("999999999999999999999999999.99999999999"), new BigDecimal("999999999999999999999999999.9999999999"), new BigDecimal("-999999999999999999999999999.999999999994"), new BigDecimal("-999999999999999999999999999.99999999999"), new BigDecimal("-999999999999999999999999999.9999999999"), new BigDecimal("-0.00000000001"), new BigDecimal("0.00000000001"), new BigDecimal("0.0"), }; ScalarType decimal128p38s11 = ScalarType.createDecimalV3Type(PrimitiveType.DECIMAL128, 38, 11); for (BigDecimal dec128 : decimal128Values) { Assert.assertTrue(DecimalLiteral.checkLiteralOverflowInDecimalStyle(dec128, decimal128p38s11)); } }
public Span nextSpan(Message message) { TraceContextOrSamplingFlags extracted = extractAndClearTraceIdProperties(processorExtractor, message, message); Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler. // When an upstream context was not present, lookup keys are unlikely added if (extracted.context() == null && !result.isNoop()) { // simplify code by re-using an existing MessagingRequest impl tagQueueOrTopic(new MessageConsumerRequest(message, destination(message)), result); } return result; }
@Test void nextSpan_should_retain_baggage_headers() throws JMSException { message.setStringProperty(BAGGAGE_FIELD_KEY, ""); jmsTracing.nextSpan(message); assertThat(message.getStringProperty(BAGGAGE_FIELD_KEY)).isEmpty(); }
public FEELFnResult<List> invoke(@ParameterName( "list" ) Object list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } // spec requires us to return a new list final List<Object> result = new ArrayList<>(); flattenList( list, result ); return FEELFnResult.ofResult( result ); }
@Test void invokeParamCollection() { FunctionTestUtil.assertResult(flattenFunction.invoke(Arrays.asList("test", 1, 2)), Arrays.asList("test", 1, 2)); FunctionTestUtil.assertResult(flattenFunction.invoke(Arrays.asList("test", 1, 2, Arrays.asList(3, 4))), Arrays.asList("test", 1, 2, 3, 4)); FunctionTestUtil.assertResult(flattenFunction.invoke(Arrays.asList("test", 1, 2, Arrays.asList(1, 2))), Arrays.asList("test", 1, 2, 1, 2)); FunctionTestUtil.assertResult( flattenFunction.invoke( Arrays.asList("test", 1, Arrays.asList(BigDecimal.ZERO, 3), 2, Arrays.asList(1, 2))), Arrays.asList("test", 1, BigDecimal.ZERO, 3, 2, 1, 2)); FunctionTestUtil.assertResult( flattenFunction.invoke( Arrays.asList("test", 1, Arrays.asList(Arrays.asList(10, 15), BigDecimal.ZERO, 3), 2, Arrays.asList(1, 2))), Arrays.asList("test", 1, 10, 15, BigDecimal.ZERO, 3, 2, 1, 2)); }
@Override public GetQueueInfoResponse getQueueInfo(GetQueueInfoRequest request) throws YarnException, IOException { if (request == null || request.getQueueName() == null) { routerMetrics.incrGetQueueInfoFailedRetrieved(); String msg = "Missing getQueueInfo request or queueName."; RouterAuditLogger.logFailure(user.getShortUserName(), GET_QUEUEINFO, UNKNOWN, TARGET_CLIENT_RM_SERVICE, msg); RouterServerUtil.logAndThrowException(msg, null); } String rSubCluster = request.getSubClusterId(); long startTime = clock.getTime(); ClientMethod remoteMethod = new ClientMethod("getQueueInfo", new Class[]{GetQueueInfoRequest.class}, new Object[]{request}); Collection<GetQueueInfoResponse> queues = null; try { if (StringUtils.isNotBlank(rSubCluster)) { queues = invoke(remoteMethod, GetQueueInfoResponse.class, rSubCluster); } else { queues = invokeConcurrent(remoteMethod, GetQueueInfoResponse.class); } } catch (Exception ex) { routerMetrics.incrGetQueueInfoFailedRetrieved(); String msg = "Unable to get queue [" + request.getQueueName() + "] to exception."; RouterAuditLogger.logFailure(user.getShortUserName(), GET_QUEUEINFO, UNKNOWN, TARGET_CLIENT_RM_SERVICE, msg); RouterServerUtil.logAndThrowException(msg, ex); } long stopTime = clock.getTime(); routerMetrics.succeededGetQueueInfoRetrieved(stopTime - startTime); RouterAuditLogger.logSuccess(user.getShortUserName(), GET_QUEUEINFO, TARGET_CLIENT_RM_SERVICE); // Merge the GetQueueInfoResponse return RouterYarnClientUtils.mergeQueues(queues); }
@Test public void testSubClusterGetQueueInfo() throws IOException, YarnException { // We have set up a unit test where we access queue information for subcluster1. GetQueueInfoResponse response = interceptor.getQueueInfo( GetQueueInfoRequest.newInstance("root", true, true, true, "1")); Assert.assertNotNull(response); QueueInfo queueInfo = response.getQueueInfo(); Assert.assertNotNull(queueInfo); Assert.assertEquals("root", queueInfo.getQueueName()); Assert.assertEquals(1.0, queueInfo.getCapacity(), 0); Assert.assertEquals(0.0, queueInfo.getCurrentCapacity(), 0); Assert.assertEquals(3, queueInfo.getChildQueues().size(), 0); Assert.assertEquals(1, queueInfo.getAccessibleNodeLabels().size()); }
@Override public NearCacheStats getNearCacheStats() { throw new UnsupportedOperationException("Replicated map has no Near Cache!"); }
@Test(expected = UnsupportedOperationException.class) public void testNearCacheStats() { localReplicatedMapStats.getNearCacheStats(); }
public static FinishedTriggersBitSet emptyWithCapacity(int capacity) { return new FinishedTriggersBitSet(new BitSet(capacity)); }
@Test public void testSetGet() { FinishedTriggersProperties.verifyGetAfterSet(FinishedTriggersBitSet.emptyWithCapacity(1)); }
@Override public synchronized List<ApplicationAttemptId> getAppsInQueue(String queueName) { if (queueName.equals(DEFAULT_QUEUE.getQueueName())) { List<ApplicationAttemptId> attempts = new ArrayList<ApplicationAttemptId>(applications.size()); for (SchedulerApplication<FifoAppAttempt> app : applications.values()) { attempts.add(app.getCurrentAppAttempt().getApplicationAttemptId()); } return attempts; } else { return null; } }
@Test public void testGetAppsInQueue() throws Exception { Application application_0 = new Application("user_0", resourceManager); application_0.submit(); Application application_1 = new Application("user_0", resourceManager); application_1.submit(); ResourceScheduler scheduler = resourceManager.getResourceScheduler(); List<ApplicationAttemptId> appsInDefault = scheduler.getAppsInQueue("default"); assertTrue(appsInDefault.contains(application_0.getApplicationAttemptId())); assertTrue(appsInDefault.contains(application_1.getApplicationAttemptId())); assertEquals(2, appsInDefault.size()); Assert.assertNull(scheduler.getAppsInQueue("someotherqueue")); }
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testShhGetFilterChanges() throws Exception { web3j.shhGetFilterChanges(Numeric.toBigInt("0x7")).send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"shh_getFilterChanges\"," + "\"params\":[\"0x7\"],\"id\":1}"); }
public SchemaRegistryClient get() { if (schemaRegistryUrl.equals("")) { return new DefaultSchemaRegistryClient(); } final RestService restService = serviceSupplier.get(); // This call sets a default sslSocketFactory. final SchemaRegistryClient client = schemaRegistryClientFactory.create( restService, 1000, ImmutableList.of( new AvroSchemaProvider(), new ProtobufSchemaProvider(), new JsonSchemaProvider()), schemaRegistryClientConfigs, httpHeaders ); // If we have an sslContext, we use it to set the sslSocketFactory on the restService client. // We need to do it in this order so that the override here is not reset by the constructor // above. if (sslContext != null) { restService.setSslSocketFactory(sslContext.getSocketFactory()); } return client; }
@Test public void shouldPassBasicAuthCredentialsToSchemaRegistryClient() { // Given final Map<String, Object> schemaRegistryClientConfigs = ImmutableMap.of( "ksql.schema.registry.basic.auth.credentials.source", "USER_INFO", "ksql.schema.registry.basic.auth.user.info", "username:password", "ksql.schema.registry.url", "some url" ); final KsqlConfig config = new KsqlConfig(schemaRegistryClientConfigs); final Map<String, Object> expectedConfigs = defaultConfigs(); expectedConfigs.put("basic.auth.credentials.source", "USER_INFO"); expectedConfigs.put("basic.auth.user.info", "username:password"); // When: new KsqlSchemaRegistryClientFactory( config, restServiceSupplier, SSL_CONTEXT, srClientFactory, Collections.emptyMap()).get(); // Then: verify(restService).setSslSocketFactory(isA(SSL_CONTEXT.getSocketFactory().getClass())); srClientFactory.create(same(restService), anyInt(), any(), eq(expectedConfigs), any()); }
@Override public ParSeqBasedCompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor) { return produceEitherStageAsync("applyEitherAsync", other, (t) -> { action.accept(t); return null; }, executor); }
@Test public void testAcceptEitherAsync() throws Exception { Consumer<String> consumer = mock(Consumer.class); CountDownLatch waitLatch = new CountDownLatch(1); CompletionStage<String> completionStage = createTestStage(TESTVALUE1); CompletionStage<String> completionStage2 = createTestStage(TESTVALUE2); finish(completionStage.acceptEitherAsync(completionStage2, r -> { assertEquals(THREAD_NAME_VALUE, Thread.currentThread().getName()); waitLatch.countDown(); }, _mockExecutor)); assertTrue(waitLatch.await(1000, TimeUnit.MILLISECONDS)); }
List<?> apply( final GenericRow row, final ProcessingLogger processingLogger ) { final Object[] args = new Object[parameterExtractors.size()]; for (int i = 0; i < parameterExtractors.size(); i++) { args[i] = evalParam(row, processingLogger, i); } try { final List<?> result = tableFunction.apply(args); if (result == null) { processingLogger.error(RecordProcessingError.recordProcessingError(nullMsg, row)); return ImmutableList.of(); } return result; } catch (final Exception e) { processingLogger.error(RecordProcessingError.recordProcessingError(exceptionMsg, e, row)); return ImmutableList.of(); } }
@Test public void shouldReturnEmptyListIfUdtfThrows() { // Given: final RuntimeException e = new RuntimeException("Boom"); when(tableFunction.apply(any())).thenThrow(e); // When: final List<?> result = applier.apply(VALUE, processingLogger); // Then: assertThat(result, is(empty())); }
void prepare(Map<String, Object> conf, IMetricsContext metrics, int partitionIndex, int numPartitions) { this.options.prepare(conf, partitionIndex, numPartitions); initLastTxn(conf, partitionIndex); }
@Test public void testPrepare() { HdfsState state = createHdfsState(); Collection<File> files = FileUtils.listFiles(new File(TEST_OUT_DIR), null, false); File hdfsDataFile = Paths.get(TEST_OUT_DIR, FILE_NAME_PREFIX + "0").toFile(); assertTrue(files.contains(hdfsDataFile)); }
public static WindowStoreIterator<ValueAndTimestamp<GenericRow>> fetch( final ReadOnlyWindowStore<GenericKey, ValueAndTimestamp<GenericRow>> store, final GenericKey key, final Instant lower, final Instant upper ) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWindowStore<GenericKey, ValueAndTimestamp<GenericRow>>> stores = getStores(store); final Function<ReadOnlyWindowStore<GenericKey, ValueAndTimestamp<GenericRow>>, WindowStoreIterator<ValueAndTimestamp<GenericRow>>> fetchFunc = windowStore -> fetchUncached(windowStore, key, lower, upper); return findFirstNonEmptyIterator(stores, fetchFunc); }
@Test public void shouldCallUnderlyingStoreSingleKey() throws IllegalAccessException { when(provider.stores(any(), any())).thenReturn(ImmutableList.of(meteredWindowStore)); SERDES_FIELD.set(meteredWindowStore, serdes); when(serdes.rawKey(any())).thenReturn(BYTES); when(meteredWindowStore.wrapped()).thenReturn(wrappedWindowStore); when(wrappedWindowStore.wrapped()).thenReturn(windowStore); when(windowStore.fetch(any(), any(), any())).thenReturn(windowStoreIterator); when(windowStoreIterator.hasNext()).thenReturn(false); WindowStoreCacheBypass.fetch(store, SOME_KEY, Instant.ofEpochMilli(100), Instant.ofEpochMilli(200)); verify(windowStore).fetch(new Bytes(BYTES), Instant.ofEpochMilli(100L), Instant.ofEpochMilli(200L)); }
public List<Favorite> search(String userId, String appId, Pageable page) { boolean isUserIdEmpty = Strings.isNullOrEmpty(userId); boolean isAppIdEmpty = Strings.isNullOrEmpty(appId); if (isAppIdEmpty && isUserIdEmpty) { throw new BadRequestException("user id and app id can't be empty at the same time"); } if (!isUserIdEmpty) { UserInfo loginUser = userInfoHolder.getUser(); //user can only search his own favorite app if (!Objects.equals(loginUser.getUserId(), userId)) { userId = loginUser.getUserId(); } } //search by userId if (isAppIdEmpty && !isUserIdEmpty) { return favoriteRepository.findByUserIdOrderByPositionAscDataChangeCreatedTimeAsc(userId, page); } //search by appId if (!isAppIdEmpty && isUserIdEmpty) { return favoriteRepository.findByAppIdOrderByPositionAscDataChangeCreatedTimeAsc(appId, page); } //search by userId and appId return Collections.singletonList(favoriteRepository.findByUserIdAndAppId(userId, appId)); }
@Test @Sql(scripts = "/sql/favorites/favorites.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void testSearchByUserId() { List<Favorite> favorites = favoriteService.search(testUser, null, PageRequest.of(0, 10)); Assert.assertEquals(4, favorites.size()); }
@Override public void collect(long elapsedTime, StatementContext ctx) { final Timer timer = getTimer(ctx); timer.update(elapsedTime, TimeUnit.NANOSECONDS); }
@Test public void updatesTimerForRawSql() throws Exception { final StatementNameStrategy strategy = new SmartNameStrategy(); final InstrumentedTimingCollector collector = new InstrumentedTimingCollector(registry, strategy); final StatementContext ctx = mock(StatementContext.class); doReturn("SELECT 1").when(ctx).getRawSql(); collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); final String name = strategy.getStatementName(ctx); final Timer timer = registry.timer(name); assertThat(name) .isEqualTo(name("sql", "raw", "SELECT 1")); assertThat(timer.getSnapshot().getMax()) .isEqualTo(2000000000); }
@Override public Committer closeForCommit() throws IOException { lock(); try { uploadCurrentPart(); return upload.getCommitter(); } finally { unlock(); } }
@Test(expected = IOException.class) public void testCloseForCommitOnClosedStreamShouldFail() throws IOException { fsDataOutputStream.closeForCommit().commit(); fsDataOutputStream.closeForCommit().commit(); }
@Override public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan, final boolean restoreInProgress) { try { final ExecuteResult result = EngineExecutor .create(primaryContext, serviceContext, plan.getConfig()) .execute(plan.getPlan(), restoreInProgress); return result; } catch (final KsqlStatementException e) { throw e; } catch (final KsqlException e) { // add the statement text to the KsqlException throw new KsqlStatementException( e.getMessage(), e.getMessage(), plan.getPlan().getStatementText(), e.getCause() ); } }
@Test public void shouldExecuteInsertIntoWithCustomQueryId() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); // Given: KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "create stream bar as select * from orders;", ksqlConfig, Collections.emptyMap() ); // When: final List<QueryMetadata> queries = KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "insert into bar with (query_id='my_insert_id') select * from orders;", ksqlConfig, Collections.emptyMap() ); // Then: assertThat(queries, hasSize(1)); assertThat(queries.get(0).getQueryId(), is(new QueryId("MY_INSERT_ID"))); }
public void createPlainAccessConfig(final String addr, final PlainAccessConfig plainAccessConfig, final long timeoutMillis) throws RemotingException, InterruptedException, MQClientException { CreateAccessConfigRequestHeader requestHeader = new CreateAccessConfigRequestHeader(); requestHeader.setAccessKey(plainAccessConfig.getAccessKey()); requestHeader.setSecretKey(plainAccessConfig.getSecretKey()); requestHeader.setAdmin(plainAccessConfig.isAdmin()); requestHeader.setDefaultGroupPerm(plainAccessConfig.getDefaultGroupPerm()); requestHeader.setDefaultTopicPerm(plainAccessConfig.getDefaultTopicPerm()); requestHeader.setWhiteRemoteAddress(plainAccessConfig.getWhiteRemoteAddress()); requestHeader.setTopicPerms(UtilAll.join(plainAccessConfig.getTopicPerms(), ",")); requestHeader.setGroupPerms(UtilAll.join(plainAccessConfig.getGroupPerms(), ",")); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_ACL_CONFIG, requestHeader); RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis); assert response != null; switch (response.getCode()) { case ResponseCode.SUCCESS: { return; } default: break; } throw new MQClientException(response.getCode(), response.getRemark()); }
@Test public void testCreatePlainAccessConfig_Success() throws InterruptedException, RemotingException { doAnswer(mock -> { RemotingCommand request = mock.getArgument(1); return createSuccessResponse4UpdateAclConfig(request); }).when(remotingClient).invokeSync(anyString(), any(RemotingCommand.class), anyLong()); PlainAccessConfig config = createUpdateAclConfig(); try { mqClientAPI.createPlainAccessConfig(brokerAddr, config, 3 * 1000); } catch (MQClientException ignored) { } }
public static List<SubscriptionItem> readFrom( final InputStream in, @Nullable final ImportExportEventListener eventListener) throws InvalidSourceException { if (in == null) { throw new InvalidSourceException("input is null"); } final List<SubscriptionItem> channels = new ArrayList<>(); try { final JsonObject parentObject = JsonParser.object().from(in); if (!parentObject.has(JSON_SUBSCRIPTIONS_ARRAY_KEY)) { throw new InvalidSourceException("Channels array is null"); } final JsonArray channelsArray = parentObject.getArray(JSON_SUBSCRIPTIONS_ARRAY_KEY); if (eventListener != null) { eventListener.onSizeReceived(channelsArray.size()); } for (final Object o : channelsArray) { if (o instanceof JsonObject) { final JsonObject itemObject = (JsonObject) o; final int serviceId = itemObject.getInt(JSON_SERVICE_ID_KEY, 0); final String url = itemObject.getString(JSON_URL_KEY); final String name = itemObject.getString(JSON_NAME_KEY); if (url != null && name != null && !url.isEmpty() && !name.isEmpty()) { channels.add(new SubscriptionItem(serviceId, url, name)); if (eventListener != null) { eventListener.onItemCompleted(name); } } } } } catch (final Throwable e) { throw new InvalidSourceException("Couldn't parse json", e); } return channels; }
@Test public void testInvalidSource() { final List<String> invalidList = Arrays.asList( "{}", "", null, "gibberish"); for (final String invalidContent : invalidList) { try { if (invalidContent != null) { final byte[] bytes = invalidContent.getBytes(StandardCharsets.UTF_8); ImportExportJsonHelper.readFrom((new ByteArrayInputStream(bytes)), null); } else { ImportExportJsonHelper.readFrom(null, null); } fail("didn't throw exception"); } catch (final Exception e) { final boolean isExpectedException = e instanceof SubscriptionExtractor.InvalidSourceException; assertTrue("\"" + e.getClass().getSimpleName() + "\" is not the expected exception", isExpectedException); } } }
@Override public AuthenticationToken authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null; String authorization = request.getHeader(HttpConstants.AUTHORIZATION_HEADER); if (authorization == null || !AuthenticationHandlerUtil.matchAuthScheme(HttpConstants.BASIC, authorization)) { response.setHeader(WWW_AUTHENTICATE, HttpConstants.BASIC); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (authorization == null) { logger.trace("Basic auth starting"); } else { logger.warn("'" + HttpConstants.AUTHORIZATION_HEADER + "' does not start with '" + HttpConstants.BASIC + "' : {}", authorization); } } else { authorization = authorization.substring(HttpConstants.BASIC.length()).trim(); final Base64 base64 = new Base64(0); // As per RFC7617, UTF-8 charset should be used for decoding. String[] credentials = new String(base64.decode(authorization), StandardCharsets.UTF_8).split(":", 2); if (credentials.length == 2) { token = authenticateUser(credentials[0], credentials[1]); response.setStatus(HttpServletResponse.SC_OK); } } return token; }
@Test(timeout = 60000) public void testRequestWithoutAuthorization() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Assert.assertNull(handler.authenticate(request, response)); Mockito.verify(response).setHeader(WWW_AUTHENTICATE, HttpConstants.BASIC); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); }
public static List<String> getServerIdentities(X509Certificate x509Certificate) { List<String> names = new ArrayList<>(); for (CertificateIdentityMapping mapping : serverCertMapping) { List<String> identities = mapping.mapIdentity(x509Certificate); Log.debug("CertificateManager: " + mapping.name() + " returned " + identities.toString()); if (!identities.isEmpty()) { names.addAll(identities); break; } } return names; }
@Test public void testServerIdentitiesXmppAddr() throws Exception { // Setup fixture. final String subjectCommonName = "MySubjectCommonName"; final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr"; final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( new X500Name( "CN=MyIssuer" ), // Issuer BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ), // Random serial number new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now new X500Name( "CN=" + subjectCommonName ), // Subject subjectKeyPair.getPublic() ); final DERSequence otherName = new DERSequence( new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String( subjectAltNameXmppAddr ) }); final GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.otherName, otherName ) ); builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames ); final X509CertificateHolder certificateHolder = builder.build( contentSigner ); final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder ); // Execute system under test final List<String> serverIdentities = CertificateManager.getServerIdentities( cert ); // Verify result assertEquals( 1, serverIdentities.size() ); assertTrue( serverIdentities.contains( subjectAltNameXmppAddr )); assertFalse( serverIdentities.contains( subjectCommonName ) ); }
public Single<Boolean> addAll(Publisher<? extends V> c) { return new PublisherAdder<V>() { @Override public RFuture<Boolean> add(Object o) { return instance.addAsync((V) o); } }.addAll(c); }
@Test public void testAddAllIndexError() { Assertions.assertThrows(RedisException.class, () -> { RListRx<Integer> list = redisson.getList("list"); sync(list.addAll(2, Arrays.asList(7, 8, 9))); }); }
@Nonnull public <T> T getInstance(@Nonnull Class<T> type) { return getInstance(new Key<>(type)); }
@Test public void shouldInjectByNamedKeys() throws Exception { injector = builder .bind(new Injector.Key<>(String.class, "namedThing"), "named value") .bind(String.class, "unnamed value") .build(); NamedParams namedParams = injector.getInstance(NamedParams.class); assertThat(namedParams.withName).isEqualTo("named value"); assertThat(namedParams.withoutName).isEqualTo("unnamed value"); }
public DataSource<T> loadDataSource(Path csvPath, String responseName) throws IOException { return loadDataSource(csvPath, Collections.singleton(responseName)); }
@Test public void testInvalidResponseName() { URL path = CSVLoader.class.getResource("/org/tribuo/data/csv/test.csv"); CSVLoader<MockOutput> loader = new CSVLoader<>(new MockOutputFactory()); assertThrows(IllegalArgumentException.class, () -> loader.loadDataSource(path, "")); assertThrows(IllegalArgumentException.class, () -> loader.loadDataSource(path, "response")); assertThrows(IllegalArgumentException.class, () -> loader.loadDataSource(path, "sdfas")); String tmp = null; assertThrows(IllegalArgumentException.class, () -> loader.loadDataSource(path, tmp)); assertThrows(IllegalArgumentException.class, () -> loader.loadDataSource(path, Collections.singleton("alkjfd"))); assertThrows(IllegalArgumentException.class, () -> loader.loadDataSource(path, new HashSet<>())); }
public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } }
@Test public void isPresent() { assertThat(Optional.of("foo")).isPresent(); }
@Override public V takeLastAndOfferFirstTo(String queueName) throws InterruptedException { return commandExecutor.getInterrupted(takeLastAndOfferFirstToAsync(queueName)); }
@Test public void testTakeLastAndOfferFirstTo() throws InterruptedException { final RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("{queue}1"); queue1.trySetCapacity(10); Executors.newSingleThreadScheduledExecutor().schedule(() -> { try { queue1.put(3); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }, 3, TimeUnit.SECONDS); RBoundedBlockingQueue<Integer> queue2 = redisson.getBoundedBlockingQueue("{queue}2"); queue2.trySetCapacity(10); queue2.put(4); queue2.put(5); queue2.put(6); long startTime = System.currentTimeMillis(); Integer value = queue1.takeLastAndOfferFirstTo(queue2.getName()); assertThat(System.currentTimeMillis() - startTime).isBetween(2900L, 3200L); assertThat(value).isEqualTo(3); assertThat(queue2).containsExactly(3, 4, 5, 6); }
@Override public DenseMatrix matrixMultiply(Matrix other) { if (dim2 == other.getDimension1Size()) { if (other instanceof DenseMatrix) { DenseMatrix otherDense = (DenseMatrix) other; double[][] output = new double[dim1][otherDense.dim2]; for (int i = 0; i < dim1; i++) { for (int j = 0; j < otherDense.dim2; j++) { output[i][j] = columnRowDot(i,j,otherDense); } } return new DenseMatrix(output); } else if (other instanceof DenseSparseMatrix) { DenseSparseMatrix otherSparse = (DenseSparseMatrix) other; int otherDim2 = otherSparse.getDimension2Size(); double[][] output = new double[dim1][otherDim2]; for (int i = 0; i < dim1; i++) { for (int j = 0; j < otherDim2; j++) { output[i][j] = columnRowDot(i,j,otherSparse); } } return new DenseMatrix(output); } else { throw new IllegalArgumentException("Unknown matrix type " + other.getClass().getName()); } } else { throw new IllegalArgumentException("Invalid matrix dimensions, this.shape=" + Arrays.toString(shape) + ", other.shape = " + Arrays.toString(other.getShape())); } }
@Test public void matrixMatrixOtherTransposeTest() { //4x4 matrices DenseMatrix a = generateA(); DenseMatrix b = generateB(); DenseMatrix c = generateC(); DenseMatrix aaT = generateAAT(); assertEquals(aaT,a.matrixMultiply(a,false,true)); DenseMatrix abT = generateABT(); assertEquals(abT,a.matrixMultiply(b,false,true)); DenseMatrix acT = generateACT(); assertEquals(acT,a.matrixMultiply(c,false,true)); DenseMatrix baT = generateBAT(); assertEquals(baT,b.matrixMultiply(a,false,true)); DenseMatrix bbT = generateBBT(); assertEquals(bbT,b.matrixMultiply(b,false,true)); DenseMatrix bcT = generateBCT(); assertEquals(bcT,b.matrixMultiply(c,false,true)); DenseMatrix caT = generateCAT(); assertEquals(caT,c.matrixMultiply(a,false,true)); DenseMatrix cbT = generateCBT(); assertEquals(cbT,c.matrixMultiply(b,false,true)); DenseMatrix ccT = generateCCT(); assertEquals(ccT,c.matrixMultiply(c,false,true)); }
@Operation(summary = "getTasksByDefinitionCode", description = "GET_TASK_LIST_BY_DEFINITION_CODE_NOTES") @Parameters({ @Parameter(name = "code", description = "PROCESS_DEFINITION_CODE", required = true, schema = @Schema(implementation = long.class, example = "100")) }) @GetMapping(value = "/{code}/tasks") @ResponseStatus(HttpStatus.OK) @ApiException(GET_TASKS_LIST_BY_PROCESS_DEFINITION_ID_ERROR) public Result getNodeListByDefinitionCode(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @Parameter(name = "projectCode", description = "PROJECT_CODE", required = true) @PathVariable long projectCode, @PathVariable("code") long code) { Map<String, Object> result = processDefinitionService.getTaskNodeListByDefinitionCode(loginUser, projectCode, code); return returnDataList(result); }
@Test public void testGetNodeListByDefinitionId() { long projectCode = 1L; Long code = 1L; Map<String, Object> result = new HashMap<>(); putMsg(result, Status.SUCCESS); Mockito.when(processDefinitionService.getTaskNodeListByDefinitionCode(user, projectCode, code)) .thenReturn(result); Result response = processDefinitionController.getNodeListByDefinitionCode(user, projectCode, code); Assertions.assertTrue(response != null && response.isSuccess()); }
@VisibleForTesting static boolean validate(TableConfig tableConfig) { String taskType = MinionConstants.UpsertCompactionTask.TASK_TYPE; String tableNameWithType = tableConfig.getTableName(); if (tableConfig.getTableType() == TableType.OFFLINE) { LOGGER.warn("Skip generation task: {} for table: {}, offline table is not supported", taskType, tableNameWithType); return false; } if (!tableConfig.isUpsertEnabled()) { LOGGER.warn("Skip generation task: {} for table: {}, table without upsert enabled is not supported", taskType, tableNameWithType); return false; } return true; }
@Test public void testValidate() { TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).setTimeColumnName(TIME_COLUMN_NAME) .build(); assertFalse(UpsertCompactionTaskGenerator.validate(tableConfig)); TableConfigBuilder tableConfigBuilder = new TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME).setTimeColumnName(TIME_COLUMN_NAME); assertFalse(UpsertCompactionTaskGenerator.validate(tableConfigBuilder.build())); tableConfigBuilder = tableConfigBuilder.setUpsertConfig(new UpsertConfig(UpsertConfig.Mode.FULL)); assertTrue(UpsertCompactionTaskGenerator.validate(tableConfigBuilder.build())); }
public static String addLengthPrefixedCoder( String coderId, RunnerApi.Components.Builder components, boolean replaceWithByteArrayCoder) { String lengthPrefixedByteArrayCoderId = addLengthPrefixByteArrayCoder(components); String urn = components.getCodersOrThrow(coderId).getSpec().getUrn(); // We handle three cases: // 1) the requested coder is already a length prefix coder. In this case we just honor the // request to replace the coder with a byte array coder. // 2) the requested coder is a known coder but not a length prefix coder. In this case we // rebuild the coder by recursively length prefixing any unknown component coders. // 3) the requested coder is an unknown coder. In this case we either wrap the requested coder // with a length prefix coder or replace it with a length prefix byte array coder. if (ModelCoders.LENGTH_PREFIX_CODER_URN.equals(urn)) { return replaceWithByteArrayCoder ? lengthPrefixedByteArrayCoderId : coderId; } else if (ModelCoders.urns().contains(urn) || otherKnownCoderUrns.contains(urn)) { return addForModelCoder(coderId, components, replaceWithByteArrayCoder); } else { return replaceWithByteArrayCoder ? lengthPrefixedByteArrayCoderId : addWrappedWithLengthPrefixCoder(coderId, components); } }
@Test public void test() throws IOException { SdkComponents sdkComponents = SdkComponents.create(); sdkComponents.registerEnvironment(Environments.createDockerEnvironment("java")); String coderId = sdkComponents.registerCoder(original); Components.Builder components = sdkComponents.toComponents().toBuilder(); String updatedCoderId = LengthPrefixUnknownCoders.addLengthPrefixedCoder(coderId, components, replaceWithByteArray); assertEquals( expected, RehydratedComponents.forComponents(components.build()).getCoder(updatedCoderId)); }
@Override public PageResult<SmsLogDO> getSmsLogPage(SmsLogPageReqVO pageReqVO) { return smsLogMapper.selectPage(pageReqVO); }
@Test public void testGetSmsLogPage() { // mock 数据 SmsLogDO dbSmsLog = randomSmsLogDO(o -> { // 等会查询到 o.setChannelId(1L); o.setTemplateId(10L); o.setMobile("15601691300"); o.setSendStatus(SmsSendStatusEnum.INIT.getStatus()); o.setSendTime(buildTime(2020, 11, 11)); o.setReceiveStatus(SmsReceiveStatusEnum.INIT.getStatus()); o.setReceiveTime(buildTime(2021, 11, 11)); }); smsLogMapper.insert(dbSmsLog); // 测试 channelId 不匹配 smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setChannelId(2L))); // 测试 templateId 不匹配 smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setTemplateId(20L))); // 测试 mobile 不匹配 smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setMobile("18818260999"))); // 测试 sendStatus 不匹配 smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setSendStatus(SmsSendStatusEnum.IGNORE.getStatus()))); // 测试 sendTime 不匹配 smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setSendTime(buildTime(2020, 12, 12)))); // 测试 receiveStatus 不匹配 smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setReceiveStatus(SmsReceiveStatusEnum.SUCCESS.getStatus()))); // 测试 receiveTime 不匹配 smsLogMapper.insert(cloneIgnoreId(dbSmsLog, o -> o.setReceiveTime(buildTime(2021, 12, 12)))); // 准备参数 SmsLogPageReqVO reqVO = new SmsLogPageReqVO(); reqVO.setChannelId(1L); reqVO.setTemplateId(10L); reqVO.setMobile("156"); reqVO.setSendStatus(SmsSendStatusEnum.INIT.getStatus()); reqVO.setSendTime(buildBetweenTime(2020, 11, 1, 2020, 11, 30)); reqVO.setReceiveStatus(SmsReceiveStatusEnum.INIT.getStatus()); reqVO.setReceiveTime(buildBetweenTime(2021, 11, 1, 2021, 11, 30)); // 调用 PageResult<SmsLogDO> pageResult = smsLogService.getSmsLogPage(reqVO); // 断言 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); assertPojoEquals(dbSmsLog, pageResult.getList().get(0)); }
public static void waitAll(CompletableFuture<?>... tasks) { try { CompletableFuture.allOf(tasks).get(); } catch (InterruptedException | ExecutionException e) { throw new ThreadException(e); } }
@Test @Disabled public void waitAndGetTest() { CompletableFuture<String> hutool = CompletableFuture.supplyAsync(() -> { ThreadUtil.sleep(1, TimeUnit.SECONDS); return "hutool"; }); CompletableFuture<String> sweater = CompletableFuture.supplyAsync(() -> { ThreadUtil.sleep(2, TimeUnit.SECONDS); return "卫衣"; }); CompletableFuture<String> warm = CompletableFuture.supplyAsync(() -> { ThreadUtil.sleep(3, TimeUnit.SECONDS); return "真暖和"; }); // 等待完成 AsyncUtil.waitAll(hutool, sweater, warm); // 获取结果 assertEquals("hutool卫衣真暖和", AsyncUtil.get(hutool) + AsyncUtil.get(sweater) + AsyncUtil.get(warm)); }
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) { Objects.requireNonNull(metric); if (batchMeasure == null) { return Optional.empty(); } Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder(); switch (metric.getType().getValueType()) { case INT: return toIntegerMeasure(builder, batchMeasure); case LONG: return toLongMeasure(builder, batchMeasure); case DOUBLE: return toDoubleMeasure(builder, batchMeasure); case BOOLEAN: return toBooleanMeasure(builder, batchMeasure); case STRING: return toStringMeasure(builder, batchMeasure); case LEVEL: return toLevelMeasure(builder, batchMeasure); case NO_VALUE: return toNoValueMeasure(builder); default: throw new IllegalArgumentException("Unsupported Measure.ValueType " + metric.getType().getValueType()); } }
@Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Int_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_INT_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); }
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testOrderByWithWildcard() { // TODO: validate output analyze("SELECT t1.* FROM t1 ORDER BY a"); }
@Override public int hashCode() { return ((key.hashCode() + (from != null ? from.hashCode() : 0)) * 31 + (to != null ? to.hashCode() : 0)) * 31; }
@Test void requireThatHashCodeIsImplemented() { assertEquals(new FeatureRange("key").hashCode(), new FeatureRange("key").hashCode()); }
public static Builder builder() { return new Builder(); }
@Test public void testEquals() { FilteredConnectPoint cp = new FilteredConnectPoint(NetTestTools.connectPoint("d", 1)); TransportEndpointDescription ted1 = TransportEndpointDescription .builder() .withEnabled(true) .withOutput(cp) .build(); TransportEndpointDescription ted2 = TransportEndpointDescription .builder() .withEnabled(true) .withOutput(cp) .build(); new EqualsTester() .addEqualityGroup(ted1) .addEqualityGroup(ted2) .testEquals(); }
public <ConfigType extends ConfigInstance> ConfigType toInstance(Class<ConfigType> clazz, String configId) { return ConfigInstanceUtil.getNewInstance(clazz, configId, this); }
@Test public void non_existent_map_of_struct_in_payload_is_ignored() { Slime slime = new Slime(); Cursor map = slime.setObject().setObject("non_existent_inner_map"); map.setObject("one").setLong("foo", 1); MaptypesConfig config = new ConfigPayload(slime).toInstance(MaptypesConfig.class, ""); assertNotNull(config); }
@Override public TopicConsumerBuilder<T> priorityLevel(int priorityLevel) { checkArgument(priorityLevel >= 0, "priorityLevel needs to be >= 0"); topicConf.setPriorityLevel(priorityLevel); return this; }
@Test public void testValidPriorityLevel() { topicConsumerBuilderImpl.priorityLevel(0); verify(topicConsumerConfigurationData).setPriorityLevel(0); }
public IndexConfig setAttributes(List<String> attributes) { checkNotNull(attributes, "Index attributes cannot be null."); this.attributes = new ArrayList<>(attributes.size()); for (String attribute : attributes) { addAttribute(attribute); } return this; }
@Test(expected = NullPointerException.class) public void testAttributesNull() { new IndexConfig().setAttributes(null); }
public MaterialAgent createAgent(MaterialRevision revision) { Material material = revision.getMaterial(); if (material instanceof DependencyMaterial) { return MaterialAgent.NO_OP; } else if (material instanceof PackageMaterial) { return MaterialAgent.NO_OP; } else if (material instanceof PluggableSCMMaterial) { return new PluggableSCMMaterialAgent(scmExtension, revision, workingDirectory, consumer); } else if (material instanceof ScmMaterial) { String destFolderPath = ((ScmMaterial) material).workingdir(workingDirectory).getAbsolutePath(); return new AbstractMaterialAgent(revision, consumer, workingDirectory, new AgentSubprocessExecutionContext(agentIdentifier, destFolderPath)); } throw new RuntimeException("Could not find MaterialChecker for material = " + material); }
@Test public void shouldCreateMaterialAgent_withAgentsUuidAsSubprocessExecutionContextNamespace() throws IOException { String agentUuid = "uuid-01783738"; MaterialAgentFactory factory = new MaterialAgentFactory(new InMemoryStreamConsumer(), tempWorkingDirectory, new AgentIdentifier("host", "1.1.1.1", agentUuid), scmExtension); GitMaterial gitMaterial = new GitMaterial("http://foo", "master", "dest_folder"); MaterialAgent agent = factory.createAgent(new MaterialRevision(gitMaterial)); assertThat(agent, is(instanceOf(AbstractMaterialAgent.class))); SubprocessExecutionContext execCtx = ReflectionUtil.getField(agent, "execCtx"); assertThat(execCtx.getProcessNamespace("fingerprint"), is(CachedDigestUtils.sha256Hex(String.format("%s%s%s", "fingerprint", agentUuid, gitMaterial.workingdir(tempWorkingDirectory))))); }
public static void deleteDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); deleteDirectoryImpl(directory.toPath()); }
@Test public void deleteDirectory_throws_IOE_if_argument_is_a_file() throws IOException { File file = temporaryFolder.newFile(); assertThatThrownBy(() -> FileUtils.deleteDirectory(file)) .isInstanceOf(IOException.class) .hasMessage("Directory '" + file.getAbsolutePath() + "' is a file"); }
public void checkIfAnyComponentsNeedIssueSync(DbSession dbSession, List<String> componentKeys) { boolean isAppOrViewOrSubview = dbClient.componentDao().existAnyOfComponentsWithQualifiers(dbSession, componentKeys, APP_VIEW_OR_SUBVIEW); boolean needIssueSync; if (isAppOrViewOrSubview) { needIssueSync = dbClient.branchDao().hasAnyBranchWhereNeedIssueSync(dbSession, true); } else { needIssueSync = dbClient.branchDao().doAnyOfComponentsNeedIssueSync(dbSession, componentKeys); } if (needIssueSync) { throw new EsIndexSyncInProgressException(IssueIndexDefinition.TYPE_ISSUE.getMainType(), "Results are temporarily unavailable. Indexing of issues is in progress."); } }
@Test public void checkIfAnyComponentsNeedIssueSync_single_view_subview_or_app() { ProjectData projectData1 = insertProjectWithBranches(true, 0); ComponentDto app = db.components().insertPublicApplication().getMainBranchComponent(); ComponentDto view = db.components().insertPrivatePortfolio(); ComponentDto subview = db.components().insertSubView(view); DbSession session = db.getSession(); List<String> appViewOrSubviewKeys = Arrays.asList(projectData1.getProjectDto().getKey(), app.getKey(), view.getKey(), subview.getKey()); // throws if flag set to TRUE assertThatThrownBy(() -> underTest.checkIfAnyComponentsNeedIssueSync(session, appViewOrSubviewKeys)) .isInstanceOf(EsIndexSyncInProgressException.class) .hasFieldOrPropertyWithValue("httpCode", 503) .hasMessage("Results are temporarily unavailable. Indexing of issues is in progress."); }
@Override public MergedResult decorate(final QueryResult queryResult, final SQLStatementContext sqlStatementContext, final EncryptRule rule) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof MySQLExplainStatement || sqlStatement instanceof MySQLShowColumnsStatement) { return new MergedEncryptShowColumnsMergedResult(queryResult, sqlStatementContext, rule); } if (sqlStatement instanceof MySQLShowCreateTableStatement) { return new MergedEncryptShowCreateTableMergedResult(globalRuleMetaData, queryResult, sqlStatementContext, rule); } return new TransparentMergedResult(queryResult); }
@Test void assertMergedResultWithShowColumnsStatement() { sqlStatementContext = getShowColumnsStatementContext(); EncryptDALResultDecorator encryptDALResultDecorator = new EncryptDALResultDecorator(mock(RuleMetaData.class)); assertThat(encryptDALResultDecorator.decorate(mock(QueryResult.class), sqlStatementContext, rule), instanceOf(MergedEncryptShowColumnsMergedResult.class)); assertThat(encryptDALResultDecorator.decorate(mock(MergedResult.class), sqlStatementContext, rule), instanceOf(DecoratedEncryptShowColumnsMergedResult.class)); }
@Override public boolean match(Message msg, StreamRule rule) { if(msg.getField(Message.FIELD_GL2_SOURCE_INPUT) == null) { return rule.getInverted(); } final String value = msg.getField(Message.FIELD_GL2_SOURCE_INPUT).toString(); return rule.getInverted() ^ value.trim().equalsIgnoreCase(rule.getValue()); }
@Test public void testUnsuccessfulMatch() { StreamRule rule = getSampleRule(); rule.setValue("input-id-dead"); Message msg = getSampleMessage(); msg.addField(Message.FIELD_GL2_SOURCE_INPUT, "input-id-beef"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); }
public Optional<Details> restartForeachInstance( RunRequest request, WorkflowInstance instance, String foreachStepId, long restartRunId) { request.updateForDownstreamIfNeeded(foreachStepId, instance); workflowHelper.updateWorkflowInstance(instance, request); instance.setWorkflowRunId(restartRunId); return instanceDao.runWorkflowInstances( instance.getWorkflowId(), Collections.singletonList(instance), 1); }
@Test public void testRestartForeachInstance() { doNothing().when(workflowHelper).updateWorkflowInstance(any(), any()); instance.setWorkflowId("maestro_foreach_x"); RestartConfig restartConfig = RestartConfig.builder() .restartPolicy(RunPolicy.RESTART_FROM_INCOMPLETE) .downstreamPolicy(RunPolicy.RESTART_FROM_BEGINNING) .addRestartNode("maestro_foreach_x", 1, null) .addRestartNode("sample-minimal-wf", 1, "foreach-step") .build(); ForeachInitiator initiator = new ForeachInitiator(); UpstreamInitiator.Info parent = new UpstreamInitiator.Info(); parent.setWorkflowId("maestro_foreach_x"); parent.setInstanceId(1); parent.setRunId(1); parent.setStepId("foreach-step"); parent.setStepAttemptId(1); initiator.setAncestors(Collections.singletonList(parent)); RunRequest runRequest = RunRequest.builder() .initiator(initiator) .currentPolicy(RunPolicy.RESTART_FROM_INCOMPLETE) .restartConfig(restartConfig) .build(); assertFalse( actionHandler .restartForeachInstance(runRequest, instance, "foreach-step", 100) .isPresent()); verify(instanceDao, times(1)).runWorkflowInstances(any(), any(), anyInt()); assertEquals(100, instance.getWorkflowRunId()); ArgumentCaptor<RunRequest> captor = ArgumentCaptor.forClass(RunRequest.class); verify(workflowHelper, times(1)).updateWorkflowInstance(any(), captor.capture()); RunRequest res = captor.getValue(); assertEquals(RunPolicy.RESTART_FROM_INCOMPLETE, res.getCurrentPolicy()); assertEquals( RestartConfig.builder() .restartPolicy(RunPolicy.RESTART_FROM_INCOMPLETE) .downstreamPolicy(RunPolicy.RESTART_FROM_BEGINNING) .addRestartNode("maestro_foreach_x", 1, null) .build(), res.getRestartConfig()); }
@Override public long addedCount() { return tail; }
@Test public void testAddedCount() { assertEquals(0, queue.addedCount()); queue.offer(1); assertEquals(1, queue.addedCount()); }
@Override public String toString() { return data.toString(); }
@Test public void testToString() { List<StopReplicaPartitionError> errors = new ArrayList<>(); errors.add(new StopReplicaPartitionError().setTopicName("foo").setPartitionIndex(0)); errors.add(new StopReplicaPartitionError().setTopicName("foo").setPartitionIndex(1) .setErrorCode(Errors.CLUSTER_AUTHORIZATION_FAILED.code())); StopReplicaResponse response = new StopReplicaResponse(new StopReplicaResponseData().setPartitionErrors(errors)); String responseStr = response.toString(); assertTrue(responseStr.contains(StopReplicaResponse.class.getSimpleName())); assertTrue(responseStr.contains(errors.toString())); assertTrue(responseStr.contains("errorCode=" + Errors.NONE.code())); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { if(containerService.isContainer(file)) { final Storage.Buckets.Get request = session.getClient().buckets().get(containerService.getContainer(file).getName()); if(containerService.getContainer(file).attributes().getCustom().containsKey(GoogleStorageAttributesFinderFeature.KEY_REQUESTER_PAYS)) { request.setUserProject(session.getHost().getCredentials().getUsername()); } return this.toAttributes(request.execute()); } else { final Storage.Objects.Get get = session.getClient().objects().get( containerService.getContainer(file).getName(), containerService.getKey(file)); if(containerService.getContainer(file).attributes().getCustom().containsKey(GoogleStorageAttributesFinderFeature.KEY_REQUESTER_PAYS)) { get.setUserProject(session.getHost().getCredentials().getUsername()); } final VersioningConfiguration versioning = null != session.getFeature(Versioning.class) ? session.getFeature(Versioning.class).getConfiguration( containerService.getContainer(file) ) : VersioningConfiguration.empty(); if(versioning.isEnabled()) { if(StringUtils.isNotBlank(file.attributes().getVersionId())) { get.setGeneration(Long.parseLong(file.attributes().getVersionId())); } } final PathAttributes attributes; try { attributes = this.toAttributes(get.execute()); } catch(IOException e) { if(file.isDirectory()) { final BackgroundException failure = new GoogleStorageExceptionMappingService().map("Failure to read attributes of {0}", e, file); if(failure instanceof NotfoundException) { if(log.isDebugEnabled()) { log.debug(String.format("Search for common prefix %s", file)); } // File may be marked as placeholder but no placeholder file exists. Check for common prefix returned. try { new GoogleStorageObjectListService(session).list(file, new CancellingListProgressListener(), String.valueOf(Path.DELIMITER), 1, VersioningConfiguration.empty()); } catch(ListCanceledException l) { // Found common prefix return PathAttributes.EMPTY; } catch(NotfoundException n) { throw e; } // Found common prefix return PathAttributes.EMPTY; } } throw e; } if(versioning.isEnabled()) { // Determine if latest version try { // Duplicate if not latest version final Storage.Objects.Get request = session.getClient().objects().get( containerService.getContainer(file).getName(), containerService.getKey(file)); if(containerService.getContainer(file).attributes().getCustom().containsKey(GoogleStorageAttributesFinderFeature.KEY_REQUESTER_PAYS)) { request.setUserProject(session.getHost().getCredentials().getUsername()); } final String latest = this.toAttributes(request.execute()).getVersionId(); if(null != latest) { attributes.setDuplicate(!latest.equals(attributes.getVersionId())); } } catch(IOException e) { // Noncurrent versions only appear in requests that explicitly call for object versions to be included final BackgroundException failure = new GoogleStorageExceptionMappingService().map("Failure to read attributes of {0}", e, file); if(failure instanceof NotfoundException) { // The latest version is a delete marker attributes.setDuplicate(true); } else { throw failure; } } } return attributes; } } catch(IOException e) { throw new GoogleStorageExceptionMappingService().map("Failure to read attributes of {0}", e, file); } }
@Test public void testFindCommonPrefix() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); assertTrue(new GoogleStorageFindFeature(session).find(container)); final String prefix = new AlphanumericRandomStringService().random(); final Path test = new GoogleStorageTouchFeature(session).touch( new Path(new Path(container, prefix, EnumSet.of(Path.Type.directory)), new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus()); assertNotNull(new GoogleStorageAttributesFinderFeature(session).find(test)); assertNotNull(new GoogleStorageAttributesFinderFeature(session).find(new Path(container, prefix, EnumSet.of(Path.Type.directory)))); new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); try { new GoogleStorageAttributesFinderFeature(session).find(test); fail(); } catch(NotfoundException e) { // Expected } try { new GoogleStorageAttributesFinderFeature(session).find(new Path(container, prefix, EnumSet.of(Path.Type.directory))); fail(); } catch(NotfoundException e) { // Expected } }
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) { return invoke(n, BigDecimal.ZERO); }
@Test void invokeRoundingEven() { FunctionTestUtil.assertResult(roundHalfUpFunction.invoke(BigDecimal.valueOf(10.25)), BigDecimal.valueOf(10)); FunctionTestUtil.assertResult(roundHalfUpFunction.invoke(BigDecimal.valueOf(10.25), BigDecimal.ONE), BigDecimal.valueOf(10.3)); }
private void updateServiceInstance(Object result) { final Optional<Object> getServer = ReflectUtils.invokeMethod(result, "getServer", null, null); if (!getServer.isPresent()) { return; } RetryContext.INSTANCE.updateServiceInstance(getServer.get()); }
@Test public void testBefore() throws Exception { final Interceptor interceptor = getInterceptor(); final ExecuteContext context = interceptor.before(TestHelper.buildDefaultContext()); assertNull(context.getResult()); final RetryRule retryRule = new RetryRule(); retryRule.setRetryOnSame(3); RetryContext.INSTANCE.buildRetryPolicy(retryRule); final Object instance = new Object(); // simulated update instance RetryContext.INSTANCE.updateServiceInstance(instance); interceptor.before(context); assertNull(context.getResult()); RetryContext.INSTANCE.remove(); }
public static List<Chunk> split(String s) { int pos = s.indexOf(SLASH); if (pos == -1) { throw new RuntimeException("path did not start with or contain '/'"); } List<Chunk> list = new ArrayList(); int startPos = 0; int searchPos = 0; boolean anyDepth = false; while (pos != -1) { if (pos == 0) { startPos = 1; searchPos = 1; } else if (s.charAt(pos - 1) == '\\') { s = s.substring(0, pos - 1) + s.substring(pos); searchPos = pos; } else { String temp = s.substring(startPos, pos); if (temp.isEmpty()) { anyDepth = true; } else { list.add(new Chunk(anyDepth, temp)); anyDepth = false; // reset } startPos = pos + 1; searchPos = startPos; } pos = s.indexOf(SLASH, searchPos); } if (startPos != s.length()) { String temp = s.substring(startPos); if (!temp.isEmpty()) { list.add(new Chunk(anyDepth, temp)); } } return list; }
@Test void testPathEdge() { List<PathSearch.Chunk> list = PathSearch.split("/hello//world"); logger.debug("list: {}", list); PathSearch.Chunk first = list.get(0); assertFalse(first.anyDepth); assertEquals("hello", first.controlType); PathSearch.Chunk second = list.get(1); assertTrue(second.anyDepth); assertEquals("world", second.controlType); }
@Override public CompletableFuture<Void> readAsync(String path, OutputStream outputStream) { return openLogManagerAsync(path) .thenCompose(DLInputStream::openReaderAsync) .thenCompose(dlInputStream -> dlInputStream.readAsync(outputStream)) .thenCompose(DLInputStream::closeAsync); }
@Test(timeOut = 60000) public void testReadNonExistentData() { String testPath = "non-existent-path"; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { storage.readAsync(testPath, outputStream).get(); } catch (Exception e) { assertTrue(e.getCause() instanceof LogNotFoundException); } }
public T getNewState() { return newState; }
@Test public void testGetNewState() { assertEquals(ClusterState.ACTIVE, clusterStateChange.getNewState()); assertEquals(ClusterState.ACTIVE, clusterStateChangeSameAttributes.getNewState()); assertEquals(Version.UNKNOWN, clusterStateChangeOtherType.getNewState()); assertEquals(ClusterState.FROZEN, clusterStateChangeOtherNewState.getNewState()); }
@Override protected void validateDataImpl(TenantId tenantId, DeviceProfile deviceProfile) { validateString("Device profile name", deviceProfile.getName()); if (deviceProfile.getType() == null) { throw new DataValidationException("Device profile type should be specified!"); } if (deviceProfile.getTransportType() == null) { throw new DataValidationException("Device profile transport type should be specified!"); } if (deviceProfile.getTenantId() == null) { throw new DataValidationException("Device profile should be assigned to tenant!"); } else { if (!tenantService.tenantExists(deviceProfile.getTenantId())) { throw new DataValidationException("Device profile is referencing to non-existent tenant!"); } } if (deviceProfile.isDefault()) { DeviceProfile defaultDeviceProfile = deviceProfileService.findDefaultDeviceProfile(tenantId); if (defaultDeviceProfile != null && !defaultDeviceProfile.getId().equals(deviceProfile.getId())) { throw new DataValidationException("Another default device profile is present in scope of current tenant!"); } } if (StringUtils.isNotEmpty(deviceProfile.getDefaultQueueName())) { Queue queue = queueService.findQueueByTenantIdAndName(tenantId, deviceProfile.getDefaultQueueName()); if (queue == null) { throw new DataValidationException("Device profile is referencing to non-existent queue!"); } } if (deviceProfile.getProvisionType() == null) { deviceProfile.setProvisionType(DeviceProfileProvisionType.DISABLED); } if (deviceProfile.getProvisionDeviceKey() != null && DeviceProfileProvisionType.X509_CERTIFICATE_CHAIN.equals(deviceProfile.getProvisionType())) { if (isDeviceProfileCertificateInJavaCacerts(deviceProfile.getProfileData().getProvisionConfiguration().getProvisionDeviceSecret())) { throw new DataValidationException("Device profile certificate cannot be well known root CA!"); } } DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); transportConfiguration.validate(); if (transportConfiguration instanceof MqttDeviceProfileTransportConfiguration) { MqttDeviceProfileTransportConfiguration mqttTransportConfiguration = (MqttDeviceProfileTransportConfiguration) transportConfiguration; if (mqttTransportConfiguration.getTransportPayloadTypeConfiguration() instanceof ProtoTransportPayloadConfiguration) { ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = (ProtoTransportPayloadConfiguration) mqttTransportConfiguration.getTransportPayloadTypeConfiguration(); validateProtoSchemas(protoTransportPayloadConfiguration); validateTelemetryDynamicMessageFields(protoTransportPayloadConfiguration); validateRpcRequestDynamicMessageFields(protoTransportPayloadConfiguration); } } else if (transportConfiguration instanceof CoapDeviceProfileTransportConfiguration) { CoapDeviceProfileTransportConfiguration coapDeviceProfileTransportConfiguration = (CoapDeviceProfileTransportConfiguration) transportConfiguration; CoapDeviceTypeConfiguration coapDeviceTypeConfiguration = coapDeviceProfileTransportConfiguration.getCoapDeviceTypeConfiguration(); if (coapDeviceTypeConfiguration instanceof DefaultCoapDeviceTypeConfiguration) { DefaultCoapDeviceTypeConfiguration defaultCoapDeviceTypeConfiguration = (DefaultCoapDeviceTypeConfiguration) coapDeviceTypeConfiguration; TransportPayloadTypeConfiguration transportPayloadTypeConfiguration = defaultCoapDeviceTypeConfiguration.getTransportPayloadTypeConfiguration(); if (transportPayloadTypeConfiguration instanceof ProtoTransportPayloadConfiguration) { ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = (ProtoTransportPayloadConfiguration) transportPayloadTypeConfiguration; validateProtoSchemas(protoTransportPayloadConfiguration); validateTelemetryDynamicMessageFields(protoTransportPayloadConfiguration); validateRpcRequestDynamicMessageFields(protoTransportPayloadConfiguration); } } } else if (transportConfiguration instanceof Lwm2mDeviceProfileTransportConfiguration) { List<LwM2MBootstrapServerCredential> lwM2MBootstrapServersConfigurations = ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).getBootstrap(); if (lwM2MBootstrapServersConfigurations != null) { validateLwm2mServersConfigOfBootstrapForClient(lwM2MBootstrapServersConfigurations, ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).isBootstrapServerUpdateEnable()); for (LwM2MBootstrapServerCredential bootstrapServerCredential : lwM2MBootstrapServersConfigurations) { validateLwm2mServersCredentialOfBootstrapForClient(bootstrapServerCredential); } } } List<DeviceProfileAlarm> profileAlarms = deviceProfile.getProfileData().getAlarms(); if (!CollectionUtils.isEmpty(profileAlarms)) { Set<String> alarmTypes = new HashSet<>(); for (DeviceProfileAlarm alarm : profileAlarms) { String alarmType = alarm.getAlarmType(); if (StringUtils.isEmpty(alarmType)) { throw new DataValidationException("Alarm rule type should be specified!"); } if (!alarmTypes.add(alarmType)) { throw new DataValidationException(String.format("Can't create device profile with the same alarm rule types: \"%s\"!", alarmType)); } } } if (deviceProfile.getDefaultRuleChainId() != null) { RuleChain ruleChain = ruleChainService.findRuleChainById(tenantId, deviceProfile.getDefaultRuleChainId()); if (ruleChain == null) { throw new DataValidationException("Can't assign non-existent rule chain!"); } if (!ruleChain.getTenantId().equals(deviceProfile.getTenantId())) { throw new DataValidationException("Can't assign rule chain from different tenant!"); } } if (deviceProfile.getDefaultDashboardId() != null) { DashboardInfo dashboard = dashboardService.findDashboardInfoById(tenantId, deviceProfile.getDefaultDashboardId()); if (dashboard == null) { throw new DataValidationException("Can't assign non-existent dashboard!"); } if (!dashboard.getTenantId().equals(deviceProfile.getTenantId())) { throw new DataValidationException("Can't assign dashboard from different tenant!"); } } validateOtaPackage(tenantId, deviceProfile, deviceProfile.getId()); }
@Test void testValidateDeviceProfile_Lwm2mBootstrap_ShortServerId_Ok() { Integer shortServerId = 123; Integer shortServerIdBs = 0; DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs); validator.validateDataImpl(tenantId, deviceProfile); verify(validator).validateString("Device profile name", deviceProfile.getName()); }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Credentials Credentials = (Credentials) o; return Objects.equals(username, Credentials.username) && Objects.equals(password, Credentials.password); }
@Test public void testList() { String username = "Prometheus"; String password = "secret"; Credentials credentials1 = new Credentials(username, password); Credentials credentials2 = new Credentials(username, password + "X"); assertFalse(credentials1.equals(credentials2)); }
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) { final Fetch<K, V> fetch = Fetch.empty(); final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>(); int recordsRemaining = fetchConfig.maxPollRecords; try { while (recordsRemaining > 0) { final CompletedFetch nextInLineFetch = fetchBuffer.nextInLineFetch(); if (nextInLineFetch == null || nextInLineFetch.isConsumed()) { final CompletedFetch completedFetch = fetchBuffer.peek(); if (completedFetch == null) break; if (!completedFetch.isInitialized()) { try { fetchBuffer.setNextInLineFetch(initialize(completedFetch)); } catch (Exception e) { // Remove a completedFetch upon a parse with exception if (1) it contains no completedFetch, and // (2) there are no fetched completedFetch with actual content preceding this exception. // The first condition ensures that the completedFetches is not stuck with the same completedFetch // in cases such as the TopicAuthorizationException, and the second condition ensures that no // potential data loss due to an exception in a following record. if (fetch.isEmpty() && FetchResponse.recordsOrFail(completedFetch.partitionData).sizeInBytes() == 0) fetchBuffer.poll(); throw e; } } else { fetchBuffer.setNextInLineFetch(completedFetch); } fetchBuffer.poll(); } else if (subscriptions.isPaused(nextInLineFetch.partition)) { // when the partition is paused we add the records back to the completedFetches queue instead of draining // them so that they can be returned on a subsequent poll if the partition is resumed at that time log.debug("Skipping fetching records for assigned partition {} because it is paused", nextInLineFetch.partition); pausedCompletedFetches.add(nextInLineFetch); fetchBuffer.setNextInLineFetch(null); } else { final Fetch<K, V> nextFetch = fetchRecords(nextInLineFetch, recordsRemaining); recordsRemaining -= nextFetch.numRecords(); fetch.add(nextFetch); } } } catch (KafkaException e) { if (fetch.isEmpty()) throw e; } finally { // add any polled completed fetches for paused partitions back to the completed fetches queue to be // re-evaluated in the next poll fetchBuffer.addAll(pausedCompletedFetches); } return fetch; }
@Test public void testCollectFetchInitializationWithUpdateHighWatermarkOnNotAssignedPartition() { final TopicPartition topicPartition0 = new TopicPartition("topic", 0); final long fetchOffset = 42; final long highWatermark = 1000; final SubscriptionState subscriptions = mock(SubscriptionState.class); when(subscriptions.hasValidPosition(topicPartition0)).thenReturn(true); when(subscriptions.positionOrNull(topicPartition0)).thenReturn(new SubscriptionState.FetchPosition(fetchOffset)); when(subscriptions.tryUpdatingHighWatermark(topicPartition0, highWatermark)).thenReturn(false); final FetchCollector<String, String> fetchCollector = createFetchCollector(subscriptions); final Records records = createRecords(); FetchResponseData.PartitionData partitionData = new FetchResponseData.PartitionData() .setPartitionIndex(topicPartition0.partition()) .setHighWatermark(highWatermark) .setRecords(records); final CompletedFetch completedFetch = new CompletedFetchBuilder() .partitionData(partitionData) .partition(topicPartition0) .fetchOffset(fetchOffset).build(); final FetchBuffer fetchBuffer = mock(FetchBuffer.class); when(fetchBuffer.nextInLineFetch()).thenReturn(null); when(fetchBuffer.peek()).thenReturn(completedFetch).thenReturn(null); final Fetch<String, String> fetch = fetchCollector.collectFetch(fetchBuffer); assertTrue(fetch.isEmpty()); verify(fetchBuffer).setNextInLineFetch(null); }
public static Table resolveCalciteTable(SchemaPlus schemaPlus, List<String> tablePath) { Schema subSchema = schemaPlus; // subSchema.getSubschema() for all except last for (int i = 0; i < tablePath.size() - 1; i++) { subSchema = subSchema.getSubSchema(tablePath.get(i)); if (subSchema == null) { throw new IllegalStateException( String.format( "While resolving table path %s, no sub-schema found for component %s (\"%s\")", tablePath, i, tablePath.get(i))); } } // for the final one call getTable() return subSchema.getTable(Iterables.getLast(tablePath)); }
@Test public void testMissingSubschema() { String subSchema = "fake_schema"; String tableName = "fake_table"; when(mockSchemaPlus.getSubSchema(subSchema)).thenReturn(null); Assert.assertThrows( IllegalStateException.class, () -> { TableResolution.resolveCalciteTable( mockSchemaPlus, ImmutableList.of(subSchema, tableName)); }); }
public Integer doCall() throws Exception { if (all) { client(Integration.class).delete(); printer().println("Integrations deleted"); } else { if (names == null) { throw new RuntimeCamelException("Missing integration name as argument or --all option."); } for (String name : Arrays.stream(names).map(KubernetesHelper::sanitize).toList()) { List<StatusDetails> status = client(Integration.class).withName(name).delete(); if (status.isEmpty()) { printer().printf("Integration %s deletion skipped - not found%n", name); } else { printer().printf("Integration %s deleted%n", name); } } } return 0; }
@Test public void shouldHandleIntegrationNotFound() throws Exception { IntegrationDelete command = createCommand(); command.names = new String[] { "mickey-mouse" }; command.doCall(); Assertions.assertEquals("Integration mickey-mouse deletion skipped - not found", printer.getOutput()); }