focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static MongoIndexRange create(ObjectId id, String indexName, DateTime begin, DateTime end, DateTime calculatedAt, int calculationDuration, List<String> streamIds) { return new AutoValue_MongoIndexRange(id, indexName, begin, end, calculatedAt, calculationDuration, streamIds); }
@Test public void testJsonMapping() throws Exception { String indexName = "test"; DateTime begin = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC); DateTime end = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC); DateTime calculatedAt = new DateTime(2015, 2, 1, 0, 0, DateTimeZone.UTC); int calculationDuration = 42; MongoIndexRange indexRange = MongoIndexRange.create(indexName, begin, end, calculatedAt, calculationDuration); ObjectMapper objectMapper = new ObjectMapperProvider().get(); String json = objectMapper.writeValueAsString(indexRange); Object document = Configuration.defaultConfiguration().jsonProvider().parse(json); assertThat((String) JsonPath.read(document, "$." + MongoIndexRange.FIELD_INDEX_NAME)).isEqualTo(indexName); assertThat((long) JsonPath.read(document, "$." + MongoIndexRange.FIELD_BEGIN)).isEqualTo(begin.getMillis()); assertThat((long) JsonPath.read(document, "$." + MongoIndexRange.FIELD_END)).isEqualTo(end.getMillis()); assertThat((long) JsonPath.read(document, "$." + MongoIndexRange.FIELD_CALCULATED_AT)).isEqualTo(calculatedAt.getMillis()); assertThat((int) JsonPath.read(document, "$." + MongoIndexRange.FIELD_TOOK_MS)).isEqualTo(calculationDuration); }
protected static ResourceSchema getBagSubSchema(HCatFieldSchema hfs) throws IOException { // there are two cases - array<Type> and array<struct<...>> // in either case the element type of the array is represented in a // tuple field schema in the bag's field schema - the second case (struct) // more naturally translates to the tuple - in the first case (array<Type>) // we simulate the tuple by putting the single field in a tuple Properties props = UDFContext.getUDFContext().getClientSystemProps(); String innerTupleName = HCatConstants.HCAT_PIG_INNER_TUPLE_NAME_DEFAULT; if (props != null && props.containsKey(HCatConstants.HCAT_PIG_INNER_TUPLE_NAME)) { innerTupleName = props.getProperty(HCatConstants.HCAT_PIG_INNER_TUPLE_NAME) .replaceAll("FIELDNAME", hfs.getName()); } String innerFieldName = HCatConstants.HCAT_PIG_INNER_FIELD_NAME_DEFAULT; if (props != null && props.containsKey(HCatConstants.HCAT_PIG_INNER_FIELD_NAME)) { innerFieldName = props.getProperty(HCatConstants.HCAT_PIG_INNER_FIELD_NAME) .replaceAll("FIELDNAME", hfs.getName()); } ResourceFieldSchema[] bagSubFieldSchemas = new ResourceFieldSchema[1]; bagSubFieldSchemas[0] = new ResourceFieldSchema().setName(innerTupleName) .setDescription("The tuple in the bag") .setType(DataType.TUPLE); HCatFieldSchema arrayElementFieldSchema = hfs.getArrayElementSchema().get(0); if (arrayElementFieldSchema.getType() == Type.STRUCT) { bagSubFieldSchemas[0].setSchema(getTupleSubSchema(arrayElementFieldSchema)); } else if (arrayElementFieldSchema.getType() == Type.ARRAY) { ResourceSchema s = new ResourceSchema(); List<ResourceFieldSchema> lrfs = Arrays.asList(getResourceSchemaFromFieldSchema(arrayElementFieldSchema)); s.setFields(lrfs.toArray(new ResourceFieldSchema[lrfs.size()])); bagSubFieldSchemas[0].setSchema(s); } else { ResourceFieldSchema[] innerTupleFieldSchemas = new ResourceFieldSchema[1]; innerTupleFieldSchemas[0] = new ResourceFieldSchema().setName(innerFieldName) .setDescription("The inner field in the tuple in the bag") .setType(getPigType(arrayElementFieldSchema)) .setSchema(null); // the element type is not a tuple - so no subschema bagSubFieldSchemas[0].setSchema(new ResourceSchema().setFields(innerTupleFieldSchemas)); } return new ResourceSchema().setFields(bagSubFieldSchemas); }
@Test public void testGetBagSubSchema() throws Exception { // Define the expected schema. ResourceFieldSchema[] bagSubFieldSchemas = new ResourceFieldSchema[1]; bagSubFieldSchemas[0] = new ResourceFieldSchema().setName("innertuple") .setDescription("The tuple in the bag").setType(DataType.TUPLE); ResourceFieldSchema[] innerTupleFieldSchemas = new ResourceFieldSchema[1]; innerTupleFieldSchemas[0] = new ResourceFieldSchema().setName("innerfield").setType(DataType.CHARARRAY); bagSubFieldSchemas[0].setSchema(new ResourceSchema().setFields(innerTupleFieldSchemas)); ResourceSchema expected = new ResourceSchema().setFields(bagSubFieldSchemas); // Get the actual converted schema. HCatSchema hCatSchema = new HCatSchema(Lists.newArrayList( new HCatFieldSchema("innerLlama", HCatFieldSchema.Type.STRING, null))); HCatFieldSchema hCatFieldSchema = new HCatFieldSchema("llama", HCatFieldSchema.Type.ARRAY, hCatSchema, null); ResourceSchema actual = PigHCatUtil.getBagSubSchema(hCatFieldSchema); Assert.assertEquals(expected.toString(), actual.toString()); }
private RemotingCommand queryConsumerOffset(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { final RemotingCommand response = RemotingCommand.createResponseCommand(QueryConsumerOffsetResponseHeader.class); final QueryConsumerOffsetResponseHeader responseHeader = (QueryConsumerOffsetResponseHeader) response.readCustomHeader(); final QueryConsumerOffsetRequestHeader requestHeader = (QueryConsumerOffsetRequestHeader) request .decodeCommandCustomHeader(QueryConsumerOffsetRequestHeader.class); TopicQueueMappingContext mappingContext = this.brokerController.getTopicQueueMappingManager().buildTopicQueueMappingContext(requestHeader); RemotingCommand rewriteResult = rewriteRequestForStaticTopic(requestHeader, mappingContext); if (rewriteResult != null) { return rewriteResult; } long offset = this.brokerController.getConsumerOffsetManager().queryOffset( requestHeader.getConsumerGroup(), requestHeader.getTopic(), requestHeader.getQueueId()); if (offset >= 0) { responseHeader.setOffset(offset); response.setCode(ResponseCode.SUCCESS); response.setRemark(null); } else { long minOffset = this.brokerController.getMessageStore().getMinOffsetInQueue(requestHeader.getTopic(), requestHeader.getQueueId()); if (requestHeader.getSetZeroIfNotFound() != null && Boolean.FALSE.equals(requestHeader.getSetZeroIfNotFound())) { response.setCode(ResponseCode.QUERY_NOT_FOUND); response.setRemark("Not found, do not set to zero, maybe this group boot first"); } else if (minOffset <= 0 && this.brokerController.getMessageStore().checkInMemByConsumeOffset( requestHeader.getTopic(), requestHeader.getQueueId(), 0, 1)) { responseHeader.setOffset(0L); response.setCode(ResponseCode.SUCCESS); response.setRemark(null); } else { response.setCode(ResponseCode.QUERY_NOT_FOUND); response.setRemark("Not found, V3_0_6_SNAPSHOT maybe this group consumer boot first"); } } RemotingCommand rewriteResponseResult = rewriteResponseForStaticTopic(requestHeader, responseHeader, mappingContext, response.getCode()); if (rewriteResponseResult != null) { return rewriteResponseResult; } return response; }
@Test public void testQueryConsumerOffset() throws RemotingCommandException, ExecutionException, InterruptedException { RemotingCommand request = buildQueryConsumerOffsetRequest(group, topic, 0, true); RemotingCommand response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.QUERY_NOT_FOUND); when(brokerController.getConsumerOffsetManager()).thenReturn(consumerOffsetManager); when(consumerOffsetManager.queryOffset(anyString(),anyString(),anyInt())).thenReturn(0L); response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); when(consumerOffsetManager.queryOffset(anyString(),anyString(),anyInt())).thenReturn(-1L); when(messageStore.getMinOffsetInQueue(anyString(),anyInt())).thenReturn(-1L); when(messageStore.checkInMemByConsumeOffset(anyString(),anyInt(),anyLong(),anyInt())).thenReturn(true); response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); TopicQueueMappingManager topicQueueMappingManager = mock(TopicQueueMappingManager.class); when(brokerController.getTopicQueueMappingManager()).thenReturn(topicQueueMappingManager); when(topicQueueMappingManager.buildTopicQueueMappingContext(any(QueryConsumerOffsetRequestHeader.class))).thenReturn(mappingContext); response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.NOT_LEADER_FOR_QUEUE); List<LogicQueueMappingItem> items = new ArrayList<>(); LogicQueueMappingItem item1 = createLogicQueueMappingItem("BrokerC", 0, 0L, 0L); items.add(item1); when(mappingContext.getMappingItemList()).thenReturn(items); when(mappingContext.getLeaderItem()).thenReturn(item1); when(mappingContext.getCurrentItem()).thenReturn(item1); when(mappingContext.isLeader()).thenReturn(true); response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); LogicQueueMappingItem item2 = createLogicQueueMappingItem("BrokerA", 0, 0L, 0L); items.add(item2); QueryConsumerOffsetResponseHeader queryConsumerOffsetResponseHeader = new QueryConsumerOffsetResponseHeader(); queryConsumerOffsetResponseHeader.setOffset(0L); RpcResponse rpcResponse = new RpcResponse(ResponseCode.SUCCESS,queryConsumerOffsetResponseHeader,null); when(responseFuture.get()).thenReturn(rpcResponse); response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); queryConsumerOffsetResponseHeader.setOffset(-1L); rpcResponse = new RpcResponse(ResponseCode.SUCCESS,queryConsumerOffsetResponseHeader,null); when(responseFuture.get()).thenReturn(rpcResponse); response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.QUERY_NOT_FOUND); }
@Override public FlinkPod decorateFlinkPod(FlinkPod flinkPod) { final Container mainContainerWithStartCmd = new ContainerBuilder(flinkPod.getMainContainer()) .withCommand(kubernetesTaskManagerParameters.getContainerEntrypoint()) .withArgs(getTaskManagerStartCommand()) .addToEnv( new EnvVarBuilder() .withName(Constants.ENV_TM_JVM_MEM_OPTS) .withValue( kubernetesTaskManagerParameters.getJvmMemOptsEnv()) .build()) .build(); return new FlinkPod.Builder(flinkPod).withMainContainer(mainContainerWithStartCmd).build(); }
@Test void testTaskManagerStartCommandsAndArgs() { final FlinkPod resultFlinkPod = cmdTaskManagerDecorator.decorateFlinkPod(baseFlinkPod); final String entryCommand = flinkConfig.get(KubernetesConfigOptions.KUBERNETES_ENTRY_PATH); assertThat(resultFlinkPod.getMainContainer().getCommand()) .containsExactlyInAnyOrder(entryCommand); List<String> flinkCommands = KubernetesUtils.getStartCommandWithBashWrapper( Constants.KUBERNETES_TASK_MANAGER_SCRIPT_PATH + " " + DYNAMIC_PROPERTIES + " " + mainClassArgs + " " + ENTRYPOINT_ARGS); assertThat(resultFlinkPod.getMainContainer().getArgs()) .containsExactlyElementsOf(flinkCommands); }
public void close(final boolean closeQueries) { primaryContext.getQueryRegistry().close(closeQueries); try { cleanupService.stopAsync().awaitTerminated( this.primaryContext.getKsqlConfig() .getLong(KsqlConfig.KSQL_QUERY_CLEANUP_SHUTDOWN_TIMEOUT_MS), TimeUnit.MILLISECONDS); } catch (final TimeoutException e) { log.warn("Timed out while closing cleanup service. " + "External resources for the following applications may be orphaned: {}", cleanupService.pendingApplicationIds() ); } engineMetrics.close(); aggregateMetricsCollector.shutdown(); }
@Test public void shouldCleanUpTransientConsumerGroupsOnCloseSharedRuntimes() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); final QueryMetadata query = KsqlEngineTestUtil.executeQuery( serviceContext, ksqlEngine, "select * from test1 EMIT CHANGES;", ksqlConfig, Collections.emptyMap() ); query.start(); // When: query.close(); // Then: awaitCleanupComplete(); final Set<String> deletedConsumerGroups = ( (FakeKafkaConsumerGroupClient) serviceContext.getConsumerGroupClient() ).getDeletedConsumerGroups(); assertThat( Iterables.getOnlyElement(deletedConsumerGroups), containsString("_confluent-ksql-default_transient_")); }
public static ExtensionMappingInstructionWrapper extension(ExtensionTreatment extension, DeviceId deviceId) { checkNotNull(extension, "Extension instruction cannot be null"); checkNotNull(deviceId, "Device ID cannot be null"); return new ExtensionMappingInstructionWrapper(extension, deviceId); }
@Test public void testExtensionMethod() { final MappingInstruction instruction = MappingInstructions.extension(extensionTreatment1, deviceId1); final MappingInstructions.ExtensionMappingInstructionWrapper wrapper = checkAndConvert(instruction, MappingInstruction.Type.EXTENSION, MappingInstructions.ExtensionMappingInstructionWrapper.class); assertThat(wrapper.deviceId(), is(deviceId1)); assertThat(wrapper.extensionMappingInstruction(), is(extensionTreatment1)); }
@Override public void onMsg(TbContext ctx, TbMsg msg) { ListenableFuture<Boolean> deleteResultFuture = config.isDeleteForSingleEntity() ? Futures.transformAsync(getTargetEntityId(ctx, msg), targetEntityId -> deleteRelationToSpecificEntity(ctx, msg, targetEntityId), MoreExecutors.directExecutor()) : deleteRelationsByTypeAndDirection(ctx, msg, ctx.getDbCallbackExecutor()); withCallback(deleteResultFuture, deleted -> { if (deleted) { ctx.tellSuccess(msg); return; } ctx.tellFailure(msg, new RuntimeException("Failed to delete relation(s) with originator!")); }, t -> ctx.tellFailure(msg, t), MoreExecutors.directExecutor()); }
@Test void givenSupportedEntityType_whenOnMsgAndDeleteForSingleEntityIsFalse_thenVerifyRelationsDeletedAndOutMsgSuccess() throws TbNodeException { // GIVEN config.setEntityType(EntityType.DEVICE); config.setEntityNamePattern("${name}"); config.setEntityTypePattern("${type}"); var nodeConfiguration = new TbNodeConfiguration(JacksonUtil.valueToTree(config)); node.init(ctxMock, nodeConfiguration); when(ctxMock.getTenantId()).thenReturn(tenantId); when(ctxMock.getRelationService()).thenReturn(relationServiceMock); when(ctxMock.getDbCallbackExecutor()).thenReturn(dbExecutor); var relationToDelete = new EntityRelation(); when(relationServiceMock.findByFromAndTypeAsync(any(), any(), any(), any())).thenReturn(Futures.immediateFuture(List.of(relationToDelete))); when(relationServiceMock.deleteRelationAsync(any(), any())).thenReturn(Futures.immediateFuture(true)); var md = getMetadataWithNameTemplate(); var msg = getTbMsg(originatorId, md); // WHEN node.onMsg(ctxMock, msg); verify(relationServiceMock).findByFromAndTypeAsync(eq(tenantId), eq(originatorId), eq(EntityRelation.CONTAINS_TYPE), eq(RelationTypeGroup.COMMON)); verify(relationServiceMock).deleteRelationAsync(eq(tenantId), eq(relationToDelete)); verify(ctxMock).tellSuccess(eq(msg)); verify(ctxMock, never()).tellNext(any(), anyString()); verify(ctxMock, never()).tellNext(any(), anySet()); verify(ctxMock, never()).tellFailure(any(), any()); verifyNoMoreInteractions(ctxMock, relationServiceMock); }
@ScalarOperator(CAST) @SqlType(StandardTypes.BIGINT) public static long castToBigint(@SqlType(StandardTypes.SMALLINT) long value) { return value; }
@Test public void testCastToBigint() { assertFunction("cast(SMALLINT'37' as bigint)", BIGINT, 37L); assertFunction("cast(SMALLINT'17' as bigint)", BIGINT, 17L); }
@Override public int numActiveElements() { return values.length; }
@Test public void activeElements() { SparseVector s = generateVectorA(); assertEquals(5, s.numActiveElements()); }
@Override public Long clusterCountKeysInSlot(int slot) { RedisClusterNode node = clusterGetNodeForSlot(slot); MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(new InetSocketAddress(node.getHost(), node.getPort())); RFuture<Long> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLUSTER_COUNTKEYSINSLOT, slot); return syncFuture(f); }
@Test public void testClusterCountKeysInSlot() { testInCluster(connection -> { Long t = connection.clusterCountKeysInSlot(1); assertThat(t).isZero(); }); }
@SneakyThrows(InterruptedException.class) public static void trigger(final Collection<CompletableFuture<?>> futures, final ExecuteCallback executeCallback) { BlockingQueue<CompletableFuture<?>> futureQueue = new LinkedBlockingQueue<>(); for (CompletableFuture<?> each : futures) { each.whenCompleteAsync(new BiConsumer<Object, Throwable>() { @SneakyThrows(InterruptedException.class) @Override public void accept(final Object unused, final Throwable throwable) { futureQueue.put(each); } }, CALLBACK_EXECUTOR); } for (int i = 1, count = futures.size(); i <= count; i++) { CompletableFuture<?> future = futureQueue.take(); try { future.get(); } catch (final ExecutionException ex) { Throwable cause = ex.getCause(); executeCallback.onFailure(null != cause ? cause : ex); throw new PipelineInternalException(ex); } } executeCallback.onSuccess(); }
@Test void assertTriggerPartSuccessFailure() { CompletableFuture<?> future1 = CompletableFuture.runAsync(new FixtureRunnable(true)); CompletableFuture<?> future2 = CompletableFuture.runAsync(new FixtureRunnable(false)); FixtureExecuteCallback executeCallback = new FixtureExecuteCallback(); try { ExecuteEngine.trigger(Arrays.asList(future1, future2), executeCallback); // CHECKSTYLE:OFF } catch (final RuntimeException ignored) { // CHECKSTYLE:ON } assertThat(executeCallback.successCount.get(), is(0)); assertThat(executeCallback.failureCount.get(), is(1)); }
public RuntimeOptionsBuilder parse(Map<String, String> properties) { return parse(properties::get); }
@Test void should_parse_rerun_files() throws IOException { mockFileResource("classpath:path/to.feature"); mockFileResource("classpath:path/to/other.feature"); properties.put(Constants.FEATURES_PROPERTY_NAME, "@" + temp.toString()); RuntimeOptions options = cucumberPropertiesParser.parse(properties).build(); assertThat(options.getFeaturePaths(), containsInAnyOrder(URI.create("classpath:path/to.feature"), URI.create("classpath:path/to/other.feature"))); }
private void preloadLangs() { String[] args = new String[]{getTesseractPath() + getTesseractProg(), "--list-langs"}; ProcessBuilder pb = new ProcessBuilder(args); setEnv(pb); Process process = null; try { process = pb.start(); getLangs(process, defaultConfig.getTimeoutSeconds()); } catch (TikaException | IOException e) { LOG.warn("Problem preloading langs", e); } finally { if (process != null) { process.destroyForcibly(); } } }
@Test public void testPreloadLangs() throws Exception { assumeTrue(canRun()); TikaConfig config; try (InputStream is = getResourceAsStream( "/test-configs/tika-config-tesseract-load-langs.xml")) { config = new TikaConfig(is); } Parser p = config.getParser(); Parser tesseractOCRParser = findParser(p, org.apache.tika.parser.ocr.TesseractOCRParser.class); assertNotNull(tesseractOCRParser); Set<String> langs = ((TesseractOCRParser) tesseractOCRParser).getLangs(); assertTrue(langs.size() > 0); TesseractOCRConfig tesseractOCRConfig = new TesseractOCRConfig(); tesseractOCRConfig.setLanguage("zzz"); ParseContext parseContext = new ParseContext(); parseContext.set(TesseractOCRConfig.class, tesseractOCRConfig); try { getRecursiveMetadata("testOCR_spacing.png", new AutoDetectParser(config), getMetadata(MediaType.image("png")), parseContext, false); fail("should have thrown exception"); } catch (TikaException e) { //expected } }
static int[] shiftRightMultiPrecision(int[] number, int length, int shifts) { if (shifts == 0) { return number; } // wordShifts = shifts / 32 int wordShifts = shifts >>> 5; // we don't want to lose any trailing bits for (int i = 0; i < wordShifts; i++) { checkState(number[i] == 0); } if (wordShifts > 0) { arraycopy(number, wordShifts, number, 0, length - wordShifts); fill(number, length - wordShifts, length, 0); } // bitShifts = shifts % 32 int bitShifts = shifts & 0b11111; if (bitShifts > 0) { // we don't want to lose any trailing bits checkState(number[0] << (Integer.SIZE - bitShifts) == 0); for (int position = 0; position < length - 1; position++) { number[position] = (number[position] >>> bitShifts) | (number[position + 1] << (Integer.SIZE - bitShifts)); } number[length - 1] = number[length - 1] >>> bitShifts; } return number; }
@Test public void testShiftRightMultiPrecision() { assertEquals(shiftRightMultiPrecision( new int[] {0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010, 0b11111111000000011010101010101011, 0b00000000000000000000000000000000}, 4, 0), new int[] {0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010, 0b11111111000000011010101010101011, 0b00000000000000000000000000000000}); assertEquals(shiftRightMultiPrecision( new int[] {0b00000000000000000000000000000000, 0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010, 0b11111111000000011010101010101011}, 5, 1), new int[] {0b10000000000000000000000000000000, 0b11010000101000101101000010100010, 0b00101011010010110101101010101010, 0b10101001011111000111110001010101, 0b1111111100000001101010101010101}); assertEquals(shiftRightMultiPrecision( new int[] {0b00000000000000000000000000000000, 0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010, 0b11111111000000011010101010101011}, 5, 32), new int[] {0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010, 0b11111111000000011010101010101011, 0b00000000000000000000000000000000}); assertEquals(shiftRightMultiPrecision( new int[] {0b00000000000000000000000000000000, 0b00000000000000000000000000000000, 0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010, 0b11111111000000011010101010101011}, 6, 33), new int[] {0b10000000000000000000000000000000, 0b11010000101000101101000010100010, 0b00101011010010110101101010101010, 0b10101001011111000111110001010101, 0b01111111100000001101010101010101, 0b00000000000000000000000000000000}); assertEquals(shiftRightMultiPrecision( new int[] {0b00000000000000000000000000000000, 0b00000000000000000000000000000000, 0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010, 0b11111111000000011010101010101011}, 6, 37), new int[] {0b00101000000000000000000000000000, 0b10101101000010100010110100001010, 0b01010010101101001011010110101010, 0b01011010100101111100011111000101, 0b00000111111110000000110101010101, 0b00000000000000000000000000000000}); assertEquals(shiftRightMultiPrecision( new int[] {0b00000000000000000000000000000000, 0b00000000000000000000000000000000, 0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010, 0b11111111000000011010101010101011}, 6, 64), new int[] {0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010, 0b11111111000000011010101010101011, 0b00000000000000000000000000000000, 0b00000000000000000000000000000000}); }
public void setDestinationType(String destinationType) { this.destinationType = destinationType; }
@Test(timeout = 60000) public void testQueueDestinationType() { activationSpec.setDestinationType(Queue.class.getName()); assertActivationSpecValid(); }
public void upgrade() { final List<User> users = userService.loadAll(); for (User user : users) { final Map<String, Set<String>> migratableEntities = getMigratableEntities(ImmutableSet.copyOf(user.getPermissions())); if (!migratableEntities.isEmpty()) { migrateUserPermissions(user, migratableEntities); } } }
@Test void migrateAllUserPermissions() { final ViewDTO view1 = mock(ViewDTO.class); final ViewDTO view2 = mock(ViewDTO.class); when(view1.type()).thenReturn(ViewDTO.Type.DASHBOARD); when(view2.type()).thenReturn(ViewDTO.Type.SEARCH); when(viewService.get("5c40ad603c034441a56943be")).thenReturn(Optional.of(view1)); when(viewService.get("5c40ad603c034441a56943c0")).thenReturn(Optional.of(view2)); User testuser1 = userService.load("testuser1"); assertThat(testuser1).isNotNull(); assertThat(testuser1.getPermissions().size()).isEqualTo(11 + userSelfEditPermissionCount); assertThat(dbGrantService.getForGranteesOrGlobal(ImmutableSet.of(grnRegistry.ofUser(testuser1)))).isEmpty(); migration.upgrade(); // check created grants for testuser1 final ImmutableSet<GrantDTO> grants = dbGrantService.getForGranteesOrGlobal(ImmutableSet.of(grnRegistry.ofUser(testuser1))); assertGrantInSet(grants, "grn::::dashboard:5e2afc66cd19517ec2dabadd", Capability.VIEW); assertGrantInSet(grants, "grn::::dashboard:5e2afc66cd19517ec2dabadf", Capability.MANAGE); assertGrantInSet(grants, "grn::::stream:5c40ad603c034441a56942bd", Capability.VIEW); assertGrantInSet(grants, "grn::::stream:5e2f5cfb4868e67ad4da562d", Capability.VIEW); assertGrantInSet(grants, "grn::::dashboard:5c40ad603c034441a56943be", Capability.MANAGE); assertGrantInSet(grants, "grn::::search:5c40ad603c034441a56943c0", Capability.VIEW); assertGrantInSet(grants, "grn::::event_definition:5c40ad603c034441a56942bf", Capability.MANAGE); assertGrantInSet(grants, "grn::::event_definition:5c40ad603c034441a56942c0", Capability.VIEW); assertThat(grants.size()).isEqualTo(8); // reload user and check that all migrated permissions have been removed testuser1 = userService.load("testuser1"); assertThat(testuser1).isNotNull(); assertThat(testuser1.getPermissions().size()).isEqualTo(userSelfEditPermissionCount); }
@Override public Optional<String> canUpgradeTo(final DataSource other) { final List<String> issues = PROPERTIES.stream() .filter(prop -> !prop.isCompatible(this, other)) .map(prop -> getCompatMessage(other, prop)) .collect(Collectors.toList()); checkSchemas(getSchema(), other.getSchema()) .map(s -> getCompatMessage(other, SCHEMA_PROP) + ". (" + s + ")") .ifPresent(issues::add); final String err = String.join("\n\tAND ", issues); return err.isEmpty() ? Optional.empty() : Optional.of(err); }
@Test public void shouldEnforceSameNameCompatbility() { // Given: final KsqlStream<String> streamA = new KsqlStream<>( "sql", SourceName.of("A"), SOME_SCHEMA, Optional.empty(), true, topic, false ); final KsqlStream<String> streamB = new KsqlStream<>( "sql", SourceName.of("B"), SOME_SCHEMA, Optional.empty(), true, topic, false ); // When: final Optional<String> err = streamA.canUpgradeTo(streamB); // Then: assertThat(err.isPresent(), is(true)); assertThat(err.get(), containsString("has name = `A` which is not upgradeable to `B`")); }
@Override public boolean isSupported() { return mIdProviderImpl != null; }
@Test public void isSupported() { XiaomiImpl xiaomi = new XiaomiImpl(mApplication); Assert.assertFalse(xiaomi.isSupported()); }
public static byte getCodeByAlias(String compress) { return TYPE_CODE_MAP.get(compress); }
@Test public void getCodeByAlias() throws Exception { Assert.assertEquals(CompressorFactory.getCodeByAlias("test"), (byte) 113); }
public ConnectionAuthContext authorizePeer(X509Certificate cert) { return authorizePeer(List.of(cert)); }
@Test void must_match_all_cn_and_san_patterns() { RequiredPeerCredential cnSuffixRequirement = createRequiredCredential(CN, "*.*.matching.suffix.cn"); RequiredPeerCredential cnPrefixRequirement = createRequiredCredential(CN, "matching.prefix.*.*.*"); RequiredPeerCredential sanPrefixRequirement = createRequiredCredential(SAN_DNS, "*.*.matching.suffix.san"); RequiredPeerCredential sanSuffixRequirement = createRequiredCredential(SAN_DNS, "matching.prefix.*.*.*"); PeerAuthorizer peerAuthorizer = createPeerAuthorizer( createPolicy(POLICY_1, cnSuffixRequirement, cnPrefixRequirement, sanPrefixRequirement, sanSuffixRequirement)); assertAuthorized(peerAuthorizer.authorizePeer(createCertificate("matching.prefix.matching.suffix.cn", List.of("matching.prefix.matching.suffix.san"), List.of()))); assertUnauthorized(peerAuthorizer.authorizePeer(createCertificate("matching.prefix.matching.suffix.cn", List.of("matching.prefix.invalid.suffix.san"), List.of()))); assertUnauthorized(peerAuthorizer.authorizePeer(createCertificate("invalid.prefix.matching.suffix.cn", List.of("matching.prefix.matching.suffix.san"), List.of()))); }
public static RestSettingBuilder delete(final RestIdMatcher idMatcher) { return single(HttpMethod.DELETE, checkNotNull(idMatcher, "ID Matcher should not be null")); }
@Test public void should_delete() throws Exception { server.resource("targets", delete("1").response(status(200)) ); running(server, () -> { HttpResponse httpResponse = helper.deleteForResponse(remoteUrl("/targets/1")); assertThat(httpResponse.getCode(), is(200)); }); }
public static boolean bindPort(Session session, String remoteHost, int remotePort, int localPort) throws JschRuntimeException { return bindPort(session, remoteHost, remotePort, "127.0.0.1", localPort); }
@Test @Disabled public void bindPortTest() { //新建会话,此会话用于ssh连接到跳板机(堡垒机),此处为10.1.1.1:22 Session session = JschUtil.getSession("looly.centos", 22, "test", "123456"); // 将堡垒机保护的内网8080端口映射到localhost,我们就可以通过访问http://localhost:8080/访问内网服务了 JschUtil.bindPort(session, "172.20.12.123", 8080, 8080); }
public static AvroGenericCoder of(Schema schema) { return AvroGenericCoder.of(schema); }
@Test public void testDeterminismTreeMapValue() { // The value is non-deterministic, so we should fail. assertNonDeterministic( AvroCoder.of(TreeMapNonDetValue.class), reasonField( UnorderedMapClass.class, "mapField", "java.util.Map<java.lang.String, java.lang.String> " + "may not be deterministically ordered")); }
public Future<Void> reconcile(boolean isOpenShift, ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets, Clock clock) { return networkPolicy() .compose(i -> serviceAccount()) .compose(i -> configMap()) .compose(i -> certificatesSecret(clock)) .compose(i -> apiSecret()) .compose(i -> service()) .compose(i -> deployment(isOpenShift, imagePullPolicy, imagePullSecrets)) .compose(i -> waitForDeploymentReadiness()); }
@Test public void reconcileDisabledCruiseControl(VertxTestContext context) { ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false); DeploymentOperator mockDepOps = supplier.deploymentOperations; SecretOperator mockSecretOps = supplier.secretOperations; ServiceAccountOperator mockSaOps = supplier.serviceAccountOperations; ServiceOperator mockServiceOps = supplier.serviceOperations; NetworkPolicyOperator mockNetPolicyOps = supplier.networkPolicyOperator; ConfigMapOperator mockCmOps = supplier.configMapOperations; ArgumentCaptor<ServiceAccount> saCaptor = ArgumentCaptor.forClass(ServiceAccount.class); when(mockSaOps.reconcile(any(), eq(NAMESPACE), eq(CruiseControlResources.serviceAccountName(NAME)), saCaptor.capture())).thenReturn(Future.succeededFuture()); ArgumentCaptor<Secret> secretCaptor = ArgumentCaptor.forClass(Secret.class); when(mockSecretOps.reconcile(any(), eq(NAMESPACE), eq(CruiseControlResources.secretName(NAME)), secretCaptor.capture())).thenReturn(Future.succeededFuture()); when(mockSecretOps.reconcile(any(), eq(NAMESPACE), eq(CruiseControlResources.apiSecretName(NAME)), secretCaptor.capture())).thenReturn(Future.succeededFuture()); ArgumentCaptor<Service> serviceCaptor = ArgumentCaptor.forClass(Service.class); when(mockServiceOps.reconcile(any(), eq(NAMESPACE), eq(CruiseControlResources.serviceName(NAME)), serviceCaptor.capture())).thenReturn(Future.succeededFuture()); ArgumentCaptor<NetworkPolicy> netPolicyCaptor = ArgumentCaptor.forClass(NetworkPolicy.class); when(mockNetPolicyOps.reconcile(any(), eq(NAMESPACE), eq(CruiseControlResources.networkPolicyName(NAME)), netPolicyCaptor.capture())).thenReturn(Future.succeededFuture()); ArgumentCaptor<ConfigMap> cmCaptor = ArgumentCaptor.forClass(ConfigMap.class); when(mockCmOps.reconcile(any(), eq(NAMESPACE), eq(CruiseControlResources.configMapName(NAME)), cmCaptor.capture())).thenReturn(Future.succeededFuture()); ArgumentCaptor<Deployment> depCaptor = ArgumentCaptor.forClass(Deployment.class); when(mockDepOps.reconcile(any(), eq(NAMESPACE), eq(CruiseControlResources.componentName(NAME)), depCaptor.capture())).thenReturn(Future.succeededFuture()); when(mockDepOps.waitForObserved(any(), eq(NAMESPACE), eq(CruiseControlResources.componentName(NAME)), anyLong(), anyLong())).thenReturn(Future.succeededFuture()); when(mockDepOps.readiness(any(), eq(NAMESPACE), eq(CruiseControlResources.componentName(NAME)), anyLong(), anyLong())).thenReturn(Future.succeededFuture()); ClusterCa clusterCa = new ClusterCa( Reconciliation.DUMMY_RECONCILIATION, new MockCertManager(), new PasswordGenerator(10, "a", "a"), NAME, ResourceUtils.createInitialCaCertSecret(NAMESPACE, NAME, AbstractModel.clusterCaCertSecretName(NAME), MockCertManager.clusterCaCert(), MockCertManager.clusterCaCertStore(), "123456"), ResourceUtils.createInitialCaKeySecret(NAMESPACE, NAME, AbstractModel.clusterCaKeySecretName(NAME), MockCertManager.clusterCaKey()) ); CruiseControlReconciler rcnclr = new CruiseControlReconciler( Reconciliation.DUMMY_RECONCILIATION, ResourceUtils.dummyClusterOperatorConfig(), supplier, new PasswordGenerator(16), KAFKA, VERSIONS, NODES, Map.of("mixed", STORAGE), Map.of(), clusterCa ); Checkpoint async = context.checkpoint(); rcnclr.reconcile(false, null, null, Clock.systemUTC()) .onComplete(context.succeeding(v -> context.verify(() -> { assertThat(saCaptor.getAllValues().size(), is(1)); assertThat(saCaptor.getValue(), is(nullValue())); assertThat(secretCaptor.getAllValues().size(), is(2)); assertThat(secretCaptor.getAllValues().get(0), is(nullValue())); assertThat(secretCaptor.getAllValues().get(1), is(nullValue())); assertThat(serviceCaptor.getAllValues().size(), is(1)); assertThat(serviceCaptor.getValue(), is(nullValue())); assertThat(netPolicyCaptor.getAllValues().size(), is(1)); assertThat(netPolicyCaptor.getValue(), is(nullValue())); assertThat(cmCaptor.getAllValues().size(), is(1)); assertThat(cmCaptor.getValue(), is(nullValue())); assertThat(depCaptor.getAllValues().size(), is(1)); assertThat(depCaptor.getValue(), is(nullValue())); async.flag(); }))); }
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchingFunctionException(arguments); } // if none were found (candidate isn't present) try again with implicit casting candidate = findMatchingCandidate(arguments, true); if (candidate.isPresent()) { return candidate.get(); } throw createNoMatchingFunctionException(arguments); }
@Test public void shouldFindNoArgs() { // Given: givenFunctions( function(EXPECTED, -1) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of()); // Then: assertThat(fun.name(), equalTo(EXPECTED)); }
public WebServer getWebServer() { return webServer; }
@Ignore( "This test isn't consistent/doesn't work." ) @Test public void test() throws Exception { CountDownLatch latch = new CountDownLatch( 1 ); System.setProperty( Const.KETTLE_SLAVE_DETECTION_TIMER, "100" ); SlaveServer master = new SlaveServer(); master.setHostname( "127.0.0.1" ); master.setPort( "9000" ); master.setUsername( "cluster" ); master.setPassword( "cluster" ); master.setMaster( true ); SlaveServerConfig config = new SlaveServerConfig(); config.setSlaveServer( master ); Carte carte = new Carte( config ); SlaveServerDetection slaveServerDetection = mock( SlaveServerDetection.class ); carte.getWebServer().getDetections().add( slaveServerDetection ); SlaveServer slaveServer = mock( SlaveServer.class, RETURNS_MOCKS ); when( slaveServerDetection.getSlaveServer() ).thenReturn( slaveServer ); when( slaveServer.getStatus() ).thenAnswer( new Answer<SlaveServerStatus>() { @Override public SlaveServerStatus answer( InvocationOnMock invocation ) throws Throwable { SlaveServerDetection anotherDetection = mock( SlaveServerDetection.class ); carte.getWebServer().getDetections().add( anotherDetection ); latch.countDown(); return new SlaveServerStatus(); } } ); latch.await( 10, TimeUnit.SECONDS ); assertEquals( carte.getWebServer().getDetections().size(), 2 ); carte.getWebServer().stopServer(); }
public List<ResContainer> makeResourcesXml(JadxArgs args) { Map<String, ICodeWriter> contMap = new HashMap<>(); for (ResourceEntry ri : resStorage.getResources()) { if (SKIP_RES_TYPES.contains(ri.getTypeName())) { continue; } String fn = getFileName(ri); ICodeWriter cw = contMap.get(fn); if (cw == null) { cw = new SimpleCodeWriter(args); cw.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); cw.startLine("<resources>"); cw.incIndent(); contMap.put(fn, cw); } addValue(cw, ri); } List<ResContainer> files = new ArrayList<>(contMap.size()); for (Map.Entry<String, ICodeWriter> entry : contMap.entrySet()) { String fileName = entry.getKey(); ICodeWriter content = entry.getValue(); content.decIndent(); content.startLine("</resources>"); ICodeInfo codeInfo = content.finish(); files.add(ResContainer.textResource(fileName, codeInfo)); } Collections.sort(files); return files; }
@Test void testAttrEnum() { ResourceStorage resStorage = new ResourceStorage(); ResourceEntry re = new ResourceEntry(2130903103, "jadx.gui.app", "attr", "size", ""); re.setNamedValues( Lists.list(new RawNamedValue(16777216, new RawValue(16, 65536)), new RawNamedValue(17039620, new RawValue(16, 1)))); resStorage.add(re); ValuesParser vp = new ValuesParser(null, resStorage.getResourcesNames()); ResXmlGen resXmlGen = new ResXmlGen(resStorage, vp); List<ResContainer> files = resXmlGen.makeResourcesXml(args); assertThat(files).hasSize(1); assertThat(files.get(0).getName()).isEqualTo("res/values/attrs.xml"); String input = files.get(0).getText().toString(); assertThat(input).isEqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n" + " <attr name=\"size\">\n" + " <enum name=\"android:string.aerr_wait\" value=\"1\" />\n" + " </attr>\n" + "</resources>"); }
@Override public int read() throws IOException { Preconditions.checkState(!closed, "Cannot read: already closed"); positionStream(); pos += 1; next += 1; readBytes.increment(); readOperations.increment(); return stream.read(); }
@Test public void testRead() throws Exception { int dataSize = 1024 * 1024 * 10; byte[] data = randomData(dataSize); setupData(data); try (SeekableInputStream in = new ADLSInputStream(fileClient(), null, azureProperties, MetricsContext.nullMetrics())) { int readSize = 1024; readAndCheck(in, in.getPos(), readSize, data, false); readAndCheck(in, in.getPos(), readSize, data, true); // Seek forward in current stream int seekSize = 1024; readAndCheck(in, in.getPos() + seekSize, readSize, data, false); readAndCheck(in, in.getPos() + seekSize, readSize, data, true); // Buffered read readAndCheck(in, in.getPos(), readSize, data, true); readAndCheck(in, in.getPos(), readSize, data, false); // Seek with new stream long seekNewStreamPosition = 2 * 1024 * 1024; readAndCheck(in, in.getPos() + seekNewStreamPosition, readSize, data, true); readAndCheck(in, in.getPos() + seekNewStreamPosition, readSize, data, false); // Backseek and read readAndCheck(in, 0, readSize, data, true); readAndCheck(in, 0, readSize, data, false); } }
public void unregisterSearch(String id) { removeGrantsForTarget(grnRegistry.newGRN(GRNTypes.SEARCH, id)); }
@Test void unregisterSearch() { entityOwnershipService.unregisterSearch("1234"); assertGrantRemoval(GRNTypes.SEARCH, "1234"); }
@Override public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) { String propertyTypeName = getTypeName(node); JType type; if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) { type = ruleFactory.getObjectRule().apply(nodeName, node, parent, jClassContainer.getPackage(), schema); } else if (node.has("existingJavaType")) { String typeName = node.path("existingJavaType").asText(); if (isPrimitive(typeName, jClassContainer.owner())) { type = primitiveType(typeName, jClassContainer.owner()); } else { type = resolveType(jClassContainer, typeName); } } else if (propertyTypeName.equals("string")) { type = jClassContainer.owner().ref(String.class); } else if (propertyTypeName.equals("number")) { type = getNumberType(jClassContainer.owner(), ruleFactory.getGenerationConfig()); } else if (propertyTypeName.equals("integer")) { type = getIntegerType(jClassContainer.owner(), node, ruleFactory.getGenerationConfig()); } else if (propertyTypeName.equals("boolean")) { type = unboxIfNecessary(jClassContainer.owner().ref(Boolean.class), ruleFactory.getGenerationConfig()); } else if (propertyTypeName.equals("array")) { type = ruleFactory.getArrayRule().apply(nodeName, node, parent, jClassContainer.getPackage(), schema); } else { type = jClassContainer.owner().ref(Object.class); } if (!node.has("javaType") && !node.has("existingJavaType") && node.has("format")) { type = ruleFactory.getFormatRule().apply(nodeName, node.get("format"), node, type, schema); } else if (!node.has("javaType") && !node.has("existingJavaType") && propertyTypeName.equals("string") && node.has("media")) { type = ruleFactory.getMediaRule().apply(nodeName, node.get("media"), node, type, schema); } return type; }
@Test public void applyGeneratesNumber() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "number"); when(config.isUseDoubleNumbers()).thenReturn(true); JType result = rule.apply("fooBar", objectNode, null, jpackage, null); assertThat(result.fullName(), is(Double.class.getName())); }
public static void main(String[] args) throws IOException { runSqlLine(args, null, System.out, System.err); }
@Test public void testSqlLine_nullCommand() throws Exception { BeamSqlLine.main(new String[] {"-e", ""}); }
@Override public void execute(Context context) { executeForBranch(treeRootHolder.getRoot()); }
@Test public void givenUpgradeEventWithTheSameSqVersion_whenStepIsExecuted_thenNothingIsPersisted() { when(sonarQubeVersion.get()).thenReturn(Version.parse("10.3")); when(dbClient.eventDao()).thenReturn(mock()); when(dbClient.eventDao().selectSqUpgradesByMostRecentFirst(any(), any())).thenReturn(getUpgradeEvents("10.3", "10.2")); underTest.execute(new TestComputationStepContext()); verifyNoMoreInteractions(eventRepository); }
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowStatement) { return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) sqlStatement)); } return Optional.empty(); }
@Test void assertCreateWithResetStatement() { Optional<DatabaseAdminExecutor> actual = new PostgreSQLAdminExecutorCreator() .create(new UnknownSQLStatementContext(new PostgreSQLResetParameterStatement("client_encoding")), "RESET client_encoding", "", Collections.emptyList()); assertTrue(actual.isPresent()); assertThat(actual.get(), instanceOf(PostgreSQLResetVariableAdminExecutor.class)); }
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) { List<Object> valuesInOrder = schema.getFields().stream() .map( field -> { try { org.apache.avro.Schema.Field avroField = record.getSchema().getField(field.getName()); Object value = avroField != null ? record.get(avroField.pos()) : null; return convertAvroFormat(field.getType(), value, options); } catch (Exception cause) { throw new IllegalArgumentException( "Error converting field " + field + ": " + cause.getMessage(), cause); } }) .collect(toList()); return Row.withSchema(schema).addValues(valuesInOrder).build(); }
@Test public void testToBeamRow_array() { Row beamRow = BigQueryUtils.toBeamRow(ARRAY_TYPE, BQ_ARRAY_ROW); assertEquals(ARRAY_ROW, beamRow); }
@Override public Span tag(String key, String value) { synchronized (state) { state.tag(key, value); } return this; }
@Test void tag() { span.tag("foo", "bar"); span.flush(); assertThat(spans).flatExtracting(s -> s.tags().entrySet()) .containsExactly(entry("foo", "bar")); }
public synchronized void release(BufferData data) { checkNotNull(data, "data"); synchronized (data) { checkArgument( canRelease(data), String.format("Unable to release buffer: %s", data)); ByteBuffer buffer = allocated.get(data); if (buffer == null) { // Likely released earlier. return; } buffer.clear(); pool.release(buffer); allocated.remove(data); } releaseDoneBlocks(); }
@Test public void testRelease() throws Exception { testReleaseHelper(BufferData.State.BLANK, true); testReleaseHelper(BufferData.State.PREFETCHING, true); testReleaseHelper(BufferData.State.CACHING, true); testReleaseHelper(BufferData.State.READY, false); }
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public @Nullable <InputT> TransformEvaluator<InputT> forApplication( AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) { return createEvaluator((AppliedPTransform) application); }
@Test public void evaluatorThrowsInCloseRethrows() throws Exception { ContiguousSet<Long> elems = ContiguousSet.create(Range.closed(0L, 20L), DiscreteDomain.longs()); TestUnboundedSource<Long> source = new TestUnboundedSource<>(BigEndianLongCoder.of(), elems.toArray(new Long[0])) .throwsOnClose(); PCollection<Long> pcollection = p.apply(Read.from(source)); AppliedPTransform<?, ?, ?> sourceTransform = DirectGraphs.getGraph(p).getProducer(pcollection); when(context.createRootBundle()).thenReturn(bundleFactory.createRootBundle()); UncommittedBundle<Long> output = bundleFactory.createBundle(pcollection); when(context.createBundle(pcollection)).thenReturn(output); WindowedValue<UnboundedSourceShard<Long, TestCheckpointMark>> shard = WindowedValue.valueInGlobalWindow( UnboundedSourceShard.unstarted(source, NeverDeduplicator.create())); CommittedBundle<UnboundedSourceShard<Long, TestCheckpointMark>> inputBundle = bundleFactory .<UnboundedSourceShard<Long, TestCheckpointMark>>createRootBundle() .add(shard) .commit(Instant.now()); UnboundedReadEvaluatorFactory factory = new UnboundedReadEvaluatorFactory(context, p.getOptions(), 0.0 /* never reuse */); TransformEvaluator<UnboundedSourceShard<Long, TestCheckpointMark>> evaluator = factory.forApplication(sourceTransform, inputBundle); thrown.expect(IOException.class); thrown.expectMessage("throws on close"); evaluator.processElement(shard); }
public static <NodeT, EdgeT> Set<NodeT> reachableNodes( Network<NodeT, EdgeT> network, Set<NodeT> startNodes, Set<NodeT> endNodes) { Set<NodeT> visitedNodes = new HashSet<>(); Queue<NodeT> queuedNodes = new ArrayDeque<>(); queuedNodes.addAll(startNodes); // Perform a breadth-first traversal rooted at the input node. while (!queuedNodes.isEmpty()) { NodeT currentNode = queuedNodes.remove(); // If we have already visited this node or it is a terminal node than do not add any // successors. if (!visitedNodes.add(currentNode) || endNodes.contains(currentNode)) { continue; } queuedNodes.addAll(network.successors(currentNode)); } return visitedNodes; }
@Test public void testReachableNodesFromAllRootsToAllRoots() { assertEquals( ImmutableSet.of("A", "D", "I", "M", "O"), Networks.reachableNodes( createNetwork(), ImmutableSet.of("A", "D", "I", "M", "O"), ImmutableSet.of("A", "D", "I", "M", "O"))); }
public <W extends T> void add(Class<W> clazz, T server) { Preconditions.checkNotNull(clazz, "clazz"); Preconditions.checkNotNull(server, "server"); Preconditions.checkArgument(clazz.isInstance(server), "Server %s is not an instance of %s", server.getClass(), clazz.getName()); try (LockResource r = new LockResource(mLock)) { mRegistry.put(clazz, server); } }
@Test public void cycle() { Registry<TestServer, Void> registry = new Registry<>(); registry.add(ServerA.class, new ServerA()); registry.add(ServerB.class, new ServerB()); registry.add(ServerC.class, new ServerC()); registry.add(ServerD.class, new ServerD()); Assert.assertThrows(RuntimeException.class, registry::getServers); }
static String getSanitizedId(String id, String modelName) { String toReturn = id.replace(".", "") .replace(",", ""); try { Integer.parseInt(toReturn); toReturn = String.format(SEGMENTID_TEMPLATE, modelName, id); } catch (NumberFormatException e) { // ignore } return toReturn; }
@Test void getSanitizedId() { final String modelName = "MODEL_NAME"; String id = "2"; String expected = String.format(SEGMENTID_TEMPLATE, modelName, id); String retrieved = KiePMMLUtil.getSanitizedId(id, modelName); assertThat(retrieved).isEqualTo(expected); id = "34.5"; expected = String.format(SEGMENTID_TEMPLATE, modelName, id); retrieved = KiePMMLUtil.getSanitizedId(id, modelName); assertThat(retrieved).isEqualTo(expected); id = "3,45"; expected = String.format(SEGMENTID_TEMPLATE, modelName, id); retrieved = KiePMMLUtil.getSanitizedId(id, modelName); assertThat(retrieved).isEqualTo(expected); }
@Override public void readLine(String line) { if (line.startsWith("%") || line.isEmpty()) { return; } if(line.startsWith("owner:") && this.organization == null) { this.organization = lineValue(line); } if(line.startsWith("country:") && this.countryCode == null) { this.countryCode = lineValue(line); } }
@Test public void testRunDirectMatch() throws Exception { LACNICResponseParser parser = new LACNICResponseParser(); for (String line : MATCH.split("\n")) { parser.readLine(line); } assertEquals("CL", parser.getCountryCode()); assertEquals("VTR BANDA ANCHA S.A.", parser.getOrganization()); }
@Override public Set<String> getEntityTypes() { return entityTypes; }
@Test public void testGetEntityTypes() throws Exception { String text = "Hey, Lets meet on this Sunday or MONDAY because i am busy on Saturday"; System.setProperty(NamedEntityParser.SYS_PROP_NER_IMPL, RegexNERecogniser.class.getName()); Tika tika = new Tika( new TikaConfig(NamedEntityParser.class.getResourceAsStream("tika-config.xml"))); Metadata md = new Metadata(); tika.parse(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), md); Set<String> days = new HashSet<>(Arrays.asList(md.getValues("NER_WEEK_DAY"))); assertTrue(days.contains("Sunday")); assertTrue(days.contains("MONDAY")); assertTrue(days.contains("Saturday")); assertTrue(days.size() == 3); //and nothing else }
@Override public List<RuleNode> findAllRuleNodeByIds(List<RuleNodeId> ruleNodeIds) { return DaoUtil.convertDataList(ruleNodeRepository.findAllById( ruleNodeIds.stream().map(RuleNodeId::getId).collect(Collectors.toList()))); }
@Test public void testFindAllRuleNodeByIds() { var fromUUIDs = ruleNodeIds.stream().map(RuleNodeId::new).collect(Collectors.toList()); var ruleNodes = ruleNodeDao.findAllRuleNodeByIds(fromUUIDs); assertEquals(40, ruleNodes.size()); }
public Collection<SQLToken> generateSQLTokens(final TablesContext tablesContext, final SetAssignmentSegment setAssignmentSegment) { String tableName = tablesContext.getSimpleTables().iterator().next().getTableName().getIdentifier().getValue(); EncryptTable encryptTable = encryptRule.getEncryptTable(tableName); Collection<SQLToken> result = new LinkedList<>(); String schemaName = tablesContext.getSchemaName().orElseGet(() -> new DatabaseTypeRegistry(databaseType).getDefaultSchemaName(databaseName)); for (ColumnAssignmentSegment each : setAssignmentSegment.getAssignments()) { String columnName = each.getColumns().get(0).getIdentifier().getValue(); if (encryptTable.isEncryptColumn(columnName)) { generateSQLToken(schemaName, encryptTable.getTable(), encryptTable.getEncryptColumn(columnName), each).ifPresent(result::add); } } return result; }
@Test void assertGenerateSQLTokenWithUpdateEmpty() { when(assignmentSegment.getValue()).thenReturn(null); assertTrue(tokenGenerator.generateSQLTokens(tablesContext, setAssignmentSegment).isEmpty()); }
public static void setInput(JobConf job, Class<? extends DBWritable> inputClass, String tableName,String conditions, String orderBy, String... fieldNames) { job.setInputFormat(DBInputFormat.class); DBConfiguration dbConf = new DBConfiguration(job); dbConf.setInputClass(inputClass); dbConf.setInputTableName(tableName); dbConf.setInputFieldNames(fieldNames); dbConf.setInputConditions(conditions); dbConf.setInputOrderBy(orderBy); }
@Test (timeout = 5000) public void testSetInput() { JobConf configuration = new JobConf(); String[] fieldNames = { "field1", "field2" }; DBInputFormat.setInput(configuration, NullDBWritable.class, "table", "conditions", "orderBy", fieldNames); assertEquals( "org.apache.hadoop.mapred.lib.db.DBInputFormat$NullDBWritable", configuration.getClass(DBConfiguration.INPUT_CLASS_PROPERTY, null) .getName()); assertEquals("table", configuration.get(DBConfiguration.INPUT_TABLE_NAME_PROPERTY, null)); String[] fields = configuration .getStrings(DBConfiguration.INPUT_FIELD_NAMES_PROPERTY); assertEquals("field1", fields[0]); assertEquals("field2", fields[1]); assertEquals("conditions", configuration.get(DBConfiguration.INPUT_CONDITIONS_PROPERTY, null)); assertEquals("orderBy", configuration.get(DBConfiguration.INPUT_ORDER_BY_PROPERTY, null)); configuration = new JobConf(); DBInputFormat.setInput(configuration, NullDBWritable.class, "query", "countQuery"); assertEquals("query", configuration.get(DBConfiguration.INPUT_QUERY, null)); assertEquals("countQuery", configuration.get(DBConfiguration.INPUT_COUNT_QUERY, null)); JobConf jConfiguration = new JobConf(); DBConfiguration.configureDB(jConfiguration, "driverClass", "dbUrl", "user", "password"); assertEquals("driverClass", jConfiguration.get(DBConfiguration.DRIVER_CLASS_PROPERTY)); assertEquals("dbUrl", jConfiguration.get(DBConfiguration.URL_PROPERTY)); assertEquals("user", jConfiguration.get(DBConfiguration.USERNAME_PROPERTY)); assertEquals("password", jConfiguration.get(DBConfiguration.PASSWORD_PROPERTY)); jConfiguration = new JobConf(); DBConfiguration.configureDB(jConfiguration, "driverClass", "dbUrl"); assertEquals("driverClass", jConfiguration.get(DBConfiguration.DRIVER_CLASS_PROPERTY)); assertEquals("dbUrl", jConfiguration.get(DBConfiguration.URL_PROPERTY)); assertNull(jConfiguration.get(DBConfiguration.USERNAME_PROPERTY)); assertNull(jConfiguration.get(DBConfiguration.PASSWORD_PROPERTY)); }
public static String prettyJSON(String json) { return prettyJSON(json, TAB_SEPARATOR); }
@Test public void testRenderResultSimpleNumber() throws Exception { assertEquals("42", prettyJSON("42")); }
@Override public ObjectNode encode(MappingTreatment treatment, CodecContext context) { checkNotNull(treatment, "Mapping treatment cannot be null"); final ObjectNode result = context.mapper().createObjectNode(); final ArrayNode jsonInstructions = result.putArray(INSTRUCTIONS); final JsonCodec<MappingInstruction> instructionCodec = context.codec(MappingInstruction.class); final JsonCodec<MappingAddress> addressCodec = context.codec(MappingAddress.class); for (final MappingInstruction instruction : treatment.instructions()) { jsonInstructions.add(instructionCodec.encode(instruction, context)); } result.set(ADDRESS, addressCodec.encode(treatment.address(), context)); return result; }
@Test public void testMappingTreatmentEncode() { MappingInstruction unicastWeight = MappingInstructions.unicastWeight(UNICAST_WEIGHT); MappingInstruction unicastPriority = MappingInstructions.unicastPriority(UNICAST_PRIORITY); MappingInstruction multicastWeight = MappingInstructions.multicastWeight(MULTICAST_WEIGHT); MappingInstruction multicastPriority = MappingInstructions.multicastPriority(MULTICAST_PRIORITY); MappingAddress address = MappingAddresses.asMappingAddress(ASN_NUMBER); MappingTreatment treatment = DefaultMappingTreatment.builder() .add(unicastWeight) .add(unicastPriority) .add(multicastWeight) .add(multicastPriority) .withAddress(address) .build(); ObjectNode treatmentJson = treatmentCodec.encode(treatment, context); assertThat(treatmentJson, MappingTreatmentJsonMatcher.matchesMappingTreatment(treatment)); }
public String getDistinguishedName() { return distinguishedName; }
@Test public void testConstruction() { LispDistinguishedNameAddress distinguishedNameAddress = address1; assertThat(distinguishedNameAddress.getDistinguishedName(), is("distAddress1")); }
@Override @NonNull public String getId() { return ID; }
@Test public void shouldGetForbiddenForBadCredentialIdOnCreate1() throws IOException, UnirestException { User user = login(); this.jwtToken = getJwtToken(j.jenkins, user.getId(), user.getId()); Map resp = createCredentials(user, MapsHelper.of("credentials", new MapsHelper.Builder<String,Object>() .put("privateKeySource", MapsHelper.of( "privateKey", "abcabc1212", "stapler-class", "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource")) .put("passphrase", "ssh2") .put("scope", "USER") .put("domain","blueocean-git-domain") .put("description", "ssh2 desc") .put("$class", "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey") .put("username", "ssh2").build() )); String credentialId = (String) resp.get("id"); Assert.assertNotNull(credentialId); post("/organizations/" + getOrgName() + "/pipelines/", MapsHelper.of("name", "demo", "$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest", "scmConfig", MapsHelper.of("uri", "[email protected]:vivek/capability-annotation.git", "credentialId", credentialId) ), 400); }
int calculatePrice(Integer basePrice, Integer percent, Integer fixedPrice) { // 1. 优先使用固定佣金 if (fixedPrice != null && fixedPrice > 0) { return ObjectUtil.defaultIfNull(fixedPrice, 0); } // 2. 根据比例计算佣金 if (basePrice != null && basePrice > 0 && percent != null && percent > 0) { return MoneyUtils.calculateRatePriceFloor(basePrice, Double.valueOf(percent)); } return 0; }
@Test public void testCalculatePrice_equalsZero() { // mock 数据 Integer payPrice = null; Integer percent = null; Integer fixedPrice = null; // 调用 int brokerage = brokerageRecordService.calculatePrice(payPrice, percent, fixedPrice); // 断言 assertEquals(brokerage, 0); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HAProxyMessage) { HAProxyMessage proxyMessage = (HAProxyMessage) msg; this.proxyMessage = proxyMessage; proxyMessage.release(); return; } // Get a buffer that contains the full frame ByteBuf buffer = (ByteBuf) msg; try { // De-serialize the command int cmdSize = (int) buffer.readUnsignedInt(); cmd.parseFrom(buffer, cmdSize); if (log.isDebugEnabled()) { log.debug("[{}] Received cmd {}", ctx.channel(), cmd.getType()); } messageReceived(); switch (cmd.getType()) { case PARTITIONED_METADATA: checkArgument(cmd.hasPartitionMetadata()); try { interceptCommand(cmd); handlePartitionMetadataRequest(cmd.getPartitionMetadata()); } catch (InterceptException e) { writeAndFlush(ctx, Commands.newPartitionMetadataResponse(getServerError(e.getErrorCode()), e.getMessage(), cmd.getPartitionMetadata().getRequestId())); } break; case PARTITIONED_METADATA_RESPONSE: checkArgument(cmd.hasPartitionMetadataResponse()); handlePartitionResponse(cmd.getPartitionMetadataResponse()); break; case LOOKUP: checkArgument(cmd.hasLookupTopic()); handleLookup(cmd.getLookupTopic()); break; case LOOKUP_RESPONSE: checkArgument(cmd.hasLookupTopicResponse()); handleLookupResponse(cmd.getLookupTopicResponse()); break; case ACK: checkArgument(cmd.hasAck()); safeInterceptCommand(cmd); handleAck(cmd.getAck()); break; case ACK_RESPONSE: checkArgument(cmd.hasAckResponse()); handleAckResponse(cmd.getAckResponse()); break; case CLOSE_CONSUMER: checkArgument(cmd.hasCloseConsumer()); safeInterceptCommand(cmd); handleCloseConsumer(cmd.getCloseConsumer()); break; case CLOSE_PRODUCER: checkArgument(cmd.hasCloseProducer()); safeInterceptCommand(cmd); handleCloseProducer(cmd.getCloseProducer()); break; case CONNECT: checkArgument(cmd.hasConnect()); handleConnect(cmd.getConnect()); break; case CONNECTED: checkArgument(cmd.hasConnected()); handleConnected(cmd.getConnected()); break; case ERROR: checkArgument(cmd.hasError()); handleError(cmd.getError()); break; case FLOW: checkArgument(cmd.hasFlow()); handleFlow(cmd.getFlow()); break; case MESSAGE: { checkArgument(cmd.hasMessage()); handleMessage(cmd.getMessage(), buffer); break; } case PRODUCER: checkArgument(cmd.hasProducer()); try { interceptCommand(cmd); handleProducer(cmd.getProducer()); } catch (InterceptException e) { writeAndFlush(ctx, Commands.newError(cmd.getProducer().getRequestId(), getServerError(e.getErrorCode()), e.getMessage())); } break; case SEND: { checkArgument(cmd.hasSend()); try { interceptCommand(cmd); // Store a buffer marking the content + headers ByteBuf headersAndPayload = buffer.markReaderIndex(); handleSend(cmd.getSend(), headersAndPayload); } catch (InterceptException e) { writeAndFlush(ctx, Commands.newSendError(cmd.getSend().getProducerId(), cmd.getSend().getSequenceId(), getServerError(e.getErrorCode()), e.getMessage())); } break; } case SEND_ERROR: checkArgument(cmd.hasSendError()); handleSendError(cmd.getSendError()); break; case SEND_RECEIPT: checkArgument(cmd.hasSendReceipt()); handleSendReceipt(cmd.getSendReceipt()); break; case SUBSCRIBE: checkArgument(cmd.hasSubscribe()); try { interceptCommand(cmd); handleSubscribe(cmd.getSubscribe()); } catch (InterceptException e) { writeAndFlush(ctx, Commands.newError(cmd.getSubscribe().getRequestId(), getServerError(e.getErrorCode()), e.getMessage())); } break; case SUCCESS: checkArgument(cmd.hasSuccess()); handleSuccess(cmd.getSuccess()); break; case PRODUCER_SUCCESS: checkArgument(cmd.hasProducerSuccess()); handleProducerSuccess(cmd.getProducerSuccess()); break; case UNSUBSCRIBE: checkArgument(cmd.hasUnsubscribe()); safeInterceptCommand(cmd); handleUnsubscribe(cmd.getUnsubscribe()); break; case SEEK: checkArgument(cmd.hasSeek()); try { interceptCommand(cmd); handleSeek(cmd.getSeek()); } catch (InterceptException e) { writeAndFlush(ctx, Commands.newError( cmd.getSeek().getRequestId(), getServerError(e.getErrorCode()), e.getMessage() ) ); } break; case PING: checkArgument(cmd.hasPing()); handlePing(cmd.getPing()); break; case PONG: checkArgument(cmd.hasPong()); handlePong(cmd.getPong()); break; case REDELIVER_UNACKNOWLEDGED_MESSAGES: checkArgument(cmd.hasRedeliverUnacknowledgedMessages()); safeInterceptCommand(cmd); handleRedeliverUnacknowledged(cmd.getRedeliverUnacknowledgedMessages()); break; case CONSUMER_STATS: checkArgument(cmd.hasConsumerStats()); handleConsumerStats(cmd.getConsumerStats()); break; case CONSUMER_STATS_RESPONSE: checkArgument(cmd.hasConsumerStatsResponse()); handleConsumerStatsResponse(cmd.getConsumerStatsResponse()); break; case REACHED_END_OF_TOPIC: checkArgument(cmd.hasReachedEndOfTopic()); handleReachedEndOfTopic(cmd.getReachedEndOfTopic()); break; case TOPIC_MIGRATED: checkArgument(cmd.hasTopicMigrated()); handleTopicMigrated(cmd.getTopicMigrated()); break; case GET_LAST_MESSAGE_ID: checkArgument(cmd.hasGetLastMessageId()); handleGetLastMessageId(cmd.getGetLastMessageId()); break; case GET_LAST_MESSAGE_ID_RESPONSE: checkArgument(cmd.hasGetLastMessageIdResponse()); handleGetLastMessageIdSuccess(cmd.getGetLastMessageIdResponse()); break; case ACTIVE_CONSUMER_CHANGE: handleActiveConsumerChange(cmd.getActiveConsumerChange()); break; case GET_TOPICS_OF_NAMESPACE: checkArgument(cmd.hasGetTopicsOfNamespace()); try { interceptCommand(cmd); handleGetTopicsOfNamespace(cmd.getGetTopicsOfNamespace()); } catch (InterceptException e) { writeAndFlush(ctx, Commands.newError(cmd.getGetTopicsOfNamespace().getRequestId(), getServerError(e.getErrorCode()), e.getMessage())); } break; case GET_TOPICS_OF_NAMESPACE_RESPONSE: checkArgument(cmd.hasGetTopicsOfNamespaceResponse()); handleGetTopicsOfNamespaceSuccess(cmd.getGetTopicsOfNamespaceResponse()); break; case GET_SCHEMA: checkArgument(cmd.hasGetSchema()); try { interceptCommand(cmd); handleGetSchema(cmd.getGetSchema()); } catch (InterceptException e) { writeAndFlush(ctx, Commands.newGetSchemaResponseError(cmd.getGetSchema().getRequestId(), getServerError(e.getErrorCode()), e.getMessage())); } break; case GET_SCHEMA_RESPONSE: checkArgument(cmd.hasGetSchemaResponse()); handleGetSchemaResponse(cmd.getGetSchemaResponse()); break; case GET_OR_CREATE_SCHEMA: checkArgument(cmd.hasGetOrCreateSchema()); try { interceptCommand(cmd); handleGetOrCreateSchema(cmd.getGetOrCreateSchema()); } catch (InterceptException e) { writeAndFlush(ctx, Commands.newGetOrCreateSchemaResponseError( cmd.getGetOrCreateSchema().getRequestId(), getServerError(e.getErrorCode()), e.getMessage())); } break; case GET_OR_CREATE_SCHEMA_RESPONSE: checkArgument(cmd.hasGetOrCreateSchemaResponse()); handleGetOrCreateSchemaResponse(cmd.getGetOrCreateSchemaResponse()); break; case AUTH_CHALLENGE: checkArgument(cmd.hasAuthChallenge()); handleAuthChallenge(cmd.getAuthChallenge()); break; case AUTH_RESPONSE: checkArgument(cmd.hasAuthResponse()); handleAuthResponse(cmd.getAuthResponse()); break; case TC_CLIENT_CONNECT_REQUEST: checkArgument(cmd.hasTcClientConnectRequest()); handleTcClientConnectRequest(cmd.getTcClientConnectRequest()); break; case TC_CLIENT_CONNECT_RESPONSE: checkArgument(cmd.hasTcClientConnectResponse()); handleTcClientConnectResponse(cmd.getTcClientConnectResponse()); break; case NEW_TXN: checkArgument(cmd.hasNewTxn()); handleNewTxn(cmd.getNewTxn()); break; case NEW_TXN_RESPONSE: checkArgument(cmd.hasNewTxnResponse()); handleNewTxnResponse(cmd.getNewTxnResponse()); break; case ADD_PARTITION_TO_TXN: checkArgument(cmd.hasAddPartitionToTxn()); handleAddPartitionToTxn(cmd.getAddPartitionToTxn()); break; case ADD_PARTITION_TO_TXN_RESPONSE: checkArgument(cmd.hasAddPartitionToTxnResponse()); handleAddPartitionToTxnResponse(cmd.getAddPartitionToTxnResponse()); break; case ADD_SUBSCRIPTION_TO_TXN: checkArgument(cmd.hasAddSubscriptionToTxn()); handleAddSubscriptionToTxn(cmd.getAddSubscriptionToTxn()); break; case ADD_SUBSCRIPTION_TO_TXN_RESPONSE: checkArgument(cmd.hasAddSubscriptionToTxnResponse()); handleAddSubscriptionToTxnResponse(cmd.getAddSubscriptionToTxnResponse()); break; case END_TXN: checkArgument(cmd.hasEndTxn()); handleEndTxn(cmd.getEndTxn()); break; case END_TXN_RESPONSE: checkArgument(cmd.hasEndTxnResponse()); handleEndTxnResponse(cmd.getEndTxnResponse()); break; case END_TXN_ON_PARTITION: checkArgument(cmd.hasEndTxnOnPartition()); handleEndTxnOnPartition(cmd.getEndTxnOnPartition()); break; case END_TXN_ON_PARTITION_RESPONSE: checkArgument(cmd.hasEndTxnOnPartitionResponse()); handleEndTxnOnPartitionResponse(cmd.getEndTxnOnPartitionResponse()); break; case END_TXN_ON_SUBSCRIPTION: checkArgument(cmd.hasEndTxnOnSubscription()); handleEndTxnOnSubscription(cmd.getEndTxnOnSubscription()); break; case END_TXN_ON_SUBSCRIPTION_RESPONSE: checkArgument(cmd.hasEndTxnOnSubscriptionResponse()); handleEndTxnOnSubscriptionResponse(cmd.getEndTxnOnSubscriptionResponse()); break; case WATCH_TOPIC_LIST: checkArgument(cmd.hasWatchTopicList()); handleCommandWatchTopicList(cmd.getWatchTopicList()); break; case WATCH_TOPIC_LIST_SUCCESS: checkArgument(cmd.hasWatchTopicListSuccess()); handleCommandWatchTopicListSuccess(cmd.getWatchTopicListSuccess()); break; case WATCH_TOPIC_UPDATE: checkArgument(cmd.hasWatchTopicUpdate()); handleCommandWatchTopicUpdate(cmd.getWatchTopicUpdate()); break; case WATCH_TOPIC_LIST_CLOSE: checkArgument(cmd.hasWatchTopicListClose()); handleCommandWatchTopicListClose(cmd.getWatchTopicListClose()); break; default: break; } } finally { buffer.release(); } }
@Test public void testChannelRead() throws Exception { long consumerId = 1234L; ByteBuf changeBuf = Commands.newActiveConsumerChange(consumerId, true); ByteBuf cmdBuf = changeBuf.slice(4, changeBuf.writerIndex() - 4); PulsarDecoder decoder = spy(new PulsarDecoder() { @Override protected void handleActiveConsumerChange(CommandActiveConsumerChange change) { } @Override protected void messageReceived() { } }); decoder.channelRead(mock(ChannelHandlerContext.class), cmdBuf); verify(decoder, times(1)).handleActiveConsumerChange(any(CommandActiveConsumerChange.class)); }
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) { final Fetch<K, V> fetch = Fetch.empty(); final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>(); int recordsRemaining = fetchConfig.maxPollRecords; try { while (recordsRemaining > 0) { final CompletedFetch nextInLineFetch = fetchBuffer.nextInLineFetch(); if (nextInLineFetch == null || nextInLineFetch.isConsumed()) { final CompletedFetch completedFetch = fetchBuffer.peek(); if (completedFetch == null) break; if (!completedFetch.isInitialized()) { try { fetchBuffer.setNextInLineFetch(initialize(completedFetch)); } catch (Exception e) { // Remove a completedFetch upon a parse with exception if (1) it contains no completedFetch, and // (2) there are no fetched completedFetch with actual content preceding this exception. // The first condition ensures that the completedFetches is not stuck with the same completedFetch // in cases such as the TopicAuthorizationException, and the second condition ensures that no // potential data loss due to an exception in a following record. if (fetch.isEmpty() && FetchResponse.recordsOrFail(completedFetch.partitionData).sizeInBytes() == 0) fetchBuffer.poll(); throw e; } } else { fetchBuffer.setNextInLineFetch(completedFetch); } fetchBuffer.poll(); } else if (subscriptions.isPaused(nextInLineFetch.partition)) { // when the partition is paused we add the records back to the completedFetches queue instead of draining // them so that they can be returned on a subsequent poll if the partition is resumed at that time log.debug("Skipping fetching records for assigned partition {} because it is paused", nextInLineFetch.partition); pausedCompletedFetches.add(nextInLineFetch); fetchBuffer.setNextInLineFetch(null); } else { final Fetch<K, V> nextFetch = fetchRecords(nextInLineFetch, recordsRemaining); recordsRemaining -= nextFetch.numRecords(); fetch.add(nextFetch); } } } catch (KafkaException e) { if (fetch.isEmpty()) throw e; } finally { // add any polled completed fetches for paused partitions back to the completed fetches queue to be // re-evaluated in the next poll fetchBuffer.addAll(pausedCompletedFetches); } return fetch; }
@Test public void testCollectFetchInitializationWithUpdatePreferredReplicaOnNotAssignedPartition() { final TopicPartition topicPartition0 = new TopicPartition("topic", 0); final long fetchOffset = 42; final long highWatermark = 1000; final long logStartOffset = 10; final long lastStableOffset = 900; final int preferredReadReplicaId = 21; final SubscriptionState subscriptions = mock(SubscriptionState.class); when(subscriptions.hasValidPosition(topicPartition0)).thenReturn(true); when(subscriptions.positionOrNull(topicPartition0)).thenReturn(new SubscriptionState.FetchPosition(fetchOffset)); when(subscriptions.tryUpdatingHighWatermark(topicPartition0, highWatermark)).thenReturn(true); when(subscriptions.tryUpdatingLogStartOffset(topicPartition0, logStartOffset)).thenReturn(true); when(subscriptions.tryUpdatingLastStableOffset(topicPartition0, lastStableOffset)).thenReturn(true); when(subscriptions.tryUpdatingPreferredReadReplica(eq(topicPartition0), eq(preferredReadReplicaId), any())).thenReturn(false); final FetchCollector<String, String> fetchCollector = createFetchCollector(subscriptions); final Records records = createRecords(); FetchResponseData.PartitionData partitionData = new FetchResponseData.PartitionData() .setPartitionIndex(topicPartition0.partition()) .setHighWatermark(highWatermark) .setRecords(records) .setLogStartOffset(logStartOffset) .setLastStableOffset(lastStableOffset) .setPreferredReadReplica(preferredReadReplicaId); final CompletedFetch completedFetch = new CompletedFetchBuilder() .partitionData(partitionData) .partition(topicPartition0) .fetchOffset(fetchOffset).build(); final FetchBuffer fetchBuffer = mock(FetchBuffer.class); when(fetchBuffer.nextInLineFetch()).thenReturn(null); when(fetchBuffer.peek()).thenReturn(completedFetch).thenReturn(null); final Fetch<String, String> fetch = fetchCollector.collectFetch(fetchBuffer); assertTrue(fetch.isEmpty()); verify(fetchBuffer).setNextInLineFetch(null); }
String format(Method method) { String signature = method.toGenericString(); Matcher matcher = METHOD_PATTERN.matcher(signature); if (matcher.find()) { String qc = matcher.group(3); String m = matcher.group(4); String qa = matcher.group(5); return format.format(new Object[] { qc, m, qa, }); } else { throw new CucumberBackendException("Cucumber bug: Couldn't format " + signature); } }
@Test void shouldUseSimpleFormatWhenMethodHasException() { assertThat(MethodFormat.FULL.format(methodWithoutArgs), startsWith("io.cucumber.java.MethodFormatTest.methodWithoutArgs()")); }
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeFilter edgeFilter, boolean excludeSingleNodeComponents) { return new TarjanSCC(graph, edgeFilter, excludeSingleNodeComponents).findComponentsRecursive(); }
@Test public void test481() { // 0->1->3->4->5->6->7 // \ | \<-----/ // 2 graph.edge(0, 1).setDistance(1).set(speedEnc, 10, 0); graph.edge(1, 2).setDistance(1).set(speedEnc, 10, 0); graph.edge(2, 0).setDistance(1).set(speedEnc, 10, 0); graph.edge(1, 3).setDistance(1).set(speedEnc, 10, 0); graph.edge(3, 4).setDistance(1).set(speedEnc, 10, 0); graph.edge(4, 5).setDistance(1).set(speedEnc, 10, 0); graph.edge(5, 6).setDistance(1).set(speedEnc, 10, 0); graph.edge(6, 7).setDistance(1).set(speedEnc, 10, 0); graph.edge(7, 4).setDistance(1).set(speedEnc, 10, 0); TarjanSCC.ConnectedComponents scc = TarjanSCC.findComponentsRecursive(graph, edgeFilter, false); List<IntArrayList> components = scc.getComponents(); assertEquals(3, scc.getTotalComponents()); assertEquals(2, components.size()); assertEquals(IntArrayList.from(2, 1, 0), components.get(1)); assertEquals(IntArrayList.from(7, 6, 5, 4), components.get(0)); assertEquals(1, scc.getSingleNodeComponents().cardinality()); assertTrue(scc.getSingleNodeComponents().get(3)); assertEquals(8, scc.getNodes()); assertEquals(components.get(0), scc.getBiggestComponent()); // exclude single scc = TarjanSCC.findComponentsRecursive(graph, edgeFilter, true); assertTrue(scc.getSingleNodeComponents().isEmpty()); assertEquals(3, scc.getTotalComponents()); assertEquals(2, scc.getComponents().size()); assertEquals(8, scc.getNodes()); }
@SuppressWarnings("unchecked") public static <E extends Enum<E>> EnumSet<E> parseEnumSet(final String key, final String valueString, final Class<E> enumClass, final boolean ignoreUnknown) throws IllegalArgumentException { // build a map of lower case string to enum values. final Map<String, E> mapping = mapEnumNamesToValues("", enumClass); // scan the input string and add all which match final EnumSet<E> enumSet = noneOf(enumClass); for (String element : getTrimmedStringCollection(valueString)) { final String item = element.toLowerCase(Locale.ROOT); if ("*".equals(item)) { enumSet.addAll(mapping.values()); continue; } final E e = mapping.get(item); if (e != null) { enumSet.add(e); } else { // no match // unless configured to ignore unknown values, raise an exception checkArgument(ignoreUnknown, "%s: Unknown option value: %s in list %s." + " Valid options for enum class %s are: %s", key, element, valueString, enumClass.getName(), mapping.keySet().stream().collect(Collectors.joining(","))); } } return enumSet; }
@Test public void testUnknownStarEnum() throws Throwable { intercept(IllegalArgumentException.class, "unrecognized", () -> parseEnumSet("key", "*, unrecognized", SimpleEnum.class, false)); }
@Nonnull public static <T> AggregateOperation1<T, PriorityQueue<T>, List<T>> bottomN( int n, @Nonnull ComparatorEx<? super T> comparator ) { return topN(n, comparator.reversed()); }
@Test public void when_bottomN() { AggregateOperationsTest.validateOpWithoutDeduct(bottomN(2, naturalOrder()), ArrayList::new, Arrays.asList(7, 1, 5, 3), Arrays.asList(8, 6, 2, 4), Arrays.asList(3, 1), Arrays.asList(2, 1), Arrays.asList(1, 2) ); }
@Override public <R> QueryResult<R> query(final Query<R> query, final PositionBound positionBound, final QueryConfig config) { return internal.query(query, positionBound, config); }
@Test public void shouldThrowOnMultiVersionedKeyQueryInvalidTimeRange() { MultiVersionedKeyQuery<String, Object> query = MultiVersionedKeyQuery.withKey("key"); final Instant fromTime = Instant.now(); final Instant toTime = Instant.ofEpochMilli(fromTime.toEpochMilli() - 100); query = query.fromTime(fromTime).toTime(toTime); final MultiVersionedKeyQuery<String, Object> finalQuery = query; final Exception exception = assertThrows(IllegalArgumentException.class, () -> store.query(finalQuery, null, null)); assertEquals("The `fromTime` timestamp must be smaller than the `toTime` timestamp.", exception.getMessage()); }
@SuppressWarnings("unchecked") public <T> T convert(DocString docString, Type targetType) { if (DocString.class.equals(targetType)) { return (T) docString; } List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType); if (docStringTypes.isEmpty()) { if (docString.getContentType() == null) { throw new CucumberDocStringException(format( "It appears you did not register docstring type for %s", targetType.getTypeName())); } throw new CucumberDocStringException(format( "It appears you did not register docstring type for '%s' or %s", docString.getContentType(), targetType.getTypeName())); } if (docStringTypes.size() > 1) { List<String> suggestedContentTypes = suggestedContentTypes(docStringTypes); if (docString.getContentType() == null) { throw new CucumberDocStringException(format( "Multiple converters found for type %s, add one of the following content types to your docstring %s", targetType.getTypeName(), suggestedContentTypes)); } throw new CucumberDocStringException(format( "Multiple converters found for type %s, and the content type '%s' did not match any of the registered types %s. Change the content type of the docstring or register a docstring type for '%s'", targetType.getTypeName(), docString.getContentType(), suggestedContentTypes, docString.getContentType())); } return (T) docStringTypes.get(0).transform(docString.getContent()); }
@Test void unregistered_to_string_uses_default() { DocString docString = DocString.create("hello world", "unregistered"); assertThat(converter.convert(docString, String.class), is("hello world")); }
@VisibleForTesting static CliExecutor createExecutor(CommandLine commandLine) throws Exception { // The pipeline definition file would remain unparsed List<String> unparsedArgs = commandLine.getArgList(); if (unparsedArgs.isEmpty()) { throw new IllegalArgumentException( "Missing pipeline definition file path in arguments. "); } Path pipelineDefPath = Paths.get(unparsedArgs.get(0)); // Take the first unparsed argument as the pipeline definition file LOG.info("Real Path pipelineDefPath {}", pipelineDefPath); // Global pipeline configuration Configuration globalPipelineConfig = getGlobalConfig(commandLine); // Load Flink environment Path flinkHome = getFlinkHome(commandLine); Configuration flinkConfig = FlinkEnvironmentUtils.loadFlinkConfiguration(flinkHome); // Savepoint SavepointRestoreSettings savepointSettings = createSavepointRestoreSettings(commandLine); // Additional JARs List<Path> additionalJars = Arrays.stream( Optional.ofNullable( commandLine.getOptionValues(CliFrontendOptions.JAR)) .orElse(new String[0])) .map(Paths::get) .collect(Collectors.toList()); // Build executor return new CliExecutor( commandLine, pipelineDefPath, flinkConfig, globalPipelineConfig, commandLine.hasOption(CliFrontendOptions.USE_MINI_CLUSTER), additionalJars, savepointSettings); }
@Test void testGlobalPipelineConfigParsing() throws Exception { CliExecutor executor = createExecutor( pipelineDef(), "--flink-home", flinkHome(), "--global-config", globalPipelineConfig()); assertThat(executor.getGlobalPipelineConfig().toMap().get("parallelism")).isEqualTo("1"); assertThat(executor.getGlobalPipelineConfig().toMap().get("schema.change.behavior")) .isEqualTo("ignore"); }
public SearchSourceBuilder create(SearchesConfig config) { return create(SearchCommand.from(config)); }
@Test void searchIncludesSearchFilters() { final SearchSourceBuilder search = this.searchRequestFactory.create(ChunkCommand.builder() .filters(Collections.singletonList(InlineQueryStringSearchFilter.builder() .title("filter 1") .queryString("test-filter-value") .build())) .indices(Collections.singleton("graylog_0")) .range(RANGE) .batchSize(BATCH_SIZE) .build()); assertThat(search.toString()).contains(TEST_SEARCH_FILTERS_STRING); }
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testLambdaWithSubqueryInOrderBy() { analyze("SELECT a FROM t1 ORDER BY (SELECT apply(0, x -> x + a))"); analyze("SELECT a AS output_column FROM t1 ORDER BY (SELECT apply(0, x -> x + output_column))"); analyze("SELECT count(*) FROM t1 GROUP BY a ORDER BY (SELECT apply(0, x -> x + a))"); analyze("SELECT count(*) AS output_column FROM t1 GROUP BY a ORDER BY (SELECT apply(0, x -> x + output_column))"); assertFails( MUST_BE_AGGREGATE_OR_GROUP_BY, "line 1:71: Subquery uses 'b' which must appear in GROUP BY clause", "SELECT count(*) FROM t1 GROUP BY a ORDER BY (SELECT apply(0, x -> x + b))"); }
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) { return new DateTime(dateStr, dateFormat); }
@SuppressWarnings("ConstantConditions") @Test public void parseISO8601Test() { final String dt = "2020-06-03 12:32:12,333"; final DateTime parse = DateUtil.parse(dt); assertEquals("2020-06-03 12:32:12", parse.toString()); }
public static ExecutableStage forGrpcPortRead( QueryablePipeline pipeline, PipelineNode.PCollectionNode inputPCollection, Set<PipelineNode.PTransformNode> initialNodes) { checkArgument( !initialNodes.isEmpty(), "%s must contain at least one %s.", GreedyStageFuser.class.getSimpleName(), PipelineNode.PTransformNode.class.getSimpleName()); // Choose the environment from an arbitrary node. The initial nodes may not be empty for this // subgraph to make any sense, there has to be at least one processor node // (otherwise the stage is gRPC Read -> gRPC Write, which doesn't do anything). Environment environment = getStageEnvironment(pipeline, initialNodes); ImmutableSet.Builder<PipelineNode.PTransformNode> fusedTransforms = ImmutableSet.builder(); fusedTransforms.addAll(initialNodes); Set<SideInputReference> sideInputs = new LinkedHashSet<>(); Set<UserStateReference> userStates = new LinkedHashSet<>(); Set<TimerReference> timers = new LinkedHashSet<>(); Set<PipelineNode.PCollectionNode> fusedCollections = new LinkedHashSet<>(); Set<PipelineNode.PCollectionNode> materializedPCollections = new LinkedHashSet<>(); Queue<PipelineNode.PCollectionNode> fusionCandidates = new ArrayDeque<>(); for (PipelineNode.PTransformNode initialConsumer : initialNodes) { fusionCandidates.addAll(pipeline.getOutputPCollections(initialConsumer)); sideInputs.addAll(pipeline.getSideInputs(initialConsumer)); userStates.addAll(pipeline.getUserStates(initialConsumer)); timers.addAll(pipeline.getTimers(initialConsumer)); } while (!fusionCandidates.isEmpty()) { PipelineNode.PCollectionNode candidate = fusionCandidates.poll(); if (fusedCollections.contains(candidate) || materializedPCollections.contains(candidate)) { // This should generally mean we get to a Flatten via multiple paths through the graph and // we've already determined what to do with the output. LOG.debug( "Skipping fusion candidate {} because it is {} in this {}", candidate, fusedCollections.contains(candidate) ? "fused" : "materialized", ExecutableStage.class.getSimpleName()); continue; } PCollectionFusibility fusibility = canFuse(pipeline, candidate, environment, fusedCollections); switch (fusibility) { case MATERIALIZE: materializedPCollections.add(candidate); break; case FUSE: // All of the consumers of the candidate PCollection can be fused into this stage. Do so. fusedCollections.add(candidate); fusedTransforms.addAll(pipeline.getPerElementConsumers(candidate)); for (PipelineNode.PTransformNode consumer : pipeline.getPerElementConsumers(candidate)) { // The outputs of every transform fused into this stage must be either materialized or // themselves fused away, so add them to the set of candidates. fusionCandidates.addAll(pipeline.getOutputPCollections(consumer)); sideInputs.addAll(pipeline.getSideInputs(consumer)); } break; default: throw new IllegalStateException( String.format( "Unknown type of %s %s", PCollectionFusibility.class.getSimpleName(), fusibility)); } } return ImmutableExecutableStage.ofFullComponents( pipeline.getComponents(), environment, inputPCollection, sideInputs, userStates, timers, fusedTransforms.build(), materializedPCollections, ExecutableStage.DEFAULT_WIRE_CODER_SETTINGS); }
@Test public void materializesWithGroupByKeyConsumer() { // (impulse.out) -> read -> read.out -> gbk -> gbk.out // Fuses to // (impulse.out) -> read -> (read.out) // GBK is the responsibility of the runner, so it is not included in a stage. Environment env = Environments.createDockerEnvironment("common"); PTransform readTransform = PTransform.newBuilder() .putInputs("input", "impulse.out") .putOutputs("output", "read.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.PAR_DO_TRANSFORM_URN) .setPayload( ParDoPayload.newBuilder() .setDoFn(FunctionSpec.newBuilder()) .build() .toByteString())) .setEnvironmentId("common") .build(); QueryablePipeline p = QueryablePipeline.forPrimitivesIn( partialComponents .toBuilder() .putTransforms("read", readTransform) .putPcollections( "read.out", PCollection.newBuilder().setUniqueName("read.out").build()) .putTransforms( "gbk", PTransform.newBuilder() .putInputs("input", "read.out") .putOutputs("output", "gbk.out") .setSpec( FunctionSpec.newBuilder() .setUrn(PTransformTranslation.GROUP_BY_KEY_TRANSFORM_URN)) .build()) .putPcollections( "gbk.out", PCollection.newBuilder().setUniqueName("parDo.out").build()) .putEnvironments("common", env) .build()); PTransformNode readNode = PipelineNode.pTransform("read", readTransform); PCollectionNode readOutput = getOnlyElement(p.getOutputPCollections(readNode)); ExecutableStage subgraph = GreedyStageFuser.forGrpcPortRead(p, impulseOutputNode, ImmutableSet.of(readNode)); assertThat(subgraph.getOutputPCollections(), contains(readOutput)); assertThat(subgraph, hasSubtransforms(readNode.getId())); }
public static void updateDetailMessage( @Nullable Throwable root, @Nullable Function<Throwable, String> throwableToMessage) { if (throwableToMessage == null) { return; } Throwable it = root; while (it != null) { String newMessage = throwableToMessage.apply(it); if (newMessage != null) { updateDetailMessageOfThrowable(it, newMessage); } it = it.getCause(); } }
@Test void testUpdateDetailMessageWithMissingPredicate() { Throwable root = new Exception("old message"); ExceptionUtils.updateDetailMessage(root, null); assertThat(root.getMessage()).isEqualTo("old message"); }
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) { String highwayValue = way.getTag("highway"); if (skipEmergency && "service".equals(highwayValue) && "emergency_access".equals(way.getTag("service"))) return; int firstIndex = way.getFirstIndex(restrictionKeys); String firstValue = firstIndex < 0 ? "" : way.getTag(restrictionKeys.get(firstIndex), ""); if (restrictedValues.contains(firstValue) && !hasTemporalRestriction(way, firstIndex, restrictionKeys)) return; if (way.hasTag("gh:barrier_edge") && way.hasTag("node_tags")) { List<Map<String, Object>> nodeTags = way.getTag("node_tags", null); Map<String, Object> firstNodeTags = nodeTags.get(0); // a barrier edge has the restriction in both nodes and the tags are the same -> get(0) firstValue = getFirstPriorityNodeTag(firstNodeTags, restrictionKeys); String barrierValue = firstNodeTags.containsKey("barrier") ? (String) firstNodeTags.get("barrier") : ""; if (restrictedValues.contains(firstValue) || barriers.contains(barrierValue) || "yes".equals(firstNodeTags.get("locked")) && !INTENDED.contains(firstValue)) return; } if (FerrySpeedCalculator.isFerry(way)) { boolean isCar = restrictionKeys.contains("motorcar"); if (INTENDED.contains(firstValue) // implied default is allowed only if foot and bicycle is not specified: || isCar && firstValue.isEmpty() && !way.hasTag("foot") && !way.hasTag("bicycle") // if hgv is allowed then smaller trucks and cars are allowed too even if not specified || isCar && way.hasTag("hgv", "yes")) { accessEnc.setBool(false, edgeId, edgeIntAccess, true); accessEnc.setBool(true, edgeId, edgeIntAccess, true); } } else { boolean isRoundabout = roundaboutEnc.getBool(false, edgeId, edgeIntAccess); boolean ignoreOneway = "no".equals(way.getFirstValue(ignoreOnewayKeys)); boolean isBwd = isBackwardOneway(way); if (!ignoreOneway && (isBwd || isRoundabout || isForwardOneway(way))) { accessEnc.setBool(isBwd, edgeId, edgeIntAccess, true); } else { accessEnc.setBool(false, edgeId, edgeIntAccess, true); accessEnc.setBool(true, edgeId, edgeIntAccess, true); } } }
@Test public void testPsvYes() { EdgeIntAccess access = new ArrayEdgeIntAccess(1); ReaderWay way = new ReaderWay(0); way.setTag("motor_vehicle", "no"); way.setTag("highway", "tertiary"); int edgeId = 0; parser.handleWayTags(edgeId, access, way, null); assertFalse(busAccessEnc.getBool(false, edgeId, access)); access = new ArrayEdgeIntAccess(1); way.setTag("psv", "yes"); parser.handleWayTags(edgeId, access, way, null); assertTrue(busAccessEnc.getBool(false, edgeId, access)); access = new ArrayEdgeIntAccess(1); way.setTag("psv", "yes"); parser.handleWayTags(edgeId, access, way, null); assertTrue(busAccessEnc.getBool(false, edgeId, access)); }
public static String from(Path path) { return from(path.toString()); }
@Test void testCssContentType() { assertThat(ContentType.from(Path.of("stylesheet.css"))).isEqualTo(TEXT_CSS); }
public void validateAndMergeOutputParams(StepRuntimeSummary runtimeSummary) { Optional<String> externalJobId = extractExternalJobId(runtimeSummary); if (externalJobId.isPresent()) { Optional<OutputData> outputDataOpt = outputDataDao.getOutputDataForExternalJob(externalJobId.get(), ExternalJobType.TITUS); outputDataOpt.ifPresent( outputData -> { ParamsMergeHelper.mergeOutputDataParams( runtimeSummary.getParams(), outputData.getParams()); }); } }
@Test public void testValidOutputParameters() { Map<String, Parameter> runtimeParams = new HashMap<>(); runtimeParams.put( "str_param", StringParameter.builder() .name("str_param") .value("v1") .evaluatedResult("v1") .mode(ParamMode.MUTABLE) .evaluatedTime(System.currentTimeMillis()) .build()); setupOutputDataDao(); runtimeSummary = runtimeSummaryBuilder().artifacts(artifacts).params(runtimeParams).build(); outputDataManager.validateAndMergeOutputParams(runtimeSummary); assertEquals("hello", runtimeSummary.getParams().get("str_param").asString()); }
public static DynamicVoter parse(String input) { input = input.trim(); int atIndex = input.indexOf("@"); if (atIndex < 0) { throw new IllegalArgumentException("No @ found in dynamic voter string."); } if (atIndex == 0) { throw new IllegalArgumentException("Invalid @ at beginning of dynamic voter string."); } String idString = input.substring(0, atIndex); int nodeId; try { nodeId = Integer.parseInt(idString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse node id in dynamic voter string.", e); } if (nodeId < 0) { throw new IllegalArgumentException("Invalid negative node id " + nodeId + " in dynamic voter string."); } input = input.substring(atIndex + 1); if (input.isEmpty()) { throw new IllegalArgumentException("No hostname found after node id."); } String host; if (input.startsWith("[")) { int endBracketIndex = input.indexOf("]"); if (endBracketIndex < 0) { throw new IllegalArgumentException("Hostname began with left bracket, but no right " + "bracket was found."); } host = input.substring(1, endBracketIndex); input = input.substring(endBracketIndex + 1); } else { int endColonIndex = input.indexOf(":"); if (endColonIndex < 0) { throw new IllegalArgumentException("No colon following hostname could be found."); } host = input.substring(0, endColonIndex); input = input.substring(endColonIndex); } if (!input.startsWith(":")) { throw new IllegalArgumentException("Port section must start with a colon."); } input = input.substring(1); int endColonIndex = input.indexOf(":"); if (endColonIndex < 0) { throw new IllegalArgumentException("No colon following port could be found."); } String portString = input.substring(0, endColonIndex); int port; try { port = Integer.parseInt(portString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse port in dynamic voter string.", e); } if (port < 0 || port > 65535) { throw new IllegalArgumentException("Invalid port " + port + " in dynamic voter string."); } String directoryIdString = input.substring(endColonIndex + 1); Uuid directoryId; try { directoryId = Uuid.fromString(directoryIdString); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Failed to parse directory ID in dynamic voter string.", e); } return new DynamicVoter(directoryId, nodeId, host, port); }
@Test public void testInvalidPositivePort() { assertEquals("Invalid port 666666 in dynamic voter string.", assertThrows(IllegalArgumentException.class, () -> DynamicVoter.parse("5@[2001:4860:4860::8888]:666666:__0IZ-0DRNazJ49kCZ1EMQ")). getMessage()); }
@Override public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) { log.trace("compiling {} {}", intent, installable); ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint(); ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint(); //TODO: handle protected path case with suggested path!! //Idea: use suggested path as primary and another path from path service as protection if (intent.suggestedPath() != null && intent.suggestedPath().size() > 0) { Path path = new DefaultPath(PID, intent.suggestedPath(), new ScalarWeight(1)); //Check intent constraints against suggested path and suggested path availability if (checkPath(path, intent.constraints()) && pathAvailable(intent)) { allocateIntentBandwidth(intent, path); return asList(createLinkCollectionIntent(ImmutableSet.copyOf(intent.suggestedPath()), DEFAULT_COST, intent)); } } if (ingressPoint.deviceId().equals(egressPoint.deviceId())) { return createZeroHopLinkCollectionIntent(intent); } // proceed with no protected paths if (!ProtectionConstraint.requireProtectedPath(intent)) { return createUnprotectedLinkCollectionIntent(intent); } try { // attempt to compute and implement backup path return createProtectedIntent(ingressPoint, egressPoint, intent, installable); } catch (PathNotFoundException e) { log.warn("Could not find disjoint Path for {}", intent); // no disjoint path extant -- maximum one path exists between devices return createSinglePathIntent(ingressPoint, egressPoint, intent, installable); } }
@Test public void testSuggestedPathBandwidthConstrainedIntentSuccess() { final double bpsTotal = 1000.0; final double bpsToReserve = 100.0; final ResourceService resourceService = MockResourceService.makeCustomBandwidthResourceService(bpsTotal); final List<Constraint> constraints = Collections.singletonList(new BandwidthConstraint(Bandwidth.bps(bpsToReserve))); String[] suggestedPathHops = {S1, S4, S5, S3}; List<Link> suggestedPath = NetTestTools.createPath(suggestedPathHops).links(); final PointToPointIntent intent = makeIntentSuggestedPath( new ConnectPoint(DID_1, PORT_1), new ConnectPoint(DID_3, PORT_2), suggestedPath, constraints); String[][] hops = {{S1, S2, S3}, suggestedPathHops}; final PointToPointIntentCompiler compiler = makeCompilerSuggestedPath(hops, resourceService); final List<Intent> compiledIntents = compiler.compile(intent, null); assertThat(compiledIntents, Matchers.notNullValue()); assertThat(compiledIntents, hasSize(1)); assertThat("key is inherited", compiledIntents.stream().map(Intent::key).collect(Collectors.toList()), everyItem(is(intent.key()))); }
@PostMapping(path = "/admission") public WebhookResponse handleAdmissionReviewRequest(@RequestBody ObjectNode request) { LOGGER.debug("request is {}:", request.toString().replace(System.lineSeparator(), "_")); return handleAdmission(request); }
@Test public void injectSermant() throws IOException { JsonNode body = mapper.readTree(getClass().getClassLoader().getResourceAsStream("test.json")); WebhookResponse response = controller.handleAdmissionReviewRequest((ObjectNode) body); Assertions.assertNotNull(response); Assertions.assertNotNull(response.getResponse()); Assertions.assertTrue(response.getResponse().isAllowed()); // Test Annotations environment feature. byte[] decodedBytes = Base64.getDecoder().decode(response.getResponse().getPatch()); String decodedString = new String(decodedBytes); JsonNode rs = mapper.readTree(decodedString); Iterator<JsonNode> iter = rs.elements(); while ( iter.hasNext() ) { JsonNode node = iter.next(); if (node.get("path") != null && node.get("path").asText().equals("/spec/containers/0/env")) { JsonNode jn = node.findValue("value"); Assertions.assertTrue(jn.toString().indexOf("key1") > 0); break; } if ( iter.hasNext() == false ) { Assertions.fail("should not get here"); } } }
@Override public Map<String, String> apply(ServerWebExchange exchange) { StainingRule stainingRule = stainingRuleManager.getStainingRule(); if (stainingRule == null) { return Collections.emptyMap(); } return ruleStainingExecutor.execute(exchange, stainingRule); }
@Test public void testWithStainingRule() { RuleStainingProperties ruleStainingProperties = new RuleStainingProperties(); ruleStainingProperties.setNamespace(testNamespace); ruleStainingProperties.setGroup(testGroup); ruleStainingProperties.setFileName(testFileName); ConfigFile configFile = Mockito.mock(ConfigFile.class); when(configFile.getContent()).thenReturn("{\n" + " \"rules\":[\n" + " {\n" + " \"conditions\":[\n" + " {\n" + " \"key\":\"${http.query.uid}\",\n" + " \"values\":[\"1000\"],\n" + " \"operation\":\"EQUALS\"\n" + " }\n" + " ],\n" + " \"labels\":[\n" + " {\n" + " \"key\":\"env\",\n" + " \"value\":\"blue\"\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}"); when(configFileService.getConfigFile(testNamespace, testGroup, testFileName)).thenReturn(configFile); StainingRuleManager stainingRuleManager = new StainingRuleManager(ruleStainingProperties, configFileService); RuleStainingExecutor ruleStainingExecutor = new RuleStainingExecutor(); RuleTrafficStainer ruleTrafficStainer = new RuleTrafficStainer(stainingRuleManager, ruleStainingExecutor); MockServerHttpRequest request = MockServerHttpRequest.get("/users") .queryParam("uid", "1000").build(); MockServerWebExchange exchange = new MockServerWebExchange.Builder(request).build(); Map<String, String> map = ruleTrafficStainer.apply(exchange); assertThat(map).isNotNull(); assertThat(map.size()).isEqualTo(1); assertThat(map.get("env")).isEqualTo("blue"); }
public static double randomDouble(final double minInclude, final double maxExclude) { return getRandom().nextDouble(minInclude, maxExclude); }
@Test public void randomDoubleTest() { double randomDouble = RandomUtil.randomDouble(0, 1, 0, RoundingMode.HALF_UP); assertTrue(randomDouble <= 1); }
public static String encode(String s) { if (s == null) { return null; } int sz = s.length(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < sz; i++) { char ch = s.charAt(i); // handle unicode if (ch > 0xfff) { buffer.append("\\u" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } else if (ch > 0xff) { buffer.append("\\u0" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } else if (ch > 0x7f) { buffer.append("\\u00" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } else if (ch < 32) { switch (ch) { case '\b': buffer.append('\\'); buffer.append('b'); break; case '\n': buffer.append('\\'); buffer.append('n'); break; case '\t': buffer.append('\\'); buffer.append('t'); break; case '\f': buffer.append('\\'); buffer.append('f'); break; case '\r': buffer.append('\\'); buffer.append('r'); break; default: if (ch > 0xf) { buffer.append("\\u00" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } else { buffer.append("\\u000" + Integer.toHexString(ch).toUpperCase(Locale.ENGLISH)); } break; } } else { switch (ch) { case '\'': buffer.append('\''); break; case '"': buffer.append('\\'); buffer.append('"'); break; case '\\': buffer.append('\\'); buffer.append('\\'); break; case '/': buffer.append('/'); break; default: buffer.append(ch); break; } } } return buffer.toString(); }
@Test public void encode_naughtyStrings_encodedCorrectly() { for (Map.Entry<String, String> e : NAUGHTY_UNICODE_STRINGS.entrySet()) { assertEquals(e.getValue(), SecurityUtils.encode(e.getKey())); } }
public HikariDataSource getDataSource() { return ds; }
@Test @Ignore public void testGetH2DataSource() { DataSource ds = SingletonServiceFactory.getBean(H2DataSource.class).getDataSource(); assertNotNull(ds); try(Connection connection = ds.getConnection()){ assertNotNull(connection); } catch (SQLException e) { e.printStackTrace(); } }
@Override public RedisClusterNode clusterGetNodeForKey(byte[] key) { int slot = executorService.getConnectionManager().calcSlot(key); return clusterGetNodeForSlot(slot); }
@Test public void testClusterGetNodeForKey() { testInCluster(connection -> { RedisClusterNode node = connection.clusterGetNodeForKey("123".getBytes()); assertThat(node).isNotNull(); }); }
@VisibleForTesting static boolean isValidUrlFormat(String url) { Matcher matcher = URL_PATTERN.matcher(url); if (matcher.find()) { String host = matcher.group(2); return InetAddresses.isInetAddress(host) || InternetDomainName.isValid(host); } return false; }
@Test public void testInvalidURL() { assertFalse(SplunkEventWriter.isValidUrlFormat("http://1.2.3")); }
public static String getGlobalRuleRootNode() { return String.join("/", "", RULE_NODE); }
@Test void assertGetGlobalRuleRootNode() { assertThat(GlobalNode.getGlobalRuleRootNode(), is("/rules")); }
public static Optional<DefaultLitePullConsumerWrapper> wrapPullConsumer( DefaultLitePullConsumer pullConsumer) { // 获取消费者相关的defaultLitePullConsumerImpl、rebalanceImpl和mQClientFactory属性值,若获取失败说明消费者启动失败,不缓存该消费者 Optional<DefaultLitePullConsumerImpl> pullConsumerImplOptional = getPullConsumerImpl(pullConsumer); if (!pullConsumerImplOptional.isPresent()) { return Optional.empty(); } DefaultLitePullConsumerImpl pullConsumerImpl = pullConsumerImplOptional.get(); Optional<RebalanceImpl> rebalanceImplOptional = getRebalanceImpl(pullConsumerImpl); if (!rebalanceImplOptional.isPresent()) { return Optional.empty(); } RebalanceImpl rebalanceImpl = rebalanceImplOptional.get(); Optional<MQClientInstance> clientFactoryOptional = getClientFactory(pullConsumerImpl); if (!clientFactoryOptional.isPresent()) { return Optional.empty(); } MQClientInstance clientFactory = clientFactoryOptional.get(); DefaultLitePullConsumerWrapper wrapper = new DefaultLitePullConsumerWrapper(pullConsumer, pullConsumerImpl, rebalanceImpl, clientFactory); initWrapperServiceMeta(wrapper); return Optional.of(wrapper); }
@Test public void testWrapPullConsumer() { Optional<DefaultLitePullConsumerWrapper> pullConsumerWrapperOptional = RocketMqWrapperUtils .wrapPullConsumer(pullConsumer); Assert.assertTrue(pullConsumerWrapperOptional.isPresent()); Assert.assertEquals(pullConsumerWrapperOptional.get().getPullConsumer(), pullConsumer); }
protected void declareRuleFromAttribute(final Attribute attribute, final String parentPath, final int attributeIndex, final List<KiePMMLDroolsRule> rules, final String statusToSet, final String characteristicReasonCode, final Number characteristicBaselineScore, final boolean isLastCharacteristic) { logger.trace("declareRuleFromAttribute {} {}", attribute, parentPath); final Predicate predicate = attribute.getPredicate(); // This means the rule should not be created at all. // Different semantics has to be implemented if the "False"/"True" predicates are declared inside // an XOR compound predicate if (predicate instanceof False) { return; } String currentRule = String.format(PATH_PATTERN, parentPath, attributeIndex); KiePMMLReasonCodeAndValue reasonCodeAndValue = getKiePMMLReasonCodeAndValue(attribute, characteristicReasonCode, characteristicBaselineScore); PredicateASTFactoryData predicateASTFactoryData = new PredicateASTFactoryData(predicate, outputFields, rules, parentPath, currentRule, fieldTypeMap); KiePMMLPredicateASTFactory.factory(predicateASTFactoryData).declareRuleFromPredicate(attribute.getPartialScore(), statusToSet, reasonCodeAndValue, isLastCharacteristic); }
@Test void declareRuleFromAttributeWithCompoundPredicate() { Attribute attribute = getCompoundPredicateAttribute(); final String parentPath = "parent_path"; final int attributeIndex = 2; final List<KiePMMLDroolsRule> rules = new ArrayList<>(); final String statusToSet = "status_to_set"; final String characteristicReasonCode = "REASON_CODE"; final double characteristicBaselineScore = 12; final boolean isLastCharacteristic = false; getKiePMMLScorecardModelCharacteristicASTFactory() .declareRuleFromAttribute(attribute, parentPath, attributeIndex, rules, statusToSet, characteristicReasonCode, characteristicBaselineScore, isLastCharacteristic); assertThat(rules).hasSize(1); commonValidateRule(rules.get(0), attribute, statusToSet, parentPath, attributeIndex, isLastCharacteristic, 1, null, BOOLEAN_OPERATOR.AND, "value >= 5.0 && value < 12.0", 2); }
@Override public ElasticAgentPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { String pluginId = descriptor.id(); PluggableInstanceSettings pluggableInstanceSettings = null; if (!extension.supportsClusterProfiles(pluginId)) { pluggableInstanceSettings = getPluginSettingsAndView(descriptor, extension); } return new ElasticAgentPluginInfo(descriptor, elasticElasticAgentProfileSettings(pluginId), elasticClusterProfileSettings(pluginId), image(pluginId), pluggableInstanceSettings, capabilities(pluginId)); }
@Test public void shouldContinueWithBuildingPluginInfoIfPluginSettingsIsNotProvidedByThePlugin() { GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build(); List<PluginConfiguration> pluginConfigurations = List.of(new PluginConfiguration("aws_password", new Metadata(true, false))); Image icon = new Image("content_type", "data", "hash"); doThrow(new RuntimeException("foo")).when(extension).getPluginSettingsConfiguration(descriptor.id()); when(pluginManager.resolveExtensionVersion("plugin1", ELASTIC_AGENT_EXTENSION, SUPPORTED_VERSIONS)).thenReturn("1.0"); when(extension.getIcon(descriptor.id())).thenReturn(icon); when(extension.getProfileMetadata(descriptor.id())).thenReturn(pluginConfigurations); when(extension.getProfileView(descriptor.id())).thenReturn("profile_view"); ElasticAgentPluginInfoBuilder builder = new ElasticAgentPluginInfoBuilder(extension); ElasticAgentPluginInfo pluginInfo = builder.pluginInfoFor(descriptor); assertThat(pluginInfo.getDescriptor(), is(descriptor)); assertThat(pluginInfo.getExtensionName(), is("elastic-agent")); assertThat(pluginInfo.getImage(), is(icon)); assertThat(pluginInfo.getElasticAgentProfileSettings(), is(new PluggableInstanceSettings(pluginConfigurations, new PluginView("profile_view")))); assertNull(pluginInfo.getPluginSettings()); }
@Override public void shutdown() { if (SHUTDOWN.compareAndSet(false, true)) { Object registration = GraceContext.INSTANCE.getGraceShutDownManager().getRegistration(); ReflectUtils.invokeMethodWithNoneParameter(registration, REGISTRATION_DEREGISTER_METHOD_NAME); checkAndCloseSc(); GraceContext.INSTANCE.getGraceShutDownManager().setShutDown(true); ClientInfo clientInfo = RegisterContext.INSTANCE.getClientInfo(); Map<String, Collection<String>> header = new HashMap<>(); header.put(GraceConstants.MARK_SHUTDOWN_SERVICE_NAME, Collections.singletonList(clientInfo.getServiceName())); header.put(GraceConstants.MARK_SHUTDOWN_SERVICE_ENDPOINT, Arrays.asList(clientInfo.getIp() + ":" + clientInfo.getPort(), clientInfo.getHost() + ":" + clientInfo.getPort())); AddressCache.INSTANCE.getAddressSet().forEach(address -> notifyToGraceHttpServer(address, header)); } }
@Test public void testShutDown() { final GraceServiceImpl spy = Mockito.spy(new GraceServiceImpl()); spy.shutdown(); spy.addAddress("test"); Mockito.doCallRealMethod().when(spy).shutdown(); Mockito.verify(spy, Mockito.times(1)).shutdown(); Mockito.verify(spy, Mockito.times(1)).addAddress("test"); Assert.assertFalse(AddressCache.INSTANCE.getAddressSet().isEmpty()); final Optional<Object> shutdown = ReflectUtils.getFieldValue(spy, "SHUTDOWN"); Assert.assertTrue(shutdown.isPresent() && shutdown.get() instanceof AtomicBoolean); Assert.assertTrue(((AtomicBoolean) shutdown.get()).get()); }
@Override public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable { // 构建请求 DescribeSmsTemplateListRequest request = new DescribeSmsTemplateListRequest(); request.setTemplateIdSet(new Long[]{Long.parseLong(apiTemplateId)}); request.setInternational(INTERNATIONAL_CHINA); // 执行请求 DescribeSmsTemplateListResponse response = client.DescribeSmsTemplateList(request); DescribeTemplateListStatus status = response.getDescribeTemplateStatusSet()[0]; if (status == null || status.getStatusCode() == null) { return null; } return new SmsTemplateRespDTO().setId(status.getTemplateId().toString()).setContent(status.getTemplateContent()) .setAuditStatus(convertSmsTemplateAuditStatus(status.getStatusCode().intValue())).setAuditReason(status.getReviewReply()); }
@Test public void testGetSmsTemplate() throws Throwable { // 准备参数 Long apiTemplateId = randomLongId(); String requestId = randomString(); // mock 方法 DescribeSmsTemplateListResponse response = randomPojo(DescribeSmsTemplateListResponse.class, o -> { DescribeTemplateListStatus[] describeTemplateListStatuses = new DescribeTemplateListStatus[1]; DescribeTemplateListStatus templateStatus = new DescribeTemplateListStatus(); templateStatus.setTemplateId(apiTemplateId); templateStatus.setStatusCode(0L);// 设置模板通过 describeTemplateListStatuses[0] = templateStatus; o.setDescribeTemplateStatusSet(describeTemplateListStatuses); o.setRequestId(requestId); }); when(client.DescribeSmsTemplateList(argThat(request -> { assertEquals(apiTemplateId, request.getTemplateIdSet()[0]); return true; }))).thenReturn(response); // 调用 SmsTemplateRespDTO result = smsClient.getSmsTemplate(apiTemplateId.toString()); // 断言 assertEquals(response.getDescribeTemplateStatusSet()[0].getTemplateId().toString(), result.getId()); assertEquals(response.getDescribeTemplateStatusSet()[0].getTemplateContent(), result.getContent()); assertEquals(SmsTemplateAuditStatusEnum.SUCCESS.getStatus(), result.getAuditStatus()); assertEquals(response.getDescribeTemplateStatusSet()[0].getReviewReply(), result.getAuditReason()); }
protected void updateResult( Result result ) { Result newResult = trans.getResult(); result.clear(); // clear only the numbers, NOT the files or rows. result.add( newResult ); if ( !Utils.isEmpty( newResult.getRows() ) || trans.isResultRowsSet() ) { result.setRows( newResult.getRows() ); } }
@Test public void updateResultTest() { JobEntryTrans jobEntryTrans = spy( getJobEntryTrans() ); Trans transMock = mock( Trans.class ); InternalState.setInternalState( jobEntryTrans, "trans", transMock ); //Transformation returns result with 5 rows when( transMock.getResult() ).thenReturn( generateDummyResult( 5 ) ); //Previous result has 3 rows Result resultToBeUpdated = generateDummyResult( 3 ); //Update the result jobEntryTrans.updateResult( resultToBeUpdated ); //Result should have 5 number of rows since the trans result has 5 rows (meaning 5 rows were returned) assertEquals( resultToBeUpdated.getRows().size(), 5 ); }
@Override public Type classify(final Throwable e) { Type type = Type.UNKNOWN; if (e instanceof KsqlSerializationException || (e instanceof StreamsException && (ExceptionUtils.indexOfThrowable(e, KsqlSerializationException.class) != -1))) { if (!hasInternalTopicPrefix(e)) { type = Type.USER; LOG.info( "Classified error as USER error based on schema mismatch. Query ID: {} Exception: {}", queryId, e); } } return type; }
@Test public void shouldClassifyWrappedKsqlSerializationExceptionWithRepartitionTopicAsUnknownError() { // Given: final String topic = "_confluent-ksql-default_query_CTAS_USERS_0-Aggregate-GroupBy-repartition"; final Exception e = new StreamsException( new KsqlSerializationException( topic, "Error serializing message to topic: " + topic, new DataException("Struct schemas do not match."))); // When: final Type type = new KsqlSerializationClassifier("").classify(e); // Then: assertThat(type, is(Type.UNKNOWN)); }
@VisibleForTesting static BigDecimal extractConversionRate(final CoinMarketCapResponse response, final String destinationCurrency) throws IOException { if (!response.priceConversionResponse().quote.containsKey(destinationCurrency)) { throw new IOException("Response does not contain conversion rate for " + destinationCurrency); } return response.priceConversionResponse().quote.get(destinationCurrency).price(); }
@Test void extractConversionRate() throws IOException { final CoinMarketCapClient.CoinMarketCapResponse parsedResponse = CoinMarketCapClient.parseResponse(RESPONSE_JSON); assertEquals(new BigDecimal("0.6625319895827952"), CoinMarketCapClient.extractConversionRate(parsedResponse, "USD")); assertThrows(IOException.class, () -> CoinMarketCapClient.extractConversionRate(parsedResponse, "CAD")); }
static void urlEncode(String str, StringBuilder sb) { for (int idx = 0; idx < str.length(); ++idx) { char c = str.charAt(idx); if ('+' == c) { sb.append("%2B"); } else if ('%' == c) { sb.append("%25"); } else { sb.append(c); } } }
@Test void testUrlEncodeForNullStringBuilder() { assertThrows(NullPointerException.class, () -> { GroupKey2.urlEncode("+", null); // Method is not expected to return due to exception thrown }); // Method is not expected to return due to exception thrown }
public static UpdateRequirement fromJson(String json) { return JsonUtil.parse(json, UpdateRequirementParser::fromJson); }
@Test public void testAssertRefSnapshotIdToJson() { String requirementType = UpdateRequirementParser.ASSERT_REF_SNAPSHOT_ID; String refName = "snapshot-name"; Long snapshotId = 1L; String json = String.format( "{\"type\":\"%s\",\"ref\":\"%s\",\"snapshot-id\":%d}", requirementType, refName, snapshotId); UpdateRequirement expected = new UpdateRequirement.AssertRefSnapshotID(refName, snapshotId); assertEquals(requirementType, expected, UpdateRequirementParser.fromJson(json)); }
@Udf(description = "Returns the hyperbolic sine of an INT value") public Double sinh( @UdfParameter( value = "value", description = "The value in radians to get the hyperbolic sine of." ) final Integer value ) { return sinh(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleNegative() { assertThat(udf.sinh(-0.43), closeTo(-0.4433742144124824, 0.000000000000001)); assertThat(udf.sinh(-Math.PI), closeTo(-11.548739357257748, 0.000000000000001)); assertThat(udf.sinh(-Math.PI * 2), closeTo(-267.74489404101644, 0.000000000000001)); assertThat(udf.sinh(-6), closeTo(-201.71315737027922, 0.000000000000001)); assertThat(udf.sinh(-6L), closeTo(-201.71315737027922, 0.000000000000001)); }
@Subscribe public void onVarbitChanged(VarbitChanged event) { if (event.getVarbitId() == Varbits.IN_RAID) { removeVarTimer(OVERLOAD_RAID); removeGameTimer(PRAYER_ENHANCE); } if (event.getVarbitId() == Varbits.VENGEANCE_COOLDOWN && config.showVengeance()) { if (event.getValue() == 1) { createGameTimer(VENGEANCE); } else { removeGameTimer(VENGEANCE); } } if (event.getVarbitId() == Varbits.SPELLBOOK_SWAP && config.showSpellbookSwap()) { if (event.getValue() == 1) { createGameTimer(SPELLBOOK_SWAP); } else { removeGameTimer(SPELLBOOK_SWAP); } } if (event.getVarbitId() == Varbits.HEAL_GROUP_COOLDOWN && config.showHealGroup()) { if (event.getValue() == 1) { createGameTimer(HEAL_GROUP); } else { removeGameTimer(HEAL_GROUP); } } if (event.getVarbitId() == Varbits.DEATH_CHARGE_COOLDOWN && config.showArceuusCooldown()) { if (event.getValue() == 1) { createGameTimer(DEATH_CHARGE_COOLDOWN); } else { removeGameTimer(DEATH_CHARGE_COOLDOWN); } } if (event.getVarbitId() == Varbits.CORRUPTION_COOLDOWN && config.showArceuusCooldown()) { if (event.getValue() == 1) { createGameTimer(CORRUPTION_COOLDOWN); } else { removeGameTimer(CORRUPTION_COOLDOWN); } } if (event.getVarbitId() == Varbits.RESURRECT_THRALL_COOLDOWN && config.showArceuusCooldown()) { if (event.getValue() == 1) { createGameTimer(RESURRECT_THRALL_COOLDOWN); } else { removeGameTimer(RESURRECT_THRALL_COOLDOWN); } } if (event.getVarbitId() == Varbits.SHADOW_VEIL_COOLDOWN && config.showArceuusCooldown()) { if (event.getValue() == 1) { createGameTimer(SHADOW_VEIL_COOLDOWN); } else { removeGameTimer(SHADOW_VEIL_COOLDOWN); } } if (event.getVarbitId() == Varbits.WARD_OF_ARCEUUS_COOLDOWN && config.showArceuusCooldown()) { if (event.getValue() == 1) { createGameTimer(WARD_OF_ARCEUUS_COOLDOWN); } else { removeGameTimer(WARD_OF_ARCEUUS_COOLDOWN); } } if (event.getVarbitId() == Varbits.VENGEANCE_ACTIVE && config.showVengeanceActive()) { updateVarCounter(VENGEANCE_ACTIVE, event.getValue()); } if (event.getVarbitId() == Varbits.DEATH_CHARGE && config.showArceuus()) { if (event.getValue() == 1) { createGameTimer(DEATH_CHARGE, Duration.of(client.getRealSkillLevel(Skill.MAGIC), RSTimeUnit.GAME_TICKS)); } else { removeGameTimer(DEATH_CHARGE); } } if (event.getVarbitId() == Varbits.RESURRECT_THRALL && event.getValue() == 0 && config.showArceuus()) { removeGameTimer(RESURRECT_THRALL); } if (event.getVarbitId() == Varbits.SHADOW_VEIL && event.getValue() == 0 && config.showArceuus()) { removeGameTimer(SHADOW_VEIL); } if (event.getVarpId() == VarPlayer.POISON && config.showAntiPoison()) { final int poisonVarp = event.getValue(); final int tickCount = client.getTickCount(); if (poisonVarp == 0) { nextPoisonTick = -1; } else if (nextPoisonTick - tickCount <= 0) { nextPoisonTick = tickCount + POISON_TICK_LENGTH; } updateVarTimer(ANTIPOISON, event.getValue(), i -> i >= 0 || i < VENOM_VALUE_CUTOFF, i -> nextPoisonTick - tickCount + Math.abs((i + 1) * POISON_TICK_LENGTH)); updateVarTimer(ANTIVENOM, event.getValue(), i -> i >= VENOM_VALUE_CUTOFF, i -> nextPoisonTick - tickCount + Math.abs((i + 1 - VENOM_VALUE_CUTOFF) * POISON_TICK_LENGTH)); } if ((event.getVarbitId() == Varbits.NMZ_OVERLOAD_REFRESHES_REMAINING || event.getVarbitId() == Varbits.COX_OVERLOAD_REFRESHES_REMAINING) && config.showOverload()) { final int overloadVarb = event.getValue(); final int tickCount = client.getTickCount(); if (overloadVarb <= 0) { nextOverloadRefreshTick = -1; } else if (nextOverloadRefreshTick - tickCount <= 0) { nextOverloadRefreshTick = tickCount + OVERLOAD_TICK_LENGTH; } GameTimer overloadTimer = client.getVarbitValue(Varbits.IN_RAID) == 1 ? OVERLOAD_RAID : OVERLOAD; updateVarTimer(overloadTimer, overloadVarb, i -> nextOverloadRefreshTick - tickCount + (i - 1) * OVERLOAD_TICK_LENGTH); } if (event.getVarbitId() == Varbits.TELEBLOCK && config.showTeleblock()) { updateVarTimer(TELEBLOCK, event.getValue() - 100, i -> i <= 0, IntUnaryOperator.identity()); } if (event.getVarpId() == VarPlayer.CHARGE_GOD_SPELL && config.showCharge()) { updateVarTimer(CHARGE, event.getValue(), i -> i * 2); } if (event.getVarbitId() == Varbits.IMBUED_HEART_COOLDOWN && config.showImbuedHeart()) { updateVarTimer(IMBUEDHEART, event.getValue(), i -> i * 10); } if (event.getVarbitId() == Varbits.DRAGONFIRE_SHIELD_COOLDOWN && config.showDFSSpecial()) { updateVarTimer(DRAGON_FIRE_SHIELD, event.getValue(), i -> i * 8); } if (event.getVarpId() == LAST_HOME_TELEPORT && config.showHomeMinigameTeleports()) { checkTeleport(LAST_HOME_TELEPORT); } if (event.getVarpId() == LAST_MINIGAME_TELEPORT && config.showHomeMinigameTeleports()) { checkTeleport(LAST_MINIGAME_TELEPORT); } if (event.getVarbitId() == Varbits.RUN_SLOWED_DEPLETION_ACTIVE || event.getVarbitId() == Varbits.STAMINA_EFFECT || event.getVarbitId() == Varbits.RING_OF_ENDURANCE_EFFECT) { // staminaEffectActive is checked to match https://github.com/Joshua-F/cs2-scripts/blob/741271f0c3395048c1bad4af7881a13734516adf/scripts/%5Bproc%2Cbuff_bar_get_value%5D.cs2#L25 int staminaEffectActive = client.getVarbitValue(Varbits.RUN_SLOWED_DEPLETION_ACTIVE); int staminaPotionEffectVarb = client.getVarbitValue(Varbits.STAMINA_EFFECT); int enduranceRingEffectVarb = client.getVarbitValue(Varbits.RING_OF_ENDURANCE_EFFECT); final int totalStaminaEffect = staminaPotionEffectVarb + enduranceRingEffectVarb; if (staminaEffectActive == 1 && config.showStamina()) { updateVarTimer(STAMINA, totalStaminaEffect, i -> i * 10); } } if (event.getVarbitId() == Varbits.ANTIFIRE && config.showAntiFire()) { final int antifireVarb = event.getValue(); final int tickCount = client.getTickCount(); if (antifireVarb == 0) { nextAntifireTick = -1; } else if (nextAntifireTick - tickCount <= 0) { nextAntifireTick = tickCount + ANTIFIRE_TICK_LENGTH; } updateVarTimer(ANTIFIRE, antifireVarb, i -> nextAntifireTick - tickCount + (i - 1) * ANTIFIRE_TICK_LENGTH); } if (event.getVarbitId() == Varbits.SUPER_ANTIFIRE && config.showAntiFire()) { final int superAntifireVarb = event.getValue(); final int tickCount = client.getTickCount(); if (superAntifireVarb == 0) { nextSuperAntifireTick = -1; } else if (nextSuperAntifireTick - tickCount <= 0) { nextSuperAntifireTick = tickCount + SUPERANTIFIRE_TICK_LENGTH; } updateVarTimer(SUPERANTIFIRE, event.getValue(), i -> nextSuperAntifireTick - tickCount + (i - 1) * SUPERANTIFIRE_TICK_LENGTH); } if (event.getVarbitId() == Varbits.MAGIC_IMBUE && config.showMagicImbue()) { updateVarTimer(MAGICIMBUE, event.getValue(), i -> i * 10); } if (event.getVarbitId() == Varbits.DIVINE_SUPER_ATTACK && config.showDivine()) { if (client.getVarbitValue(Varbits.DIVINE_SUPER_COMBAT) > event.getValue()) { return; } updateVarTimer(DIVINE_SUPER_ATTACK, event.getValue(), IntUnaryOperator.identity()); } if (event.getVarbitId() == Varbits.DIVINE_SUPER_STRENGTH && config.showDivine()) { if (client.getVarbitValue(Varbits.DIVINE_SUPER_COMBAT) > event.getValue()) { return; } updateVarTimer(DIVINE_SUPER_STRENGTH, event.getValue(), IntUnaryOperator.identity()); } if (event.getVarbitId() == Varbits.DIVINE_SUPER_DEFENCE && config.showDivine()) { if (client.getVarbitValue(Varbits.DIVINE_SUPER_COMBAT) > event.getValue() || client.getVarbitValue(Varbits.DIVINE_BASTION) > event.getValue() || client.getVarbitValue(Varbits.DIVINE_BATTLEMAGE) > event.getValue() // When drinking a dose of moonlight potion while already under its effects, desync between // Varbits.MOONLIGHT_POTION and Varbits.DIVINE_SUPER_DEFENCE can occur, with the latter being 1 tick // greater || client.getVarbitValue(Varbits.MOONLIGHT_POTION) >= event.getValue()) { return; } if (client.getVarbitValue(Varbits.MOONLIGHT_POTION) < event.getValue()) { removeVarTimer(MOONLIGHT_POTION); } updateVarTimer(DIVINE_SUPER_DEFENCE, event.getValue(), IntUnaryOperator.identity()); } if (event.getVarbitId() == Varbits.DIVINE_RANGING && config.showDivine()) { if (client.getVarbitValue(Varbits.DIVINE_BASTION) > event.getValue()) { return; } updateVarTimer(DIVINE_RANGING, event.getValue(), IntUnaryOperator.identity()); } if (event.getVarbitId() == Varbits.DIVINE_MAGIC && config.showDivine()) { if (client.getVarbitValue(Varbits.DIVINE_BATTLEMAGE) > event.getValue()) { return; } updateVarTimer(DIVINE_MAGIC, event.getValue(), IntUnaryOperator.identity()); } if (event.getVarbitId() == Varbits.DIVINE_SUPER_COMBAT && config.showDivine()) { if (client.getVarbitValue(Varbits.DIVINE_SUPER_ATTACK) == event.getValue()) { removeVarTimer(DIVINE_SUPER_ATTACK); } if (client.getVarbitValue(Varbits.DIVINE_SUPER_STRENGTH) == event.getValue()) { removeVarTimer(DIVINE_SUPER_STRENGTH); } if (client.getVarbitValue(Varbits.DIVINE_SUPER_DEFENCE) == event.getValue()) { removeVarTimer(DIVINE_SUPER_DEFENCE); } updateVarTimer(DIVINE_SUPER_COMBAT, event.getValue(), IntUnaryOperator.identity()); } if (event.getVarbitId() == Varbits.DIVINE_BASTION && config.showDivine()) { if (client.getVarbitValue(Varbits.DIVINE_RANGING) == event.getValue()) { removeVarTimer(DIVINE_RANGING); } if (client.getVarbitValue(Varbits.DIVINE_SUPER_DEFENCE) == event.getValue()) { removeVarTimer(DIVINE_SUPER_DEFENCE); } updateVarTimer(DIVINE_BASTION, event.getValue(), IntUnaryOperator.identity()); } if (event.getVarbitId() == Varbits.DIVINE_BATTLEMAGE && config.showDivine()) { if (client.getVarbitValue(Varbits.DIVINE_MAGIC) == event.getValue()) { removeVarTimer(DIVINE_MAGIC); } if (client.getVarbitValue(Varbits.DIVINE_SUPER_DEFENCE) == event.getValue()) { removeVarTimer(DIVINE_SUPER_DEFENCE); } updateVarTimer(DIVINE_BATTLEMAGE, event.getValue(), IntUnaryOperator.identity()); } if (event.getVarbitId() == Varbits.BUFF_STAT_BOOST && config.showOverload()) { updateVarTimer(SMELLING_SALTS, event.getValue(), i -> i * 25); } if (event.getVarbitId() == Varbits.MENAPHITE_REMEDY && config.showMenaphiteRemedy()) { updateVarTimer(MENAPHITE_REMEDY, event.getValue(), i -> i * 25); } if (event.getVarbitId() == Varbits.LIQUID_ADERNALINE_ACTIVE && event.getValue() == 0 && config.showLiquidAdrenaline()) { removeGameTimer(LIQUID_ADRENALINE); } if (event.getVarbitId() == Varbits.FARMERS_AFFINITY && config.showFarmersAffinity()) { updateVarTimer(FARMERS_AFFINITY, event.getValue(), i -> i * 20); } if (event.getVarbitId() == Varbits.GOD_WARS_ALTAR_COOLDOWN && config.showGodWarsAltar()) { updateVarTimer(GOD_WARS_ALTAR, event.getValue(), i -> i * 100); } if (event.getVarbitId() == Varbits.CURSE_OF_THE_MOONS && config.showCurseOfTheMoons()) { final int regionID = WorldPoint.fromLocal(client, client.getLocalPlayer().getLocalLocation()).getRegionID(); if (regionID == ECLIPSE_MOON_REGION_ID) { updateVarCounter(CURSE_OF_THE_MOONS_ECLIPSE, event.getValue()); } else { updateVarCounter(CURSE_OF_THE_MOONS_BLUE, event.getValue()); } } if (event.getVarbitId() == Varbits.COLOSSEUM_DOOM && config.showColosseumDoom()) { updateVarCounter(COLOSSEUM_DOOM, event.getValue()); } if (event.getVarbitId() == Varbits.MOONLIGHT_POTION && config.showMoonlightPotion()) { int moonlightValue = event.getValue(); // Increase the timer by 1 tick in case of desync due to drinking a dose of moonlight potion while already // under its effects. Otherwise, the timer would be 1 tick shorter than it is meant to be. if (client.getVarbitValue(Varbits.DIVINE_SUPER_DEFENCE) == moonlightValue + 1) { moonlightValue++; } updateVarTimer(MOONLIGHT_POTION, moonlightValue, IntUnaryOperator.identity()); } }
@Test public void testImbuedHeartEnd() { when(timersAndBuffsConfig.showImbuedHeart()).thenReturn(true); VarbitChanged varbitChanged = new VarbitChanged(); varbitChanged.setVarbitId(Varbits.IMBUED_HEART_COOLDOWN); varbitChanged.setValue(70); timersAndBuffsPlugin.onVarbitChanged(varbitChanged); // Calls removeIf once (on createGameTimer) ArgumentCaptor<Predicate<InfoBox>> prcaptor = ArgumentCaptor.forClass(Predicate.class); TimerTimer imbuedHeartInfoBox = new TimerTimer(GameTimer.IMBUEDHEART, Duration.ofSeconds(420), timersAndBuffsPlugin); verify(infoBoxManager, times (1)).addInfoBox(any()); verify(infoBoxManager, times(1)).removeIf(prcaptor.capture()); Predicate<InfoBox> pred = prcaptor.getValue(); assertTrue(pred.test(imbuedHeartInfoBox)); varbitChanged = new VarbitChanged(); varbitChanged.setVarbitId(Varbits.IMBUED_HEART_COOLDOWN); varbitChanged.setValue(0); timersAndBuffsPlugin.onVarbitChanged(varbitChanged); // Calls removeIf once verify(infoBoxManager, times(1)).addInfoBox(any()); verify(infoBoxManager, times(2)).removeIf(prcaptor.capture()); pred = prcaptor.getValue(); assertTrue(pred.test(imbuedHeartInfoBox)); }
public String getNextId() { return String.format("%s-%d-%d", prefix, generatorInstanceId, counter.getAndIncrement()); }
@Test public void concurrent() throws Exception { int Threads = 10; int Iterations = 100; CyclicBarrier barrier = new CyclicBarrier(Threads); CountDownLatch counter = new CountDownLatch(Threads); @Cleanup("shutdownNow") ExecutorService executor = Executors.newCachedThreadPool(); List<String> results = Collections.synchronizedList(new ArrayList<>()); for (int i = 0; i < Threads; i++) { executor.execute(() -> { try { DistributedIdGenerator gen = new DistributedIdGenerator(coordinationService, "/my/test/concurrent", "prefix"); barrier.await(); for (int j = 0; j < Iterations; j++) { results.add(gen.getNextId()); } } catch (Exception e) { e.printStackTrace(); } finally { counter.countDown(); } }); } counter.await(); assertEquals(results.size(), Threads * Iterations); // Check the list contains no duplicates Set<String> set = Sets.newHashSet(results); assertEquals(set.size(), results.size()); }
@Override public String named() { return PluginEnum.LOGGING_CONSOLE.getName(); }
@Test public void testNamed() { assertEquals(loggingConsolePlugin.named(), PluginEnum.LOGGING_CONSOLE.getName()); }
@Override public MetricType getType() { return MetricType.GAUGE_RUBYHASH; }
@Test public void getValue() { RubyHashGauge gauge = new RubyHashGauge("bar", rubyHash); assertThat(gauge.getValue().toString()).isEqualTo(RUBY_HASH_AS_STRING); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_RUBYHASH); //Null initialize final RubyHashGauge gauge2 = new RubyHashGauge("bar"); Throwable thrown = catchThrowable(() -> { gauge2.getValue().toString(); }); assertThat(thrown).isInstanceOf(NullPointerException.class); assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_RUBYHASH); }
public static List<BindAddress> validateBindAddresses(ServiceConfiguration config, Collection<String> schemes) { // migrate the existing configuration properties List<BindAddress> addresses = migrateBindAddresses(config); // parse the list of additional bind addresses Arrays .stream(StringUtils.split(StringUtils.defaultString(config.getBindAddresses()), ",")) .map(s -> { Matcher m = BIND_ADDRESSES_PATTERN.matcher(s); if (!m.matches()) { throw new IllegalArgumentException("bindAddresses: malformed: " + s); } return m; }) .map(m -> new BindAddress(m.group("name"), URI.create(m.group("url")))) .forEach(addresses::add); // apply the filter if (schemes != null) { addresses.removeIf(a -> !schemes.contains(a.getAddress().getScheme())); } return addresses; }
@Test public void testMigrationWithExtra() { ServiceConfiguration config = newEmptyConfiguration(); config.setBrokerServicePort(Optional.of(6650)); config.setBindAddresses("extra:pulsar://0.0.0.0:6652"); List<BindAddress> addresses = BindAddressValidator.validateBindAddresses(config, null); assertEquals(Arrays.asList( new BindAddress(null, URI.create("pulsar://0.0.0.0:6650")), new BindAddress("extra", URI.create("pulsar://0.0.0.0:6652"))), addresses); }
public static List<TargetInfo> parseOptTarget(CommandLine cmd, AlluxioConfiguration conf) throws IOException { String[] targets; if (cmd.hasOption(TARGET_OPTION_NAME)) { String argTarget = cmd.getOptionValue(TARGET_OPTION_NAME); if (StringUtils.isBlank(argTarget)) { throw new IOException("Option " + TARGET_OPTION_NAME + " can not be blank."); } else if (argTarget.contains(TARGET_SEPARATOR)) { targets = argTarget.split(TARGET_SEPARATOR); } else { targets = new String[]{argTarget}; } } else { // By default we set on all targets (master/workers/job_master/job_workers) targets = new String[]{ROLE_MASTER, ROLE_JOB_MASTER, ROLE_WORKERS, ROLE_JOB_WORKERS}; } return getTargetInfos(targets, conf); }
@Test public void parseZooKeeperHAMasterTarget() throws Exception { String masterAddress = "masters-1:2181"; mConf.set(PropertyKey.ZOOKEEPER_ENABLED, true); mConf.set(PropertyKey.ZOOKEEPER_ADDRESS, masterAddress); CommandLine mockCommandLine = mock(CommandLine.class); String[] mockArgs = new String[]{"--target", "master"}; when(mockCommandLine.getArgs()).thenReturn(mockArgs); when(mockCommandLine.hasOption(LogLevel.TARGET_OPTION_NAME)).thenReturn(true); when(mockCommandLine.getOptionValue(LogLevel.TARGET_OPTION_NAME)).thenReturn(mockArgs[1]); try (MockedStatic<MasterInquireClient.Factory> mockFactory = mockStatic(MasterInquireClient.Factory.class)) { MasterInquireClient mockInquireClient = mock(MasterInquireClient.class); when(mockInquireClient.getPrimaryRpcAddress()).thenReturn( new InetSocketAddress("masters-1", mConf.getInt(PropertyKey.MASTER_RPC_PORT))); when(mockInquireClient.getConnectDetails()) .thenReturn(() -> new ZookeeperAuthority(masterAddress)); mockFactory.when(() -> MasterInquireClient.Factory.create(any(), any())) .thenReturn(mockInquireClient); List<LogLevel.TargetInfo> targets = LogLevel.parseOptTarget(mockCommandLine, mConf); assertEquals(1, targets.size()); assertEquals(new LogLevel.TargetInfo("masters-1", MASTER_WEB_PORT, "master"), targets.get(0)); } }
public static Date getDate(Object date) { return getDate(date, Calendar.getInstance().getTime()); }
@Test public void testGetDateObjectDateWithInvalidStringAndNullDefault() { assertNull(Converter.getDate("invalid date", null)); }
@Override public <VO, VR> KStream<K, VR> outerJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return outerJoin(otherStream, toValueJoinerWithKey(joiner), windows); }
@SuppressWarnings("deprecation") @Test public void shouldNotAllowNullStreamJoinedOnOuterJoin() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.outerJoin( testStream, MockValueJoiner.TOSTRING_JOINER, JoinWindows.of(ofMillis(10)), (StreamJoined<String, String, String>) null)); assertThat(exception.getMessage(), equalTo("streamJoined can't be null")); }
@Override public ResultMerger newInstance(final String databaseName, final DatabaseType protocolType, final ShardingRule shardingRule, final ConfigurationProperties props, final SQLStatementContext sqlStatementContext) { if (sqlStatementContext instanceof SelectStatementContext) { return new ShardingDQLResultMerger(protocolType); } if (sqlStatementContext.getSqlStatement() instanceof DDLStatement) { return new ShardingDDLResultMerger(); } if (sqlStatementContext.getSqlStatement() instanceof DALStatement) { return new ShardingDALResultMerger(databaseName, shardingRule); } return new TransparentResultMerger(); }
@Test void assertNewInstanceWithDALStatement() { ConfigurationProperties props = new ConfigurationProperties(new Properties()); UnknownSQLStatementContext sqlStatementContext = new UnknownSQLStatementContext(new PostgreSQLShowStatement("")); assertThat(new ShardingResultMergerEngine().newInstance(DefaultDatabase.LOGIC_NAME, TypedSPILoader.getService(DatabaseType.class, "MySQL"), null, props, sqlStatementContext), instanceOf(ShardingDALResultMerger.class)); }
@Override public Long createTenantPackage(TenantPackageSaveReqVO createReqVO) { // 插入 TenantPackageDO tenantPackage = BeanUtils.toBean(createReqVO, TenantPackageDO.class); tenantPackageMapper.insert(tenantPackage); // 返回 return tenantPackage.getId(); }
@Test public void testCreateTenantPackage_success() { // 准备参数 TenantPackageSaveReqVO reqVO = randomPojo(TenantPackageSaveReqVO.class, o -> o.setStatus(randomCommonStatus())) .setId(null); // 防止 id 被赋值 // 调用 Long tenantPackageId = tenantPackageService.createTenantPackage(reqVO); // 断言 assertNotNull(tenantPackageId); // 校验记录的属性是否正确 TenantPackageDO tenantPackage = tenantPackageMapper.selectById(tenantPackageId); assertPojoEquals(reqVO, tenantPackage, "id"); }
public Optional<DateTime> nextTime(JobTriggerDto trigger) { return nextTime(trigger, trigger.nextTime()); }
@Test public void nextTimeCron() { final JobTriggerDto trigger = JobTriggerDto.builderWithClock(clock) .jobDefinitionId("abc-123") .jobDefinitionType("event-processor-execution-v1") .schedule(CronJobSchedule.builder() .cronExpression("0 0 1 * * ? *") .timezone("EST") .build()) .build(); final DateTime nextTime = strategies.nextTime(trigger).orElse(null); assertThat(nextTime) .isNotNull() .satisfies(dateTime -> { // EST is mapped to a fixed offset without daylight savings: https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html#SHORT_IDS assertThat(dateTime.getZone()).isEqualTo(DateTimeZone.forID("-05:00")); assertThat(dateTime.toString(DATE_FORMAT)).isEqualTo("14/06/2022 01:00:00"); }); }
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchIPDstTest() { Criterion criterion = Criteria.matchIPDst(ipPrefix4); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }