focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public WebAppProxyServlet() { super(); conf = new YarnConfiguration(); this.trackingUriPlugins = conf.getInstances(YarnConfiguration.YARN_TRACKING_URL_GENERATOR, TrackingUriPlugin.class); this.failurePageUrlBase = StringHelper.pjoin(WebAppUtils.getResolvedRMWebAppURLWithSchem...
@Test @Timeout(5000) void testWebAppProxyServlet() throws Exception { configuration.set(YarnConfiguration.PROXY_ADDRESS, "localhost:9090"); // overriding num of web server threads, see HttpServer.HTTP_MAXTHREADS configuration.setInt("hadoop.http.max.threads", 10); WebAppProxyServerForTest proxy = ne...
public void translate(Pipeline pipeline) { this.flinkBatchEnv = null; this.flinkStreamEnv = null; final boolean hasUnboundedOutput = PipelineTranslationModeOptimizer.hasUnboundedOutput(pipeline); if (hasUnboundedOutput) { LOG.info("Found unbounded PCollection. Switching to streaming execu...
@Test public void testTranslationModeOverrideWithUnboundedSources() { FlinkPipelineOptions options = getDefaultPipelineOptions(); options.setRunner(FlinkRunner.class); options.setStreaming(false); FlinkPipelineExecutionEnvironment flinkEnv = new FlinkPipelineExecutionEnvironment(options); Pipelin...
@Override public void onHeartbeatSuccess(ShareGroupHeartbeatResponseData response) { if (response.errorCode() != Errors.NONE.code()) { String errorMessage = String.format( "Unexpected error in Heartbeat response. Expected no error, but received: %s", Error...
@Test public void testSameAssignmentReconciledAgainWithMissingTopic() { ShareMembershipManager membershipManager = createMemberInStableState(); Uuid topic1 = Uuid.randomUuid(); Uuid topic2 = Uuid.randomUuid(); final ShareGroupHeartbeatResponseData.Assignment assignment1 = new ShareGr...
public static URI toURI(String name) { try { return new URI(name); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
@Test void testToUri() { Assertions.assertThrows(RuntimeException.class, () -> ClassUtils.toURI("#xx_abc#hello")); }
public ValidationResult validateAuthConfig(final String pluginId, final Map<String, String> configuration) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_VALIDATE_AUTH_CONFIG, new DefaultPluginInteractionCallback<>() { @Override public String requestBody(String resolvedExte...
@Test void shouldTalkToPlugin_To_ValidateAuthConfig() { String responseBody = "[{\"message\":\"Url must not be blank.\",\"key\":\"Url\"},{\"message\":\"SearchBase must not be blank.\",\"key\":\"SearchBase\"}]"; when(pluginManager.submitTo(eq(PLUGIN_ID), eq(AUTHORIZATION_EXTENSION), requestArgumentCa...
@Override public void updateNode(ResourceId path, DataNode node) { super.updateNode(toAbsoluteId(path), node); }
@Test public void testUpdateNode() { view.updateNode(relIntf, node); assertTrue(ResourceIds.isPrefix(rid, realPath)); }
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test void testFunctionDependingOnInputWithCustomTupleInput() { IdentityMapper<SameTypeVariable<String>> function = new IdentityMapper<SameTypeVariable<String>>(); TypeInformation<?> ti = TypeExtractor.getMapReturnType...
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public @Nullable <InputT> TransformEvaluator<InputT> forApplication( AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) throws IOException { return createEvaluator((AppliedPTransform) application); }
@Test public void boundedSourceEvaluatorClosesReader() throws Exception { TestSource<Long> source = new TestSource<>(BigEndianLongCoder.of(), 1L, 2L, 3L); PCollection<Long> pcollection = p.apply(Read.from(source)); AppliedPTransform<?, ?, ?> sourceTransform = DirectGraphs.getProducer(pcollection); Un...
public PDDocument createPDFFromText( Reader text ) throws IOException { PDDocument doc = new PDDocument(); createPDFFromText(doc, text); return doc; }
@Test void testCreateEmptyPdf() throws IOException { TextToPDF pdfCreator = new TextToPDF(); PDDocument pdfDoc; try (StringReader reader = new StringReader("")) { pdfDoc = pdfCreator.createPDFFromText(reader); } // In order for the PDF document to be ...
public Optional<UpdateCenter> getUpdateCenter() { return getUpdateCenter(false); }
@Test public void forceRefresh() throws Exception { when(reader.readString(new URI(URL_DEFAULT_VALUE), StandardCharsets.UTF_8)).thenReturn("sonar.versions=2.2,2.3"); underTest.getUpdateCenter(); underTest.getUpdateCenter(true); verify(reader, times(2)).readString(new URI(URL_DEFAULT_VALUE), Standard...
@Override public long getDelay(TimeUnit unit) { return original.getDelay(unit); }
@Test public void getDelay() { ScheduledFuture<Integer> future = new DelegatingScheduledFutureStripper<>( scheduler.schedule(new SimpleCallableTestTask(), 0, TimeUnit.SECONDS)); //getDelay returns the remaining delay; zero or negative values indicate that the delay has already elapse...
@Override public CanEmitBatchOfRecordsChecker getCanEmitBatchOfRecords() { return () -> false; }
@TestTemplate void testCanEmitBatchOfRecords() throws Exception { AvailabilityProvider.AvailabilityHelper availabilityHelper = new AvailabilityProvider.AvailabilityHelper(); try (StreamTaskMailboxTestHarness<String> testHarness = new StreamTaskMailboxTestHarnessBuilde...
static String toBar(double percentValue) { // NOPMD final double myPercent = Math.max(Math.min(percentValue, 100d), 0d); final StringBuilder sb = new StringBuilder(); final String body = "<img src=''?resource=bar/rb_{0}.gif'' alt=''+'' title=''" + I18N.createPercentFormat().format(myPercent) + "%'' />"; fin...
@Test public void testToBar() { assertNotNull("toBar", HtmlJavaInformationsReport.toBar(0)); assertNotNull("toBar", HtmlJavaInformationsReport.toBar(1)); assertNotNull("toBar", HtmlJavaInformationsReport.toBar(10)); assertNotNull("toBar", HtmlJavaInformationsReport.toBar(15)); assertNotNull("toBarWithAlert",...
@PUT @Consumes("application/json") @Produces("application/json") @Path("profile") public Map<String, Object> profile(InputStream is) throws Exception { JsonNode node = null; try (BufferedReader reader = new BufferedReader( new InputStreamReader(is, StandardCharsets.UTF_8)...
@Test public void testBasicProfile() throws Exception { Map<String, String> request = new HashMap<>(); request.put(TikaEvalResource.ID, "1"); request.put(TikaEvalResource.TEXT, "the quick brown fox jumped qwertyuiop"); Response response = profile(request); Map<String, Object>...
@Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return lessIsBetter ? criterionValue1.isLessThan(criterionValue2) : criterionValue1.isGreaterThan(criterionValue2); }
@Test public void betterThanWithLessIsNotBetter() { AnalysisCriterion criterion = getCriterion(new ProfitLossCriterion()); assertTrue(criterion.betterThan(numOf(5000), numOf(4500))); assertFalse(criterion.betterThan(numOf(4500), numOf(5000))); }
@Override public String getAuthenticationMethodName() { return PostgreSQLAuthenticationMethod.PASSWORD.getMethodName(); }
@Test void assertAuthenticationMethodName() { assertThat(new PostgreSQLPasswordAuthenticator().getAuthenticationMethodName(), is("password")); }
public DateTimeStamp minus(double offsetInDecimalSeconds) { return add(-offsetInDecimalSeconds); }
@Test void testNanWithMinusNonZero() { assertThrows(IllegalArgumentException.class, () -> { new DateTimeStamp("2018-04-04T10:10:00.586-0100").minus(Double.NaN); }, "IllegalAccess Not Thrown"); }
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { if (1 == queryResults.size() && !isNeedAggregateRewri...
@Test void assertBuildIteratorStreamMergedResultWithOracleLimit() throws SQLException { final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "Oracle")); final ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURN...
public static File generate(String content, int width, int height, File targetFile) { String extName = FileUtil.extName(targetFile); switch (extName) { case QR_TYPE_SVG: String svg = generateAsSvg(content, new QrConfig(width, height)); FileUtil.writeString(svg, targetFile, StandardCharsets.UTF_8); br...
@Test public void generateTest() { final BufferedImage image = QrCodeUtil.generate("https://hutool.cn/", 300, 300); Assert.notNull(image); }
@Override public void destroy() { PendingRead pendingRead; synchronized (this) { if (state.setIf(FINISHED, oldState -> !oldState.isTerminal())) { close(); } pendingRead = this.pendingRead; this.pendingRead = null; } ...
@Test public void testAddAfterDestroy() { SpoolingOutputBuffer buffer = createSpoolingOutputBuffer(); for (int i = 0; i < 2; i++) { addPage(buffer, createPage(i)); } compareTotalBuffered(buffer, 2); buffer.destroy(); // nothing in buffer com...
@Override public Expression createExpression(String expression) { org.springframework.expression.Expression defaultExpression = parser.parseExpression(expression); EvaluationContext evaluationContext = ((SpelExpression)defaultExpression).getEvaluationContext(); ((StandardEvaluationContext)ev...
@Test public void testCreateExpression() { SpringELExpressionFactory factory = new SpringELExpressionFactory(null); Assertions.assertNotNull(factory.createExpression("'Hello World'.concat('!')")); }
@Override public Stream<MappingField> resolveAndValidateFields( boolean isKey, List<MappingField> userFields, Map<String, String> options, InternalSerializationService serializationService ) { Map<QueryPath, MappingField> fieldsByPath = extractFields(userF...
@Test @Parameters({ "true, __key", "false, this" }) public void when_typeMismatchBetweenDeclaredAndClassDefinitionField_then_throws(boolean key, String prefix) { InternalSerializationService ss = new DefaultSerializationServiceBuilder().build(); ClassDefinition classD...
public int getPort() { return port; }
@Test void testDefaultPortIsSet() throws Exception { try (CouchDbEndpoint endpoint = new CouchDbEndpoint("couchdb:http://localhost/db", "http://localhost/db", new CouchDbComponent())) { assertEquals(CouchDbEndpoint.DEFAULT_PORT, endpoint.getPort()); } }
public static String jsonFromMap(Map<String, Object> jsonData) { try { JsonDocument json = new JsonDocument(); json.startGroup(); for (String key : jsonData.keySet()) { Object data = jsonData.get(key); if (data instanceof Map) { ...
@Test void testSimpleOne() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); jsonData.put("myKey", "myValue"); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":\"myValue\"}"; assertEquals(expected, json); }
public AbilityStatus isCurrentNodeAbilityRunning(AbilityKey abilityKey) { Map<String, Boolean> abilities = currentNodeAbilities.get(abilityKey.getMode()); if (abilities != null) { Boolean support = abilities.get(abilityKey.getName()); if (support != null) { return...
@Test void testIsCurrentNodeAbilityRunning() { assertEquals(AbilityStatus.SUPPORTED, abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_1)); assertEquals(AbilityStatus.NOT_SUPPORTED, abilityControlManager.isCurrentNodeAbilityRunning(AbilityKey.SERVER_TEST_2)); assertEqu...
public static SpiImplPushExecutorHolder getInstance() { return INSTANCE; }
@Test void testGetInstance() { SpiImplPushExecutorHolder instance = SpiImplPushExecutorHolder.getInstance(); assertNotNull(instance); }
@Override public void registerDeleted(Weapon weapon) { LOGGER.info("Registering {} for delete in context.", weapon.getName()); register(weapon, UnitActions.DELETE.getActionValue()); }
@Test void shouldSaveDeletedStudentWithoutWritingToDb() { armsDealer.registerDeleted(weapon1); armsDealer.registerDeleted(weapon2); assertEquals(2, context.get(UnitActions.DELETE.getActionValue()).size()); verifyNoMoreInteractions(weaponDatabase); }
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_containsNoneOf_primitiveFloatArray_success() { assertThat(array(1.0f, 2.0f, 3.0f)) .usingExactEquality() .containsNoneOf(array(99.99f, 999.999f)); }
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_contains_otherTypes_bigIntegerNotSupported() { BigInteger expected = BigInteger.valueOf(2); float[] actual = array(1.0f, 2.0f, 3.0f); expectFailureWhenTestingThat(actual).usingExactEquality().contains(expected); assertFailureKeys( "value of", "expec...
public static String asAlphaNumeric(int i) { StringBuilder stringBuilder = new StringBuilder(); int index = i % MAX; int ratio = i / MAX; if (index == 0) { ratio--; index = MAX; } for (int j = 0; j <= ratio; j++) { stringBuilder.appen...
@Test public void testAlphaUpper() { assertEquals("A", AutoPageNumberUtils.asAlphaNumeric(1)); assertEquals("Z", AutoPageNumberUtils.asAlphaNumeric(26)); assertEquals("AA", AutoPageNumberUtils.asAlphaNumeric(27)); assertEquals("ZZ", AutoPageNumberUtils.asAlphaNumeric(52)); as...
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testGrouping() { analyze("SELECT a, b, sum(c), grouping(a, b) FROM t1 GROUP BY GROUPING SETS ((a), (a, b))"); analyze("SELECT grouping(t1.a) FROM t1 GROUP BY a"); analyze("SELECT grouping(b) FROM t1 GROUP BY t1.b"); analyze("SELECT grouping(a, a, a, a, a, a, a, ...
protected String generateQueryString(MultiValuedTreeMap<String, String> parameters, boolean encode, String encodeCharset) throws ServletException { if (parameters == null || parameters.isEmpty()) { return null; } if (queryString != null) { return queryString; ...
@Test void queryString_generateQueryString_validQuery() { AwsProxyHttpServletRequest request = new AwsProxyHttpServletRequest(queryString, mockContext, null, config); String parsedString = null; try { parsedString = request.generateQueryString(request.getAwsProxyRequest().getMul...
public ShareFetch<K, V> collect(final ShareFetchBuffer fetchBuffer) { ShareFetch<K, V> fetch = ShareFetch.empty(); int recordsRemaining = fetchConfig.maxPollRecords; try { while (recordsRemaining > 0) { final ShareCompletedFetch nextInLineFetch = fetchBuffer.nextInLi...
@Test public void testFetchWithTopicAuthorizationFailed() { buildDependencies(); subscribeAndAssign(topicAPartition0); ShareCompletedFetch completedFetch = completedFetchBuilder .error(Errors.TOPIC_AUTHORIZATION_FAILED) .build(); fetchBuffer.add(compl...
@Override public void set(File file, String view, String attribute, Object value, boolean create) { if (supports(attribute)) { checkNotCreate(view, attribute, create); file.setAttribute("dos", attribute, checkType(view, attribute, value, Boolean.class)); } }
@Test public void testSet() { for (String attribute : DOS_ATTRIBUTES) { assertSetAndGetSucceeds(attribute, true); assertSetFailsOnCreate(attribute, true); } }
@Override public FileClient getMasterFileClient() { return clientCache.getUnchecked(CACHE_MASTER_ID); }
@Test public void testGetMasterFileClient() { // mock 数据 FileConfigDO fileConfig = randomFileConfigDO().setMaster(true); fileConfigMapper.insert(fileConfig); // 准备参数 Long id = fileConfig.getId(); // mock 获得 Client FileClient fileClient = new LocalFileClient(id...
public static int[] computePhysicalIndicesOrTimeAttributeMarkers( TableSource<?> tableSource, List<TableColumn> logicalColumns, boolean streamMarkers, Function<String, String> nameRemapping) { Optional<String> proctimeAttribute = getProctimeAttribute(tableSource);...
@Test void testMappingWithStreamTimeAttributes() { TestTableSource tableSource = new TestTableSource( DataTypes.BIGINT(), Collections.singletonList("rowtime"), "proctime"); int[] indices = TypeMappingUtils.computePhysicalIndicesOrTimeAttributeM...
@Override public GraphModel getGraphModel() { Workspace currentWorkspace = Lookup.getDefault().lookup(ProjectController.class).getCurrentWorkspace(); if (currentWorkspace == null) { return null; } return getGraphModel(currentWorkspace); }
@Test public void testWithConfiguration() { GraphControllerImpl graphController = new GraphControllerImpl(); Configuration configuration = graphController.getDefaultConfigurationBuilder().nodeIdType(Long.class).build(); ProjectController pc = Lookup.getDefault().lookup(ProjectController.cla...
@Override @MethodNotAvailable public void loadAll(boolean replaceExistingValues) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testLoadAll() { adapter.loadAll(true); }
public static Filter parse(String filter){ return FilterCompiler.compile(filter); }
@Test public void criteria_can_be_parsed() { Filter criteria = Filter.parse("[?(@.foo == 'baar')]"); assertThat(criteria.toString()).isEqualTo("[?(@['foo'] == 'baar')]"); criteria = Filter.parse("[?(@.foo)]"); assertThat(criteria.toString()).isEqualTo("[?(@['foo'])]"); }
public static Boolean judge(final ConditionData conditionData, final String realData) { if (Objects.isNull(conditionData) || StringUtils.isBlank(conditionData.getOperator())) { return false; } PredicateJudge predicateJudge = newInstance(conditionData.getOperator()); if (!(pre...
@Test public void testStartsJudge() { conditionData.setOperator(OperatorEnum.STARTS_WITH.getAlias()); assertTrue(PredicateJudgeFactory.judge(conditionData, "/http/**/test")); assertFalse(PredicateJudgeFactory.judge(conditionData, "/test/http/**")); assertFalse(PredicateJudgeFactory.j...
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (getEmbeddedHttp2Exception(cause) != null) { // Some exception in the causality chain is an Http2Exception - handle it. onError(ctx, false, cause); } else { sup...
@Test public void serverShouldNeverSend431HeaderSizeErrorWhenEncoding() throws Exception { int padding = 0; handler = newHandler(); Http2Exception e = new Http2Exception.HeaderListSizeException(STREAM_ID, PROTOCOL_ERROR, "Header size exceeded max allowed size 8196", false); ...
public FEELFnResult<List<Object>> invoke( @ParameterName( "list" ) List list, @ParameterName( "item" ) Object[] items ) { return invoke((Object) list, items); }
@Test void invokeEmptyParams() { FunctionTestUtil.assertResultList(appendFunction.invoke(Collections.emptyList(), new Object[]{}), Collections.emptyList()); }
@Override public List<BlockWorkerInfo> getPreferredWorkers(WorkerClusterView workerClusterView, String fileId, int count) throws ResourceExhaustedException { if (workerClusterView.size() < count) { throw new ResourceExhaustedException(String.format( "Not enough workers in the cluster %d work...
@Test public void getOneWorker() throws Exception { WorkerLocationPolicy policy = WorkerLocationPolicy.Factory.create(mConf); assertTrue(policy instanceof ConsistentHashPolicy); // Prepare a worker list WorkerClusterView workers = new WorkerClusterView(Arrays.asList( new WorkerInfo() ...
public static Builder builder() { return new Builder(); }
@Test public void testBuilderDoesNotCreateInvalidObjects() { assertThatThrownBy(() -> ListTablesResponse.builder().add(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Invalid table identifier: null"); assertThatThrownBy(() -> ListTablesResponse.builder().addAll(null)) .i...
Collection<AuxiliaryService> getServices() { return Collections.unmodifiableCollection(serviceMap.values()); }
@Test public void testAuxServicesManifestPermissions() throws IOException { Assume.assumeTrue(useManifest); Configuration conf = getABConf(); FileSystem fs = FileSystem.get(conf); fs.setPermission(new Path(manifest.getAbsolutePath()), FsPermission .createImmutable((short) 0777)); AuxServic...
@Around("@annotation(com.linecorp.flagship4j.javaflagr.annotations.ControllerFeatureToggle)") public Object processControllerFeatureToggleAnnotation(ProceedingJoinPoint joinPoint) throws Throwable { log.info("start processing controllerFeatureToggle annotation"); MethodSignature signature = (MethodS...
@Test public void processFlagrMethodWithControllerFeatureToggleTestWhenNotVariantKeyAnnotation() throws Throwable { String methodName = "methodWithControllerFeatureToggleWithoutVariantKey"; FlagrAnnotationTest flagrAnnotationTest = new FlagrAnnotationTest(); Method method = Arrays.stream(fla...
public static void tar(@NotNull File source, @NotNull File dest) throws IOException { if (!source.exists()) { throw new IllegalArgumentException("No source file or folder exists: " + source.getAbsolutePath()); } if (dest.exists()) { throw new IllegalArgumentException("Des...
@Test public void testFileArchived() throws Exception { File src = new File(randName + ".txt"); FileWriter fw = new FileWriter(src); fw.write("12345"); fw.close(); CompressBackupUtil.tar(src, dest); Assert.assertTrue("No destination archive created", dest.exists()); ...
@Override public CloseableIterator<T> iterator() { ParallelIterator<T> iter = new ParallelIterator<>(iterables, workerPool, approximateMaxQueueSize); addCloseable(iter); return iter; }
@Test public void queueSizeOne() { List<Iterable<Integer>> iterables = ImmutableList.of( () -> IntStream.range(0, 100).iterator(), () -> IntStream.range(0, 100).iterator(), () -> IntStream.range(0, 100).iterator()); Multiset<Integer> expectedValues = IntStr...
@Override public boolean add(FilteredBlock block) throws VerificationException, PrunedException { boolean success = super.add(block); if (success) { trackFilteredTransactions(block.getTransactionCount()); } return success; }
@Test public void duplicates() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); // Adding a block twice should not have any effect, in particular it should not send the block to the wallet. Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinbaseTo); ...
public static ObjectMapper createObjectMapper() { final ObjectMapper objectMapper = new ObjectMapper(); registerModules(objectMapper); return objectMapper; }
@Test void testObjectMapperOptionalSupportedEnabled() throws Exception { final ObjectMapper mapper = JacksonMapperFactory.createObjectMapper(); assertThat(mapper.writeValueAsString(new TypeWithOptional(Optional.of("value")))) .isEqualTo("{\"data\":\"value\"}"); assertThat(ma...
@Override public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { //if (!descriptor.equals("Lorg/pf4j/Extension;")) { if (!Type.getType(descriptor).getClassName().equals(Extension.class.getName())) { return super.visitAnnotation(descriptor, visible); } ...
@Test void visitAnnotationShouldReturnSuperVisitorForNonExtensionAnnotation() { ExtensionInfo extensionInfo = new ExtensionInfo("org.pf4j.asm.ExtensionInfo"); ClassVisitor extensionVisitor = new ExtensionVisitor(extensionInfo); AnnotationVisitor returnedVisitor = extensionVisitor.visitAnnot...
@Override public NacosRestTemplate createNacosRestTemplate() { HttpClientConfig httpClientConfig = buildHttpClientConfig(); final JdkHttpClientRequest clientRequest = new JdkHttpClientRequest(httpClientConfig); // enable ssl initTls((sslContext, hostnameVerifier) -> { ...
@Test void testCreateNacosRestTemplateWithSsl() throws Exception { TlsSystemConfig.tlsEnable = true; HttpClientFactory httpClientFactory = new DefaultHttpClientFactory(logger); NacosRestTemplate nacosRestTemplate = httpClientFactory.createNacosRestTemplate(); assertNotNull(nacosRestT...
static <T extends Comparable<? super T>> int compareListWithFillValue( List<T> left, List<T> right, T fillValue) { int longest = Math.max(left.size(), right.size()); for (int i = 0; i < longest; i++) { T leftElement = fillValue; T rightElement = fillValue; if (i < left.size()) { ...
@Test public void compareWithFillValue_nonEmptyListVariedSizeWithZeroFillValue_returnsNegative() { assertThat( ComparisonUtility.compareListWithFillValue( Lists.newArrayList(1, 2), Lists.newArrayList(1, 2, 3), 0)) .isLessThan(0); }
@Nonnull public static <K, V> Sink<Entry<K, V>> map(@Nonnull String mapName) { return map(mapName, Entry::getKey, Entry::getValue); }
@Test public void map_byName() { // Given List<Integer> input = sequence(itemCount); putToBatchSrcMap(input); // When Sink<Entry<String, Integer>> sink = Sinks.map(sinkName); // Then p.readFrom(Sources.<String, Integer>map(srcName)).writeTo(sink); ex...
@ApiOperation(value = "Make tenant profile default (setDefaultTenantProfile)", notes = "Makes specified tenant profile to be default. Referencing non-existing tenant profile Id will cause an error. " + SYSTEM_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('SYS_ADMIN')") @RequestMapping(value = ...
@Test public void testSetDefaultTenantProfile() throws Exception { loginSysAdmin(); TenantProfile tenantProfile = this.createTenantProfile("Tenant Profile 1"); TenantProfile savedTenantProfile = doPost("/api/tenantProfile", tenantProfile, TenantProfile.class); TenantProfile defaultTe...
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException { try { final StoregateApiClient client = session.getClient(); final MoveFileRequest move = new Mov...
@Test public void testMoveDirectory() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()), ...
@Override public MetadataReportConfig build() { MetadataReportConfig metadataReport = new MetadataReportConfig(); super.build(metadataReport); metadataReport.setAddress(address); metadataReport.setUsername(username); metadataReport.setPassword(password); metadataRepo...
@Test void build() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.address("address") .username("username") .password("password") .timeout(1000) .group("group") .retryTimes(1) .retr...
public WorkflowStartResponse toWorkflowStartResponse() { return WorkflowStartResponse.builder() .workflowId(this.workflowId) .workflowVersionId(this.workflowVersionId) .workflowInstanceId(this.workflowInstanceId) .workflowRunId(this.workflowRunId) .workflowUuid(this.workflowU...
@Test public void testToWorkflowStartResponse() { RunResponse res = RunResponse.from(stepInstance, TimelineLogEvent.info("bar")); WorkflowStartResponse response = res.toWorkflowStartResponse(); Assert.assertEquals(InstanceRunStatus.CREATED, response.getStatus()); res = RunResponse.from(instance, "foo"...
@Override public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { ensureWritable(length); setBytes(writerIndex, src, srcIndex, length); writerIndex += length; return this; }
@Test public void testWriteBytesAfterRelease3() { final ByteBuf buffer = buffer(8); try { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().writeBytes(buffer, 0, 1);...
@Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try { File pluginsFolder = new File(systemEnvironment.get(SystemEnvironment.AGENT_PLUGINS_PATH)); if (pluginsFolder.exists()) { FileUtils.forceDelete(pluginsFolder); }...
@Test void shouldHandleIOExceptionQuietly() throws Exception { doThrow(new IOException()).when(zipUtil).unzip(DownloadableFile.AGENT_PLUGINS.getLocalFile(), new File(SystemEnvironment.PLUGINS_PATH)); try { agentPluginsInitializer.onApplicationEvent(null); } catch (Exception e) { ...
protected VersionedElasticAgentExtension getVersionedElasticAgentExtension(String pluginId) { final String resolvedExtensionVersion = pluginManager.resolveExtensionVersion(pluginId, ELASTIC_AGENT_EXTENSION, goSupportedVersions()); return elasticAgentExtensionMap.get(resolvedExtensionVersion); }
@Test public void shouldHaveVersionedElasticAgentExtensionForAllSupportedVersions() { for (String supportedVersion : SUPPORTED_VERSIONS) { final String message = String.format("Must define versioned extension class for %s extension with version %s", ELASTIC_AGENT_EXTENSION, supportedVersion); ...
public void updateStatusCount(final String state, final int change) { updateStatusCount(KafkaStreams.State.valueOf(state), change); }
@Test public void shouldRoundTripWhenNotEmpty() { // Given: queryStatusCount.updateStatusCount(KafkaStreams.State.RUNNING, 2); queryStatusCount.updateStatusCount(KafkaStreams.State.ERROR, 10); queryStatusCount.updateStatusCount(KsqlQueryStatus.UNRESPONSIVE, 1); // When: final String json = as...
@Override public int compareTo(Bandwidth other) { if (other instanceof LongBandwidth) { return ComparisonChain.start() .compare(this.bps, ((LongBandwidth) other).bps) .result(); } return ComparisonChain.start() .compare(this...
@Test public void testLessThan() { assertThat(small, is(lessThan(big))); assertThat(small.compareTo(big), is(-1)); assertThat(big, is(greaterThan(small))); assertThat(big.compareTo(small), is(1)); assertThat(notLongSmall, is(lessThan(notLongBig))); assertThat(notLo...
@Override public <T> void register(Class<T> remoteInterface, T object) { register(remoteInterface, object, 1); }
@Test public void testAckWithoutResultInvocations() throws InterruptedException { RedissonClient server = createInstance(); RedissonClient client = createInstance(); try { server.getRemoteService().register(RemoteInterface.class, new RemoteImpl()); // fire and forget...
@VisibleForTesting static ParallelInstruction forParallelInstruction( ParallelInstruction input, boolean replaceWithByteArrayCoder) throws Exception { try { ParallelInstruction instruction = clone(input, ParallelInstruction.class); if (instruction.getRead() != null) { Source cloudSource ...
@Test public void testLengthPrefixReadInstructionCoder() throws Exception { ReadInstruction readInstruction = new ReadInstruction(); readInstruction.setSource( new Source() .setCodec(CloudObjects.asCloudObject(windowedValueCoder, /*sdkComponents=*/ null))); instruction.setRead(readInst...
@Operation(summary = "Get the status of a mijn digid session [VALID, INVALID]") @GetMapping("/session_status/{mijn_digid_session_id}") public ResponseEntity<MijnDigidSessionStatus> sessionStatus(@PathVariable(name = "mijn_digid_session_id") String mijnDigiDSessionId) { if(mijnDigiDSessionId == null) { ...
@Test void validateSessionStatus() { String sessionId = "id"; when(mijnDigiDSessionService.sessionStatus(sessionId)).thenReturn(MijnDigidSessionStatus.VALID); ResponseEntity<MijnDigidSessionStatus> response = mijnDigiDSessionController.sessionStatus(sessionId); verify(mijnDigiDSess...
public boolean isAllowed(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { if (!isRequestAllowed(httpRequest)) { LOG.debug("Forbidden access to monitoring from " + httpRequest.getRemoteAddr()); httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden access"); ...
@Test public void testIsAllowed() throws IOException { assertTrue("no auth", isAllowed()); setProperty(Parameter.ALLOWED_ADDR_PATTERN, REMOTE_ADDR); assertTrue("addr pattern", isAllowed()); setProperty(Parameter.ALLOWED_ADDR_PATTERN, "none"); assertFalse("addr pattern", isAllowed()); setProperty(Parameter....
@Override public Messages process(Messages messages) { try (Timer.Context ignored = executionTime.time()) { final State latestState = stateUpdater.getLatestState(); if (latestState.enableRuleMetrics()) { return process(messages, new RuleMetricsListener(metricRegistry)...
@Test public void testCreateMessage() { final RuleService ruleService = mock(MongoDbRuleService.class); when(ruleService.loadAll()).thenReturn(Collections.singleton( RuleDao.create("abc", "title", "description", ...
public NSBundle bundle() { if(cached != null) { return cached; } if(log.isInfoEnabled()) { log.info("Loading application bundle resources"); } final NSBundle main = NSBundle.mainBundle(); if(null == main) { cached = null; } ...
@Test public void testAccessDenied() { final NSBundle bundle = new BundleApplicationResourcesFinder().bundle(NSBundle.bundleWithPath("."), new Local("/usr/bin/java") { @Override public Local getSymlinkTarget() throws NotfoundException { throw new NotfoundException("f"...
public long decrementAndGet() { return getAndAddVal(-1L) - 1L; }
@Test public void testDecrementAndGet() { PaddedAtomicLong counter = new PaddedAtomicLong(); long value = counter.decrementAndGet(); assertEquals(-1, value); assertEquals(-1, counter.get()); }
public StatementExecutorResponse execute( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext executionContext, final KsqlSecurityContext securityContext ) { final String commandRunnerWarningString = commandRunnerWarning.get(); if (!commandRunnerWarningString...
@Test public void shouldThrowExceptionWhenInsertIntoUnknownStream() { // Given final PreparedStatement<Statement> preparedStatement = PreparedStatement.of("", new InsertInto(SourceName.of("s1"), mock(Query.class))); final ConfiguredStatement<Statement> configured = ConfiguredStatement.of(p...
@Override public void deleteTopics(final Collection<String> topicsToDelete) { if (topicsToDelete.isEmpty()) { return; } final DeleteTopicsResult deleteTopicsResult = adminClient.get().deleteTopics(topicsToDelete); final Map<String, KafkaFuture<Void>> results = deleteTopicsResult.topicNameValues...
@Test @SuppressWarnings("unchecked") public void shouldFailToDeleteOnKafkaDeleteTopicsException() { // Given: when(adminClient.deleteTopics(any(Collection.class))) .thenAnswer(deleteTopicsResult(new Exception("error"))); // When: assertThrows( KafkaDeleteTopicsException.class, ...
public void replace(String name, String token, String value) { name = name.trim(); Variable v = vars.get(name); if (v == null) { throw new RuntimeException("no variable found with name: " + name); } String text = v.getAsString(); String replaced = replacePlace...
@Test void testReplace() { assign("foo", "'hello <world>'"); engine.replace("foo", "world", "'blah'"); matchEquals("foo", "'hello blah'"); assign("str", "'ha <foo> ha'"); Json json = Json.of("[{token: 'foo', value: \"'bar'\" }]"); engine.replaceTable("str", json.asLis...
public CMap parse(RandomAccessRead randomAcccessRead) throws IOException { CMap result = new CMap(); Object previousToken = null; Object token = parseNextToken(randomAcccessRead); while (token != null) { if (token instanceof Operator) { ...
@Test void testParserWithMalformedbfrange2() throws IOException { CMap cMap = new CMapParser() .parse(new RandomAccessReadBufferedFile( new File("src/test/resources/cmap", "CMapMalformedbfrange2"))); assertNotNull(cMap, "Failed to parse malformed CMap fil...
@GET @Path("{path:.*}") @Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8}) public Response get(@PathParam("path") String path, @Context UriInfo uriInfo, @QueryParam(OperationParam.NAME) O...
@Test @TestDir @TestJetty @TestHdfs public void testAccess() throws Exception { createHttpFSServer(false, false); final String dir = "/xattrTest"; Path path1 = new Path(dir); DistributedFileSystem dfs = (DistributedFileSystem) FileSystem .get(path1.toUri(), TestHdfsHelper.getHdfsConf())...
public static Number parseNumber(String numberStr) throws NumberFormatException { if (StrUtil.startWithIgnoreCase(numberStr, "0x")) { // 0x04表示16进制数 return Long.parseLong(numberStr.substring(2), 16); } else if (StrUtil.startWith(numberStr, '+')) { // issue#I79VS7 numberStr = StrUtil.subSuf(numberStr, 1)...
@Test public void parseNumberTest2(){ // issue#I5M55F final String numberStr = "429900013E20220812163344551"; final Number number = NumberUtil.parseNumber(numberStr); assertNotNull(number); assertInstanceOf(BigDecimal.class, number); }
void addTo(EnvironmentVariableContext context) { context.setProperty(name, getValue(), isSecure()); }
@Test void shouldAddPlainTextEnvironmentVariableToContext() { String key = "key"; String plainText = "plainText"; EnvironmentVariableConfig environmentVariableConfig = new EnvironmentVariableConfig(goCipher, key, plainText, false); EnvironmentVariableContext context = new Environment...
@VisibleForTesting Map<String, List<Operation>> computeOperations(SegmentDirectory.Reader segmentReader) throws Exception { Map<String, List<Operation>> columnOperationsMap = new HashMap<>(); // Does not work for segment versions < V3. if (_segmentDirectory.getSegmentMetadata().getVersion().compare...
@Test public void testComputeOperationEnableForwardIndex() throws Exception { // Setup SegmentMetadataImpl existingSegmentMetadata = new SegmentMetadataImpl(_segmentDirectory); SegmentDirectory segmentLocalFSDirectory = new SegmentLocalFSDirectory(_segmentDirectory, existingSegmentMetadata, ...
@SafeVarargs public static <E> Set<E> intersection(final Supplier<Set<E>> constructor, final Set<E> first, final Set<E>... set) { final Set<E> result = constructor.get(); result.addAll(first); for (final Set<E> s : set) { result.retainAll(s); } return result; ...
@Test public void testIntersection() { final Set<String> oneSet = mkSet("a", "b", "c"); final Set<String> anotherSet = mkSet("c", "d", "e"); final Set<String> intersection = intersection(TreeSet::new, oneSet, anotherSet); assertEquals(mkSet("c"), intersection); assertEquals(...
public static String unsplit(Object[] splittee, Object splitChar) { StringBuilder retVal = new StringBuilder(); int count = -1; while (++count < splittee.length) { if (splittee[count] != null) { retVal.append(splittee[count]); } if (count + 1 <...
@Test public void testUnsplit() { assertEquals("", JOrphanUtils.unsplit(new Object[]{null, null}, 0)); assertEquals("11", JOrphanUtils.unsplit(new Object[]{null, 1}, 1)); assertEquals("-26738698", JOrphanUtils.unsplit(new Object[]{-26_738_698}, 1)); }
@VisibleForTesting public static Properties buildSyncConfig(Configuration conf) { TypedProperties props = StreamerUtil.flinkConf2TypedProperties(conf); props.setPropertyIfNonNull(META_SYNC_BASE_PATH.key(), conf.getString(FlinkOptions.PATH)); props.setPropertyIfNonNull(META_SYNC_BASE_FILE_FORMAT.key(), con...
@Test void testOptionWithoutShortcutKey() { Configuration configuration3 = new Configuration(); configuration3.setBoolean(HiveSyncConfig.HIVE_CREATE_MANAGED_TABLE.key(), true); Properties props3 = HiveSyncContext.buildSyncConfig(configuration3); assertTrue(Boolean.parseBoolean(props3.getProperty(HiveS...
@Override public Float getFloat(K name) { return null; }
@Test public void testGetFloatDefault() { assertEquals(1, HEADERS.getFloat("name1", 1), 0); }
public static Row of( final LogicalSchema schema, final GenericKey key, final GenericRow value, final long rowTime ) { return new Row(schema, key, value, rowTime, TableRowValidation::validate); }
@SuppressWarnings("UnstableApiUsage") @Test public void shouldImplementEquals() { final LogicalSchema differentSchema = LogicalSchema.builder() .keyColumn(ColumnName.of("k0"), SqlTypes.STRING) .keyColumn(ColumnName.of("k1"), SqlTypes.INTEGER) .valueColumn(ColumnName.of("diff0"), SqlTypes...
public long next() { long current = this.next; if (current < max) { this.next = Math.min(this.next * 2, this.max); } // Check for mandatory stop if (!mandatoryStopMade) { long now = clock.millis(); long timeElapsedSinceFirstBackoff = 0; ...
@Test public void mandatoryStopTestNegativeTest() { Backoff backoff = new Backoff(100, TimeUnit.MILLISECONDS, 60, TimeUnit.SECONDS, 1900, TimeUnit.MILLISECONDS); assertEquals(backoff.next(), 100); backoff.next(); // 200 backoff.next(); // 400 backoff.next(); // 800 as...
public List<InputSplit> getSplits(JobContext job) throws IOException { StopWatch sw = new StopWatch().start(); long minSize = Math.max(getFormatMinSplitSize(), getMinSplitSize(job)); long maxSize = getMaxSplitSize(job); // generate splits List<InputSplit> splits = new ArrayList<InputSplit>(); L...
@Test public void testListLocatedStatus() throws Exception { Configuration conf = getConfiguration(); conf.setInt(FileInputFormat.LIST_STATUS_NUM_THREADS, numThreads); conf.setBoolean("fs.test.impl.disable.cache", false); conf.set(FileInputFormat.INPUT_DIR, "test:///a1/a2"); MockFileSystem mockFs ...
@Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } UpdateResponse that = (UpdateResponse) object; return _status == that._status; }
@Test(dataProvider = "testEqualsDataProvider") public void testEquals ( boolean shouldEquals, @Nonnull UpdateResponse updateResponse, @Nullable Object compareObject ) { assertEquals(updateResponse.equals(compareObject), shouldEquals); }
public DoubleArrayAsIterable usingExactEquality() { return new DoubleArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_containsExactly_primitiveDoubleArray_inOrder_success() { assertThat(array(1.1, 2.2, 3.3)) .usingExactEquality() .containsExactly(array(1.1, 2.2, 3.3)) .inOrder(); }
public static void w(String tag, String message, Object... args) { sLogger.w(tag, message, args); }
@Test public void warningWithThrowable() { String tag = "TestTag"; String message = "Test message"; Throwable t = new Throwable(); LogManager.w(t, tag, message); verify(logger).w(t, tag, message); }
@CanIgnoreReturnValue public final Ordered containsExactlyElementsIn(@Nullable Iterable<?> expected) { return containsExactlyElementsIn(expected, false); }
@Test @SuppressWarnings("ContainsExactlyElementsInWithVarArgsToExactly") public void iterableContainsExactlyElementsInWithOneIterableDoesNotGiveWarning() { expectFailureWhenTestingThat(asList(1, 2, 3, 4)).containsExactlyElementsIn(asList(1, 2, 3)); assertFailureValue("unexpected (1)", "4"); }
public static <T> CompressedSerializedValue<T> fromObject(T object) throws IOException { Preconditions.checkNotNull(object, "Value must not be null"); return new CompressedSerializedValue<>(object); }
@Test void testNullValue() { assertThatThrownBy(() -> CompressedSerializedValue.fromObject(null)) .isInstanceOf(NullPointerException.class); }
public static DateTime parseUTC(String utcString) { if (utcString == null) { return null; } final int length = utcString.length(); if (StrUtil.contains(utcString, 'Z')) { if (length == DatePattern.UTC_PATTERN.length() - 4) { // 格式类似:2018-09-13T05:34:31Z,-4表示减去4个单引号的长度 return parse(utcString, DateP...
@Test public void parseUTCTest2() { // issue1503@Github // 检查不同毫秒长度都可以正常匹配 String utcTime = "2021-03-30T12:56:51.3Z"; DateTime parse = DateUtil.parseUTC(utcTime); assertEquals("2021-03-30 12:56:51", parse.toString()); utcTime = "2021-03-30T12:56:51.34Z"; parse = DateUtil.parseUTC(utcTime); assertEqual...
protected GelfMessage toGELFMessage(final Message message) { final DateTime timestamp; final Object fieldTimeStamp = message.getField(Message.FIELD_TIMESTAMP); if (fieldTimeStamp instanceof DateTime) { timestamp = (DateTime) fieldTimeStamp; } else { timestamp = To...
@Test public void testToGELFMessageWithNullLevel() throws Exception { final GelfTransport transport = mock(GelfTransport.class); final GelfOutput gelfOutput = new GelfOutput(transport); final DateTime now = DateTime.now(DateTimeZone.UTC); final Message message = messageFactory.create...
public static void checkGreaterOrEqual( long value1, String value1Name, long value2, String value2Name) { checkArgument( value1 >= value2, "'%s' (%s) must be greater than or equal to '%s' (%s).", value1Name, value1, value2Name, value2); }
@Test public void testCheckGreaterOrEqual() throws Exception { // Should not throw. Validate.checkGreaterOrEqual(10, "arg1", 5, "arg2"); // Verify it throws. intercept(IllegalArgumentException.class, "'arg1' (5) must be greater than or equal to 'arg2' (10)", () -> Validate.checkGreat...
@GetMapping("") public AdminResult<CommonPager<SelectorVO>> querySelectors(final String pluginId, final String name, @RequestParam @NotNull final Integer currentPage, @RequestParam @NotNull ...
@Test public void querySelectors() throws Exception { given(this.selectorService.searchByPageToPager(any())).willReturn(commonPager); String urlTemplate = "/selector?pluginId={pluginId}&name={name}&currentPage={currentPage}&pageSize={pageSize}"; this.mockMvc.perform(MockMvcRequestBuilders.ge...
public <T extends Tuple> DataSource<T> tupleType(Class<T> targetType) { Preconditions.checkNotNull(targetType, "The target type class must not be null."); if (!Tuple.class.isAssignableFrom(targetType)) { throw new IllegalArgumentException( "The target type must be a subcl...
@Test void testSubClass() { CsvReader reader = getCsvReader(); DataSource<SubItem> sitems = reader.tupleType(SubItem.class); TypeInformation<?> info = sitems.getType(); assertThat(info.isTupleType()).isTrue(); assertThat(info.getTypeClass()).isEqualTo(SubItem.class); ...
public NodeModel pathEnd(NodeModel commonAncestor) { return relativeNode(commonAncestor, endPath, endPath.length); }
@Test public void zeroLevelEnd(){ final NodeModel parent = root(); final NodeRelativePath nodeRelativePath = new NodeRelativePath(parent, parent); final NodeModel startingPoint = new NodeModel("startingPoint", map); assertThat(nodeRelativePath.pathEnd(startingPoint), equalTo(startingPoint)); }
String createPermalink(SinglePage page) { var permalink = encodePath(page.getSpec().getSlug(), UTF_8); permalink = StringUtils.prependIfMissing(permalink, "/"); return externalUrlSupplier.get().resolve(permalink).normalize().toString(); }
@Test void createPermalink() { SinglePage page = pageV1(); page.getSpec().setSlug("page-slug"); when(externalUrlSupplier.get()).thenReturn(URI.create("")); String permalink = singlePageReconciler.createPermalink(page); assertThat(permalink).isEqualTo("/page-slug"); ...
@Override public List<MultipartUpload> find(final Path file) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("Finding multipart uploads for %s", file)); } final List<MultipartUpload> uploads = new ArrayList<>(); // This operation lists in-p...
@Test public void testFindNotFound() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final List<MultipartUplo...
@Override public void generateError(Response response) throws IOException { final JsonNode errorNode; try { errorNode = OAuth2AccessTokenJsonExtractor.OBJECT_MAPPER.readTree(response.getBody()).get("errors").get(0); } catch (JsonProcessingException ex) { throw new OAu...
@Test public void testErrorExtraction() throws IOException { final FitBitJsonTokenExtractor extractor = new FitBitJsonTokenExtractor(); final OAuth2AccessTokenErrorResponse thrown = assertThrows(OAuth2AccessTokenErrorResponse.class, new ThrowingRunnable() { @Override ...
public final TypeRef<? extends T> getSubtype(Class<?> subclass) { if (type instanceof WildcardType) { Type[] lowerBounds = ((WildcardType) type).getLowerBounds(); if (lowerBounds.length > 0) { TypeRef<? extends T> bound = of(lowerBounds[0]); // Java supports only one lowerbound anyway. ...
@Test public void testGetSubtype() { // For issue: https://github.com/apache/fury/issues/1604 TypeRef<? extends Map<String, Object>> typeRef = TypeUtils.mapOf(MapObject.class, String.class, Object.class); assertEquals(typeRef, TypeRef.of(MapObject.class)); assertEquals( TypeUtils.mapOf...