focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public ConfigData get(String path) { if (allowedPaths == null) { throw new IllegalStateException("The provider has not been configured yet."); } Map<String, String> data = new HashMap<>(); if (path == null || path.isEmpty()) { return new ConfigData(data); ...
@Test public void testGetAllKeysAtPath() { ConfigData configData = configProvider.get("dummy"); Map<String, String> result = new HashMap<>(); result.put("testKey", "testResult"); result.put("testKey2", "testResult2"); assertEquals(result, configData.data()); assertNul...
@Deprecated @Override public Boolean hasAppendsOnly(org.apache.hadoop.hive.ql.metadata.Table hmsTable, SnapshotContext since) { TableDesc tableDesc = Utilities.getTableDesc(hmsTable); Table table = IcebergTableUtil.getTable(conf, tableDesc.getProperties()); return hasAppendsOnly(table.snapshots(), since...
@Test public void testHasAppendsOnlyReturnsNullWhenGivenSnapshotNotInTheList() { SnapshotContext since = new SnapshotContext(1); List<Snapshot> snapshotList = Arrays.asList(anySnapshot, appendSnapshot, deleteSnapshot); HiveIcebergStorageHandler storageHandler = new HiveIcebergStorageHandler(); Boolea...
CodeEmitter<T> emit(final Parameter parameter) { emitter.emit("param"); emit("name", parameter.getName()); final String parameterType = parameter.getIn(); if (ObjectHelper.isNotEmpty(parameterType)) { emit("type", RestParamType.valueOf(parameterType)); } if (...
@Test public void shouldEmitCodeForOas3RefParameters() { final Builder method = MethodSpec.methodBuilder("configure"); final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method); final OperationVisitor<?> visitor = new OperationVisitor<>(emitter, null, null, null, nu...
public void transitionTo(ClassicGroupState groupState) { assertValidTransition(groupState); previousState = state; state = groupState; currentStateTimestamp = Optional.of(time.milliseconds()); metrics.onClassicGroupStateTransition(previousState, state); }
@Test public void testStableToDeadTransition() { group.transitionTo(DEAD); assertState(group, DEAD); }
@Override public void loadData(Priority priority, DataCallback<? super T> callback) { this.callback = callback; serializer.startRequest(priority, url, this); }
@Test public void testLoadData_withInProgressRequest_isNotifiedWhenRequestCompletes() throws Exception { ChromiumUrlFetcher<ByteBuffer> firstFetcher = new ChromiumUrlFetcher<>(serializer, parser, glideUrl); ChromiumUrlFetcher<ByteBuffer> secondFetcher = new ChromiumUrlFetcher<>(serializer, par...
@Override public Set<String> scope() { // Immutability of the set is performed in the constructor/validation utils class, so // we don't need to repeat it here. return scopes; }
@Test public void noErrorIfModifyScope() { // Start with a basic set created by the caller. SortedSet<String> callerSet = new TreeSet<>(Arrays.asList("a", "b", "c")); OAuthBearerToken token = new BasicOAuthBearerToken("not.valid.token", callerSet, 0L, "jdo...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test public void testNotOrParenAnd() { final Predicate parsed = PredicateExpressionParser.parse("!(com.linkedin.data.it.AlwaysTruePredicate | com.linkedin.data.it.AlwaysTruePredicate) & !com.linkedin.data.it.AlwaysFalsePredicate"); Assert.assertEquals(parsed.getClass(), AndPredicate.class); final List...
public static List<String> parseColumnsFromPath(String filePath, List<String> columnsFromPath) throws SparkDppException { if (columnsFromPath == null || columnsFromPath.isEmpty()) { return Collections.emptyList(); } String[] strings = filePath.split("/"); if (stri...
@Test public void testParseColumnsFromPath() { DppUtils dppUtils = new DppUtils(); String path = "/path/to/file/city=beijing/date=2020-04-10/data"; List<String> columnFromPaths = new ArrayList<>(); columnFromPaths.add("city"); columnFromPaths.add("date"); try { ...
public byte[] getTail() { int size = (int) Math.min(tailSize, bytesRead); byte[] result = new byte[size]; System.arraycopy(tailBuffer, currentIndex, result, 0, size - currentIndex); System.arraycopy(tailBuffer, 0, result, size - currentIndex, currentIndex); return result; }
@Test public void testTailBeforeRead() throws IOException { TailStream stream = new TailStream(generateStream(0, 100), 50); assertEquals(0, stream.getTail().length, "Wrong buffer length"); stream.close(); }
@Override public void close() throws LiquibaseException { LiquibaseException exception = null; try { super.close(); } finally { try { dataSource.stop(); } catch (Exception e) { exception = new LiquibaseException(e); ...
@Test void testWhenClosingAllConnectionsInPoolIsReleased() throws Exception { ConnectionPool pool = dataSource.getPool(); assertThat(pool.getActive()).isEqualTo(1); liquibase.close(); assertThat(pool.getActive()).isZero(); assertThat(pool.getIdle()).isZero(); asser...
@Override public boolean equals(final Object obj) { if (!(obj instanceof OrderByItem)) { return false; } OrderByItem orderByItem = (OrderByItem) obj; return segment.getOrderDirection() == orderByItem.segment.getOrderDirection() && index == orderByItem.index; }
@SuppressWarnings({"SimplifiableAssertion", "ConstantValue"}) @Test void assertEqualsWhenObjIsNull() { assertFalse(new OrderByItem(mock(OrderByItemSegment.class)).equals(null)); }
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { long datetime = readDatetimeV2FromPayload(payload); return 0L == datetime ? MySQLTimeValueUtils.DATETIME_OF_ZERO : readDatetime(columnDef, datetime, payload); }
@Test void assertReadWithoutFraction() { when(payload.readInt1()).thenReturn(0xfe, 0xf3, 0xff, 0x7e, 0xfb); LocalDateTime expected = LocalDateTime.of(9999, 12, 31, 23, 59, 59); assertThat(new MySQLDatetime2BinlogProtocolValue().read(columnDef, payload), is(Timestamp.valueOf(expected))); ...
@Override public int run(String[] args) throws Exception { YarnConfiguration yarnConf = getConf() == null ? new YarnConfiguration() : new YarnConfiguration(getConf()); boolean isFederationEnabled = yarnConf.getBoolean(YarnConfiguration.FEDERATION_ENABLED, YarnConfiguration.DEFAULT_FEDERATION_E...
@Test public void testHelp() throws Exception { PrintStream oldOutPrintStream = System.out; PrintStream oldErrPrintStream = System.err; ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); ByteArrayOutputStream dataErr = new ByteArrayOutputStream(); System.setOut(new PrintStream(dataOut));...
void startServiceFingerprinting( ImmutableList<PluginMatchingResult<ServiceFingerprinter>> selectedServiceFingerprinters) { checkState(currentExecutionStage.equals(ExecutionStage.PORT_SCANNING)); checkState(portScanningTimer.isRunning()); this.portScanningTimer.stop(); this.serviceFingerprintingT...
@Test public void startServiceFingerprinting_whenStageNotPortScanning_throwsException() { ExecutionTracer executionTracer = new ExecutionTracer( portScanningTimer, serviceFingerprintingTimer, vulnerabilityDetectingTimer); assertThrows( IllegalStateException.class, () -> ex...
@Deprecated public static String getJwt(JwtClaims claims) throws JoseException { String jwt; RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey( jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName()); // A JWT is a JWS and/...
@Test public void longLivedCodegenJwt() throws Exception { JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("codegen.r", "codegen.w", "server.info.r"), "user"); claims.setExpirationTimeMinutesInTheFuture(5256000); String j...
@Override public int chmod(String path, long mode) { return AlluxioFuseUtils.call(LOG, () -> chmodInternal(path, mode), FuseConstants.FUSE_CHMOD, "path=%s,mode=%o", path, mode); }
@Test @DoraTestTodoItem(action = DoraTestTodoItem.Action.FIX, owner = "LuQQiu", comment = "waiting on security metadata to be implemented in Dora") @Ignore public void chmod() throws Exception { long mode = 123; mFuseFs.chmod("/foo/bar", mode); AlluxioURI expectedPath = BASE_EXPECTED_URI.join("/...
@Override public Interpreter getInterpreter(String replName, ExecutionContext executionContext) throws InterpreterNotFoundException { if (StringUtils.isBlank(replName)) { // Get the default interpreter of the defaultInterpreterSetting InterpreterSetting defau...
@Test void testUnknownRepl1() { try { interpreterFactory.getInterpreter("test.unknown_repl", new ExecutionContext("user1", "note1", "test")); fail("should fail due to no such interpreter"); } catch (InterpreterNotFoundException e) { assertEquals("No such interpreter: test.unknown_repl", e.ge...
@Override public TimestampedSegment getOrCreateSegmentIfLive(final long segmentId, final ProcessorContext context, final long streamTime) { final TimestampedSegment segment = super.getOrCreateSegmentIfLiv...
@Test public void shouldGetSegmentsWithinTimeRange() { updateStreamTimeAndCreateSegment(0); updateStreamTimeAndCreateSegment(1); updateStreamTimeAndCreateSegment(2); updateStreamTimeAndCreateSegment(3); final long streamTime = updateStreamTimeAndCreateSegment(4); segm...
public User(String name) { this.name = name; this.roles = null; }
@Test void testUser() { Set<String> roles = new HashSet<>(); roles.add("userRole1"); roles.add("userRole2"); User user = new User("userName", roles); assertThat(user.getName()).isEqualTo("userName"); assertThat(user.getRoles()).hasSize(2).contains("userRole1", "userR...
@Subscribe public void inputUpdated(InputUpdated inputUpdatedEvent) { final String inputId = inputUpdatedEvent.id(); LOG.debug("Input updated: {}", inputId); final Input input; try { input = inputService.find(inputId); } catch (NotFoundException e) { L...
@Test public void inputUpdatedStopsInputIfItIsRunning() throws Exception { final String inputId = "input-id"; final Input input = mock(Input.class); @SuppressWarnings("unchecked") final IOState<MessageInput> inputState = mock(IOState.class); when(inputService.find(inputId)).t...
public void addValueProviders(final String segmentName, final RocksDB db, final Cache cache, final Statistics statistics) { if (storeToValueProviders.isEmpty()) { logger.debug("Adding metrics record...
@Test public void shouldThrowIfStatisticsToAddIsNullButExistingStatisticsAreNotNull() { recorder.addValueProviders(SEGMENT_STORE_NAME_1, dbToAdd1, cacheToAdd1, statisticsToAdd1); final Throwable exception = assertThrows( IllegalStateException.class, () -> recorder.addValuePr...
public KsqlGenericRecord build( final List<ColumnName> columnNames, final List<Expression> expressions, final LogicalSchema schema, final DataSourceType dataSourceType ) { final List<ColumnName> columns = columnNames.isEmpty() ? implicitColumns(schema) : columnNames; i...
@Test public void shouldThrowOnInsertRowoffset() { // Given: final LogicalSchema schema = LogicalSchema.builder() .keyColumn(KEY, SqlTypes.STRING) .valueColumn(COL0, SqlTypes.STRING) .build(); final Expression exp = new StringLiteral("a"); // When: final KsqlException e = ...
public Set<Integer> nodesThatShouldBeDown(ClusterState state) { return calculate(state).nodesThatShouldBeDown(); }
@Test void down_to_down_edge_keeps_group_down() { GroupAvailabilityCalculator calc = calcForHierarchicCluster( DistributionBuilder.withGroups(2).eachWithNodeCount(4), 0.76); assertThat(calc.nodesThatShouldBeDown(clusterState( "distributor:8 storage:8 .1.s:d")), equal...
@Override public void chunk(final Path directory, final AttributedList<Path> list) throws ListCanceledException { if(directory.isRoot()) { if(list.size() >= container) { // Allow another chunk until limit is reached again container += preferences.getInteger("brows...
@Test(expected = ListCanceledException.class) public void testChunkLimitContainer() throws Exception { new LimitedListProgressListener(new DisabledProgressListener()).chunk( new Path("/", EnumSet.of(Path.Type.volume, Path.Type.directory)), new AttributedList<Path>() { @Ov...
@Override public Uuid clientInstanceId(Duration timeout) { if (!clientTelemetryReporter.isPresent()) { throw new IllegalStateException("Telemetry is not enabled. Set config `" + ProducerConfig.ENABLE_METRICS_PUSH_CONFIG + "` to `true`."); } return ClientTelemetryUtils.fetchClien...
@Test public void testClientInstanceId() { Properties props = new Properties(); props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999"); ClientTelemetryReporter clientTelemetryReporter = mock(ClientTelemetryReporter.class); clientTelemetryReporter.configure(any(...
static void dissectFrame( final DriverEventCode eventCode, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder); builder.append(": address="); enc...
@Test void dissectFrameTypeUnknown() { internalEncodeLogHeader(buffer, 0, 3, 3, () -> 3_000_000_000L); final int socketAddressOffset = encodeSocketAddress( buffer, LOG_HEADER_LENGTH, new InetSocketAddress("localhost", 8888)); final DataHeaderFlyweight flyweight = new DataHead...
@ExceptionHandler({HttpMessageNotReadableException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) protected ResponseEntity<RestError> handleHttpMessageNotReadableException(HttpMessageNotReadableException httpMessageNotReadableException) { String exceptionMessage = getExceptionMessage(httpMessageNotReadableExce...
@Test public void handleHttpMessageNotReadableException_whenCauseIsNotInvalidFormatException_shouldUseMessage() { HttpMessageNotReadableException exception = new HttpMessageNotReadableException("Message not readable", new Exception()); ResponseEntity<RestError> responseEntity = underTest.handleHttpMessageNo...
@Nullable public String getStorageClass() { return _storageClass; }
@Test public void testIntelligentTieringStorageClass() { PinotConfiguration pinotConfig = new PinotConfiguration(); pinotConfig.setProperty("storageClass", StorageClass.INTELLIGENT_TIERING.toString()); S3Config cfg = new S3Config(pinotConfig); Assert.assertEquals(cfg.getStorageClass(), "INTELLIGENT_TI...
protected boolean isInvalidOrigin(FullHttpRequest req) { final String origin = req.headers().get(HttpHeaderNames.ORIGIN); if (origin == null || !origin.toLowerCase().endsWith(originDomain)) { logger.error("Invalid Origin header {} in WebSocket upgrade request", origin); return tr...
@Test void testIsInvalidOrigin() { ZuulPushAuthHandlerTest authHandler = new ZuulPushAuthHandlerTest(); final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/ws", Unpooled.buffer()); // Invalid input assertTrue(au...
public void removePackageRepository(String id) { PackageRepository packageRepositoryToBeDeleted = this.find(id); if (packageRepositoryToBeDeleted == null) { throw new RuntimeException(String.format("Could not find repository with id '%s'", id)); } this.remove(packageRepositor...
@Test void shouldFindPackageRepositoryById() throws Exception { PackageRepositories packageRepositories = new PackageRepositories(); packageRepositories.add(PackageRepositoryMother.create("repo1")); PackageRepository repo2 = PackageRepositoryMother.create("repo2"); packageRepositorie...
@Private public void handleEvent(JobHistoryEvent event) { synchronized (lock) { // If this is JobSubmitted Event, setup the writer if (event.getHistoryEvent().getEventType() == EventType.AM_STARTED) { try { AMStartedEvent amStartedEvent = (AMStartedEvent) event.getHist...
@Test (timeout=50000) public void testDefaultFsIsUsedForHistory() throws Exception { // Create default configuration pointing to the minicluster Configuration conf = new Configuration(); conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, dfsCluster.getURI().toString()); FileOutput...
@Override public boolean retainAll(Collection<?> c) { // will throw UnsupportedOperationException return underlying().retainAll(c); }
@Test public void testDelegationOfUnsupportedFunctionRetainAll() { new PCollectionsTreeSetWrapperDelegationChecker<>() .defineMockConfigurationForUnsupportedFunction(mock -> mock.retainAll(eq(Collections.emptyList()))) .defineWrapperUnsupportedFunctionInvocation(wrapper -> wr...
public static SchemaAndValue parseString(String value) { if (value == null) { return NULL_SCHEMA_AND_VALUE; } if (value.isEmpty()) { return new SchemaAndValue(Schema.STRING_SCHEMA, value); } ValueParser parser = new ValueParser(new Parser(value)); ...
@Test public void shouldParseFractionalPartsAsIntegerWhenNoFractionalPart() { assertEquals(new SchemaAndValue(Schema.INT8_SCHEMA, (byte) 1), Values.parseString("1.0")); assertEquals(new SchemaAndValue(Schema.FLOAT32_SCHEMA, 1.1f), Values.parseString("1.1")); assertEquals(new SchemaAndValue(S...
public AstNode rewrite(final AstNode node, final C context) { return rewriter.process(node, context); }
@Test public void shouldNotRewriteExplainWithId() { // Given: final Explain explain = new Explain(location, Optional.of("id"), Optional.empty()); // When: final AstNode rewritten = rewriter.rewrite(explain, context); // Then: assertThat(rewritten, is(sameInstance(explain))); }
protected static SimpleDateFormat getLog4j2Appender() { Optional<Appender> log4j2xmlAppender = configuration.getAppenders().values().stream() .filter( a -> a.getName().equalsIgnoreCase( log4J2Appender ) ).findFirst(); if ( log4j2xmlAppender.isPresent() ) { ArrayList<String> matchesArray = ne...
@Test public void testGetLog4j2UsingAppender8() { // Testing MMM-dd,yyyy pattern KettleLogLayout.log4J2Appender = "pdi-execution-appender-test-8"; Assert.assertEquals( "MMM-dd,yyyy", KettleLogLayout.getLog4j2Appender().toPattern() ); }
@Retryable(DataAccessResourceFailureException.class) @CacheEvict(value = CACHE_AVERAGE_REVIEW_RATING, allEntries = true) public void updateSearchIndex() { if (!isEnabled()) { return; } var stopWatch = new StopWatch(); stopWatch.start(); updateSearchIndex(false...
@Test public void testHardUpdateNotExists() { var index = mockIndex(false); mockExtensions(); search.updateSearchIndex(true); assertThat(index.created).isTrue(); assertThat(index.deleted).isFalse(); assertThat(index.entries).hasSize(3); }
private Map<String, StorageUnit> getStorageUnits(final Map<String, StorageNode> storageUnitNodeMap, final Map<StorageNode, DataSource> storageNodeDataSources, final Map<String, DataSourcePoolProperties> dataSourcePoolPropsMap) { Map<String, StorageUnit> resul...
@Test void assertGetDataSources() { DataSourceProvidedDatabaseConfiguration databaseConfig = createDataSourceProvidedDatabaseConfiguration(); DataSource dataSource = databaseConfig.getStorageUnits().get("foo_ds").getDataSource(); assertTrue(dataSource instanceof MockedDataSource); }
public static void debug(final Logger logger, final String format, final Supplier<Object> supplier) { if (logger.isDebugEnabled()) { logger.debug(format, supplier.get()); } }
@Test public void testAtLeastOnceDebug() { when(logger.isDebugEnabled()).thenReturn(true); LogUtils.debug(logger, supplier); verify(supplier, atLeastOnce()).get(); }
public static UIf create( UExpression condition, UStatement thenStatement, UStatement elseStatement) { return new AutoValue_UIf(condition, thenStatement, elseStatement); }
@Test public void inlineWithoutElse() { UIf ifTree = UIf.create( UFreeIdent.create("cond"), UBlock.create( UExpressionStatement.create( UAssign.create(UFreeIdent.create("x"), UFreeIdent.create("y")))), null); bind(new UFreeIdent.K...
@Override public List<Long> bitField(byte[] key, BitFieldSubCommands subCommands) { List<Object> params = new ArrayList<>(); params.add(key); boolean writeOp = false; for (BitFieldSubCommands.BitFieldSubCommand subCommand : subCommands) { String size = "u"; i...
@Test public void testBitField() { BitFieldSubCommands c = BitFieldSubCommands.create(); c = c.set(BitFieldSubCommands.BitFieldType.INT_8).valueAt(1).to(120); List<Long> list = connection.bitField("testUnsigned".getBytes(), c); assertThat(list).containsExactly(0L); BitFieldS...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) @Override public ClusterInfo get() { return getClusterInfo(); }
@Test public void testClusterSchedulerFifoDefault() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("cluster") .path("scheduler").get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, ...
@Override public void start() { boolean hasExternalPlugins = pluginRepository.getPlugins().stream().anyMatch(plugin -> plugin.getType().equals(PluginType.EXTERNAL)); try (DbSession session = dbClient.openSession(false)) { PropertyDto property = Optional.ofNullable(dbClient.propertiesDao().selectGlobalPr...
@Test public void require_consent_when_exist_external_plugins_and_consent_property_not_exist() { setupExternalPlugin(); underTest.start(); assertThat(logTester.logs(Level.WARN)).contains("Plugin(s) detected. Plugins are not provided by SonarSource" + " and are therefore installed at your own ris...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertInt() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("int").dataType("int").build(); Column column = XuguTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), column.get...
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertUnsupported() { Column column = PhysicalColumn.of( "test", new MapType<>(BasicType.STRING_TYPE, BasicType.STRING_TYPE), (Long) null, true, nu...
public static ZMsg recvMsg(Socket socket) { return recvMsg(socket, 0); }
@Test public void testRecvMsg() { ZMQ.Context ctx = ZMQ.context(0); ZMQ.Socket socket = ctx.socket(SocketType.PULL); ZMsg.recvMsg(socket, ZMQ.NOBLOCK, (msg)-> assertThat(msg, nullValue())); socket.close(); ctx.close(); }
@Override public Optional<EncryptionInformation> getWriteEncryptionInformation(ConnectorSession session, TableEncryptionProperties tableEncryptionProperties, String dbName, String tableName) { if (!(tableEncryptionProperties instanceof DwrfTableEncryptionProperties)) { return Optional.empty(...
@Test public void testGetWriteEncryptionInformation() { Optional<EncryptionInformation> encryptionInformation = encryptionInformationSource.getWriteEncryptionInformation(SESSION, forTable("table_level", "algo", "provider"), "dbName", "tableName"); assertTrue(encryptionInformation.isPresent()); ...
@Override public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) { Preconditions.checkNotNull(path, "Unable to create UnderFileSystem instance:" + " URI path should not be null"); if (checkOBSCredentials(conf)) { try { return OBSUnderFileSystem.createInstance(new ...
@Test public void createInstanceWithNullPath() { Exception e = Assert.assertThrows(NullPointerException.class, () -> mFactory.create( null, mConf)); Assert.assertTrue(e.getMessage().contains("Unable to create UnderFileSystem instance: URI " + "path should not be null")); }
public void doesNotContain(@Nullable CharSequence string) { checkNotNull(string); if (actual == null) { failWithActual("expected a string that does not contain", string); } else if (actual.contains(string)) { failWithActual("expected not to contain", string); } }
@Test public void stringDoesNotContainCharSequence() { CharSequence charSeq = new StringBuilder("d"); assertThat("abc").doesNotContain(charSeq); }
public static String stringBlankAndThenExecute(String source, Callable<String> callable) { if (StringUtils.isBlank(source)) { try { return callable.call(); } catch (Exception e) { LogUtils.NAMING_LOGGER.error("string empty and then ex...
@Test void testStringBlankAndThenExecuteSuccess() { String word = "success"; String actual = TemplateUtils.stringBlankAndThenExecute(word, () -> "call"); assertEquals(word, actual); }
public int getType() { return type; }
@Test public void getTypeFromCode() { assertEquals( DragAndDropContainer.TYPE_BASE_STEP_TYPE, DragAndDropContainer.getType( "BaseStep" ) ); }
public static URL getResourceUrl(String resource) throws IOException { if (resource.startsWith(CLASSPATH_PREFIX)) { String path = resource.substring(CLASSPATH_PREFIX.length()); ClassLoader classLoader = ResourceUtils.class.getClassLoader(); URL url =...
@Test void testGetResourceUrlForClasspath() throws IOException { URL url = ResourceUtils.getResourceUrl("classpath:test-tls-cert.pem"); assertNotNull(url); }
public static ServiceDescriptor echoService() { return echoServiceDescriptor; }
@Test void echoService() { Assertions.assertNotNull(ServiceDescriptorInternalCache.echoService()); Assertions.assertEquals( EchoService.class, ServiceDescriptorInternalCache.echoService().getServiceInterfaceClass()); }
public static File load(String name) { try { if (name == null) { throw new IllegalArgumentException("name can't be null"); } String decodedPath = URLDecoder.decode(name, StandardCharsets.UTF_8.name()); return getFileFromFileSystem(decodedPath); ...
@Test public void testLoadNotExistFile() { File file = FileLoader.load("io/NotExistFile.txt"); Assertions.assertTrue(file == null || !file.exists()); }
public Tile getParent() { if (this.zoomLevel == 0) { return null; } return new Tile(this.tileX / 2, this.tileY / 2, (byte) (this.zoomLevel - 1), this.tileSize); }
@Test public void getParentTest() { Tile rootTile = new Tile(0, 0, (byte) 0, TILE_SIZE); Assert.assertNull(rootTile.getParent()); Assert.assertEquals(rootTile, new Tile(0, 0, (byte) 1, TILE_SIZE).getParent()); Assert.assertEquals(rootTile, new Tile(1, 0, (byte) 1, TILE_SIZE).getPare...
public static void validateRdwAid(byte[] aId) { for (final byte[] compare : RDW_AID) { if (Arrays.equals(compare, aId)) { return; } } logger.error("Driving licence has unknown aId: {}", Hex.toHexString(aId).toUpperCase()); throw new ClientException...
@Test public void validateRdwAidSuccessful() { CardValidations.validateRdwAid(Hex.decode("SSSSSSSSSSSSSSSSSSSSSS")); }
@Override public K8sHost removeHost(IpAddress hostIp) { checkArgument(hostIp != null, ERR_NULL_HOST_IP); K8sHost host = hostStore.removeHost(hostIp); log.info(String.format(MSG_HOST, hostIp.toString(), MSG_REMOVED)); return host; }
@Test(expected = IllegalArgumentException.class) public void testRemoveNullHost() { target.removeHost(null); }
public Schema addToSchema(Schema schema) { validate(schema); schema.addProp(LOGICAL_TYPE_PROP, name); schema.setLogicalType(this); return schema; }
@Test void logicalTypeInSchemaEquals() { Schema schema1 = Schema.createFixed("aDecimal", null, null, 4); Schema schema2 = Schema.createFixed("aDecimal", null, null, 4); Schema schema3 = Schema.createFixed("aDecimal", null, null, 4); assertNotSame(schema1, schema2); assertNotSame(schema1, schema3);...
@Override public TransferStatus prepare(final Path file, final Local local, final TransferStatus parent, final ProgressListener progress) throws BackgroundException { final TransferStatus status = super.prepare(file, local, parent, progress); if(status.isExists()) { final String filename...
@Test public void testFileUploadWithTemporaryFilename() throws Exception { final Path file = new Path("f", EnumSet.of(Path.Type.file)); final AtomicBoolean found = new AtomicBoolean(); final AttributesFinder attributes = new AttributesFinder() { @Override public PathA...
@Override public boolean enable(String pluginId) { return mainLock.applyWithReadLock(() -> { ThreadPoolPlugin plugin = registeredPlugins.get(pluginId); if (Objects.isNull(plugin) || !disabledPlugins.remove(pluginId)) { return false; } forQuickI...
@Test public void testEnable() { ThreadPoolPlugin plugin = new TestExecuteAwarePlugin(); Assert.assertFalse(manager.enable(plugin.getId())); manager.register(plugin); Assert.assertFalse(manager.enable(plugin.getId())); manager.disable(plugin.getId()); Assert.assertTru...
public synchronized void executeDdlStatement(String statement) throws IllegalStateException { checkIsUsable(); maybeCreateInstance(); maybeCreateDatabase(); LOG.info("Executing DDL statement '{}' on database {}.", statement, databaseId); try { databaseAdminClient .updateDatabaseDdl(...
@Test public void testExecuteDdlStatementShouldThrowExceptionWhenSpannerCreateDatabaseFails() throws ExecutionException, InterruptedException { // arrange prepareCreateInstanceMock(); when(spanner.getDatabaseAdminClient().createDatabase(any(), any()).get()) .thenThrow(InterruptedException.cl...
public static boolean isAbsoluteUri(final String uriString) { if (StringUtils.isBlank(uriString)) { return false; } try { URI uri = new URI(uriString); return uri.isAbsolute(); } catch (URISyntaxException e) { log.debug("Failed to parse uri...
@Test void isAbsoluteUri() { String[] absoluteUris = new String[] { "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt", "ldap://[2001:db8::7]/c=GB?objectClass?one", "mailto:John.Doe@example.com", "news:comp.infosystems.www....
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testParseNewStyleResourceVcoresNegativeWithSpaces() throws Exception { expectNegativeValueOfResource("vcores"); parseResourceConfigValue("memory-mb=5120, vcores=-2"); }
@Override public int hashCode() { return Objects.hash( threadName, threadState, activeTasks, standbyTasks, mainConsumerClientId, restoreConsumerClientId, producerClientIds, adminClientId); }
@Test public void shouldNotBeEqualIfDifferInActiveTasks() { final ThreadMetadata differActiveTasks = new ThreadMetadataImpl( THREAD_NAME, THREAD_STATE, MAIN_CONSUMER_CLIENT_ID, RESTORE_CONSUMER_CLIENT_ID, PRODUCER_CLIENT_IDS, ADMIN_CLIE...
@Override public String toString() { return "XmlRowAdapter{" + "record=" + record + '}'; }
@Test public void allPrimitiveDataTypes() throws XPathExpressionException, JAXBException, IOException, SAXException, ParserConfigurationException { for (Row row : DATA.allPrimitiveDataTypesRows) { NodeList entries = xmlDocumentEntries(row); assertEquals(ALL_PRIMITIVE_DATA_TYPES_SCHEMA...
ProducerListeners listeners() { return new ProducerListeners(eventListeners.toArray(new HollowProducerEventListener[0])); }
@Test public void fireNewDeltaChainDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener).onNewD...
@Override public boolean consumeBytes(Http2Stream stream, int numBytes) throws Http2Exception { assert ctx != null && ctx.executor().inEventLoop(); checkPositiveOrZero(numBytes, "numBytes"); if (numBytes == 0) { return false; } // Streams automatically consume al...
@Test public void consumeBytesForNegativeNumBytesShouldFail() throws Http2Exception { assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() throws Throwable { controller.consumeBytes(connection.stream(STREAM_ID), -1); ...
public static void parseReverseLookupDomain(PtrDnsAnswer.Builder dnsAnswerBuilder, String hostname) { dnsAnswerBuilder.fullDomain(hostname); final InternetDomainName internetDomainName = InternetDomainName.from(hostname); if (internetDomainName.hasPublicSuffix()) { // Use Guava to...
@Test public void testParseReverseLookupDomain() { // Test all of the types of domains that parsing is performed for. PtrDnsAnswer result = buildReverseLookupDomainTest("subdomain.test.co.uk"); assertEquals("subdomain.test.co.uk", result.fullDomain()); assertEquals("test.co.uk", res...
int parseAndConvert(String[] args) throws Exception { Options opts = createOptions(); int retVal = 0; try { if (args.length == 0) { LOG.info("Missing command line arguments"); printHelp(opts); return 0; } CommandLine cliParser = new GnuParser().parse(opts, args); ...
@Test public void testEmptyRulesConfigurationSpecified() throws Exception { FSConfigConverterTestCommons.configureEmptyFairSchedulerXml(); FSConfigConverterTestCommons.configureEmptyYarnSiteXml(); FSConfigConverterTestCommons.configureEmptyConversionRulesFile(); FSConfigToCSConfigArgumentHandler argu...
@Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("latLong="); stringBuilder.append(this.latLong); stringBuilder.append(", zoomLevel="); stringBuilder.append(this.zoomLevel); stringBuilder.append(", rotation="...
@Test public void toStringTest() { MapPosition mapPosition = new MapPosition(new LatLong(1.0, 2.0), (byte) 3); Assert.assertEquals(MAP_POSITION_TO_STRING, mapPosition.toString()); }
@Override public void handle(LogHandlerEvent event) { switch (event.getType()) { case APPLICATION_STARTED: LogHandlerAppStartedEvent appStartEvent = (LogHandlerAppStartedEvent) event; initApp(appStartEvent.getApplicationId(), appStartEvent.getUser(), appStartEvent.get...
@Test public void testAppLogDirCreation() throws Exception { final String inputSuffix = "logs-tfile"; this.conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDir.getAbsolutePath()); this.conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, this.remoteRootLogDir.getAbsolutePath()); this.conf....
List<DataflowPackage> stageClasspathElements( Collection<StagedFile> classpathElements, String stagingPath, CreateOptions createOptions) { return stageClasspathElements(classpathElements, stagingPath, DEFAULT_SLEEPER, createOptions); }
@Test public void testPackageUploadIsSkippedWithNonExistentResource() throws Exception { String nonExistentFile = FileSystems.matchNewResource(tmpFolder.getRoot().getPath(), true) .resolve("non-existent-file", StandardResolveOptions.RESOLVE_FILE) .toString(); assertEquals( ...
public Set<Long> calculateUsers(DelegateExecution execution, int level) { Assert.isTrue(level > 0, "level 必须大于 0"); // 获得发起人 ProcessInstance processInstance = processInstanceService.getProcessInstance(execution.getProcessInstanceId()); Long startUserId = NumberUtils.parseLong(processInst...
@Test public void testCalculateUsers_noDept() { // 准备参数 DelegateExecution execution = mockDelegateExecution(1L); // mock 方法(startUser) AdminUserRespDTO startUser = randomPojo(AdminUserRespDTO.class, o -> o.setDeptId(10L)); when(adminUserApi.getUser(eq(1L))).thenReturn(startUs...
public static RelDataType create(HazelcastIntegerType type, boolean nullable) { if (type.isNullable() == nullable) { return type; } return create0(type.getSqlTypeName(), nullable, type.getBitWidth()); }
@Test public void testNullableIntegerTypeOfBitWidth() { for (int i = 0; i < Long.SIZE + 10; ++i) { RelDataType type = HazelcastIntegerType.create(i, false); RelDataType nullableType = HazelcastIntegerType.create(i, true); if (i < Byte.SIZE) { assertType(T...
private ContentType getContentType(Exchange exchange) throws ParseException { String contentTypeStr = ExchangeHelper.getContentType(exchange); if (contentTypeStr == null) { contentTypeStr = DEFAULT_CONTENT_TYPE; } ContentType contentType = new ContentType(contentTypeStr); ...
@Test public void roundtripWithBinaryAttachments() throws IOException { String attContentType = "application/binary"; byte[] attText = { 0, 1, 2, 3, 4, 5, 6, 7 }; String attFileName = "Attachment File Name"; in.setBody("Body text"); DataSource ds = new ByteArrayDataSource(att...
public static boolean validatePlugin(PluginLookup.PluginType type, Class<?> pluginClass) { switch (type) { case INPUT: return containsAllMethods(inputMethods, pluginClass.getMethods()); case FILTER: return containsAllMethods(filterMethods, pluginClass.getM...
@Test public void testValidFilterPlugin() { Assert.assertTrue(PluginValidator.validatePlugin(PluginLookup.PluginType.FILTER, Uuid.class)); }
@Override public void finished(boolean allStepsExecuted) { if (postProjectAnalysisTasks.length == 0) { return; } ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED); for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) { ...
@Test public void ceTask_uuid_is_UUID_of_CeTask() { underTest.finished(true); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); assertThat(taskContextCaptor.getValue().getProjectAnalysis().getCeTask().getId()) .isEqualTo(ceTask.getUuid()); }
@Override public LogicalSchema getSchema() { return schema; }
@Test public void shouldHaveFullyQualifiedJoinSchemaWithNonSyntheticKey() { // Given: when(joinKey.resolveKeyName(any(), any())).thenReturn(ColumnName.of("right_rightKey")); // When: final JoinNode joinNode = new JoinNode(nodeId, OUTER, joinKey, true, left, right, empty(),"KAFKA"); ...
@Override public PageData<AuditLog> findAuditLogsByTenantIdAndUserId(UUID tenantId, UserId userId, List<ActionType> actionTypes, TimePageLink pageLink) { return DaoUtil.toPageData( auditLogRepository .findAuditLogsByTenantIdAndUserId( t...
@Test public void testFindAuditLogsByTenantIdAndUserId() { List<AuditLog> foundedAuditLogs = auditLogDao.findAuditLogsByTenantIdAndUserId(tenantId, userId1, List.of(ActionType.ADDED), new TimePageLink(20)).getData(); checkFoundedAuditLogsList(foundedAu...
@PostConstruct public void init() { ClientMeta.INSTANCE.setServiceName(serviceName); final DynamicConfigInitializer service = PluginServiceManager.getPluginService(DynamicConfigInitializer.class); service.doStart(); }
@Test public void testInit() { final DynamicProperties dynamicProperties = new DynamicProperties(); String serviceName = "testService"; ReflectUtils.setFieldValue(dynamicProperties, "serviceName", serviceName); try(final MockedStatic<ServiceManager> serviceManagerMockedStatic = Mocki...
@Override protected JobExceptionsInfoWithHistory handleRequest( HandlerRequest<EmptyRequestBody> request, ExecutionGraphInfo executionGraph) { final List<Integer> exceptionToReportMaxSizes = request.getQueryParameter(UpperLimitExceptionParameter.class); final int exceptio...
@Test void testNoExceptions() throws HandlerRequestException { final ExecutionGraphInfo executionGraphInfo = new ExecutionGraphInfo(new ArchivedExecutionGraphBuilder().build()); final HandlerRequest<EmptyRequestBody> request = createRequest(executionGraphInfo.getJobI...
@Override public void processElement1(StreamRecord<IN1> element) throws Exception { collector.setTimestamp(element); rContext.setElement(element); userFunction.processElement(element.getValue(), rContext, collector); rContext.setElement(null); }
@Test void testNoKeyedStateOnNonBroadcastSide() throws Exception { boolean exceptionThrown = false; final ValueStateDescriptor<String> valueState = new ValueStateDescriptor<>("any", BasicTypeInfo.STRING_TYPE_INFO); try (TwoInputStreamOperatorTestHarness<String, Integer, St...
@Udf(description = "Converts a TIMESTAMP value into the" + " string representation of the timestamp in the given format. Single quotes in the" + " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'" + " The system default time zone is used when no time zone is explicitly ...
@Test public void shouldReturnNullOnNullDateFormat() { // When: final String returnValue = udf.formatTimestamp( new Timestamp(1534353043000L), null); // Then: assertThat(returnValue, is(nullValue())); }
public Publisher<V> iterator() { return new SetRxIterator<V>() { @Override protected RFuture<ScanResult<Object>> scanIterator(RedisClient client, String nextIterPos) { return ((ScanIterator) instance).scanIteratorAsync(((RedissonObject) instance).getRawName(), client, nex...
@Test public void testAddBean() throws InterruptedException, ExecutionException { SimpleBean sb = new SimpleBean(); sb.setLng(1L); RSetCacheRx<SimpleBean> set = redisson.getSetCache("simple"); sync(set.add(sb)); Assertions.assertEquals(sb.getLng(), toIterator(set.iterator())....
static Schema getSchema(Class<? extends Message> clazz) { return getSchema(ProtobufUtil.getDescriptorForClass(clazz)); }
@Test public void testRequiredNestedSchema() { assertEquals( TestProtoSchemas.REQUIRED_NESTED_SCHEMA, ProtoSchemaTranslator.getSchema(Proto2SchemaMessages.RequiredNested.class)); }
@Override public String formatNotifyTemplateContent(String content, Map<String, Object> params) { return StrUtil.format(content, params); }
@Test public void testFormatNotifyTemplateContent() { // 准备参数 Map<String, Object> params = new HashMap<>(); params.put("name", "小红"); params.put("what", "饭"); // 调用,并断言 assertEquals("小红,你好,饭吃了吗?", notifyTemplateService.formatNotifyTemplateContent("{na...
public static ConnectionGroup getOrCreateGroup(String namespace) { AssertUtil.assertNotBlank(namespace, "namespace should not be empty"); ConnectionGroup group = CONN_MAP.get(namespace); if (group == null) { synchronized (CREATE_LOCK) { if ((group = CONN_MAP.get(names...
@Test public void testGetOrCreateGroupMultipleThread() throws Exception { final String namespace = "test-namespace"; int threadCount = 32; final List<ConnectionGroup> groups = new CopyOnWriteArrayList<>(); final CountDownLatch latch = new CountDownLatch(threadCount); for (int...
public static <T> void invokeAll(List<Callable<T>> callables, long timeoutMs) throws TimeoutException, ExecutionException { ExecutorService service = Executors.newCachedThreadPool(); try { invokeAll(service, callables, timeoutMs); } finally { service.shutdownNow(); } }
@Test public void invokeAllPropagatesException() throws Exception { int numTasks = 5; final AtomicInteger id = new AtomicInteger(); List<Callable<Void>> tasks = new ArrayList<>(); final Exception testException = new Exception("test message"); for (int i = 0; i < numTasks; i++) { tasks.add(ne...
public void isInOrder() { isInOrder(Ordering.natural()); }
@Test public void iterableIsInOrderWithComparatorFailure() { expectFailureWhenTestingThat(asList("1", "10", "2", "20")).isInOrder(COMPARE_AS_DECIMAL); assertFailureKeys("expected to be in order", "but contained", "followed by", "full contents"); assertFailureValue("but contained", "10"); assertFailure...
public CompletableFuture<Boolean> allowNamespaceOperationAsync(NamespaceName namespaceName, NamespaceOperation operation, String role, ...
@Test(dataProvider = "roles") public void testNamespaceOperationAsync(String role, String originalRole, boolean shouldPass) throws Exception { boolean isAuthorized = authorizationService.allowNamespaceOperationAsync(NamespaceName.get("public/default"), NamespaceOperation.PACKAGES, originalRo...
public Map<String,String> getValByRegex(String regex) { Pattern p = Pattern.compile(regex); Map<String,String> result = new HashMap<String,String>(); List<String> resultKeys = new ArrayList<>(); Matcher m; for(Map.Entry<Object,Object> item: getProps().entrySet()) { if (item.getKey() instance...
@Test public void testGetValByRegex() { Configuration conf = new Configuration(); String key1 = "t.abc.key1"; String key2 = "t.abc.key2"; String key3 = "tt.abc.key3"; String key4 = "t.abc.ey3"; conf.set(key1, "value1"); conf.set(key2, "value2"); conf.set(key3, "value3"); conf.set(k...
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { super.userEventTriggered(ctx, evt); if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; switch (event.state()) { case READER_IDLE:...
@Test void givenChannelReaderIdleState_whenNoPingResponse_thenDisconnectClient() throws Exception { ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(ctx.channel()).thenReturn(channel); when(channel.eventLoop()).thenReturn(new ...
@Override public void commit() { //no-op }
@Test public void shouldNotFailOnNoOpCommit() { globalContext.commit(); }
@Override public void transitionToActive(final StreamTask streamTask, final RecordCollector recordCollector, final ThreadCache newCache) { if (stateManager.taskType() != TaskType.ACTIVE) { throw new IllegalStateException("Tried to transition processor context to active but the state manager's " ...
@Test public void globalKeyValueStoreShouldBeReadOnly() { foreachSetUp(); when(stateManager.taskType()).thenReturn(TaskType.ACTIVE); when(stateManager.getGlobalStore(anyString())).thenReturn(null); final KeyValueStore<String, Long> keyValueStoreMock = mock(KeyValueStore.class); ...
@Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws YarnException, IOException { try { if (!RouterServerUtil.isAllowedDelegationTokenOp()) { routerMetrics.incrRenewDelegationTokenFailedRetrieved(); String msg = "Delegation To...
@Test public void testRenewDelegationToken() throws IOException, YarnException { // We design such a unit test to check // that the execution of the GetDelegationToken method is as expected // 1. Call GetDelegationToken to apply for delegationToken. // 2. Call renewDelegationToken to refresh delegati...
@Override public List<FileEntriesLayer> createLayers() { FileEntriesLayer jarLayer = FileEntriesLayer.builder() .setName(JarLayers.JAR) .addEntry(jarPath, JarLayers.APP_ROOT.resolve(jarPath.getFileName())) .build(); return Collections.singletonList(jarLayer); }
@Test public void testCreateLayers() throws URISyntaxException { Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_JAR).toURI()); SpringBootPackagedProcessor springBootProcessor = new SpringBootPackagedProcessor(springBootJar, JAR_JAVA_VERSION); List<FileEntriesLayer> layers = spri...
public static Ip4Address valueOf(int value) { byte[] bytes = ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); return new Ip4Address(bytes); }
@Test public void testValueOfInetAddressIPv4() { Ip4Address ipAddress; InetAddress inetAddress; inetAddress = InetAddresses.forString("1.2.3.4"); ipAddress = Ip4Address.valueOf(inetAddress); assertThat(ipAddress.toString(), is("1.2.3.4")); inetAddress = InetAddresse...
public static BundleCounter bundleProcessingThreadCounter(String shortId, MetricName name) { return new BundleProcessingThreadCounter(shortId, name); }
@Test public void testAccurateBundleCounterReportsValueFirstTimeWithoutMutations() throws Exception { Map<String, ByteString> report = new HashMap<>(); BundleCounter bundleCounter = Metrics.bundleProcessingThreadCounter(TEST_ID, TEST_NAME); bundleCounter.updateIntermediateMonitoringData(report); asser...
@ProcessElement public void processElement(OutputReceiver<InitialPipelineState> receiver) throws IOException { LOG.info(daoFactory.getStreamTableDebugString()); LOG.info(daoFactory.getMetadataTableDebugString()); LOG.info("ChangeStreamName: " + daoFactory.getChangeStreamName()); boolean resume = fals...
@Test public void testInitializeSkipCleanupWithDNP() throws IOException { Instant resumeTime = Instant.now().minus(Duration.standardSeconds(10000)); metadataTableDao.updateDetectNewPartitionWatermark(resumeTime); ByteString metadataRowKey = metadataTableAdminDao .getChangeStreamNamePre...
@Nullable public DataBuffer readChunk(int index) throws IOException { if (index >= mDataBuffers.length) { return null; } if (index >= mBufferCount.get()) { try (LockResource ignored = new LockResource(mBufferLocks.writeLock())) { while (index >= mBufferCount.get()) { DataBuf...
@Test public void testSequentialRead() throws Exception { int chunkNum = BLOCK_SIZE / CHUNK_SIZE; for (int i = 0; i < chunkNum; i++) { DataBuffer buffer = mDataReader.readChunk(i); Assert.assertEquals(i + 1, mDataReader.getReadChunkNum()); Assert.assertTrue(mDataReader.validateBuffer(i, buff...
public URI getHttpPublishUri() { if (httpPublishUri == null) { final URI defaultHttpUri = getDefaultHttpUri(); LOG.debug("No \"http_publish_uri\" set. Using default <{}>.", defaultHttpUri); return defaultHttpUri; } else { final InetAddress inetAddress = to...
@Test public void testHttpPublishUriWithMissingTrailingSlash() throws RepositoryException, ValidationException { jadConfig.setRepository(new InMemoryRepository(ImmutableMap.of("http_publish_uri", "http://www.example.com:12900/foo"))).addConfigurationBean(configuration).process(); assertThat(configu...