focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public List<String> build() { return switch (dialect.getId()) { case Oracle.ID -> forOracle(tableName); case H2.ID, PostgreSql.ID -> singletonList("drop table if exists " + tableName); case MsSql.ID -> // "if exists" is supported only since MSSQL 2016. singletonList("drop table " + tableName); default -> throw new IllegalStateException("Unsupported DB: " + dialect.getId()); }; }
@Test public void drop_tables_on_mssql() { assertThat(new DropTableBuilder(new MsSql(), "issues") .build()).containsOnly("drop table issues"); }
Mono<ResponseEntity<Void>> save(Post post) { return client.post() .uri("/posts") .contentType(MediaType.APPLICATION_JSON) .bodyValue(post) .exchangeToMono(response -> { if (response.statusCode().equals(HttpStatus.CREATED)) { return response.toBodilessEntity(); } return response.createError(); }); }
@SneakyThrows @Test public void testCreatePost() { var id = UUID.randomUUID(); var data = new Post(null, "title1", "content1", Status.DRAFT, null); stubFor(post("/posts") .willReturn( aResponse() .withHeader("Location", "/posts/" + id) .withStatus(201) ) ); postClient.save(data) .as(StepVerifier::create) .consumeNextWith( entity -> { assertThat(entity.getHeaders().getLocation().toString()).isEqualTo("/posts/" + id); assertThat(entity.getStatusCode().value()).isEqualTo(201); } ) .verifyComplete(); verify(postRequestedFor(urlEqualTo("/posts")) .withHeader("Content-Type", equalTo("application/json")) .withRequestBody(equalToJson(Json.write(data))) ); }
static void populateOutputFields(final PMML4Result toUpdate, final ProcessingDTO processingDTO) { logger.debug("populateOutputFields {} {}", toUpdate, processingDTO); for (KiePMMLOutputField outputField : processingDTO.getOutputFields()) { Object variableValue = outputField.evaluate(processingDTO); if (variableValue != null) { String variableName = outputField.getName(); toUpdate.addResultVariable(variableName, variableValue); processingDTO.addKiePMMLNameValue(new KiePMMLNameValue(variableName, variableValue)); } } }
@Test void populateTransformedOutputFieldWithApplyWithConstants() { // <Apply function="/"> // <Constant>100.0</Constant> // <Constant>5.0</Constant> // </Apply> KiePMMLConstant kiePMMLConstant1 = new KiePMMLConstant(PARAM_1, Collections.emptyList(), value1, null); KiePMMLConstant kiePMMLConstant2 = new KiePMMLConstant(PARAM_2, Collections.emptyList(), value2, null); KiePMMLApply kiePMMLApply = KiePMMLApply.builder("NAME", Collections.emptyList(), "/") .withKiePMMLExpressions(Arrays.asList(kiePMMLConstant1, kiePMMLConstant2)) .build(); KiePMMLOutputField outputField = KiePMMLOutputField.builder(OUTPUT_NAME, Collections.emptyList()) .withResultFeature(RESULT_FEATURE.TRANSFORMED_VALUE) .withKiePMMLExpression(kiePMMLApply) .build(); KiePMMLTestingModel kiePMMLModel = testingModelBuilder(outputField).build(); ProcessingDTO processingDTO = buildProcessingDTOWithEmptyNameValues(kiePMMLModel); PMML4Result toUpdate = new PMML4Result(); PostProcess.populateOutputFields(toUpdate, processingDTO); assertThat(toUpdate.getResultVariables()).isNotEmpty(); assertThat(toUpdate.getResultVariables()).containsKey(OUTPUT_NAME); assertThat(toUpdate.getResultVariables().get(OUTPUT_NAME)).isEqualTo(value1 / value2); }
public static String storeChangelogTopic(final String prefix, final String storeName, final String namedTopology) { if (namedTopology == null) { return prefix + "-" + storeName + STATE_CHANGELOG_TOPIC_SUFFIX; } else { return prefix + "-" + namedTopology + "-" + storeName + STATE_CHANGELOG_TOPIC_SUFFIX; } }
@Test public void shouldReturnDefaultChangelogTopicName() { final String applicationId = "appId"; final String storeName = "store"; assertThat( ProcessorStateManager.storeChangelogTopic(applicationId, storeName, null), is(applicationId + "-" + storeName + "-changelog") ); }
@Override protected void route(List<SendingMailbox> sendingMailboxes, TransferableBlock block) throws Exception { sendBlock(sendingMailboxes.get(0), block); }
@Test public void shouldRouteSingleton() throws Exception { // Given: ImmutableList<SendingMailbox> destinations = ImmutableList.of(_mailbox1); // When: new SingletonExchange(destinations, TransferableBlockUtils::splitBlock).route(destinations, _block); // Then: ArgumentCaptor<TransferableBlock> captor = ArgumentCaptor.forClass(TransferableBlock.class); // Then: Mockito.verify(_mailbox1, Mockito.times(1)).send(captor.capture()); Assert.assertEquals(captor.getValue(), _block); }
@VisibleForTesting ZonedDateTime parseZoned(final String text, final ZoneId zoneId) { final TemporalAccessor parsed = formatter.parse(text); final ZoneId parsedZone = parsed.query(TemporalQueries.zone()); ZonedDateTime resolved = DEFAULT_ZONED_DATE_TIME.apply( ObjectUtils.defaultIfNull(parsedZone, zoneId)); for (final TemporalField override : ChronoField.values()) { if (parsed.isSupported(override)) { if (!resolved.isSupported(override)) { throw new KsqlException( "Unsupported temporal field in timestamp: " + text + " (" + override + ")"); } final long value = parsed.getLong(override); if (override == ChronoField.DAY_OF_YEAR && value == LEAP_DAY_OF_THE_YEAR) { if (!parsed.isSupported(ChronoField.YEAR)) { throw new KsqlException("Leap day cannot be parsed without supplying the year field"); } // eagerly override year, to avoid mismatch with epoch year, which is not a leap year resolved = resolved.withYear(parsed.get(ChronoField.YEAR)); } resolved = resolved.with(override, value); } } return resolved; }
@Test public void shouldParseFullLocalDateWithPartialSeconds() { // Given final String format = "yyyy-MM-dd HH:mm:ss:SSS"; final String timestamp = "1605-11-05 10:10:10:010"; // When final ZonedDateTime ts = new StringToTimestampParser(format).parseZoned(timestamp, ZID); // Then assertThat(ts, is(sameInstant(FIFTH_OF_NOVEMBER .withHour(10) .withMinute(10) .withSecond(10) .withNano(10_000_000)))); }
@Override public Timer timer(String name) { return NoopTimer.INSTANCE; }
@Test public void accessingACustomTimerRegistersAndReusesIt() { final MetricRegistry.MetricSupplier<Timer> supplier = () -> timer; final Timer timer1 = registry.timer("thing", supplier); final Timer timer2 = registry.timer("thing", supplier); assertThat(timer1).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); assertThat(timer2).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); assertThat(timer1).isSameAs(timer2); verify(listener, never()).onTimerAdded("thing", timer1); }
public static String escapeString(String str) { return escapeString(str, ESCAPE_CHAR, COMMA); }
@Test (timeout = 30000) public void testEscapeString() throws Exception { assertEquals(NULL_STR, StringUtils.escapeString(NULL_STR)); assertEquals(EMPTY_STR, StringUtils.escapeString(EMPTY_STR)); assertEquals(STR_WO_SPECIAL_CHARS, StringUtils.escapeString(STR_WO_SPECIAL_CHARS)); assertEquals(ESCAPED_STR_WITH_COMMA, StringUtils.escapeString(STR_WITH_COMMA)); assertEquals(ESCAPED_STR_WITH_ESCAPE, StringUtils.escapeString(STR_WITH_ESCAPE)); assertEquals(ESCAPED_STR_WITH_BOTH2, StringUtils.escapeString(STR_WITH_BOTH2)); }
@Deprecated @Override public void init(final ProcessorContext context, final StateStore root) { this.context = context instanceof InternalProcessorContext ? (InternalProcessorContext<?, ?>) context : null; taskId = context.taskId(); initStoreSerde(context); streamsMetrics = (StreamsMetricsImpl) context.metrics(); registerMetrics(); final Sensor restoreSensor = StateStoreMetrics.restoreSensor(taskId.toString(), metricsScope, name(), streamsMetrics); // register and possibly restore the state from the logs maybeMeasureLatency(() -> super.init(context, root), time, restoreSensor); }
@Test public void testMetrics() { store.init((StateStoreContext) context, store); final JmxReporter reporter = new JmxReporter(); final MetricsContext metricsContext = new KafkaMetricsContext("kafka.streams"); reporter.contextChange(metricsContext); metrics.addReporter(reporter); assertTrue(reporter.containsMbean(String.format( "kafka.streams:type=%s,%s=%s,task-id=%s,%s-state-id=%s", STORE_LEVEL_GROUP, THREAD_ID_TAG_KEY, threadId, context.taskId().toString(), STORE_TYPE, STORE_NAME ))); }
public static String getPartitionPath(TieredStoragePartitionId partitionId, String basePath) { if (basePath == null) { return null; } while (basePath.endsWith("/") && basePath.length() > 1) { basePath = basePath.substring(0, basePath.length() - 1); } return String.format("%s/%s", basePath, TieredStorageIdMappingUtils.convertId(partitionId)); }
@Test void testGetPartitionPath() { TieredStoragePartitionId partitionId = TieredStorageIdMappingUtils.convertId(new ResultPartitionID()); String partitionPath = SegmentPartitionFile.getPartitionPath(partitionId, tempFolder.getPath()); File partitionFile = new File( tempFolder.getPath(), TieredStorageIdMappingUtils.convertId(partitionId).toString()); assertThat(partitionPath).isEqualTo(partitionFile.getPath()); }
@Override public void isEqualTo(@Nullable Object expected) { super.isEqualTo(expected); }
@Test public void isEqualTo_WithoutToleranceParameter_Fail_PlusMinusZero() { expectFailureWhenTestingThat(array(0.0d)).isEqualTo(array(-0.0d)); assertFailureValue("expected", "[-0.0]"); assertFailureValue("but was", "[0.0]"); }
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call(configForEdit); config = preprocessAndValidate(configForEdit); return new GoConfigHolder(config, configForEdit); }
@Test void shouldLoadInvertFilterForScmMaterial() throws Exception { String content = config( """ <scms> <scm id="abcd" name="scm_name"> <pluginConfiguration id="GitPathMaterial" version="1" /> <configuration> <property> <key>url</key> <value>git@github.com:gocd/gocd.git</value> </property> </configuration> </scm> </scms> <pipelines group="first"> <pipeline name="pipeline"> <materials> <scm ref="abcd" invertFilter="true"/> </materials> <stage name="stage"> <jobs> <job name="functional"> <tasks> <exec command="echo"> <runif status="passed" /> </exec> </tasks> </job> </jobs> </stage> </pipeline> </pipelines>""", CONFIG_SCHEMA_VERSION); CruiseConfig config = xmlLoader.loadConfigHolder(goConfigMigration.upgradeIfNecessary(content)).config; MaterialConfig materialConfig = config .getPipelineConfigByName(new CaseInsensitiveString("pipeline")) .materialConfigs().get(0); assertThat(materialConfig).isInstanceOf(PluggableSCMMaterialConfig.class); assertThat(materialConfig.isInvertFilter()).isTrue(); }
public static boolean isBlankChar(char c) { return isBlankChar((int) c); }
@Test public void trimTest() { //此字符串中的第一个字符为不可见字符: '\u202a' final String str = "‪C:/Users/maple/Desktop/tone.txt"; assertEquals('\u202a', str.charAt(0)); assertTrue(CharUtil.isBlankChar(str.charAt(0))); }
public static StrimziPodSet createPodSet( String name, String namespace, Labels labels, OwnerReference ownerReference, ResourceTemplate template, int replicas, Map<String, String> annotations, Labels selectorLabels, Function<Integer, Pod> podCreator ) { List<Map<String, Object>> pods = new ArrayList<>(replicas); for (int i = 0; i < replicas; i++) { Pod pod = podCreator.apply(i); pods.add(PodSetUtils.podToMap(pod)); } return new StrimziPodSetBuilder() .withNewMetadata() .withName(name) .withLabels(labels.withAdditionalLabels(TemplateUtils.labels(template)).toMap()) .withNamespace(namespace) .withAnnotations(Util.mergeLabelsOrAnnotations(annotations, TemplateUtils.annotations(template))) .withOwnerReferences(ownerReference) .endMetadata() .withNewSpec() .withSelector(new LabelSelectorBuilder().withMatchLabels(selectorLabels.toMap()).build()) .withPods(pods) .endSpec() .build(); }
@Test public void testCreateStrimziPodSetWithNullTemplate() { List<Integer> podIds = new ArrayList<>(); StrimziPodSet sps = WorkloadUtils.createPodSet( NAME, NAMESPACE, LABELS, OWNER_REFERENCE, null, REPLICAS, Map.of("extra", "annotations"), LABELS.strimziSelectorLabels(), i -> { podIds.add(i); return new PodBuilder() .withNewMetadata() .withName(NAME + "-" + i) .endMetadata() .build(); } ); assertThat(sps.getMetadata().getName(), is(NAME)); assertThat(sps.getMetadata().getNamespace(), is(NAMESPACE)); assertThat(sps.getMetadata().getOwnerReferences(), is(List.of(OWNER_REFERENCE))); assertThat(sps.getMetadata().getLabels(), is(LABELS.toMap())); assertThat(sps.getMetadata().getAnnotations(), is(Map.of("extra", "annotations"))); assertThat(sps.getSpec().getSelector().getMatchLabels().size(), is(3)); assertThat(sps.getSpec().getSelector().getMatchLabels().get(Labels.STRIMZI_CLUSTER_LABEL), is("my-cluster")); assertThat(sps.getSpec().getSelector().getMatchLabels().get(Labels.STRIMZI_NAME_LABEL), is("my-workload")); assertThat(sps.getSpec().getSelector().getMatchLabels().get(Labels.STRIMZI_KIND_LABEL), is("my-kind")); // Test generating pods from the PodCreator method assertThat(podIds.size(), is(5)); assertThat(podIds, is(List.of(0, 1, 2, 3, 4))); assertThat(sps.getSpec().getPods().size(), is(5)); assertThat(sps.getSpec().getPods().stream().map(pod -> PodSetUtils.mapToPod(pod).getMetadata().getName()).toList(), is(List.of("my-workload-0", "my-workload-1", "my-workload-2", "my-workload-3", "my-workload-4"))); }
public static PTransformMatcher createViewWithViewFn(final Class<? extends ViewFn> viewFnType) { return application -> { if (!(application.getTransform() instanceof CreatePCollectionView)) { return false; } CreatePCollectionView<?, ?> createView = (CreatePCollectionView<?, ?>) application.getTransform(); ViewFn<?, ?> viewFn = createView.getView().getViewFn(); return viewFn.getClass().equals(viewFnType); }; }
@Test public void createViewWithViewFnNotCreatePCollectionView() { PCollection<Integer> input = p.apply(Create.of(1)); PCollectionView<Iterable<Integer>> view = input.apply(View.asIterable()); PTransformMatcher matcher = PTransformMatchers.createViewWithViewFn(view.getViewFn().getClass()); assertThat(matcher.matches(getAppliedTransform(View.asIterable())), is(false)); }
@Override public DeviceCredentials findByDeviceId(TenantId tenantId, UUID deviceId) { return DaoUtil.getData(deviceCredentialsRepository.findByDeviceId(deviceId)); }
@Test public void testFindByDeviceId() { DeviceCredentials foundedDeviceCredentials = deviceCredentialsDao.findByDeviceId(SYSTEM_TENANT_ID, neededDeviceCredentials.getDeviceId().getId()); assertNotNull(foundedDeviceCredentials); assertEquals(neededDeviceCredentials.getId(), foundedDeviceCredentials.getId()); assertEquals(neededDeviceCredentials.getCredentialsId(), foundedDeviceCredentials.getCredentialsId()); }
@Override public JooqEndpoint getEndpoint() { return (JooqEndpoint) super.getEndpoint(); }
@Test public void testConsumerDelete() throws InterruptedException { MockEndpoint mockResult = getMockEndpoint("mock:resultAuthorRecord"); MockEndpoint mockInserted = getMockEndpoint("mock:insertedAuthorRecord"); mockResult.expectedMessageCount(1); mockInserted.expectedMessageCount(1); ProducerTemplate producerTemplate = context.createProducerTemplate(); // Insert AuthorRecord authorRecord = new AuthorRecord(1, null, "test", null, null, null); producerTemplate.sendBody(context.getEndpoint("direct:insertAuthorRecord"), ExchangePattern.InOut, authorRecord); MockEndpoint.assertIsSatisfied(context); assertEquals(authorRecord, mockInserted.getExchanges().get(0).getMessage().getBody()); assertEquals(0, ((Result) mockResult.getExchanges().get(0).getMessage().getBody()).size()); }
public static String showControlCharacters(String str) { int len = str.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i += 1) { char c = str.charAt(i); switch (c) { case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: sb.append(c); } } return sb.toString(); }
@Test void testControlCharacters() { String testString = "\b \t \n \f \r default"; String controlString = StringUtils.showControlCharacters(testString); assertThat(controlString).isEqualTo("\\b \\t \\n \\f \\r default"); }
public static <T> T getItemAtPositionOrNull(Collection<T> collection, int position) { if (position >= collection.size() || position < 0) { return null; } if (collection instanceof List) { return ((List<T>) collection).get(position); } Iterator<T> iterator = collection.iterator(); T item = null; for (int i = 0; i < position + 1; i++) { item = iterator.next(); } return item; }
@Test public void testGetItemAtPositionOrNull_whenNegativePosition_thenReturnNull() { Object obj = new Object(); Collection<Object> src = new ArrayList<>(); src.add(obj); Object result = getItemAtPositionOrNull(src, -1); assertNull(result); }
@Override public String buildContext() { final SelectorDO after = (SelectorDO) getAfter(); if (Objects.isNull(getBefore())) { return String.format("the namespace [%s] selector [%s] is %s", after.getNamespaceId(), after.getName(), StringUtils.lowerCase(getType().getType().toString())); } return String.format("the namespace [%s] selector [%s] is %s : %s", after.getNamespaceId(), after.getName(), StringUtils.lowerCase(getType().getType().toString()), contrast()); }
@Test void buildContextAndBeforeNotNullAndAllChange() { SelectorChangedEvent selectorChangedEvent = new SelectorChangedEvent(before, after, EventTypeEnum.SELECTOR_CREATE, "test-operator"); SelectorDO before = (SelectorDO) selectorChangedEvent.getBefore(); SelectorDO after = (SelectorDO) selectorChangedEvent.getAfter(); final StringBuilder builder = new StringBuilder(); builder.append(String.format("name[%s => %s] ", before.getName(), after.getName())); builder.append(String.format("handle[%s => %s] ", before.getHandle(), after.getHandle())); builder.append(String.format("type[%s => %s] ", before.getType(), after.getType())); builder.append(String.format("enable[%s => %s] ", before.getEnabled(), after.getEnabled())); builder.append(String.format("sort[%s => %s] ", before.getSort(), after.getSort())); builder.append(String.format("loged[%s => %s] ", before.getLoged(), after.getLoged())); String changeMsg = builder.toString(); String expectMsg = String.format("the namespace [%s] selector [%s] is %s : %s", after.getNamespaceId(), after.getName(), StringUtils.lowerCase(selectorChangedEvent.getType().getType().toString()), changeMsg); String actualMsg = selectorChangedEvent.buildContext(); assertEquals(expectMsg, actualMsg); }
public static String sanitizeDescription(String javadoc, boolean summary) { if (isNullOrEmpty(javadoc)) { return null; } // lets just use what java accepts as identifiers StringBuilder sb = new StringBuilder(); // split into lines String[] lines = javadoc.split("\n"); boolean first = true; for (String line : lines) { line = line.trim(); if (line.startsWith("**")) { continue; } // remove leading javadoc * if (line.startsWith("*")) { line = line.substring(1); line = line.trim(); } // terminate if we reach @param, @return or @deprecated as we only want the javadoc summary if (line.startsWith("@param") || line.startsWith("@return") || line.startsWith("@deprecated")) { break; } // skip lines that are javadoc references if (line.startsWith("@")) { continue; } // we are starting from a new line, so add a whitespace if (!first) { sb.append(' '); } // append data String s = line.trim(); sb.append(s); boolean empty = isNullOrEmpty(s); boolean endWithDot = s.endsWith("."); boolean haveText = !sb.isEmpty(); if (haveText && summary && (empty || endWithDot)) { // if we only want a summary, then skip at first empty line we encounter, or if the sentence ends with a dot break; } first = false; } String s = sb.toString(); // remove all XML tags s = s.replaceAll("<.*?>", ""); // remove {@link inlined javadoc links which is special handled s = s.replaceAll("\\{@link\\s\\w+\\s(\\w+)}", "$1"); s = s.replaceAll("\\{@link\\s([\\w]+)}", "$1"); // also remove the commonly mistake to do with @{link s = s.replaceAll("@\\{link\\s\\w+\\s(\\w+)}", "$1"); s = s.replaceAll("@\\{link\\s([\\w]+)}", "$1"); // remove all inlined javadoc links, eg such as {@link org.apache.camel.spi.Registry} // use #? to remove leading # in case its a local reference s = s.replaceAll("\\{@\\w+\\s#?([\\w.#(\\d,)]+)}", "$1"); // create a new line StringBuilder cb = new StringBuilder(); for (char c : s.toCharArray()) { if (Character.isJavaIdentifierPart(c) || VALID_CHARS.indexOf(c) != -1) { cb.append(c); } else if (Character.isWhitespace(c)) { // always use space as whitespace, also for line feeds etc cb.append(' '); } } s = cb.toString(); // remove double whitespaces, and trim s = s.replaceAll("\\s+", " "); // unescape http links s = s.replaceAll("\\\\(http:|https:)", "$1"); return s.trim(); }
@Test public void testSanitizeJavaDocLink() throws Exception { String s = " * Provides methods to create, delete, find, and update {@link Customer}\n" + " * objects. This class does not need to be instantiated directly. Instead, use"; String s2 = JavadocHelper.sanitizeDescription(s, false); Assertions.assertEquals( "Provides methods to create, delete, find, and update Customer objects. This class does not need to be instantiated directly. Instead, use", s2); s = " * Provides methods to interact with {@link Transaction Transactions}.\n" + " * E.g. sales, credits, refunds, searches, etc.\n"; String s3 = JavadocHelper.sanitizeDescription(s, false); Assertions.assertEquals("Provides methods to interact with Transactions. E.g. sales, credits, refunds, searches, etc.", s3); }
@Override protected int rsv(WebSocketFrame msg) { return msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame? msg.rsv() | WebSocketExtension.RSV1 : msg.rsv(); }
@Test public void testSelectivityCompressionSkip() { WebSocketExtensionFilter selectivityCompressionFilter = new WebSocketExtensionFilter() { @Override public boolean mustSkip(WebSocketFrame frame) { return (frame instanceof TextWebSocketFrame || frame instanceof BinaryWebSocketFrame) && frame.content().readableBytes() < 100; } }; EmbeddedChannel encoderChannel = new EmbeddedChannel( new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter)); EmbeddedChannel decoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE)); String textPayload = "not compressed payload"; byte[] binaryPayload = new byte[101]; random.nextBytes(binaryPayload); WebSocketFrame textFrame = new TextWebSocketFrame(textPayload); BinaryWebSocketFrame binaryFrame = new BinaryWebSocketFrame(Unpooled.wrappedBuffer(binaryPayload)); assertTrue(encoderChannel.writeOutbound(textFrame)); assertTrue(encoderChannel.writeOutbound(binaryFrame)); WebSocketFrame outboundTextFrame = encoderChannel.readOutbound(); //compression skipped for textFrame assertEquals(0, outboundTextFrame.rsv()); assertEquals(textPayload, outboundTextFrame.content().toString(UTF_8)); assertTrue(outboundTextFrame.release()); WebSocketFrame outboundBinaryFrame = encoderChannel.readOutbound(); //compression not skipped for binaryFrame assertEquals(WebSocketExtension.RSV1, outboundBinaryFrame.rsv()); assertTrue(decoderChannel.writeInbound(outboundBinaryFrame.content().retain())); ByteBuf uncompressedBinaryPayload = decoderChannel.readInbound(); assertArrayEquals(binaryPayload, ByteBufUtil.getBytes(uncompressedBinaryPayload)); assertTrue(outboundBinaryFrame.release()); assertTrue(uncompressedBinaryPayload.release()); assertFalse(encoderChannel.finish()); assertFalse(decoderChannel.finish()); }
public static <K, V> StoreBuilder<KeyValueStore<K, V>> keyValueStoreBuilder(final KeyValueBytesStoreSupplier supplier, final Serde<K> keySerde, final Serde<V> valueSerde) { Objects.requireNonNull(supplier, "supplier cannot be null"); return new KeyValueStoreBuilder<>(supplier, keySerde, valueSerde, Time.SYSTEM); }
@Test public void shouldThrowIfSupplierIsNullForKeyValueStoreBuilder() { final Exception e = assertThrows(NullPointerException.class, () -> Stores.keyValueStoreBuilder(null, Serdes.ByteArray(), Serdes.ByteArray())); assertEquals("supplier cannot be null", e.getMessage()); }
@Override public DenyUserStatement getSqlStatement() { return (DenyUserStatement) super.getSqlStatement(); }
@Test void assertNewInstance() { SQLServerDenyUserStatement sqlStatement = new SQLServerDenyUserStatement(); SimpleTableSegment table = new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("tbl_1"))); sqlStatement.setTable(table); DenyUserStatementContext actual = new DenyUserStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME); assertThat(actual, instanceOf(CommonSQLStatementContext.class)); assertThat(actual.getSqlStatement(), is(sqlStatement)); assertThat(actual.getTablesContext().getSimpleTables().stream().map(each -> each.getTableName().getIdentifier().getValue()).collect(Collectors.toList()), is(Collections.singletonList("tbl_1"))); }
@SuppressWarnings("unchecked") @Udf public <T> List<T> union( @UdfParameter(description = "First array of values") final List<T> left, @UdfParameter(description = "Second array of values") final List<T> right) { if (left == null || right == null) { return null; } final Set<T> combined = Sets.newLinkedHashSet(left); combined.addAll(right); return (List<T>) Arrays.asList(combined.toArray()); }
@Test public void shouldUnionArraysBothContainingNulls() { final List<String> input1 = Arrays.asList(null, "foo", "bar"); final List<String> input2 = Arrays.asList("foo", null); final List<String> result = udf.union(input1, input2); assertThat(result, contains((String) null, "foo", "bar")); }
@SuppressWarnings("unchecked") @Override public boolean canHandleReturnType(Class returnType) { return rxSupportedTypes.stream() .anyMatch(classType -> classType.isAssignableFrom(returnType)); }
@Test public void testCheckTypes() { assertThat(rxJava3RateLimiterAspectExt.canHandleReturnType(Flowable.class)).isTrue(); assertThat(rxJava3RateLimiterAspectExt.canHandleReturnType(Single.class)).isTrue(); }
@Override public boolean addIfExists(Duration ttl, V object) { return get(addIfExistsAsync(ttl, object)); }
@Test public void testAddIfExists() throws InterruptedException { RSetCache<String> cache = redisson.getSetCache("list"); cache.add("a", 1, TimeUnit.SECONDS); assertThat(cache.addIfExists(Duration.ofSeconds(2), "a")).isTrue(); Thread.sleep(1500); assertThat(cache.contains("a")).isTrue(); Thread.sleep(700); assertThat(cache.contains("a")).isFalse(); }
@Override public void submit(ManagedQueryExecution queryExecution, SelectionContext<C> selectionContext, Executor executor) { checkState(configurationManager.get() != null, "configurationManager not set"); createGroupIfNecessary(selectionContext, executor); groups.get(selectionContext.getResourceGroupId()).run(queryExecution); }
@Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = ".*Presto server is still initializing.*") public void testQueryFailsWithInitializingConfigurationManager() { InternalResourceGroupManager<ImmutableMap<Object, Object>> internalResourceGroupManager = new InternalResourceGroupManager<>((poolId, listener) -> {}, new QueryManagerConfig(), new NodeInfo("test"), new MBeanExporter(new TestingMBeanServer()), () -> null, new ServerConfig(), new InMemoryNodeManager()); internalResourceGroupManager.submit(new MockManagedQueryExecution(0), new SelectionContext<>(new ResourceGroupId("global"), ImmutableMap.of()), command -> {}); }
@Override public TopicAssignment place( PlacementSpec placement, ClusterDescriber cluster ) throws InvalidReplicationFactorException { RackList rackList = new RackList(random, cluster.usableBrokers()); throwInvalidReplicationFactorIfNonPositive(placement.numReplicas()); throwInvalidReplicationFactorIfZero(rackList.numUnfencedBrokers()); throwInvalidReplicationFactorIfTooFewBrokers(placement.numReplicas(), rackList.numTotalBrokers()); List<List<Integer>> placements = new ArrayList<>(placement.numPartitions()); for (int partition = 0; partition < placement.numPartitions(); partition++) { placements.add(rackList.place(placement.numReplicas())); } return new TopicAssignment( placements.stream().map(replicas -> new PartitionAssignment(replicas, cluster)).collect(Collectors.toList()) ); }
@Test public void testEvenDistribution() { MockRandom random = new MockRandom(); StripedReplicaPlacer placer = new StripedReplicaPlacer(random); TopicAssignment topicAssignment = place(placer, 0, 200, (short) 2, Arrays.asList( new UsableBroker(0, Optional.empty(), false), new UsableBroker(1, Optional.empty(), false), new UsableBroker(2, Optional.empty(), false), new UsableBroker(3, Optional.empty(), false))); Map<List<Integer>, Integer> counts = new HashMap<>(); for (PartitionAssignment partitionAssignment : topicAssignment.assignments()) { counts.put(partitionAssignment.replicas(), counts.getOrDefault(partitionAssignment.replicas(), 0) + 1); } assertEquals(14, counts.get(Arrays.asList(0, 1))); assertEquals(22, counts.get(Arrays.asList(0, 2))); assertEquals(14, counts.get(Arrays.asList(0, 3))); assertEquals(17, counts.get(Arrays.asList(1, 0))); assertEquals(17, counts.get(Arrays.asList(1, 2))); assertEquals(16, counts.get(Arrays.asList(1, 3))); assertEquals(13, counts.get(Arrays.asList(2, 0))); assertEquals(17, counts.get(Arrays.asList(2, 1))); assertEquals(20, counts.get(Arrays.asList(2, 3))); assertEquals(20, counts.get(Arrays.asList(3, 0))); assertEquals(19, counts.get(Arrays.asList(3, 1))); assertEquals(11, counts.get(Arrays.asList(3, 2))); }
public boolean isService(Object bean, String beanName) { for (RemotingParser remotingParser : allRemotingParsers) { if (remotingParser.isService(bean, beanName)) { return true; } } return false; }
@Test public void testIsServiceFromClass() { assertTrue(remotingParser.isService(SimpleRemoteBean.class)); }
@Override public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) { ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id); if (errorLog == null) { throw exception(API_ERROR_LOG_NOT_FOUND); } if (!ApiErrorLogProcessStatusEnum.INIT.getStatus().equals(errorLog.getProcessStatus())) { throw exception(API_ERROR_LOG_PROCESSED); } // 标记处理 apiErrorLogMapper.updateById(ApiErrorLogDO.builder().id(id).processStatus(processStatus) .processUserId(processUserId).processTime(LocalDateTime.now()).build()); }
@Test public void testUpdateApiErrorLogProcess_notFound() { // 准备参数 Long id = randomLongId(); Integer processStatus = randomEle(ApiErrorLogProcessStatusEnum.values()).getStatus(); Long processUserId = randomLongId(); // 调用,并断言异常 assertServiceException(() -> apiErrorLogService.updateApiErrorLogProcess(id, processStatus, processUserId), API_ERROR_LOG_NOT_FOUND); }
public static GrpcUpstream buildAliveGrpcUpstream(final String upstreamUrl) { return GrpcUpstream.builder().upstreamUrl(upstreamUrl).weight(50) .timestamp(System.currentTimeMillis()).build(); }
@Test public void buildAliveGrpcUpstream() { GrpcUpstream grpcUpstream = CommonUpstreamUtils.buildAliveGrpcUpstream(HOST); Assert.assertNotNull(grpcUpstream); Assert.assertEquals(HOST, grpcUpstream.getUpstreamUrl()); Assert.assertNull(grpcUpstream.getProtocol()); }
@Override public void createPod(Pod pod) { checkNotNull(pod, ERR_NULL_POD); checkArgument(!Strings.isNullOrEmpty(pod.getMetadata().getUid()), ERR_NULL_POD_UID); k8sPodStore.createPod(pod); log.info(String.format(MSG_POD, pod.getMetadata().getName(), MSG_CREATED)); }
@Test(expected = IllegalArgumentException.class) public void testCreateDuplicatePod() { target.createPod(POD); target.createPod(POD); }
@Override public AuthenticationDataSource getAuthDataSource() { return authenticationDataSource; }
@Test void getAuthDataOnAuthStateShouldBeNullIfNotAuthenticated() { AuthenticationStateOpenID state = new AuthenticationStateOpenID(null, null, null); assertNull(state.getAuthDataSource()); }
public static Expression substituteBoolExpression(ConfigVariableExpander cve, Expression expression) { try { if (expression instanceof BinaryBooleanExpression) { BinaryBooleanExpression binaryBoolExp = (BinaryBooleanExpression) expression; Expression substitutedLeftExp = substituteBoolExpression(cve, binaryBoolExp.getLeft()); Expression substitutedRightExp = substituteBoolExpression(cve, binaryBoolExp.getRight()); if (substitutedLeftExp != binaryBoolExp.getLeft() || substitutedRightExp != binaryBoolExp.getRight()) { Constructor<? extends BinaryBooleanExpression> constructor = binaryBoolExp.getClass().getConstructor(SourceWithMetadata.class, Expression.class, Expression.class); return constructor.newInstance(binaryBoolExp.getSourceWithMetadata(), substitutedLeftExp, substitutedRightExp); } } else if (expression instanceof UnaryBooleanExpression) { UnaryBooleanExpression unaryBoolExp = (UnaryBooleanExpression) expression; Expression substitutedExp = substituteBoolExpression(cve, unaryBoolExp.getExpression()); if (substitutedExp != unaryBoolExp.getExpression()) { Constructor<? extends UnaryBooleanExpression> constructor = unaryBoolExp.getClass().getConstructor(SourceWithMetadata.class, Expression.class); return constructor.newInstance(unaryBoolExp.getSourceWithMetadata(), substitutedExp); } } else if (expression instanceof ValueExpression && !(expression instanceof RegexValueExpression) && (((ValueExpression) expression).get() != null)) { Object expanded = CompiledPipeline.expandConfigVariableKeepingSecrets(cve, ((ValueExpression) expression).get()); return new ValueExpression(expression.getSourceWithMetadata(), expanded); } return expression; } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException | InvalidIRException e) { throw new IllegalStateException("Unable to instantiate substituted condition expression", e); } }
@Test public void basicBinaryBooleanSubstitution() throws InvalidIRException { SourceWithMetadata swm = new SourceWithMetadata("proto", "path", 1, 8, "if \"${SMALL}\" == 1 { add_tag => \"pass\" }"); ValueExpression left = new ValueExpression(swm, "${SMALL}"); ValueExpression right = new ValueExpression(swm, "1"); BinaryBooleanExpression expression = new Eq(swm, left, right); ConfigVariableExpander cve = getConfigVariableExpander(); BinaryBooleanExpression substituted = (BinaryBooleanExpression) ExpressionSubstitution.substituteBoolExpression(cve, expression); assertEquals(((ValueExpression) substituted.getLeft()).get(), "1"); }
public <T> Flux<PushNotificationExperimentSample<T>> getSamples(final String experimentName, final Class<T> stateClass) { return Flux.from(dynamoDbAsyncClient.queryPaginator(QueryRequest.builder() .tableName(tableName) .keyConditionExpression("#experiment = :experiment") .expressionAttributeNames(Map.of("#experiment", KEY_EXPERIMENT_NAME)) .expressionAttributeValues(Map.of(":experiment", AttributeValue.fromS(experimentName))) .build()) .items()) .handle((item, sink) -> { try { final Tuple2<UUID, Byte> aciAndDeviceId = parseSortKey(item.get(ATTR_ACI_AND_DEVICE_ID)); final boolean inExperimentGroup = item.get(ATTR_IN_EXPERIMENT_GROUP).bool(); final T initialState = parseState(item.get(ATTR_INITIAL_STATE).s(), stateClass); final T finalState = item.get(ATTR_FINAL_STATE) != null ? parseState(item.get(ATTR_FINAL_STATE).s(), stateClass) : null; sink.next(new PushNotificationExperimentSample<>(aciAndDeviceId.getT1(), aciAndDeviceId.getT2(), inExperimentGroup, initialState, finalState)); } catch (final JsonProcessingException e) { sink.error(e); } }); }
@Test void getSamples() throws JsonProcessingException { final String experimentName = "test-experiment"; final UUID initialSampleAccountIdentifier = UUID.randomUUID(); final byte initialSampleDeviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID); final boolean initialSampleInExperimentGroup = ThreadLocalRandom.current().nextBoolean(); final UUID finalSampleAccountIdentifier = UUID.randomUUID(); final byte finalSampleDeviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID); final boolean finalSampleInExperimentGroup = ThreadLocalRandom.current().nextBoolean(); final int initialBounciness = ThreadLocalRandom.current().nextInt(); final int finalBounciness = initialBounciness + 17; pushNotificationExperimentSamples.recordInitialState(initialSampleAccountIdentifier, initialSampleDeviceId, experimentName, initialSampleInExperimentGroup, new TestDeviceState(initialBounciness)) .join(); pushNotificationExperimentSamples.recordInitialState(finalSampleAccountIdentifier, finalSampleDeviceId, experimentName, finalSampleInExperimentGroup, new TestDeviceState(initialBounciness)) .join(); pushNotificationExperimentSamples.recordFinalState(finalSampleAccountIdentifier, finalSampleDeviceId, experimentName, new TestDeviceState(finalBounciness)) .join(); pushNotificationExperimentSamples.recordInitialState(UUID.randomUUID(), (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID), experimentName + "-different", ThreadLocalRandom.current().nextBoolean(), new TestDeviceState(ThreadLocalRandom.current().nextInt())) .join(); final Set<PushNotificationExperimentSample<TestDeviceState>> expectedSamples = Set.of( new PushNotificationExperimentSample<>(initialSampleAccountIdentifier, initialSampleDeviceId, initialSampleInExperimentGroup, new TestDeviceState(initialBounciness), null), new PushNotificationExperimentSample<>(finalSampleAccountIdentifier, finalSampleDeviceId, finalSampleInExperimentGroup, new TestDeviceState(initialBounciness), new TestDeviceState(finalBounciness))); assertEquals(expectedSamples, pushNotificationExperimentSamples.getSamples(experimentName, TestDeviceState.class).collect(Collectors.toSet()).block()); }
@Override public Map<String, String> getMetadata() { return metadata; }
@Test public void testGetNacosMetadata() { String clusterName = "cluster"; when(nacosContextProperties.getClusterName()).thenReturn(clusterName); Map<String, String> metadata = polarisRegistration1.getMetadata(); assertThat(metadata).isNotNull(); assertThat(metadata).isNotEmpty(); assertThat(metadata.size()).isEqualTo(2); assertThat(metadata.get("nacos.cluster")).isEqualTo(clusterName); }
@Override public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { final SoftwareVersionData version = this.softwareVersion(); final Matcher matcher = Pattern.compile(VERSION_REGEX).matcher(version.getRestApiVersion()); if(matcher.matches()) { if(new Version(matcher.group(1)).compareTo(new Version(preferences.getProperty("sds.version.lts"))) < 0) { throw new InteroperabilityException( LocaleFactory.localizedString("DRACOON environment needs to be updated", "SDS"), LocaleFactory.localizedString("Your DRACOON environment is outdated and no longer works with this application. Please contact your administrator.", "SDS")); } } final Credentials credentials; // The provided token is valid for two hours, every usage resets this period to two full hours again. Logging off invalidates the token. switch(SDSProtocol.Authorization.valueOf(host.getProtocol().getAuthorization())) { case oauth: case password: if("x-dracoon-action:oauth".equals(CYBERDUCK_REDIRECT_URI)) { if(matcher.matches()) { if(new Version(matcher.group(1)).compareTo(new Version("4.15.0")) >= 0) { authorizationService.withRedirectUri(CYBERDUCK_REDIRECT_URI); } } else { log.warn(String.format("Failure to parse software version %s", version)); } } credentials = authorizationService.validate(); break; default: credentials = host.getCredentials(); } final UserAccount account; try { account = new UserApi(client).requestUserInfo(StringUtils.EMPTY, false, null); if(log.isDebugEnabled()) { log.debug(String.format("Authenticated as user %s", account)); } } catch(ApiException e) { throw new SDSExceptionMappingService(nodeid).map(e); } switch(SDSProtocol.Authorization.valueOf(host.getProtocol().getAuthorization())) { case oauth: credentials.setUsername(account.getLogin()); } userAccount.set(new UserAccountWrapper(account)); requiredKeyPairVersion = this.getRequiredKeyPairVersion(); this.unlockTripleCryptKeyPair(prompt, userAccount.get(), requiredKeyPairVersion); this.updateDirectS3UploadSetting(); }
@Test(expected = LoginCanceledException.class) public void testLoginOAuthExpiredRefreshToken() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new SDSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( this.getClass().getResourceAsStream("/DRACOON (OAuth).cyberduckprofile")); final Host host = new Host(profile, "duck.dracoon.com", new Credentials( System.getProperties().getProperty("dracoon.user"), System.getProperties().getProperty("dracoon.key") )); final SDSSession session = new SDSSession(host, new DisabledX509TrustManager(), new DefaultX509KeyManager()); assertNotNull(session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback())); assertTrue(session.isConnected()); assertNotNull(session.getClient()); session.login(new DisabledLoginCallback(), new DisabledCancelCallback()); assertFalse(new SDSListService(session, new SDSNodeIdProvider(session)).list(new Path("/", EnumSet.of(Path.Type.directory)), new DisabledListProgressListener()).isEmpty()); }
public static boolean hasCauseOf(Throwable t, Class<? extends Throwable> causeType) { return Throwables.getCausalChain(t) .stream() .anyMatch(c -> causeType.isAssignableFrom(c.getClass())); }
@Test public void hasCauseOf_returnsTrueIfTheCauseIsSubtypeOfTheProvidedType() { assertThat(ExceptionUtils.hasCauseOf( new RuntimeException("parent", new SocketTimeoutException("asdasd")), IOException.class)).isTrue(); assertThat(ExceptionUtils.hasCauseOf( new RuntimeException("parent", new IOException("asdasd")), IOException.class)).isTrue(); }
public Map<String, BulkOperationResponse> removeCustomMappingForFields(final List<String> fieldNames, final Set<String> indexSetsIds, final boolean rotateImmediately) { Map<String, BulkOperationResponse> result = new HashMap<>(); for (String indexSetId : indexSetsIds) { try { indexSetService.get(indexSetId).ifPresentOrElse( indexSetConfig -> result.put(indexSetId, removeMappings(fieldNames, indexSetConfig, rotateImmediately)), () -> result.put(indexSetId, new BulkOperationResponse(List.of("Index set with following ID not present in the database: " + indexSetId))) ); } catch (Exception ex) { LOG.error("Failed to remove custom mappings for fields " + fieldNames.toString() + " in index set : " + indexSetId, ex); result.put(indexSetId, new BulkOperationResponse(List.of("Exception while removing custom field mappings for index set : " + indexSetId + ": " + ex.getMessage()))); } } return result; }
@Test void testMappingsRemoval() { doReturn(Optional.of(existingIndexSet)).when(indexSetService).get("existing_index_set"); final Map<String, BulkOperationResponse> response = toTest.removeCustomMappingForFields( List.of("existing_field", "unexisting_field"), Set.of("existing_index_set", "unexisting_index_set"), false); assertThat(response).isNotNull().hasSize(2); assertThat(response).containsOnlyKeys("existing_index_set", "unexisting_index_set"); final BulkOperationResponse existingIndexSetResponse = response.get("existing_index_set"); assertThat(existingIndexSetResponse.successfullyPerformed()).isEqualTo(1); assertThat(existingIndexSetResponse.errors()).isEmpty(); assertThat(existingIndexSetResponse.failures()).hasSize(1); final BulkOperationResponse unexistingIndexSetResponse = response.get("unexisting_index_set"); assertThat(unexistingIndexSetResponse.successfullyPerformed()).isEqualTo(0); assertThat(unexistingIndexSetResponse.errors()).hasSize(1); assertThat(unexistingIndexSetResponse.failures()).isEmpty(); }
public static InstanceAssignmentConfig getInstanceAssignmentConfig(TableConfig tableConfig, InstancePartitionsType instancePartitionsType) { Preconditions.checkState(allowInstanceAssignment(tableConfig, instancePartitionsType), "Instance assignment is not allowed for the given table config"); // Use the instance assignment config from the table config if it exists Map<String, InstanceAssignmentConfig> instanceAssignmentConfigMap = tableConfig.getInstanceAssignmentConfigMap(); if (instanceAssignmentConfigMap != null) { InstanceAssignmentConfig instanceAssignmentConfig = instanceAssignmentConfigMap.get(instancePartitionsType.toString()); if (instanceAssignmentConfig != null) { return instanceAssignmentConfig; } } // Generate default instance assignment config if it does not exist // Only allow default config for offline table with replica-group segment assignment for backward-compatibility InstanceTagPoolConfig tagPoolConfig = new InstanceTagPoolConfig(TagNameUtils.extractOfflineServerTag(tableConfig.getTenantConfig()), false, 0, null); InstanceReplicaGroupPartitionConfig replicaGroupPartitionConfig; SegmentsValidationAndRetentionConfig segmentConfig = tableConfig.getValidationConfig(); int numReplicaGroups = tableConfig.getReplication(); ReplicaGroupStrategyConfig replicaGroupStrategyConfig = segmentConfig.getReplicaGroupStrategyConfig(); Preconditions.checkState(replicaGroupStrategyConfig != null, "Failed to find the replica-group strategy config"); String partitionColumn = replicaGroupStrategyConfig.getPartitionColumn(); boolean minimizeDataMovement = segmentConfig.isMinimizeDataMovement(); if (partitionColumn != null) { int numPartitions = tableConfig.getIndexingConfig().getSegmentPartitionConfig().getNumPartitions(partitionColumn); Preconditions.checkState(numPartitions > 0, "Number of partitions for column: %s is not properly configured", partitionColumn); replicaGroupPartitionConfig = new InstanceReplicaGroupPartitionConfig(true, 0, numReplicaGroups, 0, numPartitions, replicaGroupStrategyConfig.getNumInstancesPerPartition(), minimizeDataMovement, partitionColumn); } else { // If partition column is not configured, use replicaGroupStrategyConfig.getNumInstancesPerPartition() as // number of instances per replica-group for backward-compatibility replicaGroupPartitionConfig = new InstanceReplicaGroupPartitionConfig(true, 0, numReplicaGroups, replicaGroupStrategyConfig.getNumInstancesPerPartition(), 0, 0, minimizeDataMovement, null); } return new InstanceAssignmentConfig(tagPoolConfig, null, replicaGroupPartitionConfig, null, minimizeDataMovement); }
@Test public void testGetInstanceAssignmentConfigWhenInstanceAssignmentConfigIsNotPresentAndPartitionColumnPresent() { TagOverrideConfig tagOverrideConfig = new TagOverrideConfig("broker", "Server"); Map<InstancePartitionsType, String> instancePartitionsTypeStringMap = new HashMap<>(); instancePartitionsTypeStringMap.put(InstancePartitionsType.OFFLINE, "offlineString"); TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName("testTable") .setTagOverrideConfig(tagOverrideConfig).setInstancePartitionsMap(instancePartitionsTypeStringMap) .build(); SegmentsValidationAndRetentionConfig segmentsValidationAndRetentionConfig = new SegmentsValidationAndRetentionConfig(); ReplicaGroupStrategyConfig replicaGroupStrategyConfig = new ReplicaGroupStrategyConfig("column1", 1); segmentsValidationAndRetentionConfig.setReplicaGroupStrategyConfig(replicaGroupStrategyConfig); segmentsValidationAndRetentionConfig.setReplication("1"); tableConfig.setValidationConfig(segmentsValidationAndRetentionConfig); IndexingConfig indexingConfig = new IndexingConfig(); Map<String, ColumnPartitionConfig> columnPartitionConfigMap = new HashMap<>(); ColumnPartitionConfig columnPartitionConfig = new ColumnPartitionConfig("column1", 1); columnPartitionConfigMap.put("column1", columnPartitionConfig); SegmentPartitionConfig segmentPartitionConfig = new SegmentPartitionConfig(columnPartitionConfigMap); indexingConfig.setSegmentPartitionConfig(segmentPartitionConfig); tableConfig.setIndexingConfig(indexingConfig); Assert.assertEquals(InstanceAssignmentConfigUtils.getInstanceAssignmentConfig(tableConfig, InstancePartitionsType.OFFLINE).getReplicaGroupPartitionConfig().isReplicaGroupBased(), Boolean.TRUE); Assert.assertEquals(InstanceAssignmentConfigUtils.getInstanceAssignmentConfig(tableConfig, InstancePartitionsType.OFFLINE).getReplicaGroupPartitionConfig().getPartitionColumn(), "column1"); Assert.assertEquals(InstanceAssignmentConfigUtils.getInstanceAssignmentConfig(tableConfig, InstancePartitionsType.OFFLINE).getReplicaGroupPartitionConfig().getNumInstancesPerPartition(), 1); }
public EndpointConfig setSocketKeepCount(int socketKeepCount) { Preconditions.checkPositive("socketKeepCount", socketKeepCount); Preconditions.checkTrue(socketKeepCount < MAX_SOCKET_KEEP_COUNT, "socketKeepCount value " + socketKeepCount + " is outside valid range 1 - 127"); this.socketKeepCount = socketKeepCount; return this; }
@Test public void testKeepCountValidation() { EndpointConfig endpointConfig = new EndpointConfig(); Assert.assertThrows(IllegalArgumentException.class, () -> endpointConfig.setSocketKeepCount(0)); Assert.assertThrows(IllegalArgumentException.class, () -> endpointConfig.setSocketKeepCount(128)); Assert.assertThrows(IllegalArgumentException.class, () -> endpointConfig.setSocketKeepCount(-3)); }
@Override public boolean isAuthenticatedBrowserSession() { return false; }
@Test public void isAuthenticatedGuiSession_isAlwaysFalse() { assertThat(githubWebhookUserSession.isAuthenticatedBrowserSession()).isFalse(); }
@Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { // If the request servlet path is in the whitelist, // skip Kerberos authentication and return anonymous token. final String path = request.getServletPath(); for(final String endpoint: whitelist) { if (endpoint.equals(path)) { return AuthenticationToken.ANONYMOUS; } } AuthenticationToken token = null; String authorization = request.getHeader( KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) { response.setHeader(WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (authorization == null) { LOG.trace("SPNEGO starting for url: {}", request.getRequestURL()); } else { LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' : {}", authorization); } } else { authorization = authorization.substring( KerberosAuthenticator.NEGOTIATE.length()).trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); try { final String serverPrincipal = KerberosUtil.getTokenServerName(clientToken); if (!serverPrincipal.startsWith("HTTP/")) { throw new IllegalArgumentException( "Invalid server principal " + serverPrincipal + "decoded from client request"); } token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { return runWithPrincipal(serverPrincipal, clientToken, base64, response); } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } catch (Exception ex) { throw new AuthenticationException(ex); } } return token; }
@Test 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(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); }
public void register(GracefulShutdownHook shutdownHook) { if (isShuttingDown.get()) { // Avoid any changes to the shutdown hooks set when the shutdown is already in progress throw new IllegalStateException("Couldn't register shutdown hook because shutdown is already in progress"); } shutdownHooks.add(requireNonNull(shutdownHook, "shutdownHook cannot be null")); }
@Test public void registerAndShutdown() throws Exception { final AtomicBoolean hook1Called = new AtomicBoolean(false); final AtomicBoolean hook2Called = new AtomicBoolean(false); shutdownService.register(() -> hook1Called.set(true)); shutdownService.register(() -> hook2Called.set(true)); assertThat(hook1Called).isFalse(); assertThat(hook2Called).isFalse(); stop(shutdownService); assertThat(hook1Called).isTrue(); assertThat(hook2Called).isTrue(); }
public static WorkerIdentity fromProto(alluxio.grpc.WorkerIdentity proto) throws ProtoParsingException { return Parsers.fromProto(proto); }
@Test public void legacyConvertFromProto() throws Exception { alluxio.grpc.WorkerIdentity identityProto = alluxio.grpc.WorkerIdentity.newBuilder() .setVersion(0) .setIdentifier(ByteString.copyFrom(Longs.toByteArray(2L))) .build(); WorkerIdentity identity = new WorkerIdentity(Longs.toByteArray(2L), 0); assertEquals(identity, WorkerIdentity.fromProto(identityProto)); }
@Override public Object get(String key) { return this.map.get(key); }
@Test public void keyWithDifferentCase() { map.put("key", "value"); CamelMessagingHeadersExtractAdapter adapter = new CamelMessagingHeadersExtractAdapter(map, true); assertEquals("value", adapter.get("KeY")); }
@Override public String toString() { StringBuilder builder = new StringBuilder(); String s = getClass().getName(); builder.append(s.substring(s.lastIndexOf('.') + 1)); List<? extends Coder<?>> componentCoders = getComponents(); if (!componentCoders.isEmpty()) { builder.append('('); boolean first = true; for (Coder<?> componentCoder : componentCoders) { if (first) { first = false; } else { builder.append(','); } builder.append(componentCoder.toString()); } builder.append(')'); } return builder.toString(); }
@Test public void testToString() { assertThat( new ObjectIdentityBooleanCoder().toString(), CoreMatchers.equalTo("StructuredCoderTest$ObjectIdentityBooleanCoder")); ObjectIdentityBooleanCoder coderWithArgs = new ObjectIdentityBooleanCoder() { @Override public List<? extends Coder<?>> getCoderArguments() { return ImmutableList.<Coder<?>>builder() .add(BigDecimalCoder.of(), BigIntegerCoder.of()) .build(); } }; assertThat( coderWithArgs.toString(), CoreMatchers.equalTo("StructuredCoderTest$1(BigDecimalCoder,BigIntegerCoder)")); }
public PathSpecSet copyWithScope(PathSpec parent) { if (this.isAllInclusive()) { return PathSpecSet.of(parent); } if (this.isEmpty()) { return PathSpecSet.empty(); } Builder builder = newBuilder(); this.getPathSpecs().stream() .map(childPathSpec -> { List<String> parentPathComponents = parent.getPathComponents(); List<String> childPathComponents = childPathSpec.getPathComponents(); ArrayList<String> list = new ArrayList<>(parentPathComponents.size() + childPathComponents.size()); list.addAll(parentPathComponents); list.addAll(childPathComponents); return list; }) .map(PathSpec::new) .forEach(builder::add); return builder.build(); }
@Test(dataProvider = "copyWithScopeProvider") public void testCopyWithScope(PathSpecSet input, PathSpec parent, PathSpecSet expected) { Assert.assertEquals(input.copyWithScope(parent), expected); }
public boolean isCollecting() { return (state & MASK_COLLECTING) != 0; }
@Test public void isCollecting() { LacpState state = new LacpState((byte) 0x10); assertTrue(state.isCollecting()); }
@Override @Nullable public short[] readShortArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, SHORT_ARRAY, super::readShortArray); }
@Test public void testReadShortArray() throws Exception { assertNull(reader.readShortArray("NO SUCH FIELD")); }
public synchronized Topology addSource(final String name, final String... topics) { internalTopologyBuilder.addSource(null, name, null, null, null, topics); return this; }
@Test public void shouldNotAllowToAddSourcesWithSameName() { topology.addSource("source", "topic-1"); try { topology.addSource("source", "topic-2"); fail("Should throw TopologyException for duplicate source name"); } catch (final TopologyException expected) { } }
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors( ReconnaissanceReport reconnaissanceReport) { return tsunamiPlugins.entrySet().stream() .filter(entry -> isVulnDetector(entry.getKey())) .map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanceReport)) .flatMap(Streams::stream) .collect(toImmutableList()); }
@Test public void getVulnDetectors_whenOsFilterHasMatchingClass_returnsMatches() { NetworkService wordPressService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80)) .setTransportProtocol(TransportProtocol.TCP) .setServiceName("http") .setSoftware(Software.newBuilder().setName("WordPress")) .build(); NetworkService jenkinsService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 443)) .setTransportProtocol(TransportProtocol.TCP) .setServiceName("https") .setSoftware(Software.newBuilder().setName("Jenkins")) .build(); NetworkService noNameService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 12345)) .setTransportProtocol(TransportProtocol.TCP) .build(); ReconnaissanceReport fakeReconnaissanceReport = ReconnaissanceReport.newBuilder() .setTargetInfo( TargetInfo.newBuilder() .addOperatingSystemClasses( OperatingSystemClass.newBuilder() .setVendor("Vendor") .setOsFamily("FakeOS") .setAccuracy(99))) .addNetworkServices(wordPressService) .addNetworkServices(jenkinsService) .addNetworkServices(noNameService) .build(); PluginManager pluginManager = Guice.createInjector( new FakePortScannerBootstrapModule(), new FakeServiceFingerprinterBootstrapModule(), FakeOsFilteringDetector.getModule()) .getInstance(PluginManager.class); ImmutableList<PluginMatchingResult<VulnDetector>> vulnDetectors = pluginManager.getVulnDetectors(fakeReconnaissanceReport); assertThat(vulnDetectors).hasSize(1); assertThat(vulnDetectors.get(0).tsunamiPlugin().getClass()) .isEqualTo(FakeOsFilteringDetector.class); // And matches everything (as all these services are running on the same target) assertThat(vulnDetectors.get(0).matchedServices()) .containsExactly(wordPressService, jenkinsService, noNameService); }
public PartitionMetadata from(Struct row) { return PartitionMetadata.newBuilder() .setPartitionToken(row.getString(COLUMN_PARTITION_TOKEN)) .setParentTokens(Sets.newHashSet(row.getStringList(COLUMN_PARENT_TOKENS))) .setStartTimestamp(row.getTimestamp(COLUMN_START_TIMESTAMP)) .setEndTimestamp(row.getTimestamp(COLUMN_END_TIMESTAMP)) .setHeartbeatMillis(row.getLong(COLUMN_HEARTBEAT_MILLIS)) .setState(State.valueOf(row.getString(COLUMN_STATE))) .setWatermark(row.getTimestamp(COLUMN_WATERMARK)) .setCreatedAt(row.getTimestamp(COLUMN_CREATED_AT)) .setScheduledAt( !row.isNull(COLUMN_SCHEDULED_AT) ? row.getTimestamp(COLUMN_SCHEDULED_AT) : null) .setRunningAt(!row.isNull(COLUMN_RUNNING_AT) ? row.getTimestamp(COLUMN_RUNNING_AT) : null) .setFinishedAt( !row.isNull(COLUMN_FINISHED_AT) ? row.getTimestamp(COLUMN_FINISHED_AT) : null) .build(); }
@Test public void testMapPartitionMetadataFromResultSetWithNulls() { final Struct row = Struct.newBuilder() .set(COLUMN_PARTITION_TOKEN) .to("token") .set(COLUMN_PARENT_TOKENS) .toStringArray(Collections.singletonList("parentToken")) .set(COLUMN_START_TIMESTAMP) .to(Timestamp.ofTimeMicroseconds(10L)) .set(COLUMN_END_TIMESTAMP) .to(Timestamp.ofTimeMicroseconds(20L)) .set(COLUMN_HEARTBEAT_MILLIS) .to(5_000L) .set(COLUMN_STATE) .to(State.CREATED.name()) .set(COLUMN_WATERMARK) .to(Timestamp.ofTimeMicroseconds(30L)) .set(COLUMN_CREATED_AT) .to(Timestamp.ofTimeMicroseconds(40L)) .set(COLUMN_SCHEDULED_AT) .to((Timestamp) null) .set(COLUMN_RUNNING_AT) .to((Timestamp) null) .set(COLUMN_FINISHED_AT) .to((Timestamp) null) .build(); final PartitionMetadata partition = mapper.from(row); assertEquals( new PartitionMetadata( "token", Sets.newHashSet("parentToken"), Timestamp.ofTimeMicroseconds(10L), Timestamp.ofTimeMicroseconds(20L), 5_000L, State.CREATED, Timestamp.ofTimeMicroseconds(30), Timestamp.ofTimeMicroseconds(40), null, null, null), partition); }
public SubscriptionData findSubscriptionData(final String group, final String topic) { return findSubscriptionData(group, topic, true); }
@Test public void findSubscriptionDataTest() { register(); final SubscriptionData subscriptionData = consumerManager.findSubscriptionData(GROUP, TOPIC); Assertions.assertThat(subscriptionData).isNotNull(); }
@Override public BitString newInstance() { return new BitString(bits.length, fitness, crossover, crossoverRate, mutationRate); }
@Test public void testNewInstance() { System.out.println("newInstance"); byte[] father = {1,1,1,0,1,0,0,1,0,0,0}; int length = father.length; BitString instance = new BitString(father, null, Crossover.SINGLE_POINT, 1.0, 0.0); BitString result = instance.newInstance(); assertEquals(length, result.length()); boolean same = true; for (int i = 0; i < length; i++) { if (father[i] != result.bits()[i]) { same = false; } } assertFalse(same); }
boolean shouldReplicateAcl(AclBinding aclBinding) { return !(aclBinding.entry().permissionType() == AclPermissionType.ALLOW && aclBinding.entry().operation() == AclOperation.WRITE); }
@Test public void testAclFiltering() { MirrorSourceConnector connector = new MirrorSourceConnector(new SourceAndTarget("source", "target"), new DefaultReplicationPolicy(), x -> true, getConfigPropertyFilter()); assertFalse(connector.shouldReplicateAcl( new AclBinding(new ResourcePattern(ResourceType.TOPIC, "test_topic", PatternType.LITERAL), new AccessControlEntry("kafka", "", AclOperation.WRITE, AclPermissionType.ALLOW))), "should not replicate ALLOW WRITE"); assertTrue(connector.shouldReplicateAcl( new AclBinding(new ResourcePattern(ResourceType.TOPIC, "test_topic", PatternType.LITERAL), new AccessControlEntry("kafka", "", AclOperation.ALL, AclPermissionType.ALLOW))), "should replicate ALLOW ALL"); }
@Override public Collection<DatabasePacket> execute() throws SQLException { ResponseHeader responseHeader = proxyBackendHandler.execute(); if (responseHeader instanceof QueryResponseHeader) { return processQuery((QueryResponseHeader) responseHeader); } responseType = ResponseType.UPDATE; return processUpdate((UpdateResponseHeader) responseHeader); }
@Test void assertIsQueryResponse() throws SQLException, NoSuchFieldException, IllegalAccessException { MySQLComQueryPacketExecutor mysqlComQueryPacketExecutor = new MySQLComQueryPacketExecutor(packet, connectionSession); MemberAccessor accessor = Plugins.getMemberAccessor(); accessor.set(MySQLComQueryPacketExecutor.class.getDeclaredField("proxyBackendHandler"), mysqlComQueryPacketExecutor, proxyBackendHandler); QueryHeader queryHeader = mock(QueryHeader.class); when(queryHeader.getColumnTypeName()).thenReturn("VARCHAR"); when(proxyBackendHandler.execute()).thenReturn(new QueryResponseHeader(Collections.singletonList(queryHeader))); mysqlComQueryPacketExecutor.execute(); assertThat(mysqlComQueryPacketExecutor.getResponseType(), is(ResponseType.QUERY)); }
@Override public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter) throws IOException { EthCall ethCall = web3j.ethCall( Transaction.createEthCallTransaction(fromAddress, to, data), defaultBlockParameter) .send(); assertCallNotReverted(ethCall); return ethCall.getValue(); }
@Test public void sendCallRevertedTest() throws IOException { when(response.isReverted()).thenReturn(true); when(response.getRevertReason()).thenReturn(OWNER_REVERT_MSG_STR); when(service.send(any(), any())).thenReturn(response); ReadonlyTransactionManager readonlyTransactionManager = new ReadonlyTransactionManager(web3j, ""); ContractCallException thrown = assertThrows( ContractCallException.class, () -> readonlyTransactionManager.sendCall("", "", defaultBlockParameter)); assertEquals(String.format(REVERT_ERR_STR, OWNER_REVERT_MSG_STR), thrown.getMessage()); }
@Nonnull public <T> T getInstance(@Nonnull Class<T> type) { return getInstance(new Key<>(type)); }
@Test public void whenDefaultSpecified_shouldUseSameInstance() throws Exception { Thing thing = injector.getInstance(Thing.class); assertThat(injector.getInstance(Thing.class)).isSameInstanceAs(thing); }
@Override public void merge(NormalSketch other) { Preconditions.checkArgument(data.length == other.data.length, "Trying to merge sketch with one of different size. Expected %s, actual %s", data.length, other.data.length); for (int i = 0; i < data.length; i++) { data[i] = (byte) Math.max(data[i], other.data[i]); } }
@Test public void requireThatMergeDoesElementWiseMax() { NormalSketch s1 = new NormalSketch(2); setSketchValues(s1, 0, 1, 1, 3); NormalSketch s2 = new NormalSketch(2); setSketchValues(s2, 2, 1, 1, 0); s1.merge(s2); assertBucketEquals(s1, 0, 2); assertBucketEquals(s1, 1, 1); assertBucketEquals(s1, 2, 1); assertBucketEquals(s1, 3, 3); }
public static UNewClass create( UExpression enclosingExpression, List<? extends UExpression> typeArguments, UExpression identifier, List<UExpression> arguments, @Nullable UClassDecl classBody) { return new AutoValue_UNewClass( enclosingExpression, ImmutableList.copyOf(typeArguments), identifier, ImmutableList.copyOf(arguments), classBody); }
@Test public void equality() { new EqualsTester() .addEqualityGroup( UNewClass.create(UClassIdent.create("java.lang.String"), ULiteral.stringLit("123"))) .addEqualityGroup( UNewClass.create(UClassIdent.create("java.math.BigInteger"), ULiteral.stringLit("123"))) .addEqualityGroup( UNewClass.create(UClassIdent.create("java.lang.String"), ULiteral.stringLit("foobar"))) .testEquals(); }
@Override public synchronized boolean tryReturnRecordAt( boolean isAtSplitPoint, @Nullable ShufflePosition groupStart) { if (lastGroupStart == null && !isAtSplitPoint) { throw new IllegalStateException( String.format("The first group [at %s] must be at a split point", groupStart.toString())); } if (this.startPosition != null && groupStart.compareTo(this.startPosition) < 0) { throw new IllegalStateException( String.format( "Trying to return record at %s which is before the starting position at %s", groupStart, this.startPosition)); } int comparedToLast = (lastGroupStart == null) ? 1 : groupStart.compareTo(this.lastGroupStart); if (comparedToLast < 0) { throw new IllegalStateException( String.format( "Trying to return group at %s which is before the last-returned group at %s", groupStart, this.lastGroupStart)); } if (isAtSplitPoint) { splitPointsSeen++; if (comparedToLast == 0) { throw new IllegalStateException( String.format( "Trying to return a group at a split point with same position as the " + "previous group: both at %s, last group was %s", groupStart, lastGroupWasAtSplitPoint ? "at a split point." : "not at a split point.")); } if (stopPosition != null && groupStart.compareTo(stopPosition) >= 0) { return false; } } else { checkState( comparedToLast == 0, // This case is not a violation of general RangeTracker semantics, but it is // contrary to how GroupingShuffleReader in particular works. Hitting it would // mean it's behaving unexpectedly. "Trying to return a group not at a split point, but with a different position " + "than the previous group: last group was %s at %s, current at %s", lastGroupWasAtSplitPoint ? "a split point" : "a non-split point", lastGroupStart, groupStart); } this.lastGroupStart = groupStart; this.lastGroupWasAtSplitPoint = isAtSplitPoint; return true; }
@Test public void testTryReturnRecordWithNonSplitPoints() throws Exception { GroupingShuffleRangeTracker tracker = new GroupingShuffleRangeTracker(ofBytes(1, 0, 0), ofBytes(5, 0, 0)); assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 3))); assertTrue(tracker.tryReturnRecordAt(false, ofBytes(1, 2, 3))); assertTrue(tracker.tryReturnRecordAt(false, ofBytes(1, 2, 3))); assertTrue(tracker.tryReturnRecordAt(true, ofBytes(1, 2, 5))); assertTrue(tracker.tryReturnRecordAt(false, ofBytes(1, 2, 5))); assertTrue(tracker.tryReturnRecordAt(true, ofBytes(3, 6, 8, 10))); assertTrue(tracker.tryReturnRecordAt(true, ofBytes(4, 255, 255, 255, 255))); }
@Override @MethodNotAvailable public <T> Map<K, EntryProcessorResult<T>> invokeAll(Set<? extends K> keys, EntryProcessor<K, V, T> entryProcessor, Object... arguments) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testInvokeAll() { Set<Integer> keys = new HashSet<>(asList(23, 65, 88)); adapter.invokeAll(keys, new ICacheReplaceEntryProcessor(), "value", "newValue"); }
static void readFullyDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException { int nextReadLength = Math.min(buf.remaining(), temp.length); int bytesRead = 0; while (nextReadLength > 0 && (bytesRead = f.read(temp, 0, nextReadLength)) >= 0) { buf.put(temp, 0, bytesRead); nextReadLength = Math.min(buf.remaining(), temp.length); } if (bytesRead < 0 && buf.remaining() > 0) { throw new EOFException("Reached the end of stream with " + buf.remaining() + " bytes left to read"); } }
@Test public void testDirectReadFullySmallBuffer() throws Exception { ByteBuffer readBuffer = ByteBuffer.allocateDirect(8); MockInputStream stream = new MockInputStream(); DelegatingSeekableInputStream.readFullyDirectBuffer(stream, readBuffer, TEMP.get()); Assert.assertEquals(8, readBuffer.position()); Assert.assertEquals(8, readBuffer.limit()); DelegatingSeekableInputStream.readFullyDirectBuffer(stream, readBuffer, TEMP.get()); Assert.assertEquals(8, readBuffer.position()); Assert.assertEquals(8, readBuffer.limit()); readBuffer.flip(); Assert.assertEquals("Buffer contents should match", ByteBuffer.wrap(TEST_ARRAY, 0, 8), readBuffer); }
@Override public int read() throws IOException { byte[] b = new byte[1]; if (read(b, 0, 1) != 1) { return -1; } else { return b[0]; } }
@Test public void testRead() throws Exception { DistributedLogManager dlm = mock(DistributedLogManager.class); LogReader reader = mock(LogReader.class); when(dlm.getInputStream(any(DLSN.class))).thenReturn(reader); byte[] data = "test-read".getBytes(StandardCharsets.UTF_8); LogRecordWithDLSN record = mock(LogRecordWithDLSN.class); when(record.getPayLoadInputStream()) .thenReturn(new ByteArrayInputStream(data)); when(reader.readNext(anyBoolean())) .thenReturn(record) .thenThrow(new EndOfStreamException("eos")); DLInputStream in = new DLInputStream(dlm); int numReads = 0; int readByte; while ((readByte = in.read()) != -1) { assertEquals(data[numReads], readByte); ++numReads; } assertEquals(data.length, numReads); }
@Override public TransferStatus prepare(final Path file, final Local local, final TransferStatus parent, final ProgressListener progress) throws BackgroundException { final TransferStatus status = super.prepare(file, local, parent, progress); if(status.isExists()) { final String filename = file.getName(); int no = 0; do { String proposal = String.format("%s-%d", FilenameUtils.getBaseName(filename), ++no); if(StringUtils.isNotBlank(Path.getExtension(filename))) { proposal += String.format(".%s", Path.getExtension(filename)); } final Path renamed = new Path(file.getParent(), proposal, file.getType()); if(options.temporary) { // Adjust final destination when uploading with temporary filename status.getDisplayname().withRemote(renamed).exists(false); } else { status.withRename(renamed); } } while(find.find(status.getRename().remote)); if(log.isInfoEnabled()) { log.info(String.format("Changed upload target from %s to %s", file, status.getRename().remote)); } if(log.isDebugEnabled()) { log.debug(String.format("Clear exist flag for file %s", file)); } status.setExists(false); } else { if(parent.getRename().remote != null) { final Path renamed = new Path(parent.getRename().remote, file.getName(), file.getType()); if(options.temporary) { // Adjust final destination when uploading with temporary filename status.getDisplayname().withRemote(renamed).exists(false); } else { status.withRename(renamed); } } if(log.isInfoEnabled()) { log.info(String.format("Changed upload target from %s to %s", file, status.getRename().remote)); } } return status; }
@Test public void testPrepare() throws Exception { RenameFilter f = new RenameFilter(new DisabledUploadSymlinkResolver(), new NullSession(new Host(new TestProtocol()))); final Path t = new Path("t", EnumSet.of(Path.Type.file)); f.prepare(t, new NullLocal("t"), new TransferStatus(), new DisabledProgressListener()); assertNotSame("t", t.getName()); }
private static CPUResource getCpuCores(final Configuration config) { return getCpuCoresWithFallback(config, -1.0); }
@Test void testConfigCpuCores() { final double cpuCores = 1.0; Configuration conf = new Configuration(); conf.set(TaskManagerOptions.CPU_CORES, cpuCores); validateInAllConfigurations( conf, taskExecutorProcessSpec -> assertThat(taskExecutorProcessSpec.getCpuCores()) .isEqualTo(new CPUResource(cpuCores))); }
@NonNull public static List<VideoStream> getSortedStreamVideosList( @NonNull final Context context, @Nullable final List<VideoStream> videoStreams, @Nullable final List<VideoStream> videoOnlyStreams, final boolean ascendingOrder, final boolean preferVideoOnlyStreams) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final boolean showHigherResolutions = preferences.getBoolean( context.getString(R.string.show_higher_resolutions_key), false); final MediaFormat defaultFormat = getDefaultFormat(context, R.string.default_video_format_key, R.string.default_video_format_value); return getSortedStreamVideosList(defaultFormat, showHigherResolutions, videoStreams, videoOnlyStreams, ascendingOrder, preferVideoOnlyStreams); }
@Test public void getSortedStreamVideosListTest() { List<VideoStream> result = ListHelper.getSortedStreamVideosList(MediaFormat.MPEG_4, true, VIDEO_STREAMS_TEST_LIST, VIDEO_ONLY_STREAMS_TEST_LIST, true, false); List<String> expected = List.of("144p", "240p", "360p", "480p", "720p", "720p60", "1080p", "1080p60", "1440p60", "2160p", "2160p60"); assertEquals(expected.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(result.get(i).getResolution(), expected.get(i)); assertEquals(expected.get(i), result.get(i).getResolution()); } //////////////////// // Reverse Order // ////////////////// result = ListHelper.getSortedStreamVideosList(MediaFormat.MPEG_4, true, VIDEO_STREAMS_TEST_LIST, VIDEO_ONLY_STREAMS_TEST_LIST, false, false); expected = List.of("2160p60", "2160p", "1440p60", "1080p60", "1080p", "720p60", "720p", "480p", "360p", "240p", "144p"); assertEquals(expected.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(expected.get(i), result.get(i).getResolution()); } }
public String toLoggableString(ApiMessage message) { MetadataRecordType type = MetadataRecordType.fromId(message.apiKey()); switch (type) { case CONFIG_RECORD: { if (!configSchema.isSensitive((ConfigRecord) message)) { return message.toString(); } ConfigRecord duplicate = ((ConfigRecord) message).duplicate(); duplicate.setValue("(redacted)"); return duplicate.toString(); } case USER_SCRAM_CREDENTIAL_RECORD: { UserScramCredentialRecord record = (UserScramCredentialRecord) message; return "UserScramCredentialRecord(" + "name=" + ((record.name() == null) ? "null" : "'" + record.name() + "'") + ", mechanism=" + record.mechanism() + ", salt=(redacted)" + ", storedKey=(redacted)" + ", serverKey=(redacted)" + ", iterations=" + record.iterations() + ")"; } default: return message.toString(); } }
@Test public void testUserScramCredentialRecordToString() { assertEquals("UserScramCredentialRecord(name='bob', mechanism=0, " + "salt=(redacted), storedKey=(redacted), serverKey=(redacted), iterations=128)", REDACTOR.toLoggableString(new UserScramCredentialRecord(). setName("bob"). setMechanism((byte) 0). setSalt(new byte[512]). setServerKey(new byte[128]). setStoredKey(new byte[128]). setIterations(128))); }
public DockerImage get(Node node) { Optional<DockerImage> requestedImage = node.allocation() .flatMap(allocation -> allocation.membership().cluster().dockerImageRepo()); NodeType nodeType = node.type().isHost() ? node.type().childNodeType() : node.type(); DockerImage wantedImage = nodeType != NodeType.tenant ? defaultImage : node.resources().gpuResources().isZero() ? tenantImage.orElse(defaultImage) : tenantGpuImage.orElseThrow(() -> new IllegalArgumentException(node + " has GPU resources, but there is no GPU container image available")); return requestedImage // Rewrite requested images to make sure they come from a trusted registry .map(image -> image.withRegistry(wantedImage.registry())) .orElse(wantedImage); }
@Test public void image_selection() { DockerImage defaultImage = DockerImage.fromString("different.example.com/vespa/default"); DockerImage tenantImage = DockerImage.fromString("registry.example.com/vespa/tenant"); DockerImage gpuImage = DockerImage.fromString("registry.example.com/vespa/tenant-gpu"); ContainerImages images = new ContainerImages(defaultImage, Optional.of(tenantImage), Optional.of(gpuImage)); assertEquals(defaultImage, images.get(node(NodeType.confighost))); // For preload purposes assertEquals(defaultImage, images.get(node(NodeType.config))); assertEquals(tenantImage, images.get(node(NodeType.host))); // For preload purposes assertEquals(tenantImage, images.get(node(NodeType.tenant))); assertEquals(defaultImage, images.get(node(NodeType.proxyhost))); // For preload purposes assertEquals(defaultImage, images.get(node(NodeType.proxy))); // Choose GPU when node has GPU resources assertEquals(gpuImage, images.get(node(NodeType.tenant, null, true))); // Tenant node requesting a special image DockerImage requested = DockerImage.fromString("registry.example.com/vespa/special"); assertEquals(requested, images.get(node(NodeType.tenant, requested))); // Malicious registry is rewritten to the trusted one DockerImage malicious = DockerImage.fromString("malicious.example.com/vespa/special"); assertEquals(requested, images.get(node(NodeType.tenant, malicious))); // Requested image registry for config is rewritten to the defaultImage registry assertEquals(DockerImage.fromString("different.example.com/vespa/special"), images.get(node(NodeType.config, requested))); // When there is no custom tenant image, the default one is used images = new ContainerImages(defaultImage, Optional.empty(), Optional.of(gpuImage)); assertEquals(defaultImage, images.get(node(NodeType.host))); assertEquals(defaultImage, images.get(node(NodeType.tenant))); }
static KiePMMLCompoundPredicate getKiePMMLCompoundPredicate(final CompoundPredicate compoundPredicate, final List<Field<?>> fields) { final BOOLEAN_OPERATOR booleanOperator = BOOLEAN_OPERATOR.byName(compoundPredicate.getBooleanOperator().value()); final List<KiePMMLPredicate> kiePMMLPredicates = compoundPredicate.hasPredicates() ? getKiePMMLPredicates(compoundPredicate.getPredicates(), fields) : Collections.emptyList(); return KiePMMLCompoundPredicate.builder(getKiePMMLExtensions(compoundPredicate.getExtensions()), booleanOperator) .withKiePMMLPredicates(kiePMMLPredicates) .build(); }
@Test void getKiePMMLCompoundPredicate() { List<Field<?>> fields = IntStream.range(0, 3).mapToObj(i -> getRandomDataField()).collect(Collectors.toList()); final CompoundPredicate toConvert = getRandomCompoundPredicate(fields); final KiePMMLCompoundPredicate retrieved = KiePMMLCompoundPredicateInstanceFactory.getKiePMMLCompoundPredicate(toConvert, fields); commonVerifyKKiePMMLCompoundPredicate(retrieved, toConvert); }
public WorkflowActionResponse activate(String workflowId, String version, User caller) { Checks.notNull( caller, "caller cannot be null to activate workflow [%s][%s]", workflowId, version); WorkflowVersionUpdateJobEvent jobEvent = (WorkflowVersionUpdateJobEvent) workflowDao.activate(workflowId, version, caller); LOG.info(jobEvent.getLog()); TimelineEvent event = TimelineActionEvent.builder() .action(Actions.WorkflowAction.ACTIVATE) .author(caller) .message(jobEvent.getLog()) .build(); return WorkflowActionResponse.from(workflowId, jobEvent.getCurrentActiveVersion(), event); }
@Test public void testActivateError() { AssertHelper.assertThrows( "caller cannot be null to activate workflow", NullPointerException.class, "caller cannot be null to activate workflow [sample-minimal-wf][1]", () -> actionHandler.activate("sample-minimal-wf", "1", null)); when(workflowDao.activate("sample-minimal-wf", "0", tester)) .thenThrow(new InvalidWorkflowVersionException("sample-minimal-wf", "0")); AssertHelper.assertThrows( "Workflow version must be larger than 0", InvalidWorkflowVersionException.class, "Invalid workflow version [0] for workflow [sample-minimal-wf]", () -> actionHandler.activate("sample-minimal-wf", "0", tester)); }
@Override public Result run(GoPluginDescriptor pluginDescriptor, Map<String, List<String>> extensionsInfoOfPlugin) { final ValidationResult validationResult = validate(pluginDescriptor, extensionsInfoOfPlugin); return new Result(validationResult.hasError(), validationResult.toErrorMessage()); }
@Test void shouldConsiderPluginValidWhenOneOfTheExtensionVersionUsedByThePluginIsSupportedByGoCD() { final PluginPostLoadHook.Result validationResult = pluginExtensionsAndVersionValidator.run(descriptor, Map.of(ELASTIC_AGENT_EXTENSION, List.of("a.b", "2.0"))); assertThat(validationResult.isAFailure()).isFalse(); }
public static void copy(int[] src, long[] dest, int length) { for (int i = 0; i < length; i++) { dest[i] = src[i]; } }
@Test public void testCopyFromStringArray() { ArrayCopyUtils.copy(STRING_ARRAY, INT_BUFFER, COPY_LENGTH); ArrayCopyUtils.copy(STRING_ARRAY, LONG_BUFFER, COPY_LENGTH); ArrayCopyUtils.copy(STRING_ARRAY, FLOAT_BUFFER, COPY_LENGTH); ArrayCopyUtils.copy(STRING_ARRAY, DOUBLE_BUFFER, COPY_LENGTH); for (int i = 0; i < COPY_LENGTH; i++) { Assert.assertEquals(INT_BUFFER[i], Integer.parseInt(STRING_ARRAY[i])); Assert.assertEquals(LONG_BUFFER[i], Long.parseLong(STRING_ARRAY[i])); Assert.assertEquals(FLOAT_BUFFER[i], Float.parseFloat(STRING_ARRAY[i])); Assert.assertEquals(DOUBLE_BUFFER[i], Double.parseDouble(STRING_ARRAY[i])); } }
@Override public Encoder getValueEncoder() { return encoder; }
@Test public void shouldSerializeValueCorrectly() throws Exception { assertThat(valueCodec.getValueEncoder().encode(value).toString(CharsetUtil.UTF_8)) .isEqualTo("{\"value\":\"test\"}"); }
public static <E> BoundedList<E> newArrayBacked(int maxLength) { return new BoundedList<>(maxLength, new ArrayList<>()); }
@Test public void testInitialCapacityMustNotBeZero() { assertEquals("Invalid non-positive initialCapacity of 0", assertThrows(IllegalArgumentException.class, () -> BoundedList.newArrayBacked(100, 0)).getMessage()); }
ClassicGroup getOrMaybeCreateClassicGroup( String groupId, boolean createIfNotExists ) throws GroupIdNotFoundException { Group group = groups.get(groupId); if (group == null && !createIfNotExists) { throw new GroupIdNotFoundException(String.format("Classic group %s not found.", groupId)); } if (group == null) { ClassicGroup classicGroup = new ClassicGroup(logContext, groupId, ClassicGroupState.EMPTY, time, metrics); groups.put(groupId, classicGroup); metrics.onClassicGroupStateTransition(null, classicGroup.currentState()); return classicGroup; } else { if (group.type() == CLASSIC) { return (ClassicGroup) group; } else { // We don't support upgrading/downgrading between protocols at the moment so // we throw an exception if a group exists with the wrong type. throw new GroupIdNotFoundException(String.format("Group %s is not a classic group.", groupId)); } } }
@Test public void testStaticMemberRejoinAsFollowerWithUnknownMemberId() throws Exception { GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .build(); GroupMetadataManagerTestContext.RebalanceResult rebalanceResult = context.staticMembersJoinAndRebalance( "group-id", "leader-instance-id", "follower-instance-id" ); ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup("group-id", false); // A static follower rejoin with no protocol change will not trigger rebalance. JoinGroupRequestData request = new GroupMetadataManagerTestContext.JoinGroupRequestBuilder() .withGroupId("group-id") .withGroupInstanceId("follower-instance-id") .withMemberId(UNKNOWN_MEMBER_ID) .withProtocolSuperset() .build(); GroupMetadataManagerTestContext.JoinResult followerJoinResult = context.sendClassicGroupJoin( request, true, true ); assertEquals( Collections.singletonList(GroupCoordinatorRecordHelpers.newGroupMetadataRecord(group, group.groupAssignment(), MetadataVersion.latestTesting())), followerJoinResult.records ); // Simulate a successful write to log. followerJoinResult.appendFuture.complete(null); assertTrue(followerJoinResult.joinFuture.isDone()); // Old leader shouldn't be timed out. assertTrue(group.hasStaticMember("leader-instance-id")); JoinGroupResponseData expectedFollowerResponse = new JoinGroupResponseData() .setErrorCode(Errors.NONE.code()) .setGenerationId(rebalanceResult.generationId) // The group has not changed. .setMemberId(followerJoinResult.joinFuture.get().memberId()) .setLeader(rebalanceResult.leaderId) .setProtocolName("range") .setProtocolType("consumer") .setSkipAssignment(false) .setMembers(Collections.emptyList()); checkJoinGroupResponse( expectedFollowerResponse, followerJoinResult.joinFuture.get(), group, STABLE, Collections.emptySet() ); assertNotEquals(rebalanceResult.followerId, followerJoinResult.joinFuture.get().memberId()); GroupMetadataManagerTestContext.SyncResult syncResult = context.sendClassicGroupSync( new GroupMetadataManagerTestContext.SyncGroupRequestBuilder() .withGroupId("group-id") .withGroupInstanceId("follower-instance-id") .withGenerationId(rebalanceResult.generationId) .withMemberId(followerJoinResult.joinFuture.get().memberId()) .build() ); assertTrue(syncResult.records.isEmpty()); assertTrue(syncResult.syncFuture.isDone()); assertEquals(Errors.NONE.code(), syncResult.syncFuture.get().errorCode()); assertEquals(rebalanceResult.followerAssignment, syncResult.syncFuture.get().assignment()); }
public static BookmarkCollection defaultCollection() { return FAVORITES_COLLECTION; }
@Test public void testDefault() { assertNotNull(BookmarkCollection.defaultCollection()); }
@Override public <VR> KStream<K, VR> flatMapValues(final ValueMapper<? super V, ? extends Iterable<? extends VR>> mapper) { return flatMapValues(withKey(mapper)); }
@Test public void shouldNotAllowNullNameOnFlatMapValues() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.flatMapValues(v -> Collections.emptyList(), null)); assertThat(exception.getMessage(), equalTo("named can't be null")); }
private RemotingCommand queryTopicConsumeByWho(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { final RemotingCommand response = RemotingCommand.createResponseCommand(null); QueryTopicConsumeByWhoRequestHeader requestHeader = (QueryTopicConsumeByWhoRequestHeader) request.decodeCommandCustomHeader(QueryTopicConsumeByWhoRequestHeader.class); HashSet<String> groups = this.brokerController.getConsumerManager().queryTopicConsumeByWho(requestHeader.getTopic()); Set<String> groupInOffset = this.brokerController.getConsumerOffsetManager().whichGroupByTopic(requestHeader.getTopic()); if (groupInOffset != null && !groupInOffset.isEmpty()) { groups.addAll(groupInOffset); } GroupList groupList = new GroupList(); groupList.setGroupList(groups); byte[] body = groupList.encode(); response.setBody(body); response.setCode(ResponseCode.SUCCESS); response.setRemark(null); return response; }
@Test public void testQueryTopicConsumeByWho() throws RemotingCommandException { QueryTopicConsumeByWhoRequestHeader requestHeader = new QueryTopicConsumeByWhoRequestHeader(); requestHeader.setTopic("topic"); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_TOPIC_CONSUME_BY_WHO, requestHeader); request.makeCustomHeaderToNet(); HashSet<String> groups = new HashSet<>(); groups.add("group"); when(brokerController.getConsumerManager()).thenReturn(consumerManager); when(consumerManager.queryTopicConsumeByWho(anyString())).thenReturn(groups); RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); assertThat(RemotingSerializable.decode(response.getBody(), GroupList.class) .getGroupList().contains("group")) .isEqualTo(groups.contains("group")); }
@Override public String toString() { return "MutableLong{value=" + value + '}'; }
@Test public void testToString() { MutableLong mutableLong = new MutableLong(); String s = mutableLong.toString(); assertEquals("MutableLong{value=0}", s); }
public Stream<NoSqlMigration> getMigrations() { NoSqlMigrationProvider migrationProvider = getMigrationProvider(); return getMigrations(migrationProvider); }
@Test void testNoSqlDatabaseMigrationsAreSortedCorrectly() { final NoSqlDatabaseMigrationsProvider databaseCreator = new NoSqlDatabaseMigrationsProvider(asList(MongoDBStorageProvider.class, AmazonDocumentDBStorageProvider.class)); final Stream<NoSqlMigration> databaseSpecificMigrations = databaseCreator.getMigrations(); assertThat(databaseSpecificMigrations) .isSortedAccordingTo(comparing(NoSqlMigration::getClassName)); }
public static YamlMapAccessor empty() { return new YamlMapAccessor(new LinkedHashMap<>()); }
@Test public void testEmpty() { YamlMapAccessor yamlMapAccessor = YamlMapAccessor.empty(); Optional<Object> optional = yamlMapAccessor.get("/"); assertNotNull(optional); assertTrue(optional.isPresent()); assertTrue(optional.get() instanceof Map); Map<Object, Object> map = (Map<Object, Object>) optional.get(); assertTrue(map.isEmpty()); optional = yamlMapAccessor.getOrCreate("/foo", () -> new LinkedHashMap<>()); assertNotNull(optional); assertTrue(optional.isPresent()); assertTrue(optional.get() instanceof Map); map = (Map<Object, Object>) optional.get(); map.put("value", 1); optional = yamlMapAccessor.get("/foo/value"); assertNotNull(optional); assertTrue(optional.isPresent()); assertNotNull(optional.get()); assertTrue(optional.get() instanceof Integer); assertEquals(1, ((Integer) optional.get()).intValue()); optional = yamlMapAccessor.get("/foo"); assertNotNull(optional); assertTrue(optional.isPresent()); assertTrue(optional.get() instanceof Map); map = (Map<Object, Object>) optional.get(); assertTrue(map.get("value") instanceof Integer); assertTrue(((Integer) map.get("value")) == 1); }
public OALScripts parse() throws IOException { OALScripts scripts = new OALScripts(); CommonTokenStream tokens = new CommonTokenStream(lexer); OALParser parser = new OALParser(tokens); ParseTree tree = parser.root(); ParseTreeWalker walker = new ParseTreeWalker(); walker.walk(new OALListener(scripts, sourcePackage), tree); return scripts; }
@Test public void testParse() throws IOException { ScriptParser parser = ScriptParser.createFromScriptText( "endpoint_resp_time = from(Endpoint.latency).longAvg(); //comment test" + "\n" + "Service_avg = from(Service.latency).longAvg()", TEST_SOURCE_PACKAGE ); List<AnalysisResult> results = parser.parse().getMetricsStmts(); Assertions.assertEquals(2, results.size()); AnalysisResult endpointAvg = results.get(0); Assertions.assertEquals("EndpointRespTime", endpointAvg.getMetricsName()); Assertions.assertEquals("Endpoint", endpointAvg.getFrom().getSourceName()); Assertions.assertEquals("[latency]", endpointAvg.getFrom().getSourceAttribute().toString()); Assertions.assertEquals("longAvg", endpointAvg.getAggregationFuncStmt().getAggregationFunctionName()); AnalysisResult serviceAvg = results.get(1); Assertions.assertEquals("ServiceAvg", serviceAvg.getMetricsName()); Assertions.assertEquals("Service", serviceAvg.getFrom().getSourceName()); Assertions.assertEquals("[latency]", serviceAvg.getFrom().getSourceAttribute().toString()); Assertions.assertEquals("longAvg", serviceAvg.getAggregationFuncStmt().getAggregationFunctionName()); }
public static Future<Void> reconcileJmxSecret(Reconciliation reconciliation, SecretOperator secretOperator, SupportsJmx cluster) { return secretOperator.getAsync(reconciliation.namespace(), cluster.jmx().secretName()) .compose(currentJmxSecret -> { Secret desiredJmxSecret = cluster.jmx().jmxSecret(currentJmxSecret); if (desiredJmxSecret != null) { // Desired secret is not null => should be updated return secretOperator.reconcile(reconciliation, reconciliation.namespace(), cluster.jmx().secretName(), desiredJmxSecret) .map((Void) null); } else if (currentJmxSecret != null) { // Desired secret is null but current is not => we should delete the secret return secretOperator.reconcile(reconciliation, reconciliation.namespace(), cluster.jmx().secretName(), null) .map((Void) null); } else { // Both current and desired secret are null => nothing to do return Future.succeededFuture(); } }); }
@Test public void testDisabledJmxWithExistingSecret(VertxTestContext context) { KafkaClusterSpec spec = new KafkaClusterSpecBuilder().build(); JmxModel jmx = new JmxModel(NAMESPACE, NAME, LABELS, OWNER_REFERENCE, spec); SecretOperator mockSecretOps = mock(SecretOperator.class); when(mockSecretOps.getAsync(eq(NAMESPACE), eq(NAME))).thenReturn(Future.succeededFuture(EXISTING_JMX_SECRET)); when(mockSecretOps.reconcile(any(), any(), any(), any())).thenAnswer(i -> { if (i.getArgument(3) == null) { return Future.succeededFuture(ReconcileResult.deleted()); } else { return Future.succeededFuture(ReconcileResult.patched(i.getArgument(3))); } }); Checkpoint async = context.checkpoint(); ReconcilerUtils.reconcileJmxSecret(Reconciliation.DUMMY_RECONCILIATION, mockSecretOps, new MockJmxCluster(jmx)) .onComplete(context.succeeding(v -> context.verify(() -> { verify(mockSecretOps, times(1)).reconcile(eq(Reconciliation.DUMMY_RECONCILIATION), eq(NAMESPACE), eq(NAME), eq(null)); async.flag(); }))); }
@Override public void validateNameUniqueness(Map<CaseInsensitiveString, AbstractMaterialConfig> map) { if (StringUtils.isBlank(packageId)) { return; } if (map.containsKey(new CaseInsensitiveString(packageId))) { AbstractMaterialConfig material = map.get(new CaseInsensitiveString(packageId)); material.addError(PACKAGE_ID, "Duplicate package material detected!"); addError(PACKAGE_ID, "Duplicate package material detected!"); } else { map.put(new CaseInsensitiveString(packageId), this); } }
@Test public void shouldAddErrorIfMaterialNameUniquenessValidationFails() throws Exception { PackageMaterialConfig packageMaterialConfig = new PackageMaterialConfig("package-id"); Map<CaseInsensitiveString, AbstractMaterialConfig> nameToMaterialMap = new HashMap<>(); PackageMaterialConfig existingMaterial = new PackageMaterialConfig("package-id"); nameToMaterialMap.put(new CaseInsensitiveString("package-id"), existingMaterial); nameToMaterialMap.put(new CaseInsensitiveString("foo"), git("url")); packageMaterialConfig.validateNameUniqueness(nameToMaterialMap); assertThat(packageMaterialConfig.errors().getAll().size(), is(1)); assertThat(packageMaterialConfig.errors().on(PackageMaterialConfig.PACKAGE_ID), is("Duplicate package material detected!")); assertThat(existingMaterial.errors().getAll().size(), is(1)); assertThat(existingMaterial.errors().on(PackageMaterialConfig.PACKAGE_ID), is("Duplicate package material detected!")); assertThat(nameToMaterialMap.size(), is(2)); }
public static StatementExecutorResponse execute( final ConfiguredStatement<ListProperties> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final KsqlConfigResolver resolver = new KsqlConfigResolver(); final Map<String, String> engineProperties = statement .getSessionConfig() .getConfig(false) .getAllConfigPropsWithSecretsObfuscated(); final List<Property> mergedProperties = mergedProperties(statement); final List<String> overwritten = mergedProperties .stream() .filter(property -> !Objects.equals( engineProperties.get(property.getName()), property.getValue())) .map(Property::getName) .collect(Collectors.toList()); final List<String> defaultProps = mergedProperties.stream() .filter(property -> resolver.resolve(property.getName(), false) .map(resolved -> resolved.isDefaultValue(property.getValue())) .orElse(false)) .map(Property::getName) .collect(Collectors.toList()); return StatementExecutorResponse.handled(Optional.of(new PropertiesList( statement.getMaskedStatementText(), mergedProperties, overwritten, defaultProps))); }
@Test public void shouldContainLevelField() { // When: final PropertiesList properties = (PropertiesList) CustomExecutors.LIST_PROPERTIES.execute( engine.configure("LIST PROPERTIES;"), mock(SessionProperties.class), engine.getEngine(), engine.getServiceContext() ).getEntity().orElseThrow(IllegalStateException::new); // Then: assertThat(toMap(properties).get(KsqlConfig.KSQL_EXT_DIR).getLevel(), equalTo("SERVER")); assertThat(toMap(properties).get(KsqlConfig.KSQL_STRING_CASE_CONFIG_TOGGLE).getLevel(), equalTo("QUERY")); }
@Override public RemoteEnvironment createEnvironment(Environment environment, String workerId) throws Exception { Preconditions.checkState( environment .getUrn() .equals(BeamUrns.getUrn(RunnerApi.StandardEnvironments.Environments.PROCESS)), "The passed environment does not contain a ProcessPayload."); final RunnerApi.ProcessPayload processPayload = RunnerApi.ProcessPayload.parseFrom(environment.getPayload()); String executable = processPayload.getCommand(); String provisionEndpoint = provisioningServiceServer.getApiServiceDescriptor().getUrl(); String semiPersistDir = pipelineOptions.as(RemoteEnvironmentOptions.class).getSemiPersistDir(); ImmutableList.Builder<String> argsBuilder = ImmutableList.<String>builder() .add(String.format("--id=%s", workerId)) .add(String.format("--provision_endpoint=%s", provisionEndpoint)); if (semiPersistDir != null) { argsBuilder.add(String.format("--semi_persist_dir=%s", semiPersistDir)); } LOG.debug("Creating Process for worker ID {}", workerId); // Wrap the blocking call to clientSource.get in case an exception is thrown. InstructionRequestHandler instructionHandler = null; try { ProcessManager.RunningProcess process = processManager.startProcess( workerId, executable, argsBuilder.build(), processPayload.getEnvMap()); // Wait on a client from the gRPC server. while (instructionHandler == null) { try { // If the process is not alive anymore, we abort. process.isAliveOrThrow(); instructionHandler = clientSource.take(workerId, Duration.ofSeconds(5)); } catch (TimeoutException timeoutEx) { LOG.info( "Still waiting for startup of environment '{}' for worker id {}", processPayload.getCommand(), workerId); } catch (InterruptedException interruptEx) { Thread.currentThread().interrupt(); throw new RuntimeException(interruptEx); } } } catch (Exception e) { try { processManager.stopProcess(workerId); } catch (Exception processKillException) { e.addSuppressed(processKillException); } throw e; } return ProcessEnvironment.create(processManager, environment, workerId, instructionHandler); }
@Test public void createsMultipleEnvironments() throws Exception { Environment fooEnv = Environments.createProcessEnvironment("", "", "foo", Collections.emptyMap()); RemoteEnvironment fooHandle = factory.createEnvironment(fooEnv, "workerId"); assertThat(fooHandle.getEnvironment(), is(equalTo(fooEnv))); Environment barEnv = Environments.createProcessEnvironment("", "", "bar", Collections.emptyMap()); RemoteEnvironment barHandle = factory.createEnvironment(barEnv, "workerId"); assertThat(barHandle.getEnvironment(), is(equalTo(barEnv))); }
public static String getMinInstantTime(String fileName) { Matcher fileMatcher = ARCHIVE_FILE_PATTERN.matcher(fileName); if (fileMatcher.matches()) { return fileMatcher.group(1); } else { throw new HoodieException("Unexpected archival file name: " + fileName); } }
@Test void testParseMinInstantTime() { String fileName = "001_002_0.parquet"; String minInstantTime = LSMTimeline.getMinInstantTime(fileName); assertThat(minInstantTime, is("001")); assertThrows(HoodieException.class, () -> LSMTimeline.getMinInstantTime("invalid_file_name.parquet")); }
@Override @NonNull public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); if (CorsUtils.isCorsRequest(request)) { ServerHttpResponse response = exchange.getResponse(); HttpHeaders headers = response.getHeaders(); // finger allow origins final String origin = request.getHeaders().getOrigin(); boolean allowCors = this.filterConfig.isAllowedAnyOrigin(); if (!allowCors && Objects.nonNull(this.filterConfig.getAllowedOrigin())) { final String scheme = exchange.getRequest().getURI().getScheme(); final CrossFilterConfig.AllowedOriginConfig allowedOriginConfig = this.filterConfig.getAllowedOrigin(); Set<String> allowedOrigin = Optional.ofNullable(allowedOriginConfig.getPrefixes()).orElse(Collections.emptySet()) .stream() .filter(StringUtils::isNoneBlank) // scheme://prefix spacer domain .map(prefix -> String.format("%s://%s%s%s", scheme, prefix.trim(), StringUtils.defaultString(allowedOriginConfig.getSpacer(), ".").trim(), StringUtils.defaultString(allowedOriginConfig.getDomain(), "").trim())) .collect(Collectors.toSet()); // add all origin domains allowedOrigin.addAll(Optional.ofNullable(allowedOriginConfig.getOrigins()).orElse(Collections.emptySet()) .stream() .filter(StringUtils::isNoneBlank) .map(oneOrigin -> { if (ALL.equals(oneOrigin) || oneOrigin.startsWith(String.format("%s://", scheme))) { return oneOrigin.trim(); } return String.format("%s://%s", scheme, oneOrigin.trim()); }) .collect(Collectors.toSet())); allowCors = allowedOrigin.contains(origin) || allowedOrigin.contains(ALL); // if the origin is not allow check match origin again String originRegex; if (!allowCors && StringUtils.isNotBlank(originRegex = this.filterConfig.getAllowedOrigin().getOriginRegex())) { allowCors = Pattern.matches(originRegex.trim(), origin); } } if (allowCors) { // "Access-Control-Allow-Origin" headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin); // "Access-Control-Allow-Methods" this.filterSameHeader(headers, HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, this.filterConfig.getAllowedMethods()); // "Access-Control-Max-Age" this.filterSameHeader(headers, HttpHeaders.ACCESS_CONTROL_MAX_AGE, this.filterConfig.getMaxAge()); // "Access-Control-Allow-Headers" this.filterSameHeader(headers, HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, this.filterConfig.getAllowedHeaders()); // "Access-Control-Expose-Headers" this.filterSameHeader(headers, HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, this.filterConfig.getAllowedExpose()); // "Access-Control-Allow-Credentials" this.filterSameHeader(headers, HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, String.valueOf(this.filterConfig.isAllowCredentials())); } if (request.getMethod() == HttpMethod.OPTIONS) { response.setStatusCode(HttpStatus.OK); return Mono.empty(); } } return chain.filter(exchange); }
@Test public void testOriginRegex() { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest .get("http://localhost:8080") .header("Origin", "http://abc.com") .build()); ServerHttpResponse exchangeResponse = exchange.getResponse(); exchangeResponse.getHeaders().add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "0"); exchangeResponse.getHeaders().add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "*"); WebFilterChain chainNoHeader = mock(WebFilterChain.class); when(chainNoHeader.filter(exchange)).thenReturn(Mono.empty()); CrossFilterConfig crossFilterConfig = new CrossFilterConfig(); final String regex = "^http(|s)://(.*\\.|)abc.com$"; crossFilterConfig.getAllowedOrigin().setOriginRegex(regex); CrossFilter filterNoHeader = new CrossFilter(crossFilterConfig); StepVerifier.create(filterNoHeader.filter(exchange, chainNoHeader)) .expectSubscription() .verifyComplete(); Assertions.assertTrue(Pattern.matches(regex, "http://console.ada.abc.com")); Assertions.assertTrue(Pattern.matches(regex, "http://console.abc.com")); Assertions.assertTrue(Pattern.matches(regex, "http://abc.com")); Assertions.assertFalse(Pattern.matches(regex, "http://aabc.com")); }
public static Guess performGuess(List<Date> releaseDates) { if (releaseDates.size() <= 1) { return new Guess(Schedule.UNKNOWN, null, null); } else if (releaseDates.size() > MAX_DATA_POINTS) { releaseDates = releaseDates.subList(releaseDates.size() - MAX_DATA_POINTS, releaseDates.size()); } Stats stats = getStats(releaseDates); final int maxTotalWrongDays = Math.max(1, releaseDates.size() / 5); final int maxSingleDayOff = releaseDates.size() / 10; GregorianCalendar last = new GregorianCalendar(); last.setTime(releaseDates.get(releaseDates.size() - 1)); last.set(Calendar.HOUR_OF_DAY, (int) stats.medianHour); last.set(Calendar.MINUTE, (int) ((stats.medianHour - Math.floor(stats.medianHour)) * 60)); last.set(Calendar.SECOND, 0); last.set(Calendar.MILLISECOND, 0); if (Math.abs(stats.medianDistance - ONE_DAY) < 2 * ONE_HOUR && stats.avgDeltaToMedianDistance < 2 * ONE_HOUR) { addTime(last, ONE_DAY); return new Guess(Schedule.DAILY, Arrays.asList(Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, Calendar.SUNDAY), last.getTime()); } else if (Math.abs(stats.medianDistance - ONE_WEEK) < ONE_DAY && stats.avgDeltaToMedianDistance < 2 * ONE_DAY) { // Just using last.set(Calendar.DAY_OF_WEEK) could skip a week // when the last release is delayed over week boundaries addTime(last, 3 * ONE_DAY); do { addTime(last, ONE_DAY); } while (last.get(Calendar.DAY_OF_WEEK) != stats.mostOftenDayOfWeek); return new Guess(Schedule.WEEKLY, List.of(stats.mostOftenDayOfWeek), last.getTime()); } else if (Math.abs(stats.medianDistance - 2 * ONE_WEEK) < ONE_DAY && stats.avgDeltaToMedianDistance < 2 * ONE_DAY) { // Just using last.set(Calendar.DAY_OF_WEEK) could skip a week // when the last release is delayed over week boundaries addTime(last, 10 * ONE_DAY); do { addTime(last, ONE_DAY); } while (last.get(Calendar.DAY_OF_WEEK) != stats.mostOftenDayOfWeek); return new Guess(Schedule.BIWEEKLY, List.of(stats.mostOftenDayOfWeek), last.getTime()); } else if (Math.abs(stats.medianDistance - ONE_MONTH) < 5 * ONE_DAY && stats.avgDeltaToMedianDistance < 5 * ONE_DAY) { if (stats.daysOfMonth[stats.mostOftenDayOfMonth] >= releaseDates.size() - maxTotalWrongDays) { // Just using last.set(Calendar.DAY_OF_MONTH) could skip a week // when the last release is delayed over week boundaries addTime(last, 2 * ONE_WEEK); do { addTime(last, ONE_DAY); } while (last.get(Calendar.DAY_OF_MONTH) != stats.mostOftenDayOfMonth); return new Guess(Schedule.MONTHLY, null, last.getTime()); } addTime(last, 3 * ONE_WEEK + 3 * ONE_DAY); do { addTime(last, ONE_DAY); } while (last.get(Calendar.DAY_OF_WEEK) != stats.mostOftenDayOfWeek); return new Guess(Schedule.FOURWEEKLY, List.of(stats.mostOftenDayOfWeek), last.getTime()); } // Find release days List<Integer> largeDays = new ArrayList<>(); for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) { if (stats.daysOfWeek[i] > maxSingleDayOff) { largeDays.add(i); } } // Ensure that all release days are used similarly often int averageDays = releaseDates.size() / largeDays.size(); boolean matchesAverageDays = true; for (int day : largeDays) { if (stats.daysOfWeek[day] < averageDays - maxSingleDayOff) { matchesAverageDays = false; break; } } if (matchesAverageDays && stats.medianDistance < ONE_WEEK) { // Fixed daily release schedule (eg Mo, Thu, Fri) addUntil(last, largeDays); if (largeDays.size() == 5 && largeDays.containsAll(Arrays.asList( Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY))) { return new Guess(Schedule.WEEKDAYS, largeDays, last.getTime()); } return new Guess(Schedule.SPECIFIC_DAYS, largeDays, last.getTime()); } else if (largeDays.size() == 1) { // Probably still weekly with more exceptions than others addUntil(last, largeDays); return new Guess(Schedule.WEEKLY, largeDays, last.getTime()); } addTime(last, (long) (0.6f * stats.medianDistance)); return new Guess(Schedule.UNKNOWN, null, last.getTime()); }
@Test public void testEdgeCases() { ArrayList<Date> releaseDates = new ArrayList<>(); assertEquals(ReleaseScheduleGuesser.Schedule.UNKNOWN, performGuess(releaseDates).schedule); releaseDates.add(makeDate("2024-01-01 16:30")); assertEquals(ReleaseScheduleGuesser.Schedule.UNKNOWN, performGuess(releaseDates).schedule); }
public void assignRoles( List<Object> rolesToAssign ) { List<UIRepositoryObjectAcl> acls = new ArrayList<UIRepositoryObjectAcl>(); for ( Object role : rolesToAssign ) { if ( role instanceof String ) { String roleToAssign = (String) role; acls.add( assignRole( roleToAssign ) ); } } this.firePropertyChange( "selectedRoleList", null, getSelectedRoleList() ); //$NON-NLS-1$ setSelectedAssignedRoles( acls ); setSelectedAvailableRoles( new ArrayList<String>() ); }
@Test public void testAssignRoles() { UIRepositoryObjectAcl selectedRoleAcl = new UIRepositoryObjectAcl( createRoleAce( ROLE1 ) ); repositoryObjectAcls.addAcl( selectedRoleAcl ); repositoryObjectAclModel.setAclsList( null, defaultRoleNameList ); List<Object> objectRoleList = Arrays.asList( new Object[] { ROLE2 } ); repositoryObjectAclModel.assignRoles( objectRoleList ); assertStringListMatches( Arrays.asList( new String[] { ROLE3 } ), repositoryObjectAclModel.getAvailableRoleList() ); assertNameToAclListMatches( Arrays.asList( new String[] { ROLE2 } ), repositoryObjectAclModel .getSelectedAssignedRoles() ); assertNameToAclListMatches( Arrays.asList( new String[] { ROLE2 } ), repositoryObjectAclModel.getAclsToAdd() ); repositoryObjectAclModel.updateSelectedAcls(); assertNameToAclListMatches( Arrays.asList( new String[] { ROLE1, ROLE2 } ), repositoryObjectAclModel .getSelectedAcls().getAcls() ); // For some reason, updateSelectedAcls does not clear aclsToAdd. After the update ROLE2 is still present in // the aclsToAdd list. This probably is not an issue because the interface reloads. For now, I will clear // manually now so I can exercise some unassign code. repositoryObjectAclModel.getAclsToAdd().clear(); // Unassign the pending ROLE2 and the pre-assigned ROLE1 UIRepositoryObjectAcl role2Acl = repositoryObjectAclModel.getSelectedRole( 1 ); repositoryObjectAclModel.unassign( Arrays.asList( new Object[] { role2Acl, selectedRoleAcl } ) ); assertEquals( 0, repositoryObjectAclModel.getSelectedAssignedRoles().size() ); assertStringListMatches( defaultRoleNameList, repositoryObjectAclModel.getAvailableRoleList() ); repositoryObjectAclModel.updateSelectedAcls(); assertEquals( 0, repositoryObjectAclModel.getSelectedAcls().getAcls().size() ); }
@Override public void addTask(Object key, AbstractDelayTask newTask) { lock.lock(); try { AbstractDelayTask existTask = tasks.get(key); if (null != existTask) { newTask.merge(existTask); } tasks.put(key, newTask); } finally { lock.unlock(); } }
@Test void testRemoveProcessor() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenReturn(true); nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor); nacosDelayTaskExecuteEngine.removeProcessor("test"); nacosDelayTaskExecuteEngine.addTask("test", abstractTask); TimeUnit.MILLISECONDS.sleep(200); verify(testTaskProcessor, never()).process(abstractTask); verify(taskProcessor).process(abstractTask); }
public void delete(final String name) { dynamoDbClient.deleteItem(DeleteItemRequest.builder() .tableName(tableName) .key(Map.of(KEY_NAME, AttributeValues.fromString(name))) .build()); }
@Test void testDelete() { remoteConfigs.set(new RemoteConfig("android.stickers", 50, Set.of(AuthHelper.VALID_UUID), "FALSE", "TRUE", null)); remoteConfigs.set(new RemoteConfig("ios.stickers", 50, Set.of(), "FALSE", "TRUE", null)); remoteConfigs.set(new RemoteConfig("ios.stickers", 75, Set.of(), "FALSE", "TRUE", null)); remoteConfigs.set(new RemoteConfig("value.always", 100, Set.of(), "never", "always", null)); remoteConfigs.delete("android.stickers"); List<RemoteConfig> configs = remoteConfigs.getAll(); assertThat(configs).hasSize(2); assertThat(configs.get(0).getName()).isEqualTo("ios.stickers"); assertThat(configs.get(0).getPercentage()).isEqualTo(75); assertThat(configs.get(0).getDefaultValue()).isEqualTo("FALSE"); assertThat(configs.get(0).getValue()).isEqualTo("TRUE"); assertThat(configs.get(1).getName()).isEqualTo("value.always"); assertThat(configs.get(1).getPercentage()).isEqualTo(100); assertThat(configs.get(1).getValue()).isEqualTo("always"); assertThat(configs.get(1).getDefaultValue()).isEqualTo("never"); }
@Override public int hashCode() { return Objects.hash(type, name, host, port, startedAt); }
@Test public void hashcode_is_based_on_content() { NodeDetails.Builder builder = testSupport.randomNodeDetailsBuilder(); NodeDetails underTest = builder.build(); assertThat(builder.build().hashCode()) .isEqualTo(underTest.hashCode()); }
@Override public ScannerReport.Component readComponent(int componentRef) { ensureInitialized(); return delegate.readComponent(componentRef); }
@Test public void readComponent_is_not_cached() { writer.writeComponent(COMPONENT); assertThat(underTest.readComponent(COMPONENT_REF)).isNotSameAs(underTest.readComponent(COMPONENT_REF)); }
@Override public Map<SubClusterId, List<ResourceRequest>> splitResourceRequests( List<ResourceRequest> resourceRequests, Set<SubClusterId> timedOutSubClusters) throws YarnException { if (homeSubcluster == null) { throw new FederationPolicyException("No home subcluster available"); } Map<SubClusterId, SubClusterInfo> active = getActiveSubclusters(); if (!active.containsKey(homeSubcluster)) { throw new FederationPolicyException( "The local subcluster " + homeSubcluster + " is not active"); } List<ResourceRequest> resourceRequestsCopy = new ArrayList<>(resourceRequests); return Collections.singletonMap(homeSubcluster, resourceRequestsCopy); }
@Test public void testHomeSubclusterNotActive() throws YarnException { // We setup the home subcluster to a non-existing one initializePolicyContext(getPolicy(), mock(WeightedPolicyInfo.class), getActiveSubclusters(), "badsc"); // Verify the request fails because the home subcluster is not available try { String[] hosts = new String[] {"host0", "host1", "host2", "host3"}; List<ResourceRequest> resourceRequests = createResourceRequests( hosts, 2 * 1024, 2, 1, 3, null, false); HomeAMRMProxyPolicy federationPolicy = (HomeAMRMProxyPolicy)getPolicy(); federationPolicy.splitResourceRequests(resourceRequests, new HashSet<SubClusterId>()); fail("It should fail when the home subcluster is not active"); } catch(FederationPolicyException e) { GenericTestUtils.assertExceptionContains("is not active", e); } }
@Override public boolean isResolvable(ConfigDataLocationResolverContext context, ConfigDataLocation location) { if (!location.hasPrefix(PREFIX)) { return false; } boolean contextEnabled = context.getBinder() .bind("spring.cloud.polaris.enabled", Boolean.class) .orElse(true); boolean configEnabled = context.getBinder() .bind("spring.cloud.polaris.config.enabled", Boolean.class) .orElse(true); return contextEnabled && configEnabled; }
@Test public void testIsResolvable() { when(context.getBinder()).thenReturn(environmentBinder); assertThat(this.resolver.isResolvable(this.context, ConfigDataLocation.of("configserver:"))).isFalse(); assertThat(this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris:"))).isTrue(); assertThat(this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris"))).isTrue(); }
@Deprecated public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype) throws IllegalStateException { return Types.resolveLastTypeParameter(genericContext, supertype); }
@Test void resolveLastTypeParameterWhenNotSubtype() throws Exception { Type context = LastTypeParameter.class.getDeclaredField("PARAMETERIZED_LIST_STRING").getGenericType(); Type listStringType = LastTypeParameter.class.getDeclaredField("LIST_STRING").getGenericType(); Type last = resolveLastTypeParameter(context, Parameterized.class); assertThat(last).isEqualTo(listStringType); }