focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Mono<Void> execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) { ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT); assert shenyuContext != null; return writerMap.get(shenyuContext.getRpcType()).writeWith(exchange, chain); }
@Test public void testExecute() { ServerWebExchange httpExchange = generateServerWebExchange(RpcTypeEnum.HTTP.getName()); StepVerifier.create(responsePlugin.execute(httpExchange, chain)).expectSubscription().verifyComplete(); ServerWebExchange springCloudExchange = generateServerWebExchange(RpcTypeEnum.SPRING_CLOUD.getName()); StepVerifier.create(responsePlugin.execute(springCloudExchange, chain)).expectSubscription().verifyComplete(); ServerWebExchange dubboExchange = generateServerWebExchange(RpcTypeEnum.DUBBO.getName()); StepVerifier.create(responsePlugin.execute(dubboExchange, chain)).expectSubscription().verifyComplete(); ServerWebExchange sofaExchange = generateServerWebExchange(RpcTypeEnum.SOFA.getName()); StepVerifier.create(responsePlugin.execute(sofaExchange, chain)).expectSubscription().verifyComplete(); ServerWebExchange grpcExchange = generateServerWebExchange(RpcTypeEnum.GRPC.getName()); StepVerifier.create(responsePlugin.execute(grpcExchange, chain)).expectSubscription().verifyComplete(); ServerWebExchange motanExchange = generateServerWebExchange(RpcTypeEnum.MOTAN.getName()); StepVerifier.create(responsePlugin.execute(motanExchange, chain)).expectSubscription().verifyComplete(); ServerWebExchange tarsExchange = generateServerWebExchange(RpcTypeEnum.TARS.getName()); StepVerifier.create(responsePlugin.execute(tarsExchange, chain)).expectSubscription().verifyComplete(); }
public IndexingResults bulkIndex(final List<MessageWithIndex> messageList) { return bulkIndex(messageList, false, null); }
@Test public void bulkIndexingShouldNotDoAnythingForEmptyList() throws Exception { final IndexingResults indexingResults = messages.bulkIndex(Collections.emptyList()); assertThat(indexingResults).isNotNull(); assertThat(indexingResults.allResults()).isEmpty(); verify(messagesAdapter, never()).bulkIndex(any()); }
public static String toJson(UpdateRequirement updateRequirement) { return toJson(updateRequirement, false); }
@Test public void testAssertDefaultSortOrderIdToJson() { String requirementType = UpdateRequirementParser.ASSERT_DEFAULT_SORT_ORDER_ID; int sortOrderId = 10; String expected = String.format( "{\"type\":\"%s\",\"default-sort-order-id\":%d}", requirementType, sortOrderId); UpdateRequirement actual = new UpdateRequirement.AssertDefaultSortOrderID(sortOrderId); assertThat(UpdateRequirementParser.toJson(actual)) .as("AssertDefaultSortOrderId should convert to the correct JSON value") .isEqualTo(expected); }
@Override public RFuture<Boolean> addAsync(V value) { CompletableFuture<Boolean> f = CompletableFuture.supplyAsync(() -> add(value), getServiceManager().getExecutor()); return new CompletableFutureWrapper<>(f); }
@Test public void testAddAsync() throws InterruptedException, ExecutionException { RSortedSet<Integer> set = redisson.getSortedSet("simple"); RFuture<Boolean> future = set.addAsync(2); Assertions.assertTrue(future.get()); Assertions.assertTrue(set.contains(2)); }
@Override public boolean wasNull() throws SQLException { return mergedResult.wasNull(); }
@Test void assertWasNull() throws SQLException { assertFalse(new EncryptMergedResult(database, encryptRule, selectStatementContext, mergedResult).wasNull()); }
void addFunction(final T function) { final List<ParameterInfo> parameters = function.parameterInfo(); if (allFunctions.put(function.parameters(), function) != null) { throw new KsqlFunctionException( "Can't add function " + function.name() + " with parameters " + function.parameters() + " as a function with the same name and parameter types already exists " + allFunctions.get(function.parameters()) ); } /* Build the tree for non-variadic functions, or build the tree that includes one variadic argument for variadic functions. */ final Pair<Node, Integer> variadicParentAndOffset = buildTree( root, parameters, function, false, false ); final Node variadicParent = variadicParentAndOffset.getLeft(); if (variadicParent != null) { final int offset = variadicParentAndOffset.getRight(); // Build a branch of the tree that handles var args given as list. buildTree(variadicParent, parameters, function, true, false); // Determine which side the variadic parameter is on. final boolean isLeftVariadic = parameters.get(offset).isVariadic(); /* Build a branch of the tree that handles no var args by excluding the variadic param. Note that non-variadic parameters that are always paired with another non-variadic parameter are not included in paramsWithoutVariadic. For example, if the function signature is (int, boolean..., double, bigint, decimal), then paramsWithoutVariadic will be [double, bigint]. The (int, decimal) edge will be in a node above the variadicParent, so we need to only include parameters that might be paired with a variadic parameter. */ final List<ParameterInfo> paramsWithoutVariadic = isLeftVariadic ? parameters.subList(offset + 1, parameters.size() - offset) : parameters.subList(offset, parameters.size() - offset - 1); buildTree( variadicParent, paramsWithoutVariadic, function, false, false ); // Build branches of the tree that handles more than two var args. final ParameterInfo variadicParam = isLeftVariadic ? parameters.get(offset) : parameters.get(parameters.size() - offset - 1); // Create copies of the variadic parameter that will be used to build the tree. final int maxAddedVariadics = paramsWithoutVariadic.size() + 1; final List<ParameterInfo> addedVariadics = Collections.nCopies( maxAddedVariadics, variadicParam ); // Add the copies of the variadic parameter on the same side as the variadic parameter. final List<ParameterInfo> combinedAllParams = new ArrayList<>(); int fromIndex; int toIndex; if (isLeftVariadic) { combinedAllParams.addAll(addedVariadics); combinedAllParams.addAll(paramsWithoutVariadic); fromIndex = maxAddedVariadics - 1; toIndex = combinedAllParams.size(); } else { combinedAllParams.addAll(paramsWithoutVariadic); combinedAllParams.addAll(addedVariadics); fromIndex = 0; toIndex = combinedAllParams.size() - maxAddedVariadics + 1; } /* Successively build branches of the tree that include one additional variadic parameter until maxAddedVariadics have been processed. During the first iteration, buildTree() iterates through the already-created branch for the case where there is one variadic parameter. This is necessary because the variadic loop was not added when that branch was built, but it needs to be added if there are no non-variadic parameters (i.e. paramsWithoutVariadic.size() == 0 and maxAddedVariadics == 1). The number of nodes added here is quadratic with respect to paramsWithoutVariadic.size(). However, this tree is only built on ksql startup, and this tree structure allows resolving functions with variadic arguments in the middle in linear time. The number of node generated as a function of paramsWithoutVariadic.size() is roughly 0.25x^2 + 1.5x + 3, which is not excessive for reasonable numbers of arguments. */ while (fromIndex >= 0 && toIndex <= combinedAllParams.size()) { buildTree( variadicParent, combinedAllParams.subList(fromIndex, toIndex), function, false, /* Add the variadic loop after longest branch to handle variadic parameters not paired with a non-variadic parameter. */ toIndex - fromIndex == combinedAllParams.size() ); // Increment the size of the sublist in the direction of the variadic parameters. if (isLeftVariadic) { fromIndex--; } else { toIndex++; } } } }
@Test public void shouldThrowOnAddIfFunctionWithSameNameAndParamsExists() { // Given: givenFunctions( function(EXPECTED, -1, DOUBLE) ); // When: final Exception e = assertThrows( KsqlFunctionException.class, () -> udfIndex.addFunction(function(EXPECTED, -1, DOUBLE)) ); // Then: assertThat(e.getMessage(), startsWith("Can't add function `expected` with parameters [DOUBLE] " + "as a function with the same name and parameter types already exists")); }
public static String[] getStackFrames(final Throwable throwable) { if (throwable == null) { return new String[0]; } return getStackFrames(getStackTrace(throwable)); }
@Test void testGetStackFrames() { String[] stackFrames = ExceptionUtils.getStackFrames(exception); Assertions.assertNotEquals(0, stackFrames.length); }
@Udf public Map<String, String> records(@UdfParameter final String jsonObj) { if (jsonObj == null) { return null; } final JsonNode node = UdfJsonMapper.parseJson(jsonObj); if (node.isMissingNode() || !node.isObject()) { return null; } final Map<String, String> ret = new HashMap<>(node.size()); node.fieldNames().forEachRemaining(k -> { final JsonNode value = node.get(k); if (value instanceof TextNode) { ret.put(k, value.textValue()); } else { ret.put(k, value.toString()); } }); return ret; }
@Test public void shouldReturnNullForNull() { assertNull(udf.records(null)); }
public static String formatExpression(final Expression expression) { return formatExpression(expression, FormatOptions.of(s -> false)); }
@Test public void shouldFormatNotExpression() { assertThat(ExpressionFormatter.formatExpression(new NotExpression(new LongLiteral(1))), equalTo("(NOT 1)")); }
@Override public NetconfDevice connectDevice(DeviceId deviceId) throws NetconfException { return connectDevice(deviceId, true); }
@Test public void testConnectDeviceNetConfig10() throws Exception { NetconfDevice fetchedDevice10 = ctrl.connectDevice(deviceConfig10Id); assertEquals("Incorrect device fetched - ip", fetchedDevice10.getDeviceInfo().ip().toString(), DEVICE_10_IP); assertEquals("Incorrect device fetched - port", fetchedDevice10.getDeviceInfo().port(), DEVICE_10_PORT); assertEquals("Incorrect device fetched - username", fetchedDevice10.getDeviceInfo().name(), DEVICE_10_USERNAME); assertEquals("Incorrect device fetched - password", fetchedDevice10.getDeviceInfo().password(), DEVICE_10_PASSWORD); assertEquals("Incorrect device fetched - connectTimeout", fetchedDevice10.getDeviceInfo().getConnectTimeoutSec().getAsInt(), DEVICE_10_CONNECT_TIMEOUT); assertEquals("Incorrect device fetched - replyTimeout", fetchedDevice10.getDeviceInfo().getReplyTimeoutSec().getAsInt(), DEVICE_10_REPLY_TIMEOUT); assertEquals("Incorrect device fetched - idleTimeout", fetchedDevice10.getDeviceInfo().getIdleTimeoutSec().getAsInt(), DEVICE_10_IDLE_TIMEOUT); assertEquals("Incorrect device fetched - sshClient", fetchedDevice10.getDeviceInfo().sshClientLib().get(), NetconfSshClientLib.APACHE_MINA); }
@Override public Properties loadProperties() { final Properties answer = new Properties(); final Config config = ConfigProvider.getConfig(); for (String name : config.getPropertyNames()) { try { if (isValidForActiveProfiles(name)) { answer.put(name, config.getValue(name, String.class)); } } catch (NoSuchElementException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to resolve property {} due to {}", name, e.getMessage()); } } } return answer; }
@Test public void testLoadFiltered() { PropertiesComponent pc = context.getPropertiesComponent(); Properties properties = pc.loadProperties(k -> k.matches("^start$|.*mock$|.*-profile.*")); Assertions.assertThat(properties).hasSize(4); Assertions.assertThat(properties.get("start")).isEqualTo("direct:start"); Assertions.assertThat(properties.get("my-mock")).isEqualTo("result"); Assertions.assertThat(properties.get("test-non-active-profile")).isNull(); Assertions.assertThat(properties.get("test-profile-a")).isEqualTo("Profile A"); Assertions.assertThat(properties.get("test-profile-b")).isEqualTo("Profile B"); }
@Override @Transactional(rollbackFor = Exception.class) public void updateCodegen(CodegenUpdateReqVO updateReqVO) { // 校验是否已经存在 if (codegenTableMapper.selectById(updateReqVO.getTable().getId()) == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } // 校验主表字段存在 if (Objects.equals(updateReqVO.getTable().getTemplateType(), CodegenTemplateTypeEnum.SUB.getType())) { if (codegenTableMapper.selectById(updateReqVO.getTable().getMasterTableId()) == null) { throw exception(CODEGEN_MASTER_TABLE_NOT_EXISTS, updateReqVO.getTable().getMasterTableId()); } if (CollUtil.findOne(updateReqVO.getColumns(), // 关联主表的字段不存在 column -> column.getId().equals(updateReqVO.getTable().getSubJoinColumnId())) == null) { throw exception(CODEGEN_SUB_COLUMN_NOT_EXISTS, updateReqVO.getTable().getSubJoinColumnId()); } } // 更新 table 表定义 CodegenTableDO updateTableObj = BeanUtils.toBean(updateReqVO.getTable(), CodegenTableDO.class); codegenTableMapper.updateById(updateTableObj); // 更新 column 字段定义 List<CodegenColumnDO> updateColumnObjs = BeanUtils.toBean(updateReqVO.getColumns(), CodegenColumnDO.class); updateColumnObjs.forEach(updateColumnObj -> codegenColumnMapper.updateById(updateColumnObj)); }
@Test public void testUpdateCodegen_sub_masterNotExists() { // mock 数据 CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setTemplateType(CodegenTemplateTypeEnum.SUB.getType()) .setScene(CodegenSceneEnum.ADMIN.getScene())); codegenTableMapper.insert(table); // 准备参数 CodegenUpdateReqVO updateReqVO = randomPojo(CodegenUpdateReqVO.class, o -> o.getTable().setId(table.getId()) .setTemplateType(CodegenTemplateTypeEnum.SUB.getType())); // 调用,并断言 assertServiceException(() -> codegenService.updateCodegen(updateReqVO), CODEGEN_MASTER_TABLE_NOT_EXISTS, updateReqVO.getTable().getMasterTableId()); }
@Nonnull public Results search(@Nonnull Workspace workspace, @Nonnull Query query) { return search(workspace, Collections.singletonList(query)); }
@Test void testEmpty() { Results results = searchService.search(EmptyWorkspace.get(), new Query() { // empty query }); assertTrue(results.isEmpty(), "No results should be found in an empty workspace"); }
public static UFreeIdent create(CharSequence identifier) { return new AutoValue_UFreeIdent(StringName.of(identifier)); }
@Test public void serialization() { SerializableTester.reserializeAndAssert(UFreeIdent.create("foo")); }
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) { if (targetClass != null && targetClass != method.getDeclaringClass() && isOverridable(method, targetClass)) { try { if (Modifier.isPublic(method.getModifiers())) { try { return targetClass.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException ex) { return method; } } else { return method; } } catch (SecurityException ex) { // Security settings are disallowing reflective access; fall back to 'method' below. } } return method; }
@Test public void testGetMostSpecificMethodWhichNotExistsInTargetClass() throws NoSuchMethodException { Method method = ArrayList.class.getDeclaredMethod("sort", Comparator.class); Method specificMethod = ClassUtils.getMostSpecificMethod(method, Map.class); assertEquals(ArrayList.class.getDeclaredMethod("sort", Comparator.class), specificMethod); }
@Override public YamlCDCJobConfiguration swapToYamlConfiguration(final CDCJobConfiguration data) { YamlCDCJobConfiguration result = new YamlCDCJobConfiguration(); result.setJobId(data.getJobId()); result.setDatabaseName(data.getDatabaseName()); result.setSchemaTableNames(data.getSchemaTableNames()); result.setFull(data.isFull()); result.setSourceDatabaseType(data.getSourceDatabaseType().getType()); result.setDataSourceConfiguration(dataSourceConfigSwapper.swapToYamlConfiguration(data.getDataSourceConfig())); result.setTablesFirstDataNodes(null == data.getTablesFirstDataNodes() ? null : data.getTablesFirstDataNodes().marshal()); List<String> jobShardingDataNodes = null == data.getJobShardingDataNodes() ? null : data.getJobShardingDataNodes().stream().map(JobDataNodeLine::marshal).collect(Collectors.toList()); result.setJobShardingDataNodes(jobShardingDataNodes); result.setDecodeWithTX(data.isDecodeWithTX()); result.setSinkConfig(swapToYamlSinkConfiguration(data.getSinkConfig())); result.setConcurrency(data.getConcurrency()); result.setRetryTimes(data.getRetryTimes()); return result; }
@Test void assertSwapToYamlConfig() { CDCJobConfiguration jobConfig = new CDCJobConfiguration("j0302p00007a8bf46da145dc155ba25c710b550220", "test_db", Arrays.asList("t_order", "t_order_item"), true, new MySQLDatabaseType(), null, null, null, true, new SinkConfiguration(CDCSinkType.SOCKET, new Properties()), 1, 1); YamlCDCJobConfiguration actual = new YamlCDCJobConfigurationSwapper().swapToYamlConfiguration(jobConfig); assertThat(actual.getJobId(), is("j0302p00007a8bf46da145dc155ba25c710b550220")); assertThat(actual.getDatabaseName(), is("test_db")); assertThat(actual.getSchemaTableNames(), is(Arrays.asList("t_order", "t_order_item"))); assertTrue(actual.isFull()); }
@Override public BytesInput getBytes() { // The Page Header should include: blockSizeInValues, numberOfMiniBlocks, totalValueCount if (deltaValuesToFlush != 0) { flushBlockBuffer(); } return BytesInput.concat( config.toBytesInput(), BytesInput.fromUnsignedVarInt(totalValueCount), BytesInput.fromZigZagVarLong(firstValue), BytesInput.from(baos)); }
@Test public void shouldSkipN() throws IOException { long[] data = new long[5 * blockSize + 1]; for (int i = 0; i < data.length; i++) { data[i] = i * 32; } writeData(data); reader = new DeltaBinaryPackingValuesReader(); reader.initFromPage(100, writer.getBytes().toInputStream()); int skipCount; for (int i = 0; i < data.length; i += skipCount + 1) { skipCount = (data.length - i) / 2; assertEquals(i * 32, reader.readLong()); reader.skip(skipCount); } }
public static HazelcastSqlOperatorTable instance() { return INSTANCE; }
@Test public void testOperandTypeChecker() { for (SqlOperator operator : HazelcastSqlOperatorTable.instance().getOperatorList()) { boolean valid = operator instanceof HazelcastOperandTypeCheckerAware || operator instanceof HazelcastTableFunction || operator instanceof HazelcastCaseOperator || operator == HazelcastSqlOperatorTable.ARGUMENT_ASSIGNMENT || operator == HazelcastSqlOperatorTable.DOT; assertTrue("Operator must implement one of classes from " + HazelcastFunction.class.getPackage().toString() + ": " + operator.getClass().getSimpleName(), valid); } }
public static List<?> convertToList(Schema schema, Object value) { return convertToArray(ARRAY_SELECTOR_SCHEMA, value); }
@Test public void shouldConvertIntegralTypesToDouble() { double thirdValue = Double.MAX_VALUE; List<?> list = Values.convertToList(Schema.STRING_SCHEMA, "[1, 2, " + thirdValue + "]"); assertEquals(3, list.size()); assertEquals(1, ((Number) list.get(0)).intValue()); assertEquals(2, ((Number) list.get(1)).intValue()); assertEquals(thirdValue, list.get(2)); }
@Override public V get() throws InterruptedException, ExecutionException { return peel().get(); }
@Test(expected = InterruptedException.class) public void get_interrupted() throws Exception { ScheduledFuture<Object> outer = createScheduledFutureMock(); ScheduledFuture<Object> inner = createScheduledFutureMock(); when(outer.get()).thenThrow(new InterruptedException()); when(inner.get()).thenReturn(2); new DelegatingScheduledFutureStripper<Object>(outer).get(); }
@Override public synchronized Response handle(Request req) { // note the [synchronized] if (corsEnabled && "OPTIONS".equals(req.getMethod())) { Response response = new Response(200); response.setHeader("Allow", ALLOWED_METHODS); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", ALLOWED_METHODS); List<String> requestHeaders = req.getHeaderValues("Access-Control-Request-Headers"); if (requestHeaders != null) { response.setHeader("Access-Control-Allow-Headers", requestHeaders); } return response; } if (prefix != null && req.getPath().startsWith(prefix)) { req.setPath(req.getPath().substring(prefix.length())); } // rare case when http-client is active within same jvm // snapshot existing thread-local to restore ScenarioEngine prevEngine = ScenarioEngine.get(); for (Map.Entry<Feature, ScenarioRuntime> entry : scenarioRuntimes.entrySet()) { Feature feature = entry.getKey(); ScenarioRuntime runtime = entry.getValue(); // important for graal to work properly Thread.currentThread().setContextClassLoader(runtime.featureRuntime.suite.classLoader); LOCAL_REQUEST.set(req); req.processBody(); ScenarioEngine engine = initEngine(runtime, globals, req); for (FeatureSection fs : feature.getSections()) { if (fs.isOutline()) { runtime.logger.warn("skipping scenario outline - {}:{}", feature, fs.getScenarioOutline().getLine()); break; } Scenario scenario = fs.getScenario(); if (isMatchingScenario(scenario, engine)) { Map<String, Object> configureHeaders; Variable response, responseStatus, responseHeaders, responseDelay; ScenarioActions actions = new ScenarioActions(engine); Result result = executeScenarioSteps(feature, runtime, scenario, actions); engine.mockAfterScenario(); configureHeaders = engine.mockConfigureHeaders(); response = engine.vars.remove(ScenarioEngine.RESPONSE); responseStatus = engine.vars.remove(ScenarioEngine.RESPONSE_STATUS); responseHeaders = engine.vars.remove(ScenarioEngine.RESPONSE_HEADERS); responseDelay = engine.vars.remove(RESPONSE_DELAY); globals.putAll(engine.shallowCloneVariables()); Response res = new Response(200); if (result.isFailed()) { response = new Variable(result.getError().getMessage()); responseStatus = new Variable(500); } else { if (corsEnabled) { res.setHeader("Access-Control-Allow-Origin", "*"); } res.setHeaders(configureHeaders); if (responseHeaders != null && responseHeaders.isMap()) { res.setHeaders(responseHeaders.getValue()); } if (responseDelay != null) { res.setDelay(responseDelay.getAsInt()); } } if (response != null && !response.isNull()) { res.setBody(response.getAsByteArray()); if (res.getContentType() == null) { ResourceType rt = ResourceType.fromObject(response.getValue()); if (rt != null) { res.setContentType(rt.contentType); } } } if (responseStatus != null) { res.setStatus(responseStatus.getAsInt()); } if (prevEngine != null) { ScenarioEngine.set(prevEngine); } if (mockInterceptor != null) { mockInterceptor.intercept(req, res, scenario); } return res; } } } logger.warn("no scenarios matched, returning 404: {}", req); // NOTE: not logging with engine.logger if (prevEngine != null) { ScenarioEngine.set(prevEngine); } return new Response(404); }
@Test void testPathParams() { background().scenario( "pathMatches('/hello/{name}')", "def response = 'hello ' + pathParams.name" ); request.path("/hello/john"); handle(); match(response.getBodyAsString(), "hello john"); }
@Override protected double maintain() { if ( ! nodeRepository().nodes().isWorking()) return 0.0; // Don't need to maintain spare capacity in dynamically provisioned zones; can provision more on demand. if (nodeRepository().zone().cloud().dynamicProvisioning()) return 1.0; NodeList allNodes = nodeRepository().nodes().list(); CapacityChecker capacityChecker = new CapacityChecker(allNodes); List<Node> overcommittedHosts = capacityChecker.findOvercommittedHosts(); metric.set(ConfigServerMetrics.OVERCOMMITTED_HOSTS.baseName(), overcommittedHosts.size(), null); retireOvercommitedHosts(allNodes, overcommittedHosts); boolean success = true; Optional<CapacityChecker.HostFailurePath> failurePath = capacityChecker.worstCaseHostLossLeadingToFailure(); if (failurePath.isPresent()) { int spareHostCapacity = failurePath.get().hostsCausingFailure.size() - 1; if (spareHostCapacity == 0) { List<Move> mitigation = findMitigation(failurePath.get()); if (execute(mitigation, failurePath.get())) { // We succeeded or are in the process of taking a step to mitigate. // Report with the assumption this will eventually succeed to avoid alerting before we're stuck spareHostCapacity++; } else { success = false; } } metric.set(ConfigServerMetrics.SPARE_HOST_CAPACITY.baseName(), spareHostCapacity, null); } return success ? 1.0 : 0.0; }
@Test public void testAllWorksAsSpares() { var tester = new SpareCapacityMaintainerTester(); tester.addHosts(4, new NodeResources(10, 100, 1000, 1)); tester.addNodes(0, 2, new NodeResources(5, 50, 500, 0.5), 0); tester.addNodes(1, 2, new NodeResources(5, 50, 500, 0.5), 2); tester.maintainer.maintain(); assertEquals(0, tester.deployer.activations); assertEquals(0, tester.nodeRepository.nodes().list().retired().size()); assertEquals(2, tester.metric.values.get("spareHostCapacity")); }
public B metadataReportConfig(MetadataReportConfig metadataReportConfig) { this.metadataReportConfig = metadataReportConfig; return getThis(); }
@Test void metadataReportConfig() { MetadataReportConfig metadataReportConfig = new MetadataReportConfig(); InterfaceBuilder builder = new InterfaceBuilder(); builder.metadataReportConfig(metadataReportConfig); Assertions.assertEquals(metadataReportConfig, builder.build().getMetadataReportConfig()); }
public ImmutableMap<String, Object> readAttributes(File file, String attributes) { String view = getViewName(attributes); List<String> attrs = getAttributeNames(attributes); if (attrs.size() > 1 && attrs.contains(ALL_ATTRIBUTES)) { // attrs contains * and other attributes throw new IllegalArgumentException("invalid attributes: " + attributes); } Map<String, Object> result = new HashMap<>(); if (attrs.size() == 1 && attrs.contains(ALL_ATTRIBUTES)) { // for 'view:*' format, get all keys for all providers for the view AttributeProvider provider = providersByName.get(view); readAll(file, provider, result); for (String inheritedView : provider.inherits()) { AttributeProvider inheritedProvider = providersByName.get(inheritedView); readAll(file, inheritedProvider, result); } } else { // for 'view:attr1,attr2,etc' for (String attr : attrs) { result.put(attr, getAttribute(file, view, attr)); } } return ImmutableMap.copyOf(result); }
@Test public void testReadAttributes_asMap_failsForInvalidAttributes() { File file = createFile(); try { service.readAttributes(file, "basic:fileKey,isOther,*,creationTime"); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage()).contains("invalid attributes"); } try { service.readAttributes(file, "basic:fileKey,isOther,foo"); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage()).contains("invalid attribute"); } }
@Override public void processInitState(OpenstackNode osNode) { if (!isOvsdbConnected(osNode, ovsdbPortNum, ovsdbController, deviceService)) { ovsdbController.connect(osNode.managementIp(), tpPort(ovsdbPortNum)); return; } if (!deviceService.isAvailable(osNode.intgBridge())) { createBridge(osNode, INTEGRATION_BRIDGE, osNode.intgBridge()); } if (hasDpdkTunnelBridge(osNode)) { createDpdkTunnelBridge(osNode); } }
@Test public void testComputeNodeProcessNodeInitState() { testNodeManager.createNode(COMPUTE_1); TEST_DEVICE_SERVICE.devMap.put(COMPUTE_1_OVSDB_DEVICE.id(), COMPUTE_1_OVSDB_DEVICE); assertEquals(ERR_STATE_NOT_MATCH, INIT, testNodeManager.node(COMPUTE_1_HOSTNAME).state()); target.processInitState(COMPUTE_1); assertEquals(ERR_STATE_NOT_MATCH, DEVICE_CREATED, testNodeManager.node(COMPUTE_1_HOSTNAME).state()); }
public static final StartTime relative(Duration relativeStart) { return new StartTime(StartTimeOption.RELATIVE, relativeStart, null); }
@Test public void testStartRelative() { StartTime st = StartTime.relative(Duration.ofMinutes(20)); assertEquals(StartTimeOption.RELATIVE, st.option()); assertEquals(20 * 60, st.relativeTime().getSeconds()); assertNull(st.absoluteTime()); }
public static String getUniqueSlotName(final Connection connection, final String slotNameSuffix) throws SQLException { String slotName = DigestUtils.md5Hex(String.join("_", connection.getCatalog(), slotNameSuffix).getBytes()); return String.format("%s_%s", SLOT_NAME_PREFIX, slotName); }
@Test void assertGetUniqueSlotName() throws SQLException { Connection connection = mock(Connection.class); when(connection.getCatalog()).thenReturn("foo_catalog"); assertThat(PostgreSQLSlotNameGenerator.getUniqueSlotName(connection, "foo_slot"), is("pipeline_9a2b4a79ce8b4fca2835b1e947c446eb")); }
@PostMapping(value = "/listener") public void listener(final HttpServletRequest request, final HttpServletResponse response) { longPollingListener.doLongPolling(request, response); }
@Test public void testListener() throws Exception { // Run the test final MockHttpServletResponse response = mockMvc.perform(post("/configs/listener") .accept(MediaType.APPLICATION_JSON)) .andReturn().getResponse(); // Verify the results assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); verify(mockLongPollingListener).doLongPolling(any(HttpServletRequest.class), any(HttpServletResponse.class)); }
@Override public Buffer.DataType peekNextToConsumeDataType( int nextBufferToConsume, Collection<Buffer> buffersToRecycle) { Buffer.DataType dataType = Buffer.DataType.NONE; try { dataType = checkAndGetFirstBufferIndexOrError(nextBufferToConsume, buffersToRecycle) .map(BufferIndexOrError::getDataType) .orElse(Buffer.DataType.NONE); } catch (Throwable throwable) { ExceptionUtils.rethrow(throwable); } return dataType; }
@Test void testPeekNextToConsumeDataType() throws Throwable { TestingSubpartitionConsumerInternalOperation viewNotifier = new TestingSubpartitionConsumerInternalOperation(); HsSubpartitionFileReaderImpl subpartitionFileReader = createSubpartitionFileReader(0, viewNotifier); // if no preload data in file reader, return DataType.NONE. assertThat(subpartitionFileReader.peekNextToConsumeDataType(0, new ArrayList<>())) .isEqualTo(DataType.NONE); // buffers in file: (0-0, 0-1, 0-2) writeDataToFile(0, 0, 3); Queue<MemorySegment> memorySegments = createsMemorySegments(3); subpartitionFileReader.prepareForScheduling(); // trigger reading, add buffer to queue. subpartitionFileReader.readBuffers(memorySegments, (ignore) -> {}); // if nextBufferToConsume is equal to peek elements index, return the real DataType. assertThat(subpartitionFileReader.peekNextToConsumeDataType(0, Collections.emptyList())) .isEqualTo(DataType.DATA_BUFFER); // if nextBufferToConsume is greater than peek elements index, skip this buffer and keep // looking. assertThat(subpartitionFileReader.peekNextToConsumeDataType(2, new ArrayList<>())) .isEqualTo(DataType.EVENT_BUFFER); // if nextBufferToConsume is less than peek elements index, return DataType.NONE. assertThat(subpartitionFileReader.peekNextToConsumeDataType(1, Collections.emptyList())) .isEqualTo(DataType.NONE); }
public void insertSiblingAfter(PDOutlineItem newSibling) { requireSingleNode(newSibling); PDOutlineNode parent = getParent(); newSibling.setParent(parent); PDOutlineItem next = getNextSibling(); setNextSibling(newSibling); newSibling.setPreviousSibling(this); if (next != null) { newSibling.setNextSibling(next); next.setPreviousSibling(newSibling); } else if (parent != null) { getParent().setLastChild(newSibling); } updateParentOpenCountForAddedChild(newSibling); }
@Test void cannotInsertSiblingAfterAList() { PDOutlineItem child = new PDOutlineItem(); child.insertSiblingAfter(new PDOutlineItem()); child.insertSiblingAfter(new PDOutlineItem()); assertThrows(IllegalArgumentException.class, () -> root.insertSiblingAfter(child)); }
public static LatLong fromString(String latLongString) { double[] coordinates = parseCoordinateString(latLongString, 2); return new LatLong(coordinates[0], coordinates[1]); }
@Test public void fromStringValidTest() { LatLong latLong = LatLongUtils.fromString(LATITUDE + DELIMITER + LONGITUDE); Assert.assertEquals(LATITUDE, latLong.latitude, 0); Assert.assertEquals(LONGITUDE, latLong.longitude, 0); }
public static org.apache.pinot.common.utils.regex.Matcher matcher(Pattern pattern, CharSequence input) { if (pattern instanceof Re2jPattern) { return new Re2jMatcher(pattern, input); } else { return new JavaUtilMatcher(pattern, input); } }
@Test public void testJavaUtilMatcherFactory() { JavaUtilPattern javaUtilPattern = new JavaUtilPattern("pattern"); Matcher matcher = MatcherFactory.matcher(javaUtilPattern, ""); Assert.assertTrue(matcher instanceof JavaUtilMatcher); }
@SuppressWarnings("unchecked") public static <T extends SpecificRecord> TypeInformation<Row> convertToTypeInfo( Class<T> avroClass) { return convertToTypeInfo(avroClass, true); }
@Test void testAvroClassConversion() { validateUserSchema(AvroSchemaConverter.convertToTypeInfo(User.class)); }
public JobStatsExtended enrich(JobStats jobStats) { JobStats latestJobStats = getLatestJobStats(jobStats, previousJobStats); if (lock.tryLock()) { setFirstRelevantJobStats(latestJobStats); setJobStatsExtended(latestJobStats); setPreviousJobStats(latestJobStats); lock.unlock(); } return jobStatsExtended; }
@Test void enrichGivenNoPreviousJobStatsAndWorkToDoEnqueuedAndProcessing() { JobStatsExtended extendedJobStats = jobStatsEnricher.enrich(getJobStats(1L, 1L, 0L, 0L)); assertThat(extendedJobStats.getAmountSucceeded()).isZero(); assertThat(extendedJobStats.getAmountFailed()).isZero(); assertThat(extendedJobStats.getEstimation().isProcessingDone()).isFalse(); assertThat(extendedJobStats.getEstimation().isEstimatedProcessingFinishedInstantAvailable()).isFalse(); }
String getFileName(double lat, double lon) { int lonInt = getMinLonForTile(lon); int latInt = getMinLatForTile(lat); return toLowerCase(getLatString(latInt) + getNorthString(latInt) + getLonString(lonInt) + getEastString(lonInt) + FILE_NAME_END); }
@Disabled @Test public void testGetEleHorizontalBorder() { // Border between the tiles 50n000e and 50n030e assertEquals("50n000e_20101117_gmted_mea075", instance.getFileName(53, 29.999999)); assertEquals(143, instance.getEle(53, 29.999999), precision); assertEquals("50n030e_20101117_gmted_mea075", instance.getFileName(53, 30.000001)); assertEquals(142, instance.getEle(53, 30.000001), precision); }
public boolean hasSameNameAs(Header header) { AssertParameter.notNull(header, Header.class); return this.name.equalsIgnoreCase(header.getName()); }
@Test public void header_does_not_have_same_name_as_expected() { final Header header1 = new Header("foo", "bar"); final Header header2 = new Header("bar", "baz"); assertThat(header2.hasSameNameAs(header1)).isFalse(); }
@Operation(description = "BSNKActivate retrieves a PIP based on a BSN") @PostMapping(value = "/bsnk_activate", consumes = "application/json", produces = "application/json") @ResponseBody public BsnkActivateResponse bsnkActivate(@Valid @RequestBody BsnkActivateRequest request) throws BsnkException { BsnkActivateResponse response = new BsnkActivateResponse(); response.setPip(bsnkService.bsnkActivate(request.getBsn())); response.setStatus("OK"); return response; }
@Test public void bsnkActivateResponseOkTest() throws BsnkException { BsnkActivateRequest request = new BsnkActivateRequest(); request.setBsn("PPPPPPPPP"); Mockito.when(bsnkActivateService.bsnkActivate(any())).thenReturn("pip"); BsnkActivateResponse result = controller.bsnkActivate(request); assertEquals("OK", result.getStatus()); assertEquals("pip", result.getPip()); }
@Override public int getTransactionTimeout() throws XAException { return delegate.getTransactionTimeout(); }
@Test void assertGetTransactionTimeout() throws XAException { singleXAResource.getTransactionTimeout(); verify(xaResource).getTransactionTimeout(); }
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) { GuardedByExpression expr = BINDER.visit(exp, context); checkGuardedBy(expr != null, String.valueOf(exp)); checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp); return expr; }
@Test public void inherited() { assertThat( bind( "Test", "slock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Super {", " final Object slock = new Object();", "}", "class Test extends Super {", "}"))) .isEqualTo("(SELECT (THIS) slock)"); }
public static long getPid() { return ProcessHandle.current().pid(); }
@Test public void testGetPid() { long legacyPidResult = getPidLegacy(); assumeThat(legacyPidResult).isNotEqualTo(-1); assertEquals(legacyPidResult, JVMUtil.getPid()); }
@Override public synchronized List<PrivilegedOperation> postComplete( ContainerId containerId) throws ResourceHandlerException { gpuAllocator.unassignGpus(containerId); cGroupsHandler.deleteCGroup(CGroupsHandler.CGroupController.DEVICES, containerId.toString()); return null; }
@Test public void testAllocationWhenDockerContainerEnabled() throws Exception { // When docker container is enabled, no devices should be written to // devices.deny. initializeGpus(); startContainerWithGpuRequestsDocker(1, 3); verifyDeniedDevices(getContainerId(1), Collections.emptyList()); /* Start container 2, asks 2 containers. Excepted to fail */ boolean failedToAllocate = false; try { startContainerWithGpuRequestsDocker(2, 2); } catch (ResourceHandlerException e) { failedToAllocate = true; } assertTrue("Container allocation is expected to fail!", failedToAllocate); startContainerWithGpuRequestsDocker(3, 1); verifyDeniedDevices(getContainerId(3), Collections.emptyList()); startContainerWithGpuRequestsDocker(4, 0); verifyDeniedDevices(getContainerId(4), Collections.emptyList()); gpuResourceHandler.postComplete(getContainerId(1)); verifyCgroupsDeletedForContainer(1); verifyNumberOfAvailableGpus(3, gpuResourceHandler); gpuResourceHandler.postComplete(getContainerId(3)); verifyCgroupsDeletedForContainer(3); verifyNumberOfAvailableGpus(4, gpuResourceHandler); }
@GwtIncompatible("java.util.regex.Pattern") public void doesNotContainMatch(@Nullable Pattern regex) { checkNotNull(regex); if (actual == null) { failWithActual("expected a string that does not contain a match for", regex); return; } Matcher matcher = regex.matcher(actual); if (matcher.find()) { failWithoutActual( fact("expected not to contain a match for", regex), fact("but contained", matcher.group()), fact("full string", actualCustomStringRepresentationForPackageMembersToCall())); } }
@Test @GwtIncompatible("Pattern") public void stringDoesNotContainMatchPatternFailNull() { expectFailureWhenTestingThat(null).doesNotContainMatch(Pattern.compile(".b.")); assertFailureValue("expected a string that does not contain a match for", ".b."); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof InboundPacket) { final DefaultInboundPacket other = (DefaultInboundPacket) obj; return Objects.equals(this.receivedFrom, other.receivedFrom) && Objects.equals(this.parsed, other.parsed) && Objects.equals(this.unparsed, other.unparsed); } return false; }
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(packet1, sameAsPacket1) .addEqualityGroup(packet2, sameAsPacket2) .testEquals(); }
public static NacosNamingServiceWrapper createNamingService(URL connectionURL) { boolean check = connectionURL.getParameter(NACOS_CHECK_KEY, true); int retryTimes = connectionURL.getPositiveParameter(NACOS_RETRY_KEY, 10); int sleepMsBetweenRetries = connectionURL.getPositiveParameter(NACOS_RETRY_WAIT_KEY, 10); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(connectionURL, check, retryTimes, sleepMsBetweenRetries); return new NacosNamingServiceWrapper(nacosConnectionManager, retryTimes, sleepMsBetweenRetries); }
@Test void testRetryCreate() throws NacosException { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") .addParameter("nacos.retry", 5) .addParameter("nacos.retry-wait", 10); Assertions.assertThrows( IllegalStateException.class, () -> NacosNamingServiceUtils.createNamingService(url)); try { NacosNamingServiceUtils.createNamingService(url); } catch (Throwable t) { Assertions.fail(t); } } }
public ModelReproduction<T> reproduceFromModel() throws ClassNotFoundException, JsonProcessingException { if(this.originalModel == null){ throw new IllegalStateException("No model to reproduce was provided"); } Model<T> newModel = reproduceFromProvenance(); TreeSet<String> newFeatureKeys = new TreeSet<>(newModel.getFeatureIDMap().keySet()); TreeSet<String> oldFeatureKeys = new TreeSet<>(originalModel.getFeatureIDMap().keySet()); TreeSet<String> intersectionOfKeys = new TreeSet<>(newModel.getFeatureIDMap().keySet()); intersectionOfKeys.retainAll(oldFeatureKeys); newFeatureKeys.removeAll(intersectionOfKeys); oldFeatureKeys.removeAll(intersectionOfKeys); Set<T> oldDomain = originalModel.getOutputIDInfo().generateMutableOutputInfo().getDomain(); Set<T> newDomain = newModel.getOutputIDInfo().generateMutableOutputInfo().getDomain(); Set<T> intersectionOfDomains = newModel.getOutputIDInfo().generateMutableOutputInfo().getDomain(); intersectionOfDomains.retainAll(oldDomain); newDomain.removeAll(intersectionOfDomains); oldDomain.removeAll(intersectionOfDomains); ModelReproduction<T> modelReproduction = new ModelReproduction<>( newModel, new FeatureDiff(oldFeatureKeys, newFeatureKeys), new OutputDiff<>(oldDomain, newDomain), ReproUtil.diffProvenance(newModel.getProvenance(), originalModel.getProvenance())); return modelReproduction; }
@Test public void testReproduceFromModel() throws IOException, URISyntaxException, ClassNotFoundException { CSVDataSource<Label> csvSource = getCSVDataSource(); MutableDataset<Label> datasetFromCSV = new MutableDataset<>(csvSource); LogisticRegressionTrainer trainer = new LogisticRegressionTrainer(); LinearSGDModel model = (LinearSGDModel) trainer.train(datasetFromCSV); model = (LinearSGDModel) trainer.train(datasetFromCSV); model = (LinearSGDModel) trainer.train(datasetFromCSV); ReproUtil<Label> reproUtil = new ReproUtil<>(model); ReproUtil.ModelReproduction<Label> modelReproduction = reproUtil.reproduceFromModel(); LinearSGDModel newModel = (LinearSGDModel) modelReproduction.model(); assertEquals(0, modelReproduction.featureDiff().reproducedFeatures().size()); assertEquals(0, modelReproduction.featureDiff().originalFeatures().size()); assertEquals(0, modelReproduction.outputDiff().reproducedOutput().size()); assertEquals(0, modelReproduction.outputDiff().originalOutput().size()); assertEquals(newModel.getWeightsCopy(), model.getWeightsCopy()); }
public int getAndAdvanceCurrentIndex() { int idx = this.getCurrentIndex(); this.advanceIndex(); return idx; }
@Test public void testDefaultPattern() { // Mux of size 1: 0 0 0 0 0, etc mux = new WeightedRoundRobinMultiplexer(1, "", new Configuration()); for(int i = 0; i < 10; i++) { assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); } // Mux of size 2: 0 0 1 0 0 1 0 0 1, etc mux = new WeightedRoundRobinMultiplexer(2, "", new Configuration()); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isOne(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isOne(); // Size 3: 4x0 2x1 1x2, etc mux = new WeightedRoundRobinMultiplexer(3, "", new Configuration()); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isOne(); assertThat(mux.getAndAdvanceCurrentIndex()).isOne(); assertThat(mux.getAndAdvanceCurrentIndex()).isEqualTo(2); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); // Size 4: 8x0 4x1 2x2 1x3 mux = new WeightedRoundRobinMultiplexer(4, "", new Configuration()); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); assertThat(mux.getAndAdvanceCurrentIndex()).isOne(); assertThat(mux.getAndAdvanceCurrentIndex()).isOne(); assertThat(mux.getAndAdvanceCurrentIndex()).isOne(); assertThat(mux.getAndAdvanceCurrentIndex()).isOne(); assertThat(mux.getAndAdvanceCurrentIndex()).isEqualTo(2); assertThat(mux.getAndAdvanceCurrentIndex()).isEqualTo(2); assertThat(mux.getAndAdvanceCurrentIndex()).isEqualTo(3); assertThat(mux.getAndAdvanceCurrentIndex()).isZero(); }
public static Entry entry(String name) throws BlockException { return Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0); }
@Test public void testMethodEntryType() throws BlockException, NoSuchMethodException, SecurityException { Method method = SphUTest.class.getMethod("testMethodEntryNormal"); Entry e = SphU.entry(method, EntryType.IN); assertSame(e.resourceWrapper.getEntryType(), EntryType.IN); e.exit(); }
@Override public boolean isControlBatch() { return (attributes() & CONTROL_FLAG_MASK) > 0; }
@Test public void testReadAndWriteControlBatch() { long producerId = 1L; short producerEpoch = 0; int coordinatorEpoch = 15; ByteBuffer buffer = ByteBuffer.allocate(128); MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, Compression.NONE, TimestampType.CREATE_TIME, 0L, RecordBatch.NO_TIMESTAMP, producerId, producerEpoch, RecordBatch.NO_SEQUENCE, true, true, RecordBatch.NO_PARTITION_LEADER_EPOCH, buffer.remaining()); EndTransactionMarker marker = new EndTransactionMarker(ControlRecordType.COMMIT, coordinatorEpoch); builder.appendEndTxnMarker(System.currentTimeMillis(), marker); MemoryRecords records = builder.build(); List<MutableRecordBatch> batches = TestUtils.toList(records.batches()); assertEquals(1, batches.size()); MutableRecordBatch batch = batches.get(0); assertTrue(batch.isControlBatch()); List<Record> logRecords = TestUtils.toList(records.records()); assertEquals(1, logRecords.size()); Record commitRecord = logRecords.get(0); assertEquals(marker, EndTransactionMarker.deserialize(commitRecord)); }
@Benchmark @Threads(16) public void testLargeBundleHarnessStateSampler(HarnessStateTracker state, Blackhole bh) throws Exception { state.tracker.start("processBundleId"); for (int i = 0; i < 1000; ) { state.state1.activate(); state.state2.activate(); state.state3.activate(); // trival code that is being sampled for this state i += 1; bh.consume(i); state.state3.deactivate(); state.state2.deactivate(); state.state1.deactivate(); } state.tracker.reset(); }
@Test public void testLargeBundleHarnessStateSampler() throws Exception { HarnessStateSampler state = new HarnessStateSampler(); HarnessStateTracker threadState = new HarnessStateTracker(); threadState.setup(state); new ExecutionStateSamplerBenchmark().testLargeBundleHarnessStateSampler(threadState, blackhole); state.tearDown(); threadState.tearDown(); }
public static Object applyLogicalType(Schema.Field field, Object value) { if (field == null || field.schema() == null) { return value; } Schema fieldSchema = resolveUnionSchema(field.schema()); return applySchemaTypeLogic(fieldSchema, value); }
@Test public void testApplyLogicalTypeReturnsSameValueWhenNotConversionForLogicalTypeIsKnown() { String value = "abc"; String schemaString = new StringBuilder().append("{").append(" \"type\": \"record\",").append(" \"name\": \"test\",") .append(" \"fields\": [{").append(" \"name\": \"column1\",").append(" \"type\": {") .append(" \"type\": \"bytes\",").append(" \"logicalType\": \"custom-type\"").append(" }") .append(" }]").append("}").toString(); Schema schema = new Schema.Parser().parse(schemaString); Object result = AvroSchemaUtil.applyLogicalType(schema.getField("column1"), value); Assert.assertSame(value, result); }
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "Version", getVersion()); setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel()); setAttribute(protobuf, NCLOC.getName(), statisticsSupport.getLinesOfCode()); setAttribute(protobuf, "Container", containerSupport.isRunningInContainer()); setAttribute(protobuf, "External Users and Groups Provisioning", commonSystemInformation.getManagedInstanceProviderName()); setAttribute(protobuf, "External User Authentication", commonSystemInformation.getExternalUserAuthentication()); addIfNotEmpty(protobuf, "Accepted external identity providers", commonSystemInformation.getEnabledIdentityProviders()); addIfNotEmpty(protobuf, "External identity providers whose users are allowed to sign themselves up", commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()); setAttribute(protobuf, "High Availability", false); setAttribute(protobuf, "Official Distribution", officialDistribution.check()); setAttribute(protobuf, "Force authentication", commonSystemInformation.getForceAuthentication()); setAttribute(protobuf, "Home Dir", config.get(PATH_HOME.getKey()).orElse(null)); setAttribute(protobuf, "Data Dir", config.get(PATH_DATA.getKey()).orElse(null)); setAttribute(protobuf, "Temp Dir", config.get(PATH_TEMP.getKey()).orElse(null)); setAttribute(protobuf, "Processors", Runtime.getRuntime().availableProcessors()); return protobuf.build(); }
@Test public void toProtobuf_whenNoAllowsToSignUpEnabledIdentityProviders_shouldWriteNothing() { when(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()).thenReturn(emptyList()); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, "External identity providers whose users are allowed to sign themselves up"); }
public static Map<String, String> getExternalResourceConfigurationKeys( Configuration config, String suffix) { final Set<String> resourceSet = getExternalResourceSet(config); final Map<String, String> configKeysToResourceNameMap = new HashMap<>(); LOG.info("Enabled external resources: {}", resourceSet); if (resourceSet.isEmpty()) { return Collections.emptyMap(); } final Map<String, String> externalResourceConfigs = new HashMap<>(); for (String resourceName : resourceSet) { final ConfigOption<String> configKeyOption = key(ExternalResourceOptions.getSystemConfigKeyConfigOptionForResource( resourceName, suffix)) .stringType() .noDefaultValue(); final String configKey = config.get(configKeyOption); if (StringUtils.isNullOrWhitespaceOnly(configKey)) { LOG.warn( "Could not find valid {} for {}. Will ignore that resource.", configKeyOption.key(), resourceName); } else { configKeysToResourceNameMap.compute( configKey, (ignored, previousResource) -> { if (previousResource != null) { LOG.warn( "Duplicate config key {} occurred for external resources, the one named {} will overwrite the value.", configKey, resourceName); externalResourceConfigs.remove(previousResource); } return resourceName; }); externalResourceConfigs.put(resourceName, configKey); } } return externalResourceConfigs; }
@Test public void testGetExternalResourceConfigurationKeysWithConflictConfigKey() { final Configuration config = new Configuration(); config.set(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, RESOURCE_LIST); config.setString( ExternalResourceOptions.getSystemConfigKeyConfigOptionForResource( RESOURCE_NAME_1, SUFFIX), RESOURCE_CONFIG_KEY_1); config.setString( ExternalResourceOptions.getSystemConfigKeyConfigOptionForResource( RESOURCE_NAME_2, SUFFIX), RESOURCE_CONFIG_KEY_1); final Map<String, String> configMap = ExternalResourceUtils.getExternalResourceConfigurationKeys(config, SUFFIX); // Only one of the resource name would be kept. assertThat(configMap.size(), is(1)); assertThat(configMap.values(), contains(RESOURCE_CONFIG_KEY_1)); }
public StatMap<K> merge(K key, int value) { if (key.getType() == Type.LONG) { merge(key, (long) value); return this; } int oldValue = getInt(key); int newValue = key.merge(oldValue, value); if (newValue == 0) { _map.remove(key); } else { _map.put(key, newValue); } return this; }
@Test(dataProvider = "allTypeStats", expectedExceptions = IllegalArgumentException.class) public void dynamicTypeCheckPutBoolean(MyStats stat) { if (stat.getType() == StatMap.Type.BOOLEAN) { throw new SkipException("Skipping BOOLEAN test"); } StatMap<MyStats> statMap = new StatMap<>(MyStats.class); statMap.merge(stat, true); }
public static Instant garbageCollectionTime( BoundedWindow window, WindowingStrategy windowingStrategy) { return garbageCollectionTime(window, windowingStrategy.getAllowedLateness()); }
@Test public void garbageCollectionTimeAfterEndOfGlobalWindow() { FixedWindows windowFn = FixedWindows.of(Duration.standardMinutes(5)); WindowingStrategy<?, ?> strategy = WindowingStrategy.globalDefault().withWindowFn(windowFn); IntervalWindow window = windowFn.assignWindow(BoundedWindow.TIMESTAMP_MAX_VALUE); assertThat(window.maxTimestamp(), equalTo(GlobalWindow.INSTANCE.maxTimestamp())); assertThat( LateDataUtils.garbageCollectionTime(window, strategy), equalTo(GlobalWindow.INSTANCE.maxTimestamp())); }
public static boolean isPullRequest(Item item) { // TODO probably want to be using SCMHeadCategory instances to categorize them instead of hard-coding for PRs return SCMHead.HeadByItem.findHead(item) instanceof ChangeRequestSCMHead; }
@Test public void testIsPullRequest(){ BlueOrganization organization = mockOrganization(); OrganizationFolder organizationFolder = mockOrgFolder(organization); PullRequestSCMHead changeRequestSCMHead = Mockito.mock(PullRequestSCMHead.class); mockedStatic = Mockito.mockStatic(SCMHead.HeadByItem.class); Mockito.when(SCMHead.HeadByItem.findHead(organizationFolder)).thenReturn(changeRequestSCMHead); assertTrue(PipelineJobFilters.isPullRequest(organizationFolder)); assertFalse(new PipelineJobFilters.OriginFilter().getFilter().test(organizationFolder)); assertTrue(new PipelineJobFilters.PullRequestFilter().getFilter().test(organizationFolder)); }
public static String[] splitString( String string, String separator ) { /* * 0123456 Example a;b;c;d --> new String[] { a, b, c, d } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); List<String> list = new ArrayList<>(); if ( string == null || string.length() == 0 ) { return new String[] {}; } int sepLen = separator.length(); int from = 0; int end = string.length() - sepLen + 1; for ( int i = from; i < end; i += sepLen ) { if ( string.substring( i, i + sepLen ).equalsIgnoreCase( separator ) ) { // OK, we found a separator, the string to add to the list // is [from, i[ list.add( nullToEmpty( string.substring( from, i ) ) ); from = i + sepLen; } } // Wait, if the string didn't end with a separator, we still have information at the end of the string... // In our example that would be "d"... if ( from + sepLen <= string.length() ) { list.add( nullToEmpty( string.substring( from, string.length() ) ) ); } return list.toArray( new String[list.size()] ); }
@Test public void testSplitStringWithNestedEscapedEnclosure() { String[] result; String enclosure = "\""; String delimiter = ","; // Actual data contains enclosure withing data with escaped enclosure like: "0","Test\"Data1","Test\"Data2","Test\"Data3" String splitString = "\"0\",\"Test\\\"Data1\",\"Test\\\"Data2\",\"Test\\\"Data3\""; // Test with removeEnclosure=false result = Const.splitString( splitString, delimiter, enclosure, false ); assertNotNull( result ); assertEquals( result.length, 4 ); assertEquals( result[0], "\"0\"" ); assertEquals( result[1], "\"Test\\\"Data1\"" ); assertEquals( result[2], "\"Test\\\"Data2\"" ); assertEquals( result[3], "\"Test\\\"Data3\"" ); // Test with removeEnclosure=true result = Const.splitString( splitString, delimiter, enclosure, true ); assertNotNull( result ); assertEquals( result.length, 4 ); assertEquals( result[0], "0" ); assertEquals( result[1], "Test\\\"Data1" ); assertEquals( result[2], "Test\\\"Data2" ); assertEquals( result[3], "Test\\\"Data3" ); }
public static String getHeader(boolean qOption) { return qOption ? ALL_HEADER : SUMMARY_HEADER; }
@Test public void testGetHeaderWithQuota() { String header = " QUOTA REM_QUOTA SPACE_QUOTA " + "REM_SPACE_QUOTA DIR_COUNT FILE_COUNT CONTENT_SIZE "; assertEquals(header, ContentSummary.getHeader(true)); }
@Udf(description = "Subtracts a duration from a time") public Time timeSub( @UdfParameter(description = "A unit of time, for example SECOND or HOUR") final TimeUnit unit, @UdfParameter( description = "An integer number of intervals to subtract") final Integer interval, @UdfParameter(description = "A TIME value.") final Time time ) { if (unit == null || interval == null || time == null) { return null; } final long nanoResult = LocalTime.ofNanoOfDay(time.getTime() * 1000_000) .minus(unit.toNanos(interval), ChronoUnit.NANOS) .toNanoOfDay(); return new Time(TimeUnit.NANOSECONDS.toMillis(nanoResult)); }
@Test public void handleNullTime() { assertNull(udf.timeSub(TimeUnit.MILLISECONDS, -300, null)); }
public <T> T convert(String property, Class<T> targetClass) { final AbstractPropertyConverter<?> converter = converterRegistry.get(targetClass); if (converter == null) { throw new MissingFormatArgumentException("converter not found, can't convert from String to " + targetClass.getCanonicalName()); } return (T) converter.convert(property); }
@Test void testConvertBooleanForEmptyProperty() { assertNull(compositeConverter.convert(null, Boolean.class)); }
@Override public Set<Principal> getPrincipals() { throw notAllowed("getPrincipals"); }
@Test(expected=UnsupportedOperationException.class) public void testGetPrincipals() { ctx.getPrincipals(); }
public String getHost() { if (host == null) { try { host = HostUtils.getLocalHostName(); } catch (UnknownHostException e) { LOG.warn(e.getMessage(), e); host = "unknown"; } } return host; }
@Test public void testHostDefaultIsNotNull() { SplunkHECConfiguration config = new SplunkHECConfiguration(); assertNotNull(config.getHost()); }
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids); criteria.forEach(criterion -> processCriterion(criterion, query)); return query; }
@Test public void convert_metric_to_lower_case() { ProjectMeasuresQuery query = newProjectMeasuresQuery(asList( Criterion.builder().setKey("NCLOC").setOperator(GT).setValue("10").build(), Criterion.builder().setKey("coVERage").setOperator(LTE).setValue("80").build()), emptySet()); assertThat(query.getMetricCriteria()) .extracting(MetricCriterion::getMetricKey, MetricCriterion::getOperator, MetricCriterion::getValue) .containsOnly( tuple("ncloc", GT, 10d), tuple("coverage", Operator.LTE, 80d)); }
@VisibleForTesting void validateDictTypeNameUnique(Long id, String name) { DictTypeDO dictType = dictTypeMapper.selectByName(name); if (dictType == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典类型 if (id == null) { throw exception(DICT_TYPE_NAME_DUPLICATE); } if (!dictType.getId().equals(id)) { throw exception(DICT_TYPE_NAME_DUPLICATE); } }
@Test public void testValidateDictTypeNameUnique_nameDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String name = randomString(); // mock 数据 dictTypeMapper.insert(randomDictTypeDO(o -> o.setName(name))); // 调用,校验异常 assertServiceException(() -> dictTypeService.validateDictTypeNameUnique(id, name), DICT_TYPE_NAME_DUPLICATE); }
public static List<Criterion> parse(String filter) { return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false) .map(FilterParser::parseCriterion) .toList(); }
@Test public void parse_filter_having_in_empty_list() { List<Criterion> criterion = FilterParser.parse("languages IN ()"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValues, Criterion::getValue) .containsOnly( tuple("languages", IN, Collections.emptyList(), null)); }
@Override public void collect(MetricsEmitter metricsEmitter) { for (Map.Entry<MetricKey, KafkaMetric> entry : ledger.getMetrics()) { MetricKey metricKey = entry.getKey(); KafkaMetric metric = entry.getValue(); try { collectMetric(metricsEmitter, metricKey, metric); } catch (Exception e) { // catch and log to continue processing remaining metrics log.error("Error processing Kafka metric {}", metricKey, e); } } }
@Test public void testSecondDeltaCollectDouble() { Sensor sensor = metrics.sensor("test"); sensor.add(metricName, new CumulativeSum()); sensor.record(); sensor.record(); time.sleep(60 * 1000L); testEmitter.onlyDeltaMetrics(true); collector.collect(testEmitter); // Update it again by 5 and advance time by another 60 seconds. sensor.record(); sensor.record(); sensor.record(); sensor.record(); sensor.record(); time.sleep(60 * 1000L); testEmitter.reset(); collector.collect(testEmitter); List<SinglePointMetric> result = testEmitter.emittedMetrics(); assertEquals(2, result.size()); Metric cumulative = result.stream() .flatMap(metrics -> Stream.of(metrics.builder().build())) .filter(metric -> metric.getName().equals("test.domain.group1.name1")).findFirst().get(); NumberDataPoint point = cumulative.getSum().getDataPoints(0); assertEquals(AggregationTemporality.AGGREGATION_TEMPORALITY_DELTA, cumulative.getSum().getAggregationTemporality()); assertTrue(cumulative.getSum().getIsMonotonic()); assertEquals(5d, point.getAsDouble(), 0.0); assertEquals(TimeUnit.SECONDS.toNanos(Instant.ofEpochSecond(121L).getEpochSecond()) + Instant.ofEpochSecond(121L).getNano(), point.getTimeUnixNano()); assertEquals(TimeUnit.SECONDS.toNanos(Instant.ofEpochSecond(61L).getEpochSecond()) + Instant.ofEpochSecond(61L).getNano(), point.getStartTimeUnixNano()); }
public List<KinesisRecord> apply(List<KinesisRecord> records, ShardCheckpoint checkpoint) { List<KinesisRecord> filteredRecords = newArrayList(); for (KinesisRecord record : records) { if (checkpoint.isBeforeOrAt(record)) { filteredRecords.add(record); } } return filteredRecords; }
@Test public void shouldFilterOutRecordsBeforeOrAtCheckpoint() { when(checkpoint.isBeforeOrAt(record1)).thenReturn(false); when(checkpoint.isBeforeOrAt(record2)).thenReturn(true); when(checkpoint.isBeforeOrAt(record3)).thenReturn(true); when(checkpoint.isBeforeOrAt(record4)).thenReturn(false); when(checkpoint.isBeforeOrAt(record5)).thenReturn(true); List<KinesisRecord> records = Lists.newArrayList(record1, record2, record3, record4, record5); RecordFilter underTest = new RecordFilter(); List<KinesisRecord> retainedRecords = underTest.apply(records, checkpoint); Assertions.assertThat(retainedRecords).containsOnly(record2, record3, record5); }
@Override public Local find(final Host bookmark) { if(null != bookmark.getDownloadFolder()) { if(bookmark.getDownloadFolder().exists()) { return bookmark.getDownloadFolder(); } } final Local directory = LocalFactory.get(preferences.getProperty("queue.download.folder")).withBookmark( preferences.getProperty("queue.download.folder.bookmark")); if(log.isInfoEnabled()) { log.info(String.format("Suggest default download folder %s for bookmark %s", directory, bookmark)); } return directory; }
@Test public void testFind() throws Exception { final Host host = new Host(new TestProtocol()); assertNull(host.getDownloadFolder()); final DownloadDirectoryFinder finder = new DownloadDirectoryFinder(); assertEquals(System.getProperty("user.dir"), finder.find(host).getAbsolute()); // Does not exist host.setDownloadFolder(new Local(String.format("/%s", UUID.randomUUID()))); assertEquals(System.getProperty("user.dir"), finder.find(host).getAbsolute()); final Local folder = new Local("~/Documents"); new DefaultLocalDirectoryFeature().mkdir(folder); host.setDownloadFolder(folder); assertEquals(String.format("~%sDocuments", PreferencesFactory.get().getProperty("local.delimiter")), finder.find(host).getAbbreviatedPath()); }
@Override public Map<String, String> getAddresses() { AwsCredentials credentials = awsCredentialsProvider.credentials(); List<String> taskAddresses = emptyList(); if (!awsConfig.anyOfEc2PropertiesConfigured()) { taskAddresses = awsEcsApi.listTaskPrivateAddresses(cluster, credentials); LOGGER.fine("AWS ECS DescribeTasks found the following addresses: %s", taskAddresses); } if (!taskAddresses.isEmpty()) { return awsEc2Api.describeNetworkInterfaces(taskAddresses, credentials); } else if (DiscoveryMode.Client == awsConfig.getDiscoveryMode() && !awsConfig.anyOfEcsPropertiesConfigured()) { LOGGER.fine("No tasks found in ECS cluster: '%s'. Trying AWS EC2 Discovery.", cluster); return awsEc2Api.describeInstances(credentials); } return emptyMap(); }
@Test public void getAddressesNoPublicAddresses() { // given List<String> privateIps = singletonList("123.12.1.0"); Map<String, String> privateToPublicIps = singletonMap("123.12.1.0", null); given(awsEcsApi.listTaskPrivateAddresses(CLUSTER, CREDENTIALS)).willReturn(privateIps); given(awsEc2Api.describeNetworkInterfaces(privateIps, CREDENTIALS)).willReturn(privateToPublicIps); // when Map<String, String> result = awsEcsClient.getAddresses(); // then assertEquals(singletonMap("123.12.1.0", null), result); }
private static Map<String, Set<Dependency>> checkOptionalFlags( Map<String, Set<Dependency>> bundledDependenciesByModule, Map<String, DependencyTree> dependenciesByModule) { final Map<String, Set<Dependency>> allViolations = new HashMap<>(); for (String module : bundledDependenciesByModule.keySet()) { LOG.debug("Checking module '{}'.", module); if (!dependenciesByModule.containsKey(module)) { throw new IllegalStateException( String.format( "Module %s listed by shade-plugin, but not dependency-plugin.", module)); } final Collection<Dependency> bundledDependencies = bundledDependenciesByModule.get(module); final DependencyTree dependencyTree = dependenciesByModule.get(module); final Set<Dependency> violations = checkOptionalFlags(module, bundledDependencies, dependencyTree); if (violations.isEmpty()) { LOG.info("OK: {}", module); } else { allViolations.put(module, violations); } } return allViolations; }
@Test void testDirectBundledOptionalDependencyIsAccepted() { final Dependency dependency = createOptionalDependency("a"); final Set<Dependency> bundled = Collections.singleton(dependency); final DependencyTree dependencyTree = new DependencyTree().addDirectDependency(dependency); final Set<Dependency> violations = ShadeOptionalChecker.checkOptionalFlags(MODULE, bundled, dependencyTree); assertThat(violations).isEmpty(); }
static void move(File src, File dest) throws IOException { try { Files.move(src.toPath(), dest.toPath()); } catch (IOException x) { throw x; } catch (RuntimeException x) { throw new IOException(x); } }
@Test public void move() throws Exception { File src = tmp.newFile(); File dest = new File(tmp.getRoot(), "dest"); RunIdMigrator.move(src, dest); File dest2 = tmp.newFile(); assertThrows(IOException.class, () -> RunIdMigrator.move(dest, dest2)); }
boolean hasMoreAvailableCapacityThan(final ClientState other) { if (capacity <= 0) { throw new IllegalStateException("Capacity of this ClientState must be greater than 0."); } if (other.capacity <= 0) { throw new IllegalStateException("Capacity of other ClientState must be greater than 0"); } final double otherLoad = (double) other.assignedTaskCount() / other.capacity; final double thisLoad = (double) assignedTaskCount() / capacity; if (thisLoad < otherLoad) { return true; } else if (thisLoad > otherLoad) { return false; } else { return capacity > other.capacity; } }
@Test public void shouldThrowIllegalStateExceptionIfCapacityOfOtherClientStateIsZero() { assertThrows(IllegalStateException.class, () -> client.hasMoreAvailableCapacityThan(zeroCapacityClient)); }
@Override public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewName(), "New name must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); byte[] newKeyBuf = toByteArray(command.getNewName()); if (executorService.getConnectionManager().calcSlot(keyBuf) == executorService.getConnectionManager().calcSlot(newKeyBuf)) { return super.rename(commands); } return read(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.DUMP, keyBuf) .filter(Objects::nonNull) .zipWith( Mono.defer(() -> pTtl(command.getKey()) .filter(Objects::nonNull) .map(ttl -> Math.max(0, ttl)) .switchIfEmpty(Mono.just(0L)) ) ) .flatMap(valueAndTtl -> { return write(newKeyBuf, StringCodec.INSTANCE, RedisCommands.RESTORE, newKeyBuf, valueAndTtl.getT2(), valueAndTtl.getT1()); }) .thenReturn(new BooleanResponse<>(command, true)) .doOnSuccess((ignored) -> del(command.getKey())); }); }
@Test public void testRename() { connection.stringCommands().set(originalKey, value).block(); if (hasTtl) { connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block(); } Integer originalSlot = getSlotForKey(originalKey); newKey = getNewKeyForSlot(new String(originalKey.array()), getTargetSlot(originalSlot)); Boolean response = connection.keyCommands().rename(originalKey, newKey).block(); assertThat(response).isTrue(); final ByteBuffer newKeyValue = connection.stringCommands().get(newKey).block(); assertThat(newKeyValue).isEqualTo(value); if (hasTtl) { assertThat(connection.keyCommands().ttl(newKey).block()).isGreaterThan(0); } else { assertThat(connection.keyCommands().ttl(newKey).block()).isEqualTo(-1); } }
public Optional<String> getType(Set<String> streamIds, String field) { final Map<String, Set<String>> allFieldTypes = this.get(streamIds); final Set<String> fieldTypes = allFieldTypes.get(field); return typeFromFieldType(fieldTypes); }
@Test void returnsFieldTypeIfSingleTypeExistsForFieldInAllStreams() { final Pair<IndexFieldTypesService, StreamService> services = mockServices( IndexFieldTypesDTO.create("indexSet1", "stream1", ImmutableSet.of( FieldTypeDTO.create("somefield", "long") )), IndexFieldTypesDTO.create("indexSet2", "stream2", ImmutableSet.of( FieldTypeDTO.create("somefield", "long") )) ); final FieldTypesLookup lookup = new FieldTypesLookup(services.getLeft(), services.getRight()); final Optional<String> result = lookup.getType(ImmutableSet.of("stream1", "stream2"), "somefield"); assertThat(result).contains("long"); }
public static StreamedRow toRowFromDelimited(final Buffer buff) { try { final QueryResponseMetadata metadata = deserialize(buff, QueryResponseMetadata.class); return StreamedRow.header(new QueryId(Strings.nullToEmpty(metadata.queryId)), createSchema(metadata)); } catch (KsqlRestClientException e) { // Not a {@link QueryResponseMetadata} } try { final KsqlErrorMessage error = deserialize(buff, KsqlErrorMessage.class); return StreamedRow.error(new RuntimeException(error.getMessage()), error.getErrorCode()); } catch (KsqlRestClientException e) { // Not a {@link KsqlErrorMessage} } try { final PushContinuationToken continuationToken = deserialize(buff, PushContinuationToken.class); return StreamedRow.continuationToken(continuationToken); } catch (KsqlRestClientException e) { // Not a {@link KsqlErrorMessage} } try { final List<?> row = deserialize(buff, List.class); return StreamedRow.pushRow(GenericRow.fromList(row)); } catch (KsqlRestClientException e) { // Not a {@link List} } throw new IllegalStateException("Couldn't parse message: " + buff.toString()); }
@Test public void shouldParseError() { // When: final StreamedRow row = KsqlTargetUtil.toRowFromDelimited(Buffer.buffer( "{\"@type\":\"generic_error\",\"error_code\": 500,\"message\":\"Really bad problem\"}")); // Then: assertThat(row.getErrorMessage().isPresent(), is(true)); assertThat(row.getErrorMessage().get().getErrorCode(), is(500)); assertThat(row.getErrorMessage().get().getMessage(), is("Really bad problem")); }
@Udf public <T> List<T> slice( @UdfParameter(description = "the input array") final List<T> in, @UdfParameter(description = "start index") final Integer from, @UdfParameter(description = "end index") final Integer to) { if (in == null) { return null; } try { // SQL systems are usually 1-indexed and are inclusive of end index final int start = from == null ? 0 : from - 1; final int end = to == null ? in.size() : to; return in.subList(start, end); } catch (final IndexOutOfBoundsException e) { return null; } }
@Test public void shouldOneIndexSlice() { // Given: final List<String> list = Lists.newArrayList("a", "b", "c"); // When: final List<String> slice = new Slice().slice(list, 1, 2); // Then: assertThat(slice, is(Lists.newArrayList("a", "b"))); }
public static Builder builder() { return new Builder(); }
@Test public void testSetPlatforms_emptyPlatformsSet() { try { ContainerBuildPlan.builder().setPlatforms(Collections.emptySet()); Assert.fail(); } catch (IllegalArgumentException ex) { Assert.assertEquals("platforms set cannot be empty", ex.getMessage()); } }
public Path extract(Path targetPath) throws IOException, UserException { try { Path zipPath = downloadZip(targetPath); return extractZip(zipPath, targetPath); } finally { // clean temp path; for (Path p : cleanPathList) { FileUtils.deleteQuietly(p.toFile()); } } }
@Test public void testExtract() { try { Files.copy(PluginTestUtil.getTestPath("source/test.zip"), PluginTestUtil.getTestPath("source/test-a.zip")); PluginZip util = new PluginZip(PluginTestUtil.getTestPathString("source/test-a.zip"), null); Path actualPath = util.extract(PluginTestUtil.getTestPath("target")); assertTrue(Files.isDirectory(actualPath)); Path txtPath = FileSystems.getDefault().getPath(actualPath.toString(), "test.txt"); assertTrue(Files.exists(txtPath)); assertTrue(FileUtils.deleteQuietly(actualPath.toFile())); } catch (Exception e) { e.printStackTrace(); assert false; } }
public static String substVars(String val, PropertyContainer pc1) throws ScanException { return substVars(val, pc1, null); }
@Test public void trailingColon_LOGBACK_1140() throws ScanException { String prefix = "c:"; String suffix = "/tmp"; context.putProperty("var", prefix); String r = OptionHelper.substVars("${var}" + suffix, context); assertEquals(prefix + suffix, r); }
public String getQueryCondition() { StringBuilder sb = new StringBuilder(); if (!StringUtils.isEmpty(taskId)) { sb.append("task_id = '").append(taskId).append("'").append(LINK); } if (!CollectionUtils.isEmpty(taskIds)) { String taskIdsInQuery = taskIds.stream().map(id -> String.format("'%s'", id)).collect(Collectors.joining(", ")); sb.append("task_id in (").append(taskIdsInQuery).append(")").append(LINK); } if (subInstanceId != null) { sb.append("sub_instance_id = ").append(subInstanceId).append(LINK); } if (instanceId != null) { sb.append("instance_id = ").append(instanceId).append(LINK); } if (!StringUtils.isEmpty(address)) { sb.append("address = '").append(address).append("'").append(LINK); } if (!StringUtils.isEmpty(taskName)) { sb.append("task_name = '").append(taskName).append("'").append(LINK); } if (status != null) { sb.append("status = ").append(status).append(LINK); } // 自定义查询模式专用 if (StringUtils.isNotEmpty(fullCustomQueryCondition)) { sb.append(fullCustomQueryCondition); return sb.toString(); } if (!StringUtils.isEmpty(queryCondition)) { sb.append(queryCondition).append(LINK); } String substring = sb.substring(0, sb.length() - LINK.length()); if (!StringUtils.isEmpty(otherCondition)) { substring += otherCondition; } if (limit != null) { substring = substring + " limit " + limit; } return substring; }
@Test void test() { SimpleTaskQuery simpleTaskQuery = new SimpleTaskQuery(); simpleTaskQuery.setInstanceId(10086L); simpleTaskQuery.setTaskIds(Lists.newArrayList("taskId1", "taskId2", "taskId3")); String queryCondition = simpleTaskQuery.getQueryCondition(); System.out.println(queryCondition); assertEquals("task_id in ('taskId1', 'taskId2', 'taskId3') and instance_id = 10086", queryCondition); }
@NotNull public SocialUserDO authSocialUser(Integer socialType, Integer userType, String code, String state) { // 优先从 DB 中获取,因为 code 有且可以使用一次。 // 在社交登录时,当未绑定 User 时,需要绑定登录,此时需要 code 使用两次 SocialUserDO socialUser = socialUserMapper.selectByTypeAndCodeAnState(socialType, code, state); if (socialUser != null) { return socialUser; } // 请求获取 AuthUser authUser = socialClientService.getAuthUser(socialType, userType, code, state); Assert.notNull(authUser, "三方用户不能为空"); // 保存到 DB 中 socialUser = socialUserMapper.selectByTypeAndOpenid(socialType, authUser.getUuid()); if (socialUser == null) { socialUser = new SocialUserDO(); } socialUser.setType(socialType).setCode(code).setState(state) // 需要保存 code + state 字段,保证后续可查询 .setOpenid(authUser.getUuid()).setToken(authUser.getToken().getAccessToken()).setRawTokenInfo((toJsonString(authUser.getToken()))) .setNickname(authUser.getNickname()).setAvatar(authUser.getAvatar()).setRawUserInfo(toJsonString(authUser.getRawUserInfo())); if (socialUser.getId() == null) { socialUserMapper.insert(socialUser); } else { socialUserMapper.updateById(socialUser); } return socialUser; }
@Test public void testAuthSocialUser_insert() { // 准备参数 Integer socialType = SocialTypeEnum.GITEE.getType(); Integer userType = randomEle(SocialTypeEnum.values()).getType(); String code = "tudou"; String state = "yuanma"; // mock 方法 AuthUser authUser = randomPojo(AuthUser.class); when(socialClientService.getAuthUser(eq(socialType), eq(userType), eq(code), eq(state))).thenReturn(authUser); // 调用 SocialUserDO result = socialUserService.authSocialUser(socialType, userType, code, state); // 断言 assertBindSocialUser(socialType, result, authUser); assertEquals(code, result.getCode()); assertEquals(state, result.getState()); }
public User id(Long id) { this.id = id; return this; }
@Test public void idTest() { // TODO: test id }
public List<IdentityProvider> getAllEnabledAndSorted() { return providersByKey.values().stream() .filter(IS_ENABLED_FILTER) .sorted(Comparator.comparing(TO_NAME)) .toList(); }
@Test public void return_sorted_enabled_providers() { IdentityProviderRepository underTest = new IdentityProviderRepository(asList(GITHUB, BITBUCKET)); List<IdentityProvider> providers = underTest.getAllEnabledAndSorted(); assertThat(providers).containsExactly(BITBUCKET, GITHUB); }
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor( DoFn<InputT, OutputT> fn) { return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn); }
@Test public void testOnWindowExpirationWithNoParam() throws Exception { class MockFn extends DoFn<String, String> { @ProcessElement public void process(ProcessContext c) {} @OnWindowExpiration public void onWindowExpiration() {} } MockFn fn = mock(MockFn.class); DoFnInvoker<String, String> invoker = DoFnInvokers.invokerFor(fn); invoker.invokeOnWindowExpiration(mockArgumentProvider); verify(fn).onWindowExpiration(); }
@Deprecated public static String getJwt(JwtClaims claims) throws JoseException { String jwt; RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey( jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName()); // A JWT is a JWS and/or a JWE with JSON claims as the payload. // In this example it is a JWS nested inside a JWE // So we first create a JsonWebSignature object. JsonWebSignature jws = new JsonWebSignature(); // The payload of the JWS is JSON content of the JWT Claims jws.setPayload(claims.toJson()); // The JWT is signed using the sender's private key jws.setKey(privateKey); // Get provider from security config file, it should be two digit // And the provider id will set as prefix for keyid in the token header, for example: 05100 // if there is no provider id, we use "00" for the default value String provider_id = ""; if (jwtConfig.getProviderId() != null) { provider_id = jwtConfig.getProviderId(); if (provider_id.length() == 1) { provider_id = "0" + provider_id; } else if (provider_id.length() > 2) { logger.error("provider_id defined in the security.yml file is invalid; the length should be 2"); provider_id = provider_id.substring(0, 2); } } jws.setKeyIdHeaderValue(provider_id + jwtConfig.getKey().getKid()); // Set the signature algorithm on the JWT/JWS that will integrity protect the claims jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS // representation, which is a string consisting of three dot ('.') separated // base64url-encoded parts in the form Header.Payload.Signature jwt = jws.getCompactSerialization(); return jwt; }
@Test public void longlivedLightPortalConfigServer() throws Exception { JwtClaims claims = ClaimsUtil.getTestClaims("[email protected]", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e73", Arrays.asList("portal.r", "portal.w"), "user CfgPltAdmin CfgPltRead CfgPltWrite"); claims.setExpirationTimeMinutesInTheFuture(5256000); String jwt = JwtIssuer.getJwt(claims, long_kid, KeyUtil.deserializePrivateKey(long_key, KeyUtil.RSA)); System.out.println("***Long lived token for portal config server ***: " + jwt); }
public static String mobilePhone(String num) { if (StrUtil.isBlank(num)) { return StrUtil.EMPTY; } return StrUtil.hide(num, 3, num.length() - 4); }
@Test public void mobilePhoneTest() { assertEquals("180****1999", DesensitizedUtil.mobilePhone("18049531999")); }
@VisibleForTesting Map<ExecutionVertexID, Collection<ExecutionAttemptID>> findSlowTasks( final ExecutionGraph executionGraph) { final long currentTimeMillis = System.currentTimeMillis(); final Map<ExecutionVertexID, Collection<ExecutionAttemptID>> slowTasks = new HashMap<>(); final List<ExecutionJobVertex> jobVerticesToCheck = getJobVerticesToCheck(executionGraph); for (ExecutionJobVertex ejv : jobVerticesToCheck) { final ExecutionTimeWithInputBytes baseline = getBaseline(ejv, currentTimeMillis); for (ExecutionVertex ev : ejv.getTaskVertices()) { if (ev.getExecutionState().isTerminal()) { continue; } final List<ExecutionAttemptID> slowExecutions = findExecutionsExceedingBaseline( ev.getCurrentExecutions(), baseline, currentTimeMillis); if (!slowExecutions.isEmpty()) { slowTasks.put(ev.getID(), slowExecutions); } } } return slowTasks; }
@Test void testAllTasksInCreatedAndNoSlowTasks() throws Exception { final int parallelism = 3; final JobVertex jobVertex = createNoOpVertex(parallelism); final JobGraph jobGraph = JobGraphTestUtils.streamingJobGraph(jobVertex); // all tasks are in the CREATED state, which is not classified as slow tasks. final ExecutionGraph executionGraph = SchedulerTestingUtils.createScheduler( jobGraph, ComponentMainThreadExecutorServiceAdapter.forMainThread(), EXECUTOR_RESOURCE.getExecutor()) .getExecutionGraph(); final ExecutionTimeBasedSlowTaskDetector slowTaskDetector = createSlowTaskDetector(0, 1, 0); final Map<ExecutionVertexID, Collection<ExecutionAttemptID>> slowTasks = slowTaskDetector.findSlowTasks(executionGraph); assertThat(slowTasks).isEmpty(); }
public CellFormatter getFormatter(String columnId) { checkId(columnId); CellFormatter fmt = formatters.get(columnId); return fmt == null ? DEF_FMT : fmt; }
@Test public void defaultFormatter() { tm = new TableModel(FOO); fmt = tm.getFormatter(FOO); assertTrue("Wrong formatter", fmt instanceof DefaultCellFormatter); }
@VisibleForTesting Object evaluate(final GenericRow row) { return term.getValue(new TermEvaluationContext(row)); }
@Test public void shouldEvaluateCastToInteger() { // Given: final Expression cast1 = new Cast( new LongLiteral(10L), new Type(SqlPrimitiveType.of("INTEGER")) ); final Expression cast2 = new Cast( new StringLiteral("1234"), new Type(SqlPrimitiveType.of("INTEGER")) ); final Expression cast3 = new Cast( new DoubleLiteral(12.5), new Type(SqlPrimitiveType.of("INTEGER")) ); final Expression cast4 = new Cast( new DecimalLiteral(new BigDecimal("4567.5")), new Type(SqlPrimitiveType.of("INTEGER")) ); // When: InterpretedExpression interpreter1 = interpreter(cast1); InterpretedExpression interpreter2 = interpreter(cast2); InterpretedExpression interpreter3 = interpreter(cast3); InterpretedExpression interpreter4 = interpreter(cast4); // Then: assertThat(interpreter1.evaluate(ROW), is(10)); assertThat(interpreter2.evaluate(ROW), is(1234)); assertThat(interpreter3.evaluate(ROW), is(12)); assertThat(interpreter4.evaluate(ROW), is(4567)); }
@Bean @ConditionalOnMissingBean(TaskQueue.class) @Qualifier("taskQueue") @ConditionalOnProperty("shenyu.shared-pool.max-work-queue-memory") public TaskQueue<Runnable> memoryLimitedTaskQueue(final ShenyuConfig shenyuConfig) { final Instrumentation instrumentation = ByteBuddyAgent.install(); final ShenyuConfig.SharedPool sharedPool = shenyuConfig.getSharedPool(); final Long maxWorkQueueMemory = sharedPool.getMaxWorkQueueMemory(); if (maxWorkQueueMemory <= 0) { throw new ShenyuException("${shenyu.sharedPool.maxWorkQueueMemory} must bigger than 0 !"); } return new MemoryLimitedTaskQueue<>(maxWorkQueueMemory, instrumentation); }
@Test public void testMemoryLimitedTaskQueue() { ShenyuConfig shenyuConfig = mock(ShenyuConfig.class); ShenyuConfig.SharedPool sharedPool = mock(ShenyuConfig.SharedPool.class); when(shenyuConfig.getSharedPool()).thenReturn(sharedPool); when(sharedPool.getMaxWorkQueueMemory()).thenReturn(1024L); assertTrue(shenyuThreadPoolConfiguration.memoryLimitedTaskQueue(shenyuConfig) instanceof MemoryLimitedTaskQueue); when(sharedPool.getMaxWorkQueueMemory()).thenReturn(0L); assertThrows(ShenyuException.class, () -> shenyuThreadPoolConfiguration.memoryLimitedTaskQueue(shenyuConfig)); }
@Override public boolean matches(String name, Metric metric) { return patterns.stream().anyMatch(pattern -> pattern.matcher(name).matches()); }
@Test void test() { final List<MapperConfig> mapperConfigs = ImmutableList.of( new MapperConfig("foo.*.bar.*.baz", "test1", Collections.emptyMap()), new MapperConfig("hello.world", "test2", Collections.emptyMap()) ); final PrometheusMetricFilter filter = new PrometheusMetricFilter(mapperConfigs); final Metric metric = new Counter(); assertThat(filter.matches("foo.123.bar.456.baz", metric)).isTrue(); assertThat(filter.matches("foo.abc.bar.456.baz", metric)).isTrue(); assertThat(filter.matches("foo.123.nope.bar.456.baz", metric)).isFalse(); assertThat(filter.matches("nope.foo.123.bar.456.baz", metric)).isFalse(); assertThat(filter.matches("foo.123.bar.456.baz.nope", metric)).isFalse(); assertThat(filter.matches("hello.world", metric)).isTrue(); assertThat(filter.matches("hello.123.world", metric)).isFalse(); }
public ProcessCommands createAfterClean(int processNumber) { return createForProcess(processNumber, true); }
@Test public void getProcessCommands_fails_if_processNumber_is_less_than_0() throws Exception { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int processNumber = -2; assertThatThrownBy(() -> commands.createAfterClean(processNumber)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Process number " + processNumber + " is not valid"); } }
public static <K, E, V> Collector<E, ImmutableSetMultimap.Builder<K, V>, ImmutableSetMultimap<K, V>> unorderedFlattenIndex( Function<? super E, K> keyFunction, Function<? super E, Stream<V>> valueFunction) { verifyKeyAndValueFunctions(keyFunction, valueFunction); BiConsumer<ImmutableSetMultimap.Builder<K, V>, E> accumulator = (map, element) -> { K key = requireNonNull(keyFunction.apply(element), KEY_FUNCTION_CANT_RETURN_NULL_MESSAGE); Stream<V> valueStream = requireNonNull(valueFunction.apply(element), VALUE_FUNCTION_CANT_RETURN_NULL_MESSAGE); valueStream.forEach(value -> map.put(key, value)); }; BinaryOperator<ImmutableSetMultimap.Builder<K, V>> merger = (m1, m2) -> { for (Map.Entry<K, V> entry : m2.build().entries()) { m1.put(entry.getKey(), entry.getValue()); } return m1; }; return Collector.of( ImmutableSetMultimap::builder, accumulator, merger, ImmutableSetMultimap.Builder::build); }
@Test public void unorderedFlattenIndex_with_valueFunction_returns_SetMultimap() { SetMultimap<Integer, String> multimap = LIST2.stream() .collect(unorderedFlattenIndex(MyObj2::getId, MyObj2::getTexts)); assertThat(multimap.size()).isEqualTo(4); Map<Integer, Collection<String>> map = multimap.asMap(); assertThat(map.get(1)).containsOnly("A", "X"); assertThat(map.get(2)).containsOnly("B"); assertThat(map.get(3)).containsOnly("C"); }
public static double round(double value, int decimalPlaces) { double factor = Math.pow(10, decimalPlaces); return Math.round(value * factor) / factor; }
@Test public void testRound() { assertEquals(100.94, Helper.round(100.94, 2), 1e-7); assertEquals(100.9, Helper.round(100.94, 1), 1e-7); assertEquals(101.0, Helper.round(100.95, 1), 1e-7); // using negative values for decimalPlaces means we are rounding with precision > 1 assertEquals(1040, Helper.round(1041.02, -1), 1.e-7); assertEquals(1000, Helper.round(1041.02, -2), 1.e-7); }
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) { return validate(klass, options, false); }
@Test public void testWhenOptionIsDefinedOnMultipleInterfacesOnlyListedOnceWhenNotPresent() { JoinedOptions options = PipelineOptionsFactory.as(JoinedOptions.class); options.setFoo("Hello"); options.setRunner(CrashingRunner.class); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("required value for group [both]"); expectedException.expectMessage("properties [getBoth()]"); PipelineOptionsValidator.validate(JoinedOptions.class, options); }
@SuppressWarnings("unchecked") public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException { if (metric == null) { throw new NullPointerException("metric == null"); } if (metric instanceof MetricRegistry) { final MetricRegistry childRegistry = (MetricRegistry) metric; final String childName = name; childRegistry.addListener(new MetricRegistryListener() { @Override public void onGaugeAdded(String name, Gauge<?> gauge) { register(name(childName, name), gauge); } @Override public void onGaugeRemoved(String name) { remove(name(childName, name)); } @Override public void onCounterAdded(String name, Counter counter) { register(name(childName, name), counter); } @Override public void onCounterRemoved(String name) { remove(name(childName, name)); } @Override public void onHistogramAdded(String name, Histogram histogram) { register(name(childName, name), histogram); } @Override public void onHistogramRemoved(String name) { remove(name(childName, name)); } @Override public void onMeterAdded(String name, Meter meter) { register(name(childName, name), meter); } @Override public void onMeterRemoved(String name) { remove(name(childName, name)); } @Override public void onTimerAdded(String name, Timer timer) { register(name(childName, name), timer); } @Override public void onTimerRemoved(String name) { remove(name(childName, name)); } }); } else if (metric instanceof MetricSet) { registerAll(name, (MetricSet) metric); } else { final Metric existing = metrics.putIfAbsent(name, metric); if (existing == null) { onMetricAdded(name, metric); } else { throw new IllegalArgumentException("A metric named " + name + " already exists"); } } return metric; }
@Test public void registeringAMeterTriggersANotification() { assertThat(registry.register("thing", meter)) .isEqualTo(meter); verify(listener).onMeterAdded("thing", meter); }
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 noRetryAndFailed() throws Exception { Mockito.when(mockCallable.call()).thenThrow(new TimeoutException("timeout exception")); TimeoutException e = assertThrows(TimeoutException.class, () -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(0), 100, mockTime)); Mockito.verify(mockCallable, Mockito.times(1)).call(); assertEquals("timeout exception", e.getMessage()); }
public RegisteredClient() { this.client = new ClientDetailsEntity(); }
@Test public void testRegisteredClient() { // make sure all the pass-through getters and setters work RegisteredClient c = new RegisteredClient(); c.setClientId("s6BhdRkqt3"); c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk"); c.setClientSecretExpiresAt(new Date(1577858400L * 1000L)); c.setRegistrationAccessToken("this.is.an.access.token.value.ffx83"); c.setRegistrationClientUri("https://server.example.com/connect/register?client_id=s6BhdRkqt3"); c.setApplicationType(ClientDetailsEntity.AppType.WEB); c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2")); c.setClientName("My Example"); c.setLogoUri("https://client.example.org/logo.png"); c.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json"); c.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC); c.setJwksUri("https://client.example.org/my_public_keys.jwks"); c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5); c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256); c.setContacts(ImmutableSet.of("[email protected]", "[email protected]")); c.setRequestUris(ImmutableSet.of("https://client.example.org/rf.txt#qpXaRLh_n93TTR9F252ValdatUQvQiJi5BDub2BeznA")); assertEquals("s6BhdRkqt3", c.getClientId()); assertEquals("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk", c.getClientSecret()); assertEquals(new Date(1577858400L * 1000L), c.getClientSecretExpiresAt()); assertEquals("this.is.an.access.token.value.ffx83", c.getRegistrationAccessToken()); assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", c.getRegistrationClientUri()); assertEquals(ClientDetailsEntity.AppType.WEB, c.getApplicationType()); assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris()); assertEquals("My Example", c.getClientName()); assertEquals("https://client.example.org/logo.png", c.getLogoUri()); assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE, c.getSubjectType()); assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri()); assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod()); assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri()); assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg()); assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc()); assertEquals(ImmutableSet.of("[email protected]", "[email protected]"), c.getContacts()); assertEquals(ImmutableSet.of("https://client.example.org/rf.txt#qpXaRLh_n93TTR9F252ValdatUQvQiJi5BDub2BeznA"), c.getRequestUris()); }
@Override public void setUnixPermission(final Path file, final TransferStatus status) throws BackgroundException { final FileAttributes attr = new FileAttributes.Builder() .withPermissions(Integer.parseInt(status.getPermission().getMode(), 8)) .build(); try { session.sftp().setAttributes(file.getAbsolute(), attr); } catch(IOException e) { throw new SFTPExceptionMappingService().map("Failure to write attributes of {0}", e, file); } }
@Test public void testSetUnixPermission() throws Exception { final Path home = new SFTPHomeDirectoryService(session).find(); { final Path file = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new SFTPTouchFeature(session).touch(file, new TransferStatus()); new SFTPUnixPermissionFeature(session).setUnixPermission(file, new Permission(666)); assertEquals("666", new SFTPListService(session).list(home, new DisabledListProgressListener()).get(file).attributes().getPermission().getMode()); new SFTPDeleteFeature(session).delete(Collections.<Path>singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); } { final Path directory = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)); new SFTPDirectoryFeature(session).mkdir(directory, new TransferStatus()); new SFTPUnixPermissionFeature(session).setUnixPermission(directory, new Permission(666)); assertEquals("666", new SFTPListService(session).list(home, new DisabledListProgressListener()).get(directory).attributes().getPermission().getMode()); new SFTPDeleteFeature(session).delete(Collections.<Path>singletonList(directory), new DisabledLoginCallback(), new Delete.DisabledCallback()); } }
public RuleDescriptionSectionsGenerator getRuleDescriptionSectionsGenerator(RulesDefinition.Rule ruleDef) { Set<RuleDescriptionSectionsGenerator> generatorsFound = ruleDescriptionSectionsGenerators.stream() .filter(generator -> generator.isGeneratorForRule(ruleDef)) .collect(toSet()); checkState(generatorsFound.size() < 2, "More than one rule description section generator found for rule with key %s", ruleDef.key()); checkState(!generatorsFound.isEmpty(), "No rule description section generator found for rule with key %s", ruleDef.key()); return generatorsFound.iterator().next(); }
@Test public void getRuleDescriptionSectionsGenerator_whenNoGeneratorFound_throwsWithCorrectMessage() { assertThatIllegalStateException() .isThrownBy(() -> resolver.getRuleDescriptionSectionsGenerator(rule)) .withMessage("No rule description section generator found for rule with key RULE_KEY"); }
@Override public Mono<ExtensionStore> delete(String name, Long version) { return repository.findById(name) .flatMap(extensionStore -> { // reset the version extensionStore.setVersion(version); return repository.delete(extensionStore).thenReturn(extensionStore); }); }
@Test void shouldDoNotThrowExceptionWhenDeletingNonExistExt() { when(repository.findById(anyString())).thenReturn(Mono.empty()); client.delete("/registry/posts/hello-halo", 1L).block(); }