focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void configureAuthDataStatefulSet(V1StatefulSet statefulSet, Optional<FunctionAuthData> functionAuthData) { if (!functionAuthData.isPresent()) { return; } V1PodSpec podSpec = statefulSet.getSpec().getTemplate().getSpec(); // configure pod mount secret w...
@Test public void testConfigureAuthDataStatefulSet() { byte[] testBytes = new byte[]{0, 1, 2, 3, 4}; CoreV1Api coreV1Api = mock(CoreV1Api.class); KubernetesSecretsTokenAuthProvider kubernetesSecretsTokenAuthProvider = new KubernetesSecretsTokenAuthProvider(); kubernetesSecretsTokenA...
static void filterProperties(Message message, Set<String> namesToClear) { List<Object> retainedProperties = messagePropertiesBuffer(); try { filterProperties(message, namesToClear, retainedProperties); } finally { retainedProperties.clear(); // ensure no object references are held due to any exc...
@Test void filterProperties_message_allTypes() throws JMSException { TextMessage message = newMessageWithAllTypes(); message.setStringProperty("b3", "00f067aa0ba902b7-00f067aa0ba902b7-1"); PropertyFilter.filterProperties(message, Collections.singleton("b3")); assertThat(message).isEqualToIgnoringGiven...
@CanIgnoreReturnValue public final Ordered containsExactlyEntriesIn(Multimap<?, ?> expectedMultimap) { checkNotNull(expectedMultimap, "expectedMultimap"); checkNotNull(actual); ListMultimap<?, ?> missing = difference(expectedMultimap, actual); ListMultimap<?, ?> extra = difference(actual, expectedMult...
@Test public void containsExactlyInOrder() { ImmutableMultimap<Integer, String> actual = ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four"); ImmutableMultimap<Integer, String> expected = ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four"); assert...
public static boolean isInteger(String s) { if (StrUtil.isBlank(s)) { return false; } try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } return true; }
@Test public void isIntegerTest() { assertTrue(NumberUtil.isInteger("-12")); assertTrue(NumberUtil.isInteger("256")); assertTrue(NumberUtil.isInteger("0256")); assertTrue(NumberUtil.isInteger("0")); assertFalse(NumberUtil.isInteger("23.4")); assertFalse(NumberUtil.isInteger(null)); assertFalse(NumberUtil...
@Override public Object read(final MySQLPacketPayload payload, final boolean unsigned) throws SQLException { int length = payload.readInt1(); switch (length) { case 0: throw new SQLFeatureNotSupportedException("Can not support date format if year, month, day is absent.");...
@Test void assertReadWithElevenBytes() throws SQLException { when(payload.readInt1()).thenReturn(11, 12, 31, 10, 59, 0); when(payload.readInt2()).thenReturn(2018); when(payload.readInt4()).thenReturn(230000); LocalDateTime actual = LocalDateTime.ofInstant(Instant.ofEpochMilli(((Times...
public boolean isCheckpointPending() { return !pendingCheckpoints.isEmpty(); }
@Test void testNoFastPathWithChannelFinishedDuringCheckpointsCancel() throws Exception { BufferOrEvent[] sequence = { createBarrier(1, 0, 0), createEndOfPartition(0), createCancellationBarrier(1, 1) }; ValidatingCheckpointHandler checkpointHandler = new ValidatingCheckpointHandl...
public boolean matchFile(@Nullable String filePath) { return filePath != null && filePattern.match(filePath); }
@Test public void shouldMatchJavaFile() { String javaFile = "org/foo/Bar.java"; assertThat(new IssuePattern("org/foo/Bar.java", "*").matchFile(javaFile)).isTrue(); assertThat(new IssuePattern("org/foo/*", "*").matchFile(javaFile)).isTrue(); assertThat(new IssuePattern("**Bar.java", "*").matchFile(java...
public String callServer(String api, Map<String, String> params, Map<String, String> body, String curServer, String method) throws NacosException { long start = System.currentTimeMillis(); long end = 0; String namespace = params.get(CommonParams.NAMESPACE_ID); String group = ...
@Test void testCallServerFail() throws Exception { assertThrows(NacosException.class, () -> { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any(...
public byte getByte(long pos) { checkOffsetAndCount(size, pos, 1); for (Segment s = head; true; s = s.next) { int segmentByteCount = s.limit - s.pos; if (pos < segmentByteCount) return s.data[s.pos + (int) pos]; pos -= segmentByteCount; } }
@Test public void getByteOfEmptyBuffer() throws Exception { Buffer buffer = new Buffer(); try { buffer.getByte(0); fail(); } catch (IndexOutOfBoundsException expected) { } }
@Transactional public void deleteChecklistLikeByChecklistId(User user, long checklistId) { Checklist checklist = checklistRepository.getById(checklistId); validateChecklistOwnership(user, checklist); ChecklistLike checklistLike = checklistLikeRepository.getByChecklistId(checklistId); ...
@DisplayName("체크리스트 좋아요 삭제 성공") @Test void deleteChecklistLikeByChecklistId() { // given Checklist checklist = checklistRepository.save(ChecklistFixture.CHECKLIST1_USER1); ChecklistLike checklistLike = checklistLikeRepository.save(ChecklistFixture.CHECKLIST1_LIKE); // when ...
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filte...
@Test public void shouldRemoveBrokenRefs() throws IOException { final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH); openAPI.getPaths().get("/pet/{petId}").getGet().getResponses().getDefault().getHeaders().remove("X-Rate-Limit-Limit"); assertNotNull(openAPI.getComponents().getSchemas().get("Pe...
@PostMapping(value = "/artifact/download") public ResponseEntity<String> importArtifact(@RequestParam(value = "url", required = true) String url, @RequestParam(value = "mainArtifact", defaultValue = "true") boolean mainArtifact, @RequestParam(value = "secretName", required = false) String secretNam...
@Test void shouldReturnBadRequest() throws MockRepositoryImportException { // arrange String apiPastry = "https://raw.githubusercontent.com/microcks/microcks/master/samples/APIPastry-openapi.yaml"; Mockito.when(serviceService.importServiceDefinition(Mockito.any(File.class), Mockito.any(ReferenceRe...
public static <T extends Message> Read<T> readProtos(Class<T> messageClass) { // TODO: Stop using ProtoCoder and instead parse the payload directly. // We should not be relying on the fact that ProtoCoder's wire format is identical to // the protobuf wire format, as the wire format is not part of a coder's ...
@Test public void testProto() { ProtoCoder<Primitive> coder = ProtoCoder.of(Primitive.class); ImmutableList<Primitive> inputs = ImmutableList.of( Primitive.newBuilder().setPrimitiveInt32(42).build(), Primitive.newBuilder().setPrimitiveBool(true).build(), Primitive.n...
@ApiOperation(value = "Get a single table", tags = { "Database tables" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the table exists and the table count is returned."), @ApiResponse(code = 404, message = "Indicates the requested table does not exist.") }) ...
@Test public void testGetTable() throws Exception { Map<String, Long> tableCounts = managementService.getTableCount(); String tableNameToGet = tableCounts.keySet().iterator().next(); CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeReso...
@PUT @Path("{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response updateSubnet(@PathParam("id") String id, InputStream input) throws IOException { log.trace(String.format(MESSAGE, "UPDATE " + id)); String inputStr = IOUtils.toString(input, RE...
@Test public void testUpdateSubnetWithUpdatingOperation() { expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes(); replay(mockOpenstackHaService); mockOpenstackNetworkAdminService.updateSubnet(anyObject()); replay(mockOpenstackNetworkAdminService); final WebTa...
public static String getFlowName(String activationMethod) { return switch (activationMethod) { case ActivationMethod.ACCOUNT -> ActivateAppWithRequestWebsite.NAME; case ActivationMethod.PASSWORD -> ActivateAppWithPasswordLetterFlow.NAME; case ActivationMethod.SMS -> ActivateA...
@Test void getFlowNameNonexistentTest() { Exception exception = assertThrows(IllegalStateException.class, () -> flowService.getFlowName("nope") ); assertEquals("Unexpected value: nope", exception.getMessage()); }
public List<String> generate(String tableName, String columnName, boolean isAutoGenerated) throws SQLException { return generate(tableName, singleton(columnName), isAutoGenerated); }
@Test public void generate_for_oracle_autogenerated_false() throws SQLException { when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT)); when(db.getDialect()).thenReturn(ORACLE); List<String> sqls = underTest.generate(TABLE_NAME, PK_COLUMN, false); assertThat(sq...
public InstantAndValue<T> remove(MetricKey metricKey) { return counters.remove(metricKey); }
@Test public void testRemove() { LastValueTracker<Double> lastValueTracker = new LastValueTracker<>(); lastValueTracker.getAndSet(METRIC_NAME, instant1, 1d); assertTrue(lastValueTracker.contains(METRIC_NAME)); InstantAndValue<Double> result = lastValueTracker.remove(METRIC_NAME); ...
public static String getType(String fileStreamHexHead) { if(StrUtil.isBlank(fileStreamHexHead)){ return null; } if (MapUtil.isNotEmpty(FILE_TYPE_MAP)) { for (final Entry<String, String> fileTypeEntry : FILE_TYPE_MAP.entrySet()) { if (StrUtil.startWithIgnoreCase(fileStreamHexHead, fileTypeEntry.getKey())...
@Test @Disabled public void getTypeFromInputStream() throws IOException { final File file = FileUtil.file("d:/test/pic.jpg"); final BufferedInputStream inputStream = FileUtil.getInputStream(file); inputStream.mark(0); final String type = FileTypeUtil.getType(inputStream); inputStream.reset(); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PiLpmFieldMatch that = (PiLpmFieldMatch) o; return prefixLength == that.prefixLength && O...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(piLpmFieldMatch1, sameAsPiLpmFieldMatch1) .addEqualityGroup(piLpmFieldMatch2) .testEquals(); }
String availabilityZoneEc2() { String uri = ec2MetadataEndpoint.concat("/placement/availability-zone/"); return metadataClient(uri, awsConfig).get().getBody(); }
@Test public void availabilityZoneEc2() { // given String availabilityZone = "eu-central-1b"; stubFor(get(urlEqualTo("/placement/availability-zone/")) .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody(availabilityZone))); // when String resul...
public List<ContainerLogMeta> collect( LogAggregationFileController fileController) throws IOException { List<ContainerLogMeta> containersLogMeta = new ArrayList<>(); RemoteIterator<FileStatus> appDirs = fileController. getApplicationDirectoriesOfUser(logsRequest.getUser()); while (appDirs.ha...
@Test void testMultipleFileRegex() throws IOException { ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder request = new ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder(); request.setAppId(null); request.setContainerId(null); request.setFileName(String.format("%s.*", BIG_FILE_NAME)); ...
@Udf public Map<String, String> splitToMap( @UdfParameter( description = "Separator string and values to join") final String input, @UdfParameter( description = "Separator string and values to join") final String entryDelimiter, @UdfParameter( description = "Separator s...
@Test public void shouldDropEntriesWithoutKeyAndValue() { Map<String, String> result = udf.splitToMap("foo:=apple/cherry", "/", ":="); assertThat(result, hasEntry("foo", "apple")); assertThat(result.size(), equalTo(1)); }
@Override public String handlePlaceHolder() { return handlePlaceHolder(inlineExpression); }
@Test void assertHandlePlaceHolder() { assertThat(TypedSPILoader.getService(InlineExpressionParser.class, "GROOVY", PropertiesBuilder.build( new PropertiesBuilder.Property(InlineExpressionParser.INLINE_EXPRESSION_KEY, "t_$->{[\"new$->{1+2}\"]}"))).handlePlaceHolder(), is("t_${[\"new${1+2}\"]...
static void printTargets(PrintWriter writer, OptionalInt screenWidth, List<String> targetFiles, List<TargetDirectory> targetDirectories) { printEntries(writer, "", screenWidth, targetFiles); boolean needIntro = !targe...
@Test public void testPrintTargets() throws Exception { try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { try (PrintWriter writer = new PrintWriter(new OutputStreamWriter( stream, StandardCharsets.UTF_8))) { LsCommandHandler.printTargets(write...
public List<ShardingCondition> createShardingConditions(final SQLStatementContext sqlStatementContext, final List<Object> params) { if (!(sqlStatementContext instanceof WhereAvailable)) { return Collections.emptyList(); } Collection<ColumnSegment> columnSegments = ((WhereAvailable) s...
@Test void assertCreateShardingConditionsForSelectInStatement() { ColumnSegment left = new ColumnSegment(0, 0, new IdentifierValue("foo_sharding_col")); ListExpression right = new ListExpression(0, 0); LiteralExpressionSegment literalExpressionSegment = new LiteralExpressionSegment(0, 0, 5);...
private AccessLog(String logFormat, Object... args) { Objects.requireNonNull(logFormat, "logFormat"); this.logFormat = logFormat; this.args = args; }
@Test void accessLogFiltering() { disposableServer = createServer() .handle((req, resp) -> { resp.withConnection(conn -> { ChannelHandler handler = conn.channel().pipeline().get(NettyPipeline.AccessLogHandler); resp.header(ACCESS_LOG_HANDLER, handler != null ? FOUND : NOT_FOUND); }); r...
public short getMode() { return mMode; }
@Test public void getMode() { AccessControlList acl = new AccessControlList(); assertEquals(0, acl.getMode()); acl.setEntry(new AclEntry.Builder().setType(AclEntryType.OWNING_USER).setSubject(OWNING_USER) .addAction(AclAction.READ).build()); acl.setEntry(new AclEntry.Builder().setType(AclEntry...
public static String getTextValue(final Object jdbcBoolValue) { if (null == jdbcBoolValue) { return null; } return (Boolean) jdbcBoolValue ? "t" : "f"; }
@Test void assertGetTextValue() { Object jdbcBoolValue = true; String textValue = PostgreSQLTextBoolUtils.getTextValue(jdbcBoolValue); assertThat(textValue, is("t")); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ItemCounter that = (ItemCounter) o; if (!map.equals(that.map)) { return false; } ...
@Test public void testEquals_returnsFalseDifferentClass() { assertFalse(counter.equals(new Object())); }
public static <T> T retryUntilTimeout(Callable<T> callable, Supplier<String> description, Duration timeoutDuration, long retryBackoffMs) throws Exception { return retryUntilTimeout(callable, description, timeoutDuration, retryBackoffMs, Time.SYSTEM); }
@Test public void testNoBackoffTimeAndSucceed() throws Exception { Mockito.when(mockCallable.call()) .thenThrow(new TimeoutException()) .thenThrow(new TimeoutException()) .thenThrow(new TimeoutException()) .thenReturn("success"); asser...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PiActionParam that = (PiActionParam) o; return Objects.equal(id, that.id) && Objects.equa...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(piActionParam1, sameAsPiActionParam1) .addEqualityGroup(piActionParam2) .testEquals(); }
public void retrieveDocuments() throws DocumentRetrieverException { boolean first = true; String route = params.cluster.isEmpty() ? params.route : resolveClusterRoute(params.cluster); MessageBusParams messageBusParams = createMessageBusParams(params.configId, params.timeout, route); doc...
@Test void testShowDocSize() throws DocumentRetrieverException { ClientParameters params = createParameters() .setDocumentIds(asIterator(DOC_ID_1)) .setShowDocSize(true) .build(); Document document = new Document(DataType.DOCUMENT, new DocumentId(DOC_...
public static CheckpointStorage load( @Nullable CheckpointStorage fromApplication, StateBackend configuredStateBackend, Configuration jobConfig, Configuration clusterConfig, ClassLoader classLoader, @Nullable Logger logger) throws Illeg...
@Test void testConfigureJobManagerStorage() throws Exception { final String savepointDir = new Path(TempDirUtils.newFolder(tmp).toURI()).toString(); final Path expectedSavepointPath = new Path(savepointDir); final int maxSize = 100; final Configuration config = new Configuration();...
@Override public void destroy() { if (this.mqttClient != null) { this.mqttClient.disconnect(); } }
@Test public void givenMqttClientIsNotNull_whenDestroy_thenDisconnect() { ReflectionTestUtils.setField(mqttNode, "mqttClient", mqttClientMock); mqttNode.destroy(); then(mqttClientMock).should().disconnect(); }
@Override public String getTableName(final int columnIndex) throws SQLException { try { return resultSetMetaData.getTableName(columnIndex); } catch (final SQLFeatureNotSupportedException ignore) { return ""; } }
@Test void assertGetTableName() throws SQLException { assertThat(queryResultMetaData.getTableName(1), is("order")); }
@Override public WorkAttempt tryDoWork() { retrieveCookieIfNecessary(); return doWork(); }
@Test void workStatusShouldDeriveFromWorkTypeForNoWork() { work = mock(NoWork.class); prepareForWork(); assertThat(agentController.tryDoWork()).isEqualTo(WorkAttempt.NOTHING_TO_DO); }
@Override public String getFingerprint(Schema schema) { return schema2fingerprintMap.get(schema); }
@Test public void testDifferentFPs() { String fp1 = reg.getFingerprint(schema1); String fp2 = reg.getFingerprint(schema2); assertNotEquals(fp1, fp2); }
static Optional<Timestamp> readTimestampOfLastEventInSegment(Path segmentPath) throws IOException { byte[] eventBytes = null; try (RecordIOReader recordReader = new RecordIOReader(segmentPath)) { int blockId = (int) Math.ceil(((Files.size(segmentPath) - VERSION_SIZE) / (double) BLOCK_SIZE)) ...
@Test public void testReadTimestampOfLastEventInSegmentWithDeletedSegment() throws IOException { // Exercise Optional<Timestamp> timestamp = DeadLetterQueueWriter.readTimestampOfLastEventInSegment(Path.of("non_existing_file.txt")); // Verify assertTrue(timestamp.isEmpty()); }
@Override public Addresses loadAddresses(ClientConnectionProcessListenerRegistry listenerRunner) throws Exception { privateToPublic = getAddresses.call(); Set<Address> addresses = privateToPublic.keySet(); listenerRunner.onPossibleAddressesCollected(addresses); return new...
@Test(expected = IllegalStateException.class) public void testLoadAddresses_whenExceptionIsThrown() throws Exception { RemoteAddressProvider provider = new RemoteAddressProvider(() -> { throw new IllegalStateException("Expected exception"); }, true); provider.loadAddresses(creat...
public static final SingleKieModuleDeploymentHelper newSingleInstance() { return new KieModuleDeploymentHelperImpl(); }
@Test public void testSingleDeploymentHelper() throws Exception { int numFiles = 0; int numDirs = 0; SingleKieModuleDeploymentHelper deploymentHelper = KieModuleDeploymentHelper.newSingleInstance(); List<String> resourceFilePaths = new ArrayList<String>(); resourceFilePaths....
public List<ColumnMatchResult<?>> getMismatchedColumns(List<Column> columns, ChecksumResult controlChecksum, ChecksumResult testChecksum) { return columns.stream() .flatMap(column -> columnValidators.get(column.getCategory()).get().validate(column, controlChecksum, testChecksum).stream()) ...
@Test public void testValidateVarcharArrayAsDoubleArray() { Map<String, Object> equalNullCount = ImmutableMap.<String, Object>builder() .put("varchar_array$null_count", 1L) .put("varchar_array_as_double$null_count", 1L) .build(); Map<String, Object...
@ShellMethod(key = "fetch table schema", value = "Fetches latest table schema") public String fetchTableSchema( @ShellOption(value = {"--outputFilePath"}, defaultValue = ShellOption.NULL, help = "File path to write schema") final String outputFilePath) throws Exception { HoodieTableMetaClient ...
@Test public void testFetchTableSchema() throws Exception { // Create table and connect HoodieCLI.conf = storageConf(); new TableCommand().createTable( tablePath, tableName, HoodieTableType.COPY_ON_WRITE.name(), "", TimelineLayoutVersion.VERSION_1, "org.apache.hudi.common.model.HoodieAvroP...
public static NamenodeRole convert(NamenodeRoleProto role) { switch (role) { case NAMENODE: return NamenodeRole.NAMENODE; case BACKUP: return NamenodeRole.BACKUP; case CHECKPOINT: return NamenodeRole.CHECKPOINT; } return null; }
@Test public void testConvertBlockType() { BlockType bContiguous = BlockType.CONTIGUOUS; BlockTypeProto bContiguousProto = PBHelperClient.convert(bContiguous); BlockType bContiguous2 = PBHelperClient.convert(bContiguousProto); assertEquals(bContiguous, bContiguous2); BlockType bStriped = BlockTyp...
public static List<String> colNamesFromSchema(final String schema) { return splitAcrossOneLevelDeepComma(schema).stream() .map(RowUtil::removeBackTickAndKeyTrim) .map(RowUtil::splitAndGetFirst) .collect(Collectors.toList()); }
@Test public void shouldGetColumnNamesFromSchema() { // Given final String schema = "`K` STRUCT<`F1` ARRAY<STRING>>, " + "`STR` STRING, " + "`LONG` BIGINT, " + "`DEC` DECIMAL(4, 2)," + "`BYTES_` BYTES, " + "`ARRAY` ARRAY<STRING>, " + "`MA...
@Override public Health health() { Map<String, Health> healths = circuitBreakerRegistry.getAllCircuitBreakers().stream() .filter(this::isRegisterHealthIndicator) .collect(Collectors.toMap(CircuitBreaker::getName, this::mapBackendMonitorState)); Status status ...
@Test public void testHealthStatus() { CircuitBreaker openCircuitBreaker = mock(CircuitBreaker.class); CircuitBreaker halfOpenCircuitBreaker = mock(CircuitBreaker.class); CircuitBreaker closeCircuitBreaker = mock(CircuitBreaker.class); Map<CircuitBreaker.State, CircuitBreaker> expec...
@NonNull public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) { Comparator<FeedItem> comparator = null; Permutor<FeedItem> permutor = null; switch (sortOrder) { case EPISODE_TITLE_A_Z: comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTi...
@Test public void testPermutorForRule_EPISODE_TITLE_ASC_NullTitle() { Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.EPISODE_TITLE_A_Z); List<FeedItem> itemList = getTestList(); itemList.get(2) // itemId 2 .setTitle(null); assertTrue(checkIdOrd...
public static Optional<Expression> convert( org.apache.flink.table.expressions.Expression flinkExpression) { if (!(flinkExpression instanceof CallExpression)) { return Optional.empty(); } CallExpression call = (CallExpression) flinkExpression; Operation op = FILTERS.get(call.getFunctionDefi...
@Test public void testLessThanEquals() { UnboundPredicate<Integer> expected = org.apache.iceberg.expressions.Expressions.lessThanOrEqual("field1", 1); Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.convert(resolve(Expressions.$("field1").isLessOrEqual(Expressions.li...
public static JSONObject createObj() { return new JSONObject(); }
@Test public void customValueTest() { final JSONObject jsonObject = JSONUtil.createObj() .set("test2", (JSONString) () -> NumberUtil.decimalFormat("#.0", 12.00D)); assertEquals("{\"test2\":12.0}", jsonObject.toString()); }
@Override public boolean isExpire(long currentTime) { return isEphemeral() && getAllPublishedService().isEmpty() && currentTime - getLastUpdatedTime() > ClientConfig .getInstance().getClientExpiredTime(); }
@Test void testIsExpire() { long mustExpireTime = ipPortBasedClient.getLastUpdatedTime() + ClientConfig.getInstance().getClientExpiredTime() * 2; assertTrue(ipPortBasedClient.isExpire(mustExpireTime)); }
@Override public void addListener(String key, String group, ConfigurationListener listener) {}
@Test void testAddListener() { configuration.addListener(null, null); configuration.addListener(null, null, null); }
@SafeVarargs public static <T> Stream<T> of(T... array) { Assert.notNull(array, "Array must be not null!"); return Stream.of(array); }
@Test public void ofTest(){ final Stream<Integer> stream = StreamUtil.of(2, x -> x * 2, 4); final String result = stream.collect(CollectorUtil.joining(",")); assertEquals("2,4,8,16", result); }
public QueueCapacityVector parse(String capacityString, QueuePath queuePath) { if (queuePath.isRoot()) { return QueueCapacityVector.of(100f, ResourceUnitCapacityType.PERCENTAGE); } if (capacityString == null) { return new QueueCapacityVector(); } // Trim all spaces from capacity string...
@Test public void testPercentageCapacityConfig() { QueueCapacityVector percentageCapacityVector = capacityConfigParser.parse(Float.toString(PERCENTAGE_VALUE), QUEUE_PATH); QueueCapacityVectorEntry memory = percentageCapacityVector.getResource(MEMORY_URI); QueueCapacityVectorEntry vcore = percentag...
public static Map<String, String> resolveAttachments(Object invocation, boolean isApache) { if (invocation == null) { return Collections.emptyMap(); } final Map<String, String> attachments = new HashMap<>(); if (isApache) { attachments.putAll(getAttachmentsFromCon...
@Test public void testObjectAttachments() { final TestObjectInvocation testObjectInvocation = new TestObjectInvocation(buildObjectAttachments()); final Map<String, String> attachmentsByObject = DubboAttachmentsHelper .resolveAttachments(testObjectInvocation, false); Assert.as...
public SqlEndpoint() { }
@Test public void testSQLEndpoint() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); template.sendBody("direct:start", ""); MockEndpoint.assertIsSatisfied(context); }
public Optional<UserDto> authenticate(HttpRequest request) { return extractCredentialsFromHeader(request) .flatMap(credentials -> Optional.ofNullable(authenticate(credentials, request))); }
@Test public void authenticate_from_user_token() { UserDto user = db.users().insertUser(); when(userTokenAuthentication.authenticate(request)).thenReturn(Optional.of(new UserAuthResult(user, new UserTokenDto().setName("my-token"), UserAuthResult.AuthType.TOKEN))); when(request.getHeader(AUTHORIZATION_HEAD...
public void setParentVersion(String parentVersion) { this.parentVersion = parentVersion; }
@Test public void testSetParentVersion() { String parentVersion = "1.0"; Model instance = new Model(); instance.setParentVersion(parentVersion); assertNotNull(instance.getParentVersion()); }
public static ByteArrayOutputStream getPayload(MultipartPayload multipartPayload) throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); final String preamble = multipartPayload.getPreamble(); if (preamble != null) { os.write((preamble + "\r\n").getBytes(...
@Test public void testEmptyMultipartPayload() throws IOException { final MultipartPayload mP = new MultipartPayload(); final StringBuilder headersString = new StringBuilder(); for (Map.Entry<String, String> header : mP.getHeaders().entrySet()) { headersString.append(header.getKe...
public static URL parseDecodedStr(String decodedURLStr) { Map<String, String> parameters = null; int pathEndIdx = decodedURLStr.indexOf('?'); if (pathEndIdx >= 0) { parameters = parseDecodedParams(decodedURLStr, pathEndIdx + 1); } else { pathEndIdx = decodedURLStr...
@Test void testPond() { String str = "https://a#@b"; URL url1 = URL.valueOf(str); URL url2 = URLStrParser.parseDecodedStr(str); Assertions.assertEquals("https", url1.getProtocol()); Assertions.assertEquals("https", url2.getProtocol()); Assertions.assertEquals("a", u...
public static String getRemoteAddrFromRequest(Request request, Set<IpSubnet> trustedSubnets) { final String remoteAddr = request.getRemoteAddr(); final String XForwardedFor = request.getHeader("X-Forwarded-For"); if (XForwardedFor != null) { for (IpSubnet s : trustedSubnets) { ...
@Test public void getRemoteAddrFromRequestReturnsHeaderContentWithXForwardedForHeaderFromTrustedNetwork() throws Exception { final Request request = mock(Request.class); when(request.getRemoteAddr()).thenReturn("127.0.0.1"); when(request.getHeader("X-Forwarded-For")).thenReturn("192.168.100....
@VisibleForTesting static void validateTaskConfigs(TableConfig tableConfig, Schema schema) { TableTaskConfig taskConfig = tableConfig.getTaskConfig(); if (taskConfig != null) { for (Map.Entry<String, Map<String, String>> taskConfigEntry : taskConfig.getTaskTypeConfigsMap().entrySet()) { String t...
@Test public void testUpsertCompactionTaskConfig() { Schema schema = new Schema.SchemaBuilder().setSchemaName(TABLE_NAME).addSingleValueDimension("myCol", FieldSpec.DataType.STRING) .addDateTime(TIME_COLUMN, FieldSpec.DataType.LONG, "1:MILLISECONDS:EPOCH", "1:MILLISECONDS") .setPri...
CompletableFuture<Void> beginExecute( @Nonnull List<? extends Tasklet> tasklets, @Nonnull CompletableFuture<Void> cancellationFuture, @Nonnull ClassLoader jobClassLoader ) { final ExecutionTracker executionTracker = new ExecutionTracker(tasklets.size(), cancellationFuture...
@Test public void when_nonBlockingCancelled_then_doneCallBackFiredAfterActualDone() { // Given CountDownLatch proceedLatch = new CountDownLatch(1); final List<MockTasklet> tasklets = Stream.generate(() -> new MockTasklet().waitOnLatch(proceedLatch).callsBeforeDone(Integer.MAX...
@Override public boolean next() throws SQLException { if (orderByValuesQueue.isEmpty()) { return false; } if (isFirstNext) { isFirstNext = false; return true; } OrderByValue firstOrderByValue = orderByValuesQueue.poll(); if (firstOr...
@Test void assertNextForCaseInsensitive() throws SQLException { List<QueryResult> queryResults = Arrays.asList(mock(QueryResult.class), mock(QueryResult.class), mock(QueryResult.class)); for (int i = 0; i < 3; i++) { QueryResultMetaData metaData = mock(QueryResultMetaData.class); ...
@Override public Status check() { DataStore dataStore = applicationModel.getExtensionLoader(DataStore.class).getDefaultExtension(); Map<String, Object> executors = dataStore.get(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY); StringBuilder msg = new StringBuilder(); ...
@Test void test() { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); ExecutorService executorService1 = Executors.newFixedThreadPool(1); ExecutorService executorService2 = Executors.newFixedThreadPool(10); dataStore.put(...
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testMergeMapOverwrite() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'tomergemap': {'type': 'MAP', 'value': {'tomerge': {'type': 'STRING','value': 'hello', 'validator': '@notEmpty'}}}}"); Map<String, ParamDefinition> params...
@Override public String getNodeHttpAddress(HttpServletRequest req, String appId, String appAttemptId, String containerId, String clusterId) { UserGroupInformation callerUGI = LogWebServiceUtils.getUser(req); String cId = clusterId != null ? clusterId : defaultClusterid; MultivaluedMap<String, String...
@Test public void testGetContainer() { String address = logWebService .getNodeHttpAddress(request, appId.toString(), null, cId.toString(), null); Assert.assertEquals(this.nodeHttpAddress, address); }
public Class<?> getClass(String name, Class<?> defaultValue) { String valueString = getTrimmed(name); if (valueString == null) return defaultValue; try { return getClassByName(valueString); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }
@Test public void testGetClass() throws IOException { out=new BufferedWriter(new FileWriter(CONFIG)); startConfig(); appendProperty("test.class1", "java.lang.Integer"); appendProperty("test.class2", " java.lang.Integer "); endConfig(); Path fileResource = new Path(CONFIG); conf.addResource...
public boolean eval(StructLike data) { return new EvalVisitor().eval(data); }
@Test public void testOr() { Evaluator evaluator = new Evaluator(STRUCT, or(equal("x", 7), notNull("z"))); assertThat(evaluator.eval(TestHelpers.Row.of(7, 0, 3))).as("7, 3 => true").isTrue(); assertThat(evaluator.eval(TestHelpers.Row.of(8, 0, 3))).as("8, 3 => true").isTrue(); assertThat(evaluator.eval...
public Result tick() { if (System.currentTimeMillis() >= mLastEventHorizonMs) { return Result.EXPIRED; } if (System.currentTimeMillis() < mNextEventMs) { return Result.NOT_READY; } mNextEventMs = System.currentTimeMillis() + mIntervalMs; long next = Math.min(mIntervalMs * 2, mMaxInte...
@Test(timeout = 2000) public void backoff() { int n = 10; ExponentialTimer timer = new ExponentialTimer(1, 1000, 0, 1000); long start = System.currentTimeMillis(); for (int i = 0; i < n; i++) { while (timer.tick() == ExponentialTimer.Result.NOT_READY) { CommonUtils.sleepMs(10); } ...
public boolean isEnabled() { return config.getBoolean(ENABLED).orElseThrow(DEFAULT_VALUE_MISSING) && clientId() != null && clientSecret() != null; }
@Test public void is_enabled_always_return_false_when_client_secret_is_null() { settings.setProperty("sonar.auth.bitbucket.enabled", true); settings.setProperty("sonar.auth.bitbucket.clientId.secured", "id"); settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", (String) null); assertThat...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "Example with ref") public void testExampleWithRef() { Components components = new Components(); components.addExamples("Id", new Example().description("Id Example").summary("Id Example").value("1")); OpenAPI oas = new OpenAPI() .info(new Info().descripti...
public String getEvent() { return event; }
@Test public void getEvent() { SAExposureData exposureData = new SAExposureData("ExposeEvent"); Assert.assertEquals("ExposeEvent", exposureData.getEvent()); }
public static String toString(final Collection<?> col) { if (col == null) { return "null"; } if (col.isEmpty()) { return "[]"; } return CycleDependencyHandler.wrap(col, o -> { StringBuilder sb = new StringBuilder(32); sb.append("["...
@Test public void testCollectionToString() { List<String> nullCollection = null; List<String> emptyCollection = new ArrayList<>(); List<Object> filledCollection = new ArrayList<>(); filledCollection.add("Foo"); filledCollection.add("Bar"); filledCollection.add(filled...
@VisibleForTesting protected void updateCache(DefaultTapiResolver resolver, DefaultContext context) { updateNodes(resolver, getNodes(context)); updateNeps(resolver, getNeps(context)); }
@Test public void testUpdateCacheWithoutNep() { DcsBasedTapiDataProducer dataProvider = new DcsBasedTapiDataProducer(); DefaultTapiResolver mockResolver = EasyMock.createMock(DefaultTapiResolver.class); topology.addToNode(node1); topology.addToNode(node2); List<TapiNodeRef...
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext, final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon...
@Test void assertNewInstanceForDCLForNoSingleTable() { DCLStatement dclStatement = mock(DCLStatement.class); when(sqlStatementContext.getSqlStatement()).thenReturn(dclStatement); QueryContext queryContext = new QueryContext(sqlStatementContext, "", Collections.emptyList(), new HintValueConte...
public T runWithDelay() throws Exception { try { return execute(); } catch(Exception e) { if (e.getClass().equals(retryExceptionType)){ tries++; if (MAX_RETRIES == tries) { throw e; } else { Thread.sleep((long) DELAY * tries); return runWithDelay...
@Test public void testRetryFailureWithDelayMoreThanTimeout() { Retry<Void> retriable = new Retry<Void>(NullPointerException.class) { @Override public Void execute() { throw new NullPointerException(); } }; long startTime = System.currentTimeMillis(); try { retriable.run...
public long getRevisedRowCount(final SelectStatementContext selectStatementContext) { if (isMaxRowCount(selectStatementContext)) { return Integer.MAX_VALUE; } return rowCountSegment instanceof LimitValueSegment ? actualOffset + actualRowCount : actualRowCount; }
@Test void assertGetRevisedRowCountForOracle() { getRevisedRowCount(new OracleSelectStatement()); }
public static Optional<Expression> convert( org.apache.flink.table.expressions.Expression flinkExpression) { if (!(flinkExpression instanceof CallExpression)) { return Optional.empty(); } CallExpression call = (CallExpression) flinkExpression; Operation op = FILTERS.get(call.getFunctionDefi...
@Test public void testNotEquals() { for (Pair<String, Object> pair : FIELD_VALUE_LIST) { UnboundPredicate<?> expected = org.apache.iceberg.expressions.Expressions.notEqual(pair.first(), pair.second()); Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.conve...
public static <T> List<LocalProperty<T>> grouped(Collection<T> columns) { return ImmutableList.of(new GroupingProperty<>(columns)); }
@Test public void testGroupedDoubleThenSingle() { List<LocalProperty<String>> actual = builder() .grouped("a", "b") .grouped("c") .build(); assertMatch( actual, builder().grouped("a", "b", "c", "d").build(), ...
@Override protected ServerSocketFactory getServerSocketFactory() throws Exception { if (socketFactory == null) { SSLContext sslContext = getSsl().createContext(this); SSLParametersConfiguration parameters = getSsl().getParameters(); parameters.setContext(getContext()); ...
@Test public void testGetServerSocketFactory() throws Exception { ServerSocketFactory socketFactory = receiver.getServerSocketFactory(); assertNotNull(socketFactory); assertTrue(ssl.isContextCreated()); assertTrue(parameters.isContextInjected()); }
@Override public Result reconcile(Request request) { String name = request.name(); if (!isSystemSetting(name)) { return new Result(false, null); } client.fetch(ConfigMap.class, name) .ifPresent(configMap -> { addFinalizerIfNecessary(configMap);...
@Test void reconcileCategoriesRule() { ConfigMap configMap = systemConfigMapForRouteRule(rules -> { rules.setCategories("categories-new"); return rules; }); when(environmentFetcher.getConfigMapBlocking()).thenReturn(Optional.of(configMap)); when(client.fetch(e...
@Override public Message receive() { MessageExt rmqMsg = localMessageCache.poll(); return rmqMsg == null ? null : OMSUtil.msgConvert(rmqMsg); }
@Test public void testPoll() { final byte[] testBody = new byte[] {'a', 'b'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); consumedMsg.setBody(testBody); consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC"); consume...
@Override public byte[] fromConnectData(String topic, Schema schema, Object value) { if (schema == null && value == null) { return null; } JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value); ...
@Test public void mapToJsonStringKeys() { Schema stringIntMap = SchemaBuilder.map(Schema.STRING_SCHEMA, Schema.INT32_SCHEMA).build(); Map<String, Integer> input = new HashMap<>(); input.put("key1", 12); input.put("key2", 15); JsonNode converted = parse(converter.fromConnectDa...
@Override public String getSchema(final Connection connection) { try { return Optional.ofNullable(connection.getMetaData().getUserName()).map(String::toUpperCase).orElse(null); } catch (final SQLException ignored) { return null; } }
@Test void assertGetSchemaIfExceptionThrown() throws SQLException { Connection connection = mock(Connection.class, RETURNS_DEEP_STUBS); when(connection.getMetaData().getUserName()).thenThrow(SQLException.class); assertNull(dialectDatabaseMetaData.getSchema(connection)); }
public void close(final Timer timer) { // we do not need to re-enable wakeups since we are closing already client.disableWakeups(); try { maybeAutoCommitOffsetsSync(timer); while (pendingAsyncCommits.get() > 0 && timer.notExpired()) { ensureCoordinatorRead...
@Test public void testLeaveGroupOnClose() { subscriptions.subscribe(singleton(topic1), Optional.of(rebalanceListener)); joinAsFollowerAndReceiveAssignment(coordinator, singletonList(t1p)); final AtomicBoolean received = new AtomicBoolean(false); client.prepareResponse(body -> { ...
@Override public ExecutionSchedule createExecutionSchedule(Session session, Collection<StageExecutionAndScheduler> stages) { if (stages.size() > getMaxStageCountForEagerScheduling(session)) { return new PhasedExecutionSchedule(stages); } else { return new AllAtOnc...
@Test public void testCreateExecutionSchedule() { Session session = testSessionBuilder(new SessionPropertyManager(new SystemSessionProperties( new QueryManagerConfig(), new TaskManagerConfig(), new MemoryManagerConfig(), new FeaturesConfig(...
private ExposeExternallyMode getExposeExternallyMode(Map<String, Comparable> properties) { Boolean exposeExternally = getOrNull(properties, KUBERNETES_SYSTEM_PREFIX, EXPOSE_EXTERNALLY); if (exposeExternally == null) { return ExposeExternallyMode.AUTO; } else if (exposeExternally) { ...
@Test public void kubernetesApiExposeExternally() { // given Map<String, Comparable> properties = createProperties(); properties.put(KubernetesProperties.EXPOSE_EXTERNALLY.key(), true); // when KubernetesConfig config = new KubernetesConfig(properties); // then ...
public static Map<String, String> resolve(ServerWebExchange exchange) { Map<String, String> result = new HashMap<>(); HttpHeaders headers = exchange.getRequest().getHeaders(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); if (StringUtils.isBlank(key)) { ...
@Test public void testSCTTransitiveMetadata() { MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest.get(""); builder.header("X-SCT-Metadata-Transitive-a", "test"); MockServerWebExchange exchange = MockServerWebExchange.from(builder); Map<String, String> resolve = CustomTransitiveMetadataResolv...
@Override public Optional<SimpleAddress> selectAddress(Optional<String> addressSelectionContext) { if (addressSelectionContext.isPresent()) { return addressSelectionContext .map(HostAndPort::fromString) .map(SimpleAddress::new); } List<...
@Test(expectedExceptions = IllegalArgumentException.class) public void testAddressSelectionContextPresentWithInvalidAddress() { InMemoryNodeManager internalNodeManager = new InMemoryNodeManager(); RandomResourceManagerAddressSelector selector = new RandomResourceManagerAddressSelector(internalNo...
public static void write(Node node, Writer writer, String charset, int indent) { transform(new DOMSource(node), new StreamResult(writer), charset, indent); }
@Test @Disabled public void writeTest() { final String result = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"// + "<returnsms>"// + "<returnstatus>Success(成功)</returnstatus>"// + "<message>ok</message>"// + "<remainpoint>1490</remainpoint>"// + "<taskID>885</taskID>"// + "<successCounts>1</s...
public boolean validate(final Protocol protocol, final LoginOptions options) { return protocol.validate(this, options); }
@Test public void testLoginAnonymous2() { Credentials credentials = new Credentials(PreferencesFactory.get().getProperty("connection.login.anon.name"), null); assertTrue(credentials.validate(new TestProtocol(Scheme.ftp), new LoginOptions())); }
public static void preserve(FileSystem targetFS, Path path, CopyListingFileStatus srcFileStatus, EnumSet<FileAttribute> attributes, boolean preserveRawXattrs) throws IOException { // strip out those attributes we don't need a...
@Test public void testPreserveUserOnFile() throws IOException { FileSystem fs = FileSystem.get(config); EnumSet<FileAttribute> attributes = EnumSet.of(FileAttribute.USER); Path dst = new Path("/tmp/dest2"); Path src = new Path("/tmp/src2"); createFile(fs, src); createFile(fs, dst); fs.s...
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) { checkArgument( OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp); return new AutoValue_UBinary(binaryOp, lhs, rhs); }
@Test public void equal() { assertUnifiesAndInlines( "4 == 17", UBinary.create(Kind.EQUAL_TO, ULiteral.intLit(4), ULiteral.intLit(17))); }
public static Set<String> validateScopes(String scopeClaimName, Collection<String> scopes) throws ValidateException { if (scopes == null) throw new ValidateException(String.format("%s value must be non-null", scopeClaimName)); Set<String> copy = new HashSet<>(); for (String scope :...
@Test public void testValidateScopesDisallowsEmptyNullAndWhitespace() { assertThrows(ValidateException.class, () -> ClaimValidationUtils.validateScopes("scope", Arrays.asList("a", ""))); assertThrows(ValidateException.class, () -> ClaimValidationUtils.validateScopes("scope", Arrays.asList("a", null)...
public static boolean isIbmJdk() { return System.getProperty("java.vendor").contains("IBM"); }
@Test public void testIsIBMJdk() { System.setProperty("java.vendor", "Oracle Corporation"); assertFalse(Java.isIbmJdk()); System.setProperty("java.vendor", "IBM Corporation"); assertTrue(Java.isIbmJdk()); }
public static Map<String, String> getKiePMMLNodeSourcesMap(final NodeNamesDTO nodeNamesDTO, final List<Field<?>> fields, final String packageName) { logger.trace("getKiePMMLNodeSourcesMa...
@Test void getKiePMMLNodeSourcesMap() { final KiePMMLNodeFactory.NodeNamesDTO nodeNamesDTO = new KiePMMLNodeFactory.NodeNamesDTO(node1, createNodeClassName(), null, 1.0); Map<String, String> retrieved = KiePMMLNodeFactory.getKiePMMLNodeSourcesMap(node...
public static PathData[] expandAsGlob(String pattern, Configuration conf) throws IOException { Path globPath = new Path(pattern); FileSystem fs = globPath.getFileSystem(conf); FileStatus[] stats = fs.globStatus(globPath); PathData[] items = null; if (stats == null) { // remove any q...
@Test (timeout = 30000) public void testRelativeGlob() throws Exception { PathData[] items = PathData.expandAsGlob("d1/f1*", conf); assertEquals( sortedString("d1/f1", "d1/f1.1"), sortedString(items) ); }
public static PDImageXObject createFromFile(PDDocument document, File file) throws IOException { return createFromFile(document, file, 0); }
@Test void testCreateFromRandomAccessMulti() throws IOException { String tiffPath = "src/test/resources/org/apache/pdfbox/pdmodel/graphics/image/ccittg4multi.tif"; ImageInputStream is = ImageIO.createImageInputStream(new File(tiffPath)); ImageReader imageReader = ImageIO.getImag...
@Override public OverlayData createOverlayData(ComponentName remoteApp) { if (!OS_SUPPORT_FOR_ACCENT) { return EMPTY; } try { final ActivityInfo activityInfo = mLocalContext .getPackageManager() .getActivityInfo(remoteApp, PackageManager.GET_META_DATA); ...
@Test public void testAddsFullOpaqueToTextColor() throws Exception { setupReturnedColors(R.style.CompletelyTransparentAttribute); final OverlayData overlayData = mUnderTest.createOverlayData(mComponentName); Assert.assertEquals(Color.parseColor("#FF112233"), overlayData.getPrimaryTextColor()); }
void handleLine(final String line) { final String trimmedLine = Optional.ofNullable(line).orElse("").trim(); if (trimmedLine.isEmpty()) { return; } handleStatements(trimmedLine); }
@Test public void shouldDescribeTableFunction() { final String expectedOutput = "Name : EXPLODE\n" + "Author : Confluent\n" + "Overview : Explodes an array. This function outputs one value for each element of the array.\n" + "Type : TABLE\n" ...