focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override @Transactional public boolean updateAfterApproval(Long userId, Integer userType, String clientId, Map<String, Boolean> requestedScopes) { // 如果 requestedScopes 为空,说明没有要求,则返回 true 通过 if (CollUtil.isEmpty(requestedScopes)) { return true; } // 更新批准的信息 boolean success = false; // 需要至少有一个同意 LocalDateTime expireTime = LocalDateTime.now().plusSeconds(TIMEOUT); for (Map.Entry<String, Boolean> entry : requestedScopes.entrySet()) { if (entry.getValue()) { success = true; } saveApprove(userId, userType, clientId, entry.getKey(), entry.getValue(), expireTime); } return success; }
@Test public void testUpdateAfterApproval_none() { // 准备参数 Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); String clientId = randomString(); // 调用 boolean success = oauth2ApproveService.updateAfterApproval(userId, userType, clientId, null); // 断言 assertTrue(success); List<OAuth2ApproveDO> result = oauth2ApproveMapper.selectList(); assertEquals(0, result.size()); }
@Override public Collection<RedisServer> masters() { List<Map<String, String>> masters = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_MASTERS); return toRedisServersList(masters); }
@Test public void testMasters() { Collection<RedisServer> masters = connection.masters(); assertThat(masters).hasSize(1); }
@Override public Num calculate(BarSeries series, Position position) { return position.getProfit(); }
@Test public void calculateOnlyWithProfitPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series, series.numOf(50)), Trade.sellAt(2, series, series.numOf(50)), Trade.buyAt(3, series, series.numOf(50)), Trade.sellAt(5, series, series.numOf(50))); AnalysisCriterion profit = getCriterion(); assertNumEquals(500 + 250, profit.calculate(series, tradingRecord)); }
@Override public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterSlaveMap() { Iterable<RedisClusterNode> res = clusterGetNodes(); Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>(); for (Iterator<RedisClusterNode> iterator = res.iterator(); iterator.hasNext();) { RedisClusterNode redisClusterNode = iterator.next(); if (redisClusterNode.isMaster()) { masters.add(redisClusterNode); } } Map<RedisClusterNode, Collection<RedisClusterNode>> result = new HashMap<RedisClusterNode, Collection<RedisClusterNode>>(); for (Iterator<RedisClusterNode> iterator = res.iterator(); iterator.hasNext();) { RedisClusterNode redisClusterNode = iterator.next(); for (RedisClusterNode masterNode : masters) { if (redisClusterNode.getMasterId() != null && redisClusterNode.getMasterId().equals(masterNode.getId())) { Collection<RedisClusterNode> list = result.get(masterNode); if (list == null) { list = new ArrayList<RedisClusterNode>(); result.put(masterNode, list); } list.add(redisClusterNode); } } } return result; }
@Test public void testClusterGetMasterSlaveMap() { Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterSlaveMap(); assertThat(map).hasSize(3); for (Collection<RedisClusterNode> slaves : map.values()) { assertThat(slaves).hasSize(1); } }
@Override public void reset() { super.reset(); this.minDeltaInCurrentBlock = Integer.MAX_VALUE; }
@Test public void randomDataTest() throws IOException { int maxSize = 1000; int[] data = new int[maxSize]; for (int round = 0; round < 100000; round++) { int size = random.nextInt(maxSize); for (int i = 0; i < size; i++) { data[i] = random.nextInt(); } shouldReadAndWrite(data, size); writer.reset(); } }
public Gson create() { List<TypeAdapterFactory> factories = new ArrayList<>(this.factories.size() + this.hierarchyFactories.size() + 3); factories.addAll(this.factories); Collections.reverse(factories); List<TypeAdapterFactory> hierarchyFactories = new ArrayList<>(this.hierarchyFactories); Collections.reverse(hierarchyFactories); factories.addAll(hierarchyFactories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); return new Gson( excluder, fieldNamingPolicy, new HashMap<>(instanceCreators), serializeNulls, complexMapKeySerialization, generateNonExecutableJson, escapeHtmlChars, formattingStyle, strictness, serializeSpecialFloatingPointValues, useJdkUnsafe, longSerializationPolicy, datePattern, dateStyle, timeStyle, new ArrayList<>(this.factories), new ArrayList<>(this.hierarchyFactories), factories, objectToNumberStrategy, numberToNumberStrategy, new ArrayList<>(reflectionFilters)); }
@Test public void testDefaultStrictness() throws IOException { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); assertThat(gson.newJsonReader(new StringReader("{}")).getStrictness()) .isEqualTo(Strictness.LEGACY_STRICT); assertThat(gson.newJsonWriter(new StringWriter()).getStrictness()) .isEqualTo(Strictness.LEGACY_STRICT); }
public synchronized LogAction record(double... values) { return record(DEFAULT_RECORDER_NAME, timer.monotonicNow(), values); }
@Test public void testLoggingWithValue() { assertTrue(helper.record(1).shouldLog()); for (int i = 0; i < 4; i++) { timer.advance(LOG_PERIOD / 5); assertFalse(helper.record(i % 2 == 0 ? 0 : 1).shouldLog()); } timer.advance(LOG_PERIOD); LogAction action = helper.record(0.5); assertTrue(action.shouldLog()); assertEquals(5, action.getCount()); assertEquals(0.5, action.getStats(0).getMean(), 0.01); assertEquals(1.0, action.getStats(0).getMax(), 0.01); assertEquals(0.0, action.getStats(0).getMin(), 0.01); }
@Override public Result reconcile(Request request) { client.fetch(Theme.class, request.name()) .ifPresent(theme -> { if (isDeleted(theme)) { cleanUpResourcesAndRemoveFinalizer(request.name()); return; } addFinalizerIfNecessary(theme); themeSettingDefaultConfig(theme); reconcileStatus(request.name()); }); return new Result(false, null); }
@Test void reconcileDeleteRetry() { Theme theme = fakeTheme(); final MetadataOperator metadata = theme.getMetadata(); Path testWorkDir = tempDirectory.resolve("reconcile-delete"); when(themeRoot.get()).thenReturn(testWorkDir); final ThemeReconciler themeReconciler = new ThemeReconciler(extensionClient, themeRoot, systemVersionSupplier); final int[] retryFlags = {0, 0}; when(extensionClient.fetch(eq(Setting.class), eq("theme-test-setting"))) .thenAnswer((Answer<Optional<Setting>>) invocation -> { retryFlags[0]++; // retry 2 times if (retryFlags[0] < 3) { return Optional.of(new Setting()); } return Optional.empty(); }); when(extensionClient.list(eq(AnnotationSetting.class), any(), eq(null))) .thenAnswer((Answer<List<AnnotationSetting>>) invocation -> { retryFlags[1]++; // retry 2 times if (retryFlags[1] < 3) { return List.of(new AnnotationSetting()); } return List.of(); }); themeReconciler.reconcile(new Reconciler.Request(metadata.getName())); String settingName = theme.getSpec().getSettingName(); verify(extensionClient, times(2)).fetch(eq(Theme.class), eq(metadata.getName())); verify(extensionClient, times(3)).fetch(eq(Setting.class), eq(settingName)); verify(extensionClient, times(3)).list(eq(AnnotationSetting.class), any(), eq(null)); }
public Optional<Long> getTokenTimeout( final Optional<String> token, final KsqlConfig ksqlConfig, final Optional<KsqlAuthTokenProvider> authTokenProvider ) { final long maxTimeout = ksqlConfig.getLong(KsqlConfig.KSQL_WEBSOCKET_CONNECTION_MAX_TIMEOUT_MS); if (maxTimeout > 0) { if (authTokenProvider.isPresent() && token.isPresent()) { try { final long tokenTimeout = authTokenProvider.get() .getLifetimeMs(StringUtils.removeStart(token.get(), BEARER)) - clock.millis(); return Optional.of(Math.min(tokenTimeout, maxTimeout)); } catch (final Exception e) { log.error(e.getMessage()); } } return Optional.of(maxTimeout); } else { return Optional.empty(); } }
@Test public void shouldReturnDefaultWhenNoTokenPresent() { assertThat(authenticationUtil.getTokenTimeout(Optional.empty(), ksqlConfig, Optional.of(authTokenProvider)), equalTo(Optional.of(60000L))); }
private void stop(int numOfServicesStarted, boolean stopOnlyStartedServices) { // stop in reverse order of start Exception firstException = null; List<Service> services = getServices(); for (int i = numOfServicesStarted - 1; i >= 0; i--) { Service service = services.get(i); if (LOG.isDebugEnabled()) { LOG.debug("Stopping service #" + i + ": " + service); } STATE state = service.getServiceState(); //depending on the stop police if (state == STATE.STARTED || (!stopOnlyStartedServices && state == STATE.INITED)) { Exception ex = ServiceOperations.stopQuietly(LOG, service); if (ex != null && firstException == null) { firstException = ex; } } } //after stopping all services, rethrow the first exception raised if (firstException != null) { throw ServiceStateException.convert(firstException); } }
@Test(timeout = 10000) public void testAddStartedChildInStop() throws Throwable { CompositeService parent = new CompositeService("parent"); BreakableService child = new BreakableService(); child.init(new Configuration()); child.start(); parent.init(new Configuration()); parent.start(); parent.stop(); AddSiblingService.addChildToService(parent, child); assertInState(STATE.STARTED, child); }
public Exchange createDbzExchange(DebeziumConsumer consumer, final SourceRecord sourceRecord) { final Exchange exchange; if (consumer != null) { exchange = consumer.createExchange(false); } else { exchange = super.createExchange(); } final Message message = exchange.getIn(); final Schema valueSchema = sourceRecord.valueSchema(); final Object value = sourceRecord.value(); // extract values from SourceRecord final Map<String, Object> sourceMetadata = extractSourceMetadataValueFromValueStruct(valueSchema, value); final Object operation = extractValueFromValueStruct(valueSchema, value, Envelope.FieldName.OPERATION); final Object before = extractValueFromValueStruct(valueSchema, value, Envelope.FieldName.BEFORE); final Object body = extractBodyValueFromValueStruct(valueSchema, value); final Object timestamp = extractValueFromValueStruct(valueSchema, value, Envelope.FieldName.TIMESTAMP); final Object ddl = extractValueFromValueStruct(valueSchema, value, HistoryRecord.Fields.DDL_STATEMENTS); // set message headers message.setHeader(DebeziumConstants.HEADER_IDENTIFIER, sourceRecord.topic()); message.setHeader(DebeziumConstants.HEADER_KEY, sourceRecord.key()); message.setHeader(DebeziumConstants.HEADER_SOURCE_METADATA, sourceMetadata); message.setHeader(DebeziumConstants.HEADER_OPERATION, operation); message.setHeader(DebeziumConstants.HEADER_BEFORE, before); message.setHeader(DebeziumConstants.HEADER_TIMESTAMP, timestamp); message.setHeader(DebeziumConstants.HEADER_DDL_SQL, ddl); message.setHeader(Exchange.MESSAGE_TIMESTAMP, timestamp); message.setBody(body); return exchange; }
@Test void testIfCreatesExchangeFromSourceUpdateRecord() { final SourceRecord sourceRecord = createUpdateRecord(); final Exchange exchange = debeziumEndpoint.createDbzExchange(null, sourceRecord); final Message inMessage = exchange.getIn(); assertNotNull(exchange); // assert headers assertEquals("dummy", inMessage.getHeader(DebeziumConstants.HEADER_IDENTIFIER)); assertEquals(Envelope.Operation.UPDATE.code(), inMessage.getHeader(DebeziumConstants.HEADER_OPERATION)); final Struct key = (Struct) inMessage.getHeader(DebeziumConstants.HEADER_KEY); assertEquals(12345, key.getInt32("id").intValue()); assertSourceMetadata(inMessage); // assert value final Struct before = (Struct) inMessage.getHeader(DebeziumConstants.HEADER_BEFORE); final Struct after = (Struct) inMessage.getBody(); assertNotNull(before); assertNotNull(after); assertEquals((byte) 1, before.getInt8("id").byteValue()); assertEquals((byte) 2, after.getInt8("id").byteValue()); }
public void runExtractor(Message msg) { try(final Timer.Context ignored = completeTimer.time()) { final String field; try (final Timer.Context ignored2 = conditionTimer.time()) { // We can only work on Strings. if (!(msg.getField(sourceField) instanceof String)) { conditionMissesCounter.inc(); return; } field = (String) msg.getField(sourceField); // Decide if to extract at all. if (conditionType.equals(ConditionType.STRING)) { if (field.contains(conditionValue)) { conditionHitsCounter.inc(); } else { conditionMissesCounter.inc(); return; } } else if (conditionType.equals(ConditionType.REGEX)) { if (regexConditionPattern.matcher(field).find()) { conditionHitsCounter.inc(); } else { conditionMissesCounter.inc(); return; } } } try (final Timer.Context ignored2 = executionTimer.time()) { Result[] results; try { results = run(field); } catch (ExtractorException e) { final String error = "Could not apply extractor <" + getTitle() + " (" + getId() + ")>"; msg.addProcessingError(new Message.ProcessingError( ProcessingFailureCause.ExtractorException, error, ExceptionUtils.getRootCauseMessage(e))); return; } if (results == null || results.length == 0 || Arrays.stream(results).anyMatch(result -> result.getValue() == null)) { return; } else if (results.length == 1 && results[0].target == null) { // results[0].target is null if this extractor cannot produce multiple fields use targetField in that case msg.addField(targetField, results[0].getValue()); } else { for (final Result result : results) { msg.addField(result.getTarget(), result.getValue()); } } // Remove original from message? if (cursorStrategy.equals(CursorStrategy.CUT) && !targetField.equals(sourceField) && !Message.RESERVED_FIELDS.contains(sourceField) && results[0].beginIndex != -1) { final StringBuilder sb = new StringBuilder(field); final List<Result> reverseList = Arrays.stream(results) .sorted(Comparator.<Result>comparingInt(result -> result.endIndex).reversed()) .collect(Collectors.toList()); // remove all from reverse so that the indices still match for (final Result result : reverseList) { sb.delete(result.getBeginIndex(), result.getEndIndex()); } final String builtString = sb.toString(); final String finalResult = builtString.trim().isEmpty() ? "fullyCutByExtractor" : builtString; msg.removeField(sourceField); // TODO don't add an empty field back, or rather don't add fullyCutByExtractor msg.addField(sourceField, finalResult); } runConverters(msg); } } }
@Test public void testConvertersAreExecutedInOrder() throws Exception { final Converter converter1 = new TestConverter.Builder() .callback(new Function<Object, Object>() { @Nullable @Override public Object apply(Object input) { return ((String) input) + "1"; } }) .build(); final Converter converter2 = new TestConverter.Builder() .callback(new Function<Object, Object>() { @Nullable @Override public Object apply(Object input) { return ((String) input) + "2"; } }) .build(); final Converter converter3 = new TestConverter.Builder() .callback(new Function<Object, Object>() { @Nullable @Override public Object apply(Object input) { return ((String) input) + "3"; } }) .build(); final TestExtractor extractor = new TestExtractor.Builder() .converters(Lists.newArrayList(converter1, converter2, converter3)) .callback(new Callable<Result[]>() { @Override public Result[] call() throws Exception { return new Result[] { new Result("converter", -1, -1) }; } }) .build(); final Message msg = createMessage("message"); extractor.runExtractor(msg); assertThat(msg.getField("target")).isEqualTo("converter123"); }
public FEELFnResult<String> invoke(@ParameterName("from") Object val) { if ( val == null ) { return FEELFnResult.ofResult( null ); } else { return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) ); } }
@Test void invokeDurationDays() { FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofDays(9)), "P9D"); FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofDays(-9)), "-P9D"); }
public void write(CruiseConfig configForEdit, OutputStream output, boolean skipPreprocessingAndValidation) throws Exception { LOGGER.debug("[Serializing Config] Starting to write. Validation skipped? {}", skipPreprocessingAndValidation); MagicalGoConfigXmlLoader loader = new MagicalGoConfigXmlLoader(configCache, registry); if (!configForEdit.getOrigin().isLocal()) { throw new GoConfigInvalidException(configForEdit, "Attempted to save merged configuration with partials"); } if (!skipPreprocessingAndValidation) { loader.preprocessAndValidate(configForEdit); LOGGER.debug("[Serializing Config] Done with cruise config validators."); } Document document = createEmptyCruiseConfigDocument(); write(configForEdit, document.getRootElement(), configCache, registry); LOGGER.debug("[Serializing Config] XSD and DOM validation."); verifyXsdValid(document); MagicalGoConfigXmlLoader.validateDom(document.getRootElement(), registry); LOGGER.info("[Serializing Config] Generating config partial."); XmlUtils.writeXml(document, output); LOGGER.debug("[Serializing Config] Finished writing config partial."); }
@Test public void shouldNotAllowMultiplePackagesWithSameId() throws Exception { Configuration packageConfiguration = new Configuration(getConfigurationProperty("name", false, "go-agent")); Configuration repositoryConfiguration = new Configuration(getConfigurationProperty("url", false, "http://go")); PackageRepository packageRepository = createPackageRepository("plugin-id-1", "version", "id1", "name1", repositoryConfiguration, new Packages(new PackageDefinition("id", "name", packageConfiguration))); PackageRepository anotherPackageRepository = createPackageRepository("plugin-id-2", "version", "id2", "name2", repositoryConfiguration, new Packages(new PackageDefinition("id", "name", packageConfiguration))); cruiseConfig.setPackageRepositories(new PackageRepositories(packageRepository, anotherPackageRepository)); try { xmlWriter.write(cruiseConfig, output, false); fail("should not have allowed two package repositories with same id"); } catch (XsdValidationException e) { assertThat(e.getMessage(), anyOf( is("Duplicate unique value [id] declared for identity constraint of element \"cruise\"."), is("Duplicate unique value [id] declared for identity constraint \"uniquePackageId\" of element \"cruise\".") )); } }
public boolean accept(final T t) { checkContext(); if (isComplete() || hasSentComplete()) { throw new IllegalStateException("Cannot call accept after complete is called"); } if (!isCancelled() && !isFailed()) { if (getDemand() == 0) { buffer.add(t); } else { doOnNext(t); } } return buffer.size() >= bufferMaxSize; }
@Test public void shouldNotAllowAcceptingAfterComplete() throws Exception { TestSubscriber<String> subscriber = new TestSubscriber<>(context); subscribeOnContext(subscriber); execOnContextAndWait(getBufferedPublisher()::complete); AtomicBoolean failed = new AtomicBoolean(); execOnContextAndWait(() -> { try { getBufferedPublisher().accept("foo"); failed.set(true); } catch (IllegalStateException e) { // OK } }); assertThat(failed.get(), equalTo(false)); }
@Udf public String chr(@UdfParameter( description = "Decimal codepoint") final Integer decimalCode) { if (decimalCode == null) { return null; } if (!Character.isValidCodePoint(decimalCode)) { return null; } final char[] resultChars = Character.toChars(decimalCode); return String.valueOf(resultChars); }
@Test public void shouldConvertControlChar() { final String result = udf.chr(9); assertThat(result, is("\t")); }
@Override public double getStdDev() { // two-pass algorithm for variance, avoids numeric overflow if (values.length <= 1) { return 0; } final double mean = getMean(); double variance = 0; for (int i = 0; i < values.length; i++) { final double diff = values[i] - mean; variance += normWeights[i] * diff*diff; } return Math.sqrt(variance); }
@Test public void calculatesTheStdDev() throws Exception { assertThat(snapshot.getStdDev()) .isEqualTo(1.2688, offset(0.0001)); }
@Override public Object decorate(RequestedField field, Object value, SearchUser searchUser) { try { final Node node = nodeService.byNodeId(value.toString()); return node.getTitle(); } catch (NodeNotFoundException e) { return value; } }
@Test void testUnknownNode() { final Object decorated = decorator.decorate(RequestedField.parse(Message.FIELD_GL2_SOURCE_NODE), "2e7e1436-9ca4-43e3-b857-c75e61dea424", TestSearchUser.builder().build()); Assertions.assertThat(decorated).isEqualTo("2e7e1436-9ca4-43e3-b857-c75e61dea424"); }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; GitMaterial that = (GitMaterial) o; return Objects.equals(url, that.url) && Objects.equals(refSpecOrBranch, that.refSpecOrBranch) && Objects.equals(submoduleFolder, that.submoduleFolder); }
@Test void shouldNotBeEqualWhenTypeDifferent() { Material material = MaterialsMother.gitMaterials("url1").get(0); final Material hgMaterial = MaterialsMother.hgMaterials("url1", "hgdir").get(0); assertThat(material.equals(hgMaterial)).isFalse(); assertThat(hgMaterial.equals(material)).isFalse(); }
@Override public void seek(long newPos) { Preconditions.checkState(!closed, "already closed"); Preconditions.checkArgument(newPos >= 0, "position is negative: %s", newPos); // this allows a seek beyond the end of the stream but the next read will fail next = newPos; }
@Test public void testSeek() throws Exception { S3URI uri = new S3URI("s3://bucket/path/to/seek.dat"); byte[] expected = randomData(1024 * 1024); writeS3Data(uri, expected); try (SeekableInputStream in = new S3InputStream(s3, uri)) { in.seek(expected.length / 2); byte[] actual = new byte[expected.length / 2]; IOUtil.readFully(in, actual, 0, expected.length / 2); assertThat(actual) .isEqualTo(Arrays.copyOfRange(expected, expected.length / 2, expected.length)); } }
@JsonProperty public URI getUri() { return uri; }
@Test public void testQueryDividedIntoSplitsFirstSplitHasRightTime() throws URISyntaxException { Instant now = LocalDateTime.of(2019, 10, 2, 7, 26, 56, 0).toInstant(UTC); PrometheusConnectorConfig config = getCommonConfig(prometheusHttpServer.resolve("/prometheus-data/prometheus-metrics.json")); PrometheusClient client = new PrometheusClient(config, METRIC_CODEC, TYPE_MANAGER); PrometheusTable table = client.getTable("default", "up"); PrometheusTableHandle tableHandle = new PrometheusTableHandle("default", table.getName()); TupleDomain<ColumnHandle> columnConstraints = TupleDomain.withColumnDomains( ImmutableMap.of( new PrometheusColumnHandle("value", BIGINT, 1), Domain.all(VARCHAR), new PrometheusColumnHandle("text", createUnboundedVarcharType(), 0), Domain.all(VARCHAR))); PrometheusTableLayoutHandle tableLayoutHandle = new PrometheusTableLayoutHandle(tableHandle, columnConstraints); PrometheusSplitManager splitManager = new PrometheusSplitManager(client, fixedClockAt(now), config); ConnectorSplitSource splits = splitManager.getSplits( null, null, tableLayoutHandle, null); PrometheusSplit split = (PrometheusSplit) splits.getNextBatch(NOT_PARTITIONED, 1).getNow(null).getSplits().get(0); String queryInSplit = split.getUri().getQuery(); String timeShouldBe = decimalSecondString(now.toEpochMilli() - config.getMaxQueryRangeDuration().toMillis() + config.getQueryChunkSizeDuration().toMillis() - OFFSET_MILLIS * 20); assertEquals(queryInSplit, new URI("http://doesnotmatter.example:9090/api/v1/query?query=up[" + getQueryChunkSizeDurationAsPrometheusCompatibleDurationString(config) + "]" + "&time=" + timeShouldBe).getQuery()); }
public static boolean classInJarImplementsIface(java.io.File jar, String fqcn, Class xface) { boolean ret = false; java.net.URLClassLoader loader = null; try { loader = (URLClassLoader) ClassLoaderUtils.loadJar(jar); if (xface.isAssignableFrom(Class.forName(fqcn, false, loader))){ ret = true; } } catch (ClassNotFoundException | NoClassDefFoundError | IOException e) { throw new RuntimeException(e); } finally { if (loader != null) { try { loader.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } } return ret; }
@Test public void testClassInJarImplementsIface() { assertTrue(Reflections.classImplementsIface(aImplementation.class.getName(), aInterface.class)); assertFalse(Reflections.classImplementsIface(aImplementation.class.getName(), bInterface.class)); }
public static ReferenceMap toReferenceMap(Map<String, Object> m) { final ImmutableMap.Builder<String, Reference> mapBuilder = ImmutableMap.builder(); for (Map.Entry<String, Object> entry : m.entrySet()) { final Object value = entry.getValue(); if (value instanceof Collection) { @SuppressWarnings("unchecked") final List<Object> childList = (List<Object>) value; mapBuilder.put(entry.getKey(), toReferenceList(childList)); } if (value instanceof Map) { @SuppressWarnings("unchecked") final Map<String, Object> childMap = (Map<String, Object>) value; mapBuilder.put(entry.getKey(), toReferenceMap(childMap)); } else { final ValueReference valueReference = ValueReference.of(value); if (valueReference != null) { mapBuilder.put(entry.getKey(), valueReference); } } } return new ReferenceMap(mapBuilder.build()); }
@Test public void toReferenceMap() { final ImmutableMap<String, Object> map = ImmutableMap.<String, Object>builder() .put("boolean", true) .put("double", 2.0D) .put("float", 1.0f) .put("integer", 42) .put("long", 10000000000L) .put("string", "String") .put("enum", TestEnum.A) .put("list", ImmutableList.of(1, 2.0f, "3", true)) .put("nestedList", ImmutableList.of( ImmutableMap.of( "k1", "v1", "k2", 2), ImmutableMap.of( "k1", "v2", "k2", 4) )) .put("map", ImmutableMap.of( "k1", "v1", "k2", 2)) .build(); final ReferenceMap expectedMap = new ReferenceMap(ImmutableMap.<String, Reference>builder() .put("boolean", ValueReference.of(true)) .put("double", ValueReference.of(2.0D)) .put("float", ValueReference.of(1.0f)) .put("integer", ValueReference.of(42)) .put("long", ValueReference.of(10000000000L)) .put("string", ValueReference.of("String")) .put("enum", ValueReference.of(TestEnum.A)) .put("list", new ReferenceList(ImmutableList.of( ValueReference.of(1), ValueReference.of(2.0f), ValueReference.of("3"), ValueReference.of(true)))) .put("nestedList", new ReferenceList(ImmutableList.of( new ReferenceMap(ImmutableMap.of( "k1", ValueReference.of("v1"), "k2", ValueReference.of(2))), new ReferenceMap(ImmutableMap.of( "k1", ValueReference.of("v2"), "k2", ValueReference.of(4)))))) .put("map", new ReferenceMap(ImmutableMap.of( "k1", ValueReference.of("v1"), "k2", ValueReference.of(2)))) .build()); final ReferenceMap valueReferenceMap = ReferenceMapUtils.toReferenceMap(map); assertThat(valueReferenceMap).isEqualTo(expectedMap); }
protected static String clusterNameWithRouting(final String clusterName, final String destinationColo, final String masterColo, final boolean defaultRoutingToMasterColo, final boolean enableSymlink) { final String defaultColoClusterName; if (!"".matches(destinationColo) && defaultRoutingToMasterColo) { // If this service is configured to route all requests to the master colo by default // then we need to configure the service to use the master colo. if (enableSymlink) { defaultColoClusterName = D2Utils.getSymlinkNameForMaster(clusterName); } else { defaultColoClusterName = D2Utils.addSuffixToBaseName(clusterName, masterColo); } } else { // For regular service node, if not route to master colo, the cluster name should be the original // cluster without suffix. defaultColoClusterName = clusterName; } return defaultColoClusterName; }
@Test public static void testClusterNameWithRouting() throws Exception { String clusterNameWithRouting; clusterNameWithRouting = D2Config.clusterNameWithRouting("clusterName", "destinationColo", "masterColo", false, false); assertEquals("clusterName", clusterNameWithRouting); clusterNameWithRouting = D2Config.clusterNameWithRouting("clusterName", "destinationColo", "masterColo", true, false); assertEquals("clusterName-masterColo", clusterNameWithRouting); clusterNameWithRouting = D2Config.clusterNameWithRouting("clusterName", "destinationColo", "masterColo", true, true); assertEquals(D2Utils.getSymlinkNameForMaster("clusterName"), clusterNameWithRouting); clusterNameWithRouting = D2Config.clusterNameWithRouting("clusterName", "", "masterColo", false, false); assertEquals("clusterName", clusterNameWithRouting); clusterNameWithRouting = D2Config.clusterNameWithRouting("clusterName", "", "masterColo", true, false); assertEquals("clusterName", clusterNameWithRouting); }
@Override public String getAuthorizeUrl(Integer socialType, Integer userType, String redirectUri) { // 获得对应的 AuthRequest 实现 AuthRequest authRequest = buildAuthRequest(socialType, userType); // 生成跳转地址 String authorizeUri = authRequest.authorize(AuthStateUtils.createState()); return HttpUtils.replaceUrlQuery(authorizeUri, "redirect_uri", redirectUri); }
@Test public void testGetAuthorizeUrl() { try (MockedStatic<AuthStateUtils> authStateUtilsMock = mockStatic(AuthStateUtils.class)) { // 准备参数 Integer socialType = SocialTypeEnum.WECHAT_MP.getType(); Integer userType = randomPojo(UserTypeEnum.class).getValue(); String redirectUri = "sss"; // mock 获得对应的 AuthRequest 实现 AuthRequest authRequest = mock(AuthRequest.class); when(authRequestFactory.get(eq("WECHAT_MP"))).thenReturn(authRequest); // mock 方法 authStateUtilsMock.when(AuthStateUtils::createState).thenReturn("aoteman"); when(authRequest.authorize(eq("aoteman"))).thenReturn("https://www.iocoder.cn?redirect_uri=yyy"); // 调用 String url = socialClientService.getAuthorizeUrl(socialType, userType, redirectUri); // 断言 assertEquals("https://www.iocoder.cn?redirect_uri=sss", url); } }
public static RowCoder of(Schema schema) { return new RowCoder(schema); }
@Test public void testConsistentWithEqualsArrayOfArrayOfBytes() throws Exception { FieldType fieldType = FieldType.array(FieldType.array(FieldType.BYTES)); Schema schema = Schema.of(Schema.Field.of("f1", fieldType)); RowCoder coder = RowCoder.of(schema); List<byte[]> innerList1 = Collections.singletonList(new byte[] {1, 2, 3, 4}); List<List<byte[]>> list1 = Collections.singletonList(innerList1); Row row1 = Row.withSchema(schema).addValue(list1).build(); List<byte[]> innerList2 = Collections.singletonList(new byte[] {1, 2, 3, 4}); List<List<byte[]>> list2 = Collections.singletonList(innerList2); Row row2 = Row.withSchema(schema).addValue(list2).build(); Assume.assumeTrue(coder.consistentWithEquals()); CoderProperties.coderConsistentWithEquals(coder, row1, row2); }
public static void defineParams(WebService.NewAction action, Languages languages) { action.createParam(PARAM_QUALITY_PROFILE) .setDescription("Quality profile name.") .setRequired(true) .setExampleValue("Sonar way"); action.createParam(PARAM_LANGUAGE) .setDescription("Quality profile language.") .setRequired(true) .setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet())); }
@Test public void define_ws_parameters() { WebService.Context context = new WebService.Context(); WebService.NewController controller = context.createController("api/qualityprofiles"); WebService.NewAction newAction = controller.createAction("do").setHandler((request, response) -> { }); Languages languages = new Languages(newLanguage("java"), newLanguage("js")); QProfileReference.defineParams(newAction, languages); controller.done(); WebService.Action action = context.controller("api/qualityprofiles").action("do"); assertThat(action.param("language")).isNotNull(); assertThat(action.param("language").possibleValues()).containsOnly("java", "js"); assertThat(action.param("qualityProfile")).isNotNull(); }
boolean isWriteEnclosureForWriteField( byte[] str ) { return ( meta.isEnclosureForced() && !meta.isPadded() ) || isEnclosureFixDisabledAndContainsSeparatorOrEnclosure( str ); }
@Test public void testWriteEnclosureForWriteFieldWithEnclosureForced() { TextFileOutputData data = new TextFileOutputData(); data.writer = new ByteArrayOutputStream(); data.binarySeparator = new byte[1]; TextFileOutputMeta meta = getTextFileOutputMeta(); meta.setEnclosureForced(true); meta.setPadded(true); meta.setEnclosureFixDisabled(true); stepMockHelper.stepMeta.setStepMetaInterface( meta ); TextFileOutput textFileOutput = getTextFileOutput(data, meta); byte[] str = new byte[1]; assertFalse(textFileOutput.isWriteEnclosureForWriteField(str)); }
public static Short min(Short a, Short b) { return a <= b ? a : b; }
@Test void testMin() { assertThat(summarize(-1000, 0, 1, 50, 999, 1001).getMin().shortValue()) .isEqualTo((short) -1000); assertThat(summarize((int) Short.MIN_VALUE, -1000, 0).getMin().shortValue()) .isEqualTo(Short.MIN_VALUE); assertThat(summarize(1, 8, 7, 6, 9, 10, 2, 3, 5, 0, 11, -2, 3).getMin().shortValue()) .isEqualTo((short) -2); assertThat( summarize(1, 8, 7, 6, 9, null, 10, 2, 3, 5, null, 0, 11, -2, 3) .getMin() .shortValue()) .isEqualTo((short) -2); assertThat(summarize().getMin()).isNull(); }
public boolean hasOobLog(String secretString) { // making a blocking call to get result Optional<PollingResult> result = sendPollingRequest(secretString); if (result.isPresent()) { // In the future we may refactor hasOobLog() to return finer grained info about what kind // of oob is logged return result.get().getHasDnsInteraction() || result.get().getHasHttpInteraction(); } else { // we may choose to retry sendPollingRequest() if oob interactions do arrive late. return false; } }
@Test public void isVulnerable_noLogRecordFetched_returnsFalse() throws IOException { MockWebServer mockWebServer = new MockWebServer(); mockWebServer.enqueue( new MockResponse().setResponseCode(HttpStatus.NOT_FOUND.code()).setBody("")); client = new TcsClient(VALID_DOMAIN, VALID_PORT, mockWebServer.url("/").toString(), httpClient); boolean detectionResult = client.hasOobLog(SECRET); assertThat(detectionResult).isFalse(); mockWebServer.shutdown(); }
@Override public long extract(final Object key, final GenericRow value) { final String colValue = (String) extractor.extract(key, value); try { return timestampParser.parse(colValue); } catch (final KsqlException e) { throw new KsqlException("Unable to parse string timestamp." + " timestamp=" + value + " timestamp_format=" + format, e); } }
@Test public void shouldExtractTimestampFromStringWithFormat() throws ParseException { // Given: when(columnExtractor.extract(any(), any())).thenReturn("2010-Jan-11"); // When: final long actualTime = extractor.extract(key, value); final long expectedTime = new SimpleDateFormat(FORAMT).parse("2010-Jan-11").getTime(); assertThat(actualTime, equalTo(expectedTime)); }
@Override public Optional<BufferOrEvent> pollNext() throws IOException, InterruptedException { return getNextBufferOrEvent(false); }
@Test void testEmptyPull() throws IOException, InterruptedException { final SingleInputGate inputGate1 = createInputGate(1); TestInputChannel inputChannel1 = new TestInputChannel(inputGate1, 0, false, true); inputGate1.setInputChannels(inputChannel1); final SingleInputGate inputGate2 = createInputGate(1); TestInputChannel inputChannel2 = new TestInputChannel(inputGate2, 0, false, true); inputGate2.setInputChannels(inputChannel2); UnionInputGate inputGate = new UnionInputGate(inputGate1, inputGate2); inputChannel1.notifyChannelNonEmpty(); assertThat(inputGate.getAvailableFuture()).isDone(); assertThat(inputGate.pollNext()).isNotPresent(); assertThat(inputGate.getAvailableFuture()).isNotDone(); }
@Override public int hashCode() { return Objects.hash( Arrays.hashCode(salt), Arrays.hashCode(storedKey), Arrays.hashCode(serverKey), iterations ); }
@Test public void testEqualsSameInstance() { byte[] salt = {1, 2, 3}; byte[] storedKey = {4, 5, 6}; byte[] serverKey = {7, 8, 9}; int iterations = 1000; ScramCredentialData data = new ScramCredentialData(salt, storedKey, serverKey, iterations); // Test equals method for same instance assertEquals(data, data); assertEquals(data.hashCode(), data.hashCode()); }
public ChannelFuture enqueue(QueuedCommand command, boolean rst) { return enqueue(command); }
@Test @Disabled void testChunk() throws Exception { WriteQueue writeQueue = new WriteQueue(); // test deque chunk size EmbeddedChannel embeddedChannel = new EmbeddedChannel(); TripleStreamChannelFuture tripleStreamChannelFuture = new TripleStreamChannelFuture(embeddedChannel); writeMethodCalledTimes.set(0); for (int i = 0; i < DEQUE_CHUNK_SIZE; i++) { writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()) .channel(channel)); } writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()) .channel(channel)); while (writeMethodCalledTimes.get() != (DEQUE_CHUNK_SIZE + 1)) { Thread.sleep(50); } Mockito.verify(channel, Mockito.times(DEQUE_CHUNK_SIZE + 1)).write(Mockito.any(), Mockito.any()); }
@Override public HttpResponseOutputStream<Metadata> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final DbxUserFilesRequests files = new DbxUserFilesRequests(session.getClient(file)); final UploadSessionStartUploader start = files.uploadSessionStart(); new DefaultStreamCloser().close(start.getOutputStream()); final String sessionId = start.finish().getSessionId(); if(log.isDebugEnabled()) { log.debug(String.format("Obtained session id %s for upload %s", sessionId, file)); } final UploadSessionAppendV2Uploader uploader = open(files, sessionId, 0L); return new SegmentingUploadProxyOutputStream(file, status, files, uploader, sessionId); } catch(DbxException ex) { throw new DropboxExceptionMappingService().map("Upload failed.", ex, file); } }
@Test(expected = AccessDeniedException.class) public void testWriteDesktopIni() throws Exception { final DropboxWriteFeature write = new DropboxWriteFeature(session); final TransferStatus status = new TransferStatus(); final byte[] content = RandomUtils.nextBytes(0); status.setLength(content.length); final Path test = new Path(new DefaultHomeFinderService(session).find(), "desktop.ini", EnumSet.of(Path.Type.file)); final OutputStream out = write.write(test, status, new DisabledConnectionCallback()); new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out); }
@Override public boolean test(Pickle pickle) { if (expressions.isEmpty()) { return true; } List<String> tags = pickle.getTags(); return expressions.stream() .allMatch(expression -> expression.evaluate(tags)); }
@Test void single_tag_predicate_does_not_match_pickle_with_no_tags() { Pickle pickle = createPickleWithTags(); TagPredicate predicate = createPredicate("@FOO"); assertFalse(predicate.test(pickle)); }
@Public @Deprecated public static ApplicationAttemptId toApplicationAttemptId( String applicationAttemptIdStr) { return ApplicationAttemptId.fromString(applicationAttemptIdStr); }
@Test @SuppressWarnings("deprecation") void testInvalidAppattemptId() { assertThrows(IllegalArgumentException.class, () -> { ConverterUtils.toApplicationAttemptId("appattempt_1423221031460"); }); }
public static void main(String[] args) throws Exception { Arguments arguments = new Arguments(); CommandLine commander = new CommandLine(arguments); try { commander.parseArgs(args); if (arguments.help) { commander.usage(commander.getOut()); return; } if (arguments.generateDocs) { CmdGenerateDocs cmd = new CmdGenerateDocs("pulsar"); cmd.addCommand("initialize-transaction-coordinator-metadata", commander); cmd.run(null); return; } } catch (Exception e) { commander.usage(commander.getOut()); throw e; } if (arguments.configurationStore == null) { System.err.println("Configuration store address argument is required (--configuration-store)"); commander.usage(commander.getOut()); System.exit(1); } if (arguments.numTransactionCoordinators <= 0) { System.err.println("Number of transaction coordinators must greater than 0"); System.exit(1); } try (MetadataStoreExtended configStore = PulsarClusterMetadataSetup .initConfigMetadataStore(arguments.configurationStore, arguments.zkSessionTimeoutMillis)) { PulsarResources pulsarResources = new PulsarResources(null, configStore); // Create system tenant PulsarClusterMetadataSetup .createTenantIfAbsent(pulsarResources, NamespaceName.SYSTEM_NAMESPACE.getTenant(), arguments.cluster); // Create system namespace PulsarClusterMetadataSetup.createNamespaceIfAbsent(pulsarResources, NamespaceName.SYSTEM_NAMESPACE, arguments.cluster); // Create transaction coordinator assign partitioned topic PulsarClusterMetadataSetup.createPartitionedTopic(configStore, SystemTopicNames.TRANSACTION_COORDINATOR_ASSIGN, arguments.numTransactionCoordinators); } System.out.println("Transaction coordinator metadata setup success"); }
@Test public void testMainGenerateDocs() throws Exception { PrintStream oldStream = System.out; try { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(baoStream)); Class argumentsClass = Class.forName("org.apache.pulsar.PulsarTransactionCoordinatorMetadataSetup$Arguments"); PulsarTransactionCoordinatorMetadataSetup.main(new String[]{"-cs", "cs", "-c", "c", "-g"}); String message = baoStream.toString(); Field[] fields = argumentsClass.getDeclaredFields(); for (Field field : fields) { boolean fieldHasAnno = field.isAnnotationPresent(Option.class); if (fieldHasAnno) { Option fieldAnno = field.getAnnotation(Option.class); String[] names = fieldAnno.names(); if (names.length == 0) { continue; } String nameStr = Arrays.asList(names).toString(); nameStr = nameStr.substring(1, nameStr.length() - 1); assertTrue(message.indexOf(nameStr) > 0); } } } finally { System.setOut(oldStream); } }
@Override public SendResult send(final Message message) { return send(message, this.rocketmqProducer.getSendMsgTimeout()); }
@Test public void testSend_WithException() throws InterruptedException, RemotingException, MQClientException, MQBrokerException { when(rocketmqProducer.send(any(Message.class), anyLong())).thenThrow(MQClientException.class); try { producer.send(producer.createBytesMessage("HELLO_TOPIC", new byte[] {'a'})); failBecauseExceptionWasNotThrown(OMSRuntimeException.class); } catch (Exception e) { assertThat(e).hasMessageContaining("Send message to RocketMQ broker failed."); } }
public abstract ImmutableListMultimap<String, String> attributes();
@Test void attributes() { final LDAPEntry entry = LDAPEntry.builder() .dn("cn=jane,ou=people,dc=example,dc=com") .base64UniqueId(Base64.encode("unique-id")) .addAttribute("foo", "bar") .build(); assertThat(entry.attributes().get("foo")).containsExactly("bar"); assertThat(entry.attributes().get("hello")).isEmpty(); }
@Override public Proxy find(final String target) { for(java.net.Proxy proxy : selector.select(URI.create(target))) { switch(proxy.type()) { case DIRECT: { return Proxy.DIRECT; } case HTTP: { if(proxy.address() instanceof InetSocketAddress) { final InetSocketAddress address = (InetSocketAddress) proxy.address(); return new Proxy(Proxy.Type.HTTP, address.getHostName(), address.getPort()); } } case SOCKS: { if(proxy.address() instanceof InetSocketAddress) { final InetSocketAddress address = (InetSocketAddress) proxy.address(); return new Proxy(Proxy.Type.SOCKS, address.getHostName(), address.getPort()); } } } } return Proxy.DIRECT; }
@Test public void testSimpleExcluded() { final DefaultProxyFinder proxy = new DefaultProxyFinder(); assertEquals(Proxy.Type.DIRECT, proxy.find("http://simple").getType()); assertEquals(Proxy.Type.DIRECT, proxy.find("sftp://simple").getType()); }
@Override public void open() throws Exception { super.open(); collector = new TimestampedCollector<>(output); context = new ContextImpl(userFunction); internalTimerService = getInternalTimerService(CLEANUP_TIMER_NAME, StringSerializer.INSTANCE, this); }
@TestTemplate void testContextCorrectRightTimestamp() throws Exception { IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op = new IntervalJoinOperator<>( -1, 1, true, true, null, null, TestElem.serializer(), TestElem.serializer(), new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() { @Override public void processElement( TestElem left, TestElem right, Context ctx, Collector<Tuple2<TestElem, TestElem>> out) throws Exception { assertThat(ctx.getRightTimestamp()).isEqualTo(right.ts); } }); try (TestHarness testHarness = new TestHarness( op, (elem) -> elem.key, (elem) -> elem.key, TypeInformation.of(String.class))) { testHarness.setup(); testHarness.open(); processElementsAndWatermarks(testHarness); } }
@Override public double getMean() { if (values.length == 0) { return 0; } double sum = 0; for (int i = 0; i < values.length; i++) { sum += values[i] * normWeights[i]; } return sum; }
@Test public void expectNoOverflowForLowWeights() throws Exception { final Snapshot scatteredSnapshot = new WeightedSnapshot( WeightedArray( new long[]{ 1, 2, 3 }, new double[]{ Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE } ) ); assertThat(scatteredSnapshot.getMean()) .isEqualTo(2); }
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) .defaultValue(column.getDefaultValue()); switch (column.getDataType().getSqlType()) { case BOOLEAN: builder.columnType(SQLSERVER_BIT); builder.dataType(SQLSERVER_BIT); break; case TINYINT: builder.columnType(SQLSERVER_TINYINT); builder.dataType(SQLSERVER_TINYINT); break; case SMALLINT: builder.columnType(SQLSERVER_SMALLINT); builder.dataType(SQLSERVER_SMALLINT); break; case INT: builder.columnType(SQLSERVER_INT); builder.dataType(SQLSERVER_INT); break; case BIGINT: builder.columnType(SQLSERVER_BIGINT); builder.dataType(SQLSERVER_BIGINT); break; case FLOAT: builder.columnType(SQLSERVER_REAL); builder.dataType(SQLSERVER_REAL); break; case DOUBLE: builder.columnType(SQLSERVER_FLOAT); builder.dataType(SQLSERVER_FLOAT); break; case DECIMAL: DecimalType decimalType = (DecimalType) column.getDataType(); long precision = decimalType.getPrecision(); int scale = decimalType.getScale(); if (precision <= 0) { precision = DEFAULT_PRECISION; scale = DEFAULT_SCALE; log.warn( "The decimal column {} type decimal({},{}) is out of range, " + "which is precision less than 0, " + "it will be converted to decimal({},{})", column.getName(), decimalType.getPrecision(), decimalType.getScale(), precision, scale); } else if (precision > MAX_PRECISION) { scale = (int) Math.max(0, scale - (precision - MAX_PRECISION)); precision = MAX_PRECISION; log.warn( "The decimal column {} type decimal({},{}) is out of range, " + "which exceeds the maximum precision of {}, " + "it will be converted to decimal({},{})", column.getName(), decimalType.getPrecision(), decimalType.getScale(), MAX_PRECISION, precision, scale); } if (scale < 0) { scale = 0; log.warn( "The decimal column {} type decimal({},{}) is out of range, " + "which is scale less than 0, " + "it will be converted to decimal({},{})", column.getName(), decimalType.getPrecision(), decimalType.getScale(), precision, scale); } else if (scale > MAX_SCALE) { scale = MAX_SCALE; log.warn( "The decimal column {} type decimal({},{}) is out of range, " + "which exceeds the maximum scale of {}, " + "it will be converted to decimal({},{})", column.getName(), decimalType.getPrecision(), decimalType.getScale(), MAX_SCALE, precision, scale); } builder.columnType(String.format("%s(%s,%s)", SQLSERVER_DECIMAL, precision, scale)); builder.dataType(SQLSERVER_DECIMAL); builder.precision(precision); builder.scale(scale); break; case STRING: if (column.getColumnLength() == null || column.getColumnLength() <= 0) { builder.columnType(MAX_NVARCHAR); builder.dataType(MAX_NVARCHAR); } else if (column.getColumnLength() <= MAX_NVARCHAR_LENGTH) { builder.columnType( String.format("%s(%s)", SQLSERVER_NVARCHAR, column.getColumnLength())); builder.dataType(SQLSERVER_NVARCHAR); builder.length(column.getColumnLength()); } else { builder.columnType(MAX_NVARCHAR); builder.dataType(MAX_NVARCHAR); builder.length(column.getColumnLength()); } break; case BYTES: if (column.getColumnLength() == null || column.getColumnLength() <= 0) { builder.columnType(MAX_VARBINARY); builder.dataType(SQLSERVER_VARBINARY); } else if (column.getColumnLength() <= MAX_BINARY_LENGTH) { builder.columnType( String.format("%s(%s)", SQLSERVER_VARBINARY, column.getColumnLength())); builder.dataType(SQLSERVER_VARBINARY); builder.length(column.getColumnLength()); } else { builder.columnType(MAX_VARBINARY); builder.dataType(SQLSERVER_VARBINARY); builder.length(column.getColumnLength()); } break; case DATE: builder.columnType(SQLSERVER_DATE); builder.dataType(SQLSERVER_DATE); break; case TIME: if (column.getScale() != null && column.getScale() > 0) { int timeScale = column.getScale(); if (timeScale > MAX_TIME_SCALE) { timeScale = MAX_TIME_SCALE; log.warn( "The time column {} type time({}) is out of range, " + "which exceeds the maximum scale of {}, " + "it will be converted to time({})", column.getName(), column.getScale(), MAX_SCALE, timeScale); } builder.columnType(String.format("%s(%s)", SQLSERVER_TIME, timeScale)); builder.scale(timeScale); } else { builder.columnType(SQLSERVER_TIME); } builder.dataType(SQLSERVER_TIME); break; case TIMESTAMP: if (column.getScale() != null && column.getScale() > 0) { int timestampScale = column.getScale(); if (timestampScale > MAX_TIMESTAMP_SCALE) { timestampScale = MAX_TIMESTAMP_SCALE; log.warn( "The timestamp column {} type timestamp({}) is out of range, " + "which exceeds the maximum scale of {}, " + "it will be converted to timestamp({})", column.getName(), column.getScale(), MAX_TIMESTAMP_SCALE, timestampScale); } builder.columnType( String.format("%s(%s)", SQLSERVER_DATETIME2, timestampScale)); builder.scale(timestampScale); } else { builder.columnType(SQLSERVER_DATETIME2); } builder.dataType(SQLSERVER_DATETIME2); break; default: throw CommonError.convertToConnectorTypeError( DatabaseIdentifier.SQLSERVER, column.getDataType().getSqlType().name(), column.getName()); } return builder.build(); }
@Test public void testReconvertLong() { Column column = PhysicalColumn.builder().name("test").dataType(BasicType.LONG_TYPE).build(); BasicTypeDefine typeDefine = SqlServerTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.assertEquals( SqlServerTypeConverter.SQLSERVER_BIGINT, typeDefine.getColumnType()); Assertions.assertEquals(SqlServerTypeConverter.SQLSERVER_BIGINT, typeDefine.getDataType()); }
public SmppMessage createSmppMessage(CamelContext camelContext, AlertNotification alertNotification) { SmppMessage smppMessage = new SmppMessage(camelContext, alertNotification, configuration); smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.AlertNotification.toString()); smppMessage.setHeader(SmppConstants.SEQUENCE_NUMBER, alertNotification.getSequenceNumber()); smppMessage.setHeader(SmppConstants.COMMAND_ID, alertNotification.getCommandId()); smppMessage.setHeader(SmppConstants.COMMAND_STATUS, alertNotification.getCommandStatus()); smppMessage.setHeader(SmppConstants.SOURCE_ADDR, alertNotification.getSourceAddr()); smppMessage.setHeader(SmppConstants.SOURCE_ADDR_NPI, alertNotification.getSourceAddrNpi()); smppMessage.setHeader(SmppConstants.SOURCE_ADDR_TON, alertNotification.getSourceAddrTon()); smppMessage.setHeader(SmppConstants.ESME_ADDR, alertNotification.getEsmeAddr()); smppMessage.setHeader(SmppConstants.ESME_ADDR_NPI, alertNotification.getEsmeAddrNpi()); smppMessage.setHeader(SmppConstants.ESME_ADDR_TON, alertNotification.getEsmeAddrTon()); return smppMessage; }
@Test public void createSmppMessageFromDeliverSmWithPayloadInOptionalParameterShouldReturnASmppMessage() throws Exception { DeliverSm deliverSm = new DeliverSm(); deliverSm.setSequenceNumber(1); deliverSm.setCommandId(1); deliverSm.setSourceAddr("1818"); deliverSm.setSourceAddrNpi(NumberingPlanIndicator.NATIONAL.value()); deliverSm.setSourceAddrTon(TypeOfNumber.NATIONAL.value()); deliverSm.setDestAddress("1919"); deliverSm.setDestAddrNpi(NumberingPlanIndicator.INTERNET.value()); deliverSm.setDestAddrTon(TypeOfNumber.NETWORK_SPECIFIC.value()); deliverSm.setScheduleDeliveryTime("090831230627004+"); deliverSm.setValidityPeriod("090901230627004+"); deliverSm.setServiceType("WAP"); deliverSm.setOptionalParameters(new OctetString(OptionalParameter.Tag.MESSAGE_PAYLOAD, "Hello SMPP world!")); SmppMessage smppMessage = binding.createSmppMessage(camelContext, deliverSm); assertEquals("Hello SMPP world!", smppMessage.getBody()); assertEquals(15, smppMessage.getHeaders().size()); assertEquals(1, smppMessage.getHeader(SmppConstants.SEQUENCE_NUMBER)); assertEquals(1, smppMessage.getHeader(SmppConstants.COMMAND_ID)); assertEquals("1818", smppMessage.getHeader(SmppConstants.SOURCE_ADDR)); assertEquals((byte) 8, smppMessage.getHeader(SmppConstants.SOURCE_ADDR_NPI)); assertEquals((byte) 2, smppMessage.getHeader(SmppConstants.SOURCE_ADDR_TON)); assertEquals("1919", smppMessage.getHeader(SmppConstants.DEST_ADDR)); assertEquals((byte) 14, smppMessage.getHeader(SmppConstants.DEST_ADDR_NPI)); assertEquals((byte) 3, smppMessage.getHeader(SmppConstants.DEST_ADDR_TON)); assertEquals("090831230627004+", smppMessage.getHeader(SmppConstants.SCHEDULE_DELIVERY_TIME)); assertEquals("090901230627004+", smppMessage.getHeader(SmppConstants.VALIDITY_PERIOD)); assertEquals("WAP", smppMessage.getHeader(SmppConstants.SERVICE_TYPE)); assertEquals(SmppMessageType.DeliverSm.toString(), smppMessage.getHeader(SmppConstants.MESSAGE_TYPE)); }
public static boolean isValidRule(AuthorityRule rule) { return rule != null && !StringUtil.isBlank(rule.getResource()) && rule.getStrategy() >= 0 && StringUtil.isNotBlank(rule.getLimitApp()) && RuleManager.checkRegexResourceField(rule); }
@Test public void testIsValidRule() { AuthorityRule ruleA = new AuthorityRule(); AuthorityRule ruleB = null; AuthorityRule ruleC = new AuthorityRule(); ruleC.setResource("abc"); AuthorityRule ruleD = new AuthorityRule(); ruleD.setResource("bcd").setLimitApp("abc"); assertFalse(AuthorityRuleManager.isValidRule(ruleA)); assertFalse(AuthorityRuleManager.isValidRule(ruleB)); assertFalse(AuthorityRuleManager.isValidRule(ruleC)); assertTrue(AuthorityRuleManager.isValidRule(ruleD)); }
@Override public void executeUpdate(final RegisterStorageUnitStatement sqlStatement, final ContextManager contextManager) { checkDataSource(sqlStatement, contextManager); Map<String, DataSourcePoolProperties> propsMap = DataSourceSegmentsConverter.convert(database.getProtocolType(), sqlStatement.getStorageUnits()); if (sqlStatement.isIfNotExists()) { Collection<String> currentStorageUnits = getCurrentStorageUnitNames(contextManager); Collection<String> logicalDataSourceNames = getLogicalDataSourceNames(); propsMap.keySet().removeIf(currentStorageUnits::contains); propsMap.keySet().removeIf(logicalDataSourceNames::contains); } if (propsMap.isEmpty()) { return; } validateHandler.validate(propsMap, getExpectedPrivileges(sqlStatement)); try { contextManager.getPersistServiceFacade().getMetaDataManagerPersistService().registerStorageUnits(database.getName(), propsMap); } catch (final SQLException | ShardingSphereExternalException ex) { throw new StorageUnitsOperateException("register", propsMap.keySet(), ex); } }
@Test void assertExecuteUpdateWithDuplicateStorageUnitNamesWithDataSourceContainedRule() { ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS); when(contextManager.getMetaDataContexts()).thenReturn(mock(MetaDataContexts.class, RETURNS_DEEP_STUBS)); DataSourceMapperRuleAttribute ruleAttribute = mock(DataSourceMapperRuleAttribute.class); when(ruleAttribute.getDataSourceMapper()).thenReturn(Collections.singletonMap("ds_0", Collections.emptyList())); when(database.getRuleMetaData().getAttributes(DataSourceMapperRuleAttribute.class)).thenReturn(Collections.singleton(ruleAttribute)); assertThrows(DuplicateStorageUnitException.class, () -> executor.executeUpdate(createRegisterStorageUnitStatement(), contextManager)); }
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) { if (list == null) { return FEELFnResult.ofResult(true); } boolean result = true; for (final Object element : list) { if (element != null && !(element instanceof Boolean)) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not" + " a Boolean")); } else { if (element != null) { result &= (Boolean) element; } } } return FEELFnResult.ofResult(result); }
@Test void invokeArrayParamReturnTrue() { FunctionTestUtil.assertResult(nnAllFunction.invoke(new Object[]{Boolean.TRUE, Boolean.TRUE}), true); }
public static String wrapWithMarkdownClassDiv(String html) { return new StringBuilder() .append("<div class=\"markdown-body\">\n") .append(html) .append("\n</div>") .toString(); }
@Test void testItalics() { InterpreterResult result = md.interpret("This is *italics* text", null); assertEquals( wrapWithMarkdownClassDiv("<p>This is <em>italics</em> text</p>\n"), result.message().get(0).getData()); }
public void addRule(ElementSelector elementSelector, Supplier<Action> actionSupplier) { Supplier<Action> existing = rules.get(elementSelector); if (existing == null) { rules.put(elementSelector, actionSupplier); } else { throw new IllegalStateException(elementSelector.toString() + " already has an associated action supplier"); } }
@Test public void smokeII() throws Exception { srs.addRule(new ElementSelector("a/b"), () -> new XAction()); Exception e = assertThrows(IllegalStateException.class, () -> { srs.addRule(new ElementSelector("a/b"), () -> new YAction()); }); assertEquals("[a][b] already has an associated action supplier", e.getMessage()); }
public RemotingCommand getConsumerListByGroup(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { final RemotingCommand response = RemotingCommand.createResponseCommand(GetConsumerListByGroupResponseHeader.class); final GetConsumerListByGroupRequestHeader requestHeader = (GetConsumerListByGroupRequestHeader) request .decodeCommandCustomHeader(GetConsumerListByGroupRequestHeader.class); ConsumerGroupInfo consumerGroupInfo = this.brokerController.getConsumerManager().getConsumerGroupInfo( requestHeader.getConsumerGroup()); if (consumerGroupInfo != null) { List<String> clientIds = consumerGroupInfo.getAllClientId(); if (!clientIds.isEmpty()) { GetConsumerListByGroupResponseBody body = new GetConsumerListByGroupResponseBody(); body.setConsumerIdList(clientIds); response.setBody(body.encode()); response.setCode(ResponseCode.SUCCESS); response.setRemark(null); return response; } else { LOGGER.warn("getAllClientId failed, {} {}", requestHeader.getConsumerGroup(), RemotingHelper.parseChannelRemoteAddr(ctx.channel())); } } else { LOGGER.warn("getConsumerGroupInfo failed, {} {}", requestHeader.getConsumerGroup(), RemotingHelper.parseChannelRemoteAddr(ctx.channel())); } response.setCode(ResponseCode.SYSTEM_ERROR); response.setRemark("no consumer for this group, " + requestHeader.getConsumerGroup()); return response; }
@Test public void testGetConsumerListByGroup() throws RemotingCommandException { GetConsumerListByGroupRequestHeader requestHeader = new GetConsumerListByGroupRequestHeader(); requestHeader.setConsumerGroup(group); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_LIST_BY_GROUP, requestHeader); request.makeCustomHeaderToNet(); RemotingCommand response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SYSTEM_ERROR); brokerController.getConsumerManager().getConsumerTable().put(group,new ConsumerGroupInfo(group)); response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SYSTEM_ERROR); ConsumerGroupInfo consumerGroupInfo = this.brokerController.getConsumerManager().getConsumerGroupInfo( requestHeader.getConsumerGroup()); consumerGroupInfo.getChannelInfoTable().put(channel,new ClientChannelInfo(channel)); response = consumerManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); }
@POST @Timed @Path("tables/{idOrName}/purge") @ApiOperation(value = "Purge Lookup Table Cache on the cluster-wide level") @NoAuditEvent("Cache purge only") @RequiresPermissions(RestPermissions.LOOKUP_TABLES_READ) public Map<String, CallResult<Void>> performPurge( @ApiParam(name = "idOrName") @PathParam("idOrName") @NotEmpty String idOrName, @ApiParam(name = "key") @QueryParam("key") String key) { return requestOnAllNodes(RemoteLookupTableResource.class, client -> client.performPurge(idOrName, key)); }
@Test public void performPurge_whenAllCallsSucceedThenResponseWithPerNodeDetailsReturned() throws Exception { // given when(nodeService.allActive()).thenReturn(nodeMap()); mock204Response("testName", "testKey", remoteLookupTableResource1); mock204Response("testName", "testKey", remoteLookupTableResource2); // when final Map<String, ProxiedResource.CallResult<Void>> res = underTest.performPurge("testName", "testKey"); // then verify(remoteLookupTableResource1).performPurge("testName", "testKey"); verify(remoteLookupTableResource2).performPurge("testName", "testKey"); assertThat(res.get("node_1")).satisfies(nodeRes -> { assertThat(nodeRes.isCallExecuted()).isTrue(); assertThat(nodeRes.serverErrorMessage()).isNull(); assertThat(nodeRes.response().code()).isEqualTo(204); assertThat(nodeRes.response().entity()).isEmpty(); assertThat(nodeRes.response().errorText()).isNull(); }); assertThat(res.get("node_2")).satisfies(nodeRes -> { assertThat(nodeRes.isCallExecuted()).isTrue(); assertThat(nodeRes.serverErrorMessage()).isNull(); assertThat(nodeRes.response().code()).isEqualTo(204); assertThat(nodeRes.response().entity()).isEmpty(); assertThat(nodeRes.response().errorText()).isNull(); }); }
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()))) { String json = reader.readLine(); log.debug("Converting response from influxDb: {}", json); Map result = getResultObject(json); List<Map> seriesList = (List<Map>) result.get("series"); if (CollectionUtils.isEmpty(seriesList)) { log.warn("Received no data from Influxdb."); return null; } Map series = seriesList.get(0); List<String> seriesColumns = (List<String>) series.get("columns"); List<List> seriesValues = (List<List>) series.get("values"); List<InfluxDbResult> influxDbResultsList = new ArrayList<InfluxDbResult>(seriesValues.size()); // TODO(joerajeev): if returning tags (other than the field names) we will need to skip tags // from this loop, // and to extract and set the tag values to the influxDb result. for (int i = 1; i < seriesColumns.size(); i++) { // Starting from index 1 to skip 'time' column String id = seriesColumns.get(i); long firstTimeMillis = extractTimeInMillis(seriesValues, 0); long stepMillis = calculateStep(seriesValues, firstTimeMillis); List<Double> values = new ArrayList<>(seriesValues.size()); for (List<Object> valueRow : seriesValues) { if (valueRow.get(i) != null) { String val = valueRow.get(i).toString(); values.add(Double.valueOf(val)); } } influxDbResultsList.add(new InfluxDbResult(id, firstTimeMillis, stepMillis, null, values)); } log.debug("Converted response: {} ", influxDbResultsList); return influxDbResultsList; } catch (IOException e) { e.printStackTrace(); } return null; }
@Test public void deserialize() throws Exception { List<InfluxDbResult> results = setupAllIntegers(); TypedInput input = new TypedByteArray(MIME_TYPE, EXAMPLE_ALL_INTEGERS.getBytes()); List<InfluxDbResult> result = (List<InfluxDbResult>) influxDbResponseConverter.fromBody(input, List.class); assertThat(result).isEqualTo(results); }
public static ServiceURI create(String uriStr) { requireNonNull(uriStr, "service uri string is null"); if (uriStr.contains("[") && uriStr.contains("]")) { // deal with ipv6 address Splitter splitter = Splitter.on(CharMatcher.anyOf(",;")); List<String> hosts = splitter.splitToList(uriStr); if (hosts.size() > 1) { // deal with multi ipv6 hosts String firstHost = hosts.get(0); String lastHost = hosts.get(hosts.size() - 1); boolean hasPath = lastHost.contains("/"); String path = hasPath ? lastHost.substring(lastHost.indexOf("/")) : ""; firstHost += path; URI uri = URI.create(firstHost); ServiceURI serviceURI = create(uri); List<String> multiHosts = new ArrayList<>(); multiHosts.add(serviceURI.getServiceHosts()[0]); multiHosts.addAll(hosts.subList(1, hosts.size())); multiHosts = multiHosts .stream() .map(host -> validateHostName(serviceURI.getServiceName(), serviceURI.getServiceInfos(), host)) .collect(Collectors.toList()); return new ServiceURI( serviceURI.getServiceName(), serviceURI.getServiceInfos(), serviceURI.getServiceUser(), multiHosts.toArray(new String[multiHosts.size()]), serviceURI.getServicePath(), serviceURI.getUri()); } } // a service uri first should be a valid java.net.URI URI uri = URI.create(uriStr); return create(uri); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyServiceUriString() { ServiceURI.create(""); }
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { try { Metrics.summary(CONTENT_LENGTH_DISTRIBUTION_NAME, TRAFFIC_SOURCE_TAG, trafficSourceTag) .record(requestContext.getLength()); Metrics.counter(IP_VERSION_METRIC, TRAFFIC_SOURCE_TAG, trafficSourceTag, IP_VERSION_TAG, resolveIpVersion(requestContext)) .increment(); } catch (final Exception e) { logger.warn("Error recording request statistics", e); } }
@Test void testFilter() throws Exception { final RequestStatisticsFilter requestStatisticsFilter = new RequestStatisticsFilter(TrafficSource.WEBSOCKET); final ContainerRequestContext requestContext = mock(ContainerRequestContext.class); when(requestContext.getLength()).thenReturn(-1); when(requestContext.getLength()).thenReturn(Integer.MAX_VALUE); when(requestContext.getLength()).thenThrow(RuntimeException.class); requestStatisticsFilter.filter(requestContext); requestStatisticsFilter.filter(requestContext); requestStatisticsFilter.filter(requestContext); }
void addRoutingProcessor(final String channel, final DynamicRouterProcessor processor) { if (processors.putIfAbsent(channel, processor) != null) { throw new IllegalArgumentException( "Dynamic Router can have only one processor per channel; channel '" + channel + "' already has a processor"); } }
@Test void testAddRoutingProcessor() { component.addRoutingProcessor(DYNAMIC_ROUTER_CHANNEL, processor); assertEquals(processor, component.getRoutingProcessor(DYNAMIC_ROUTER_CHANNEL)); }
static void dissectRemovePublicationCleanup( final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int absoluteOffset = offset; absoluteOffset += dissectLogHeader(CONTEXT, REMOVE_PUBLICATION_CLEANUP, buffer, absoluteOffset, builder); builder.append(": sessionId=").append(buffer.getInt(absoluteOffset, LITTLE_ENDIAN)); absoluteOffset += SIZE_OF_INT; builder.append(" streamId=").append(buffer.getInt(absoluteOffset, LITTLE_ENDIAN)); absoluteOffset += SIZE_OF_INT; builder.append(" channel="); buffer.getStringAscii(absoluteOffset, builder); }
@Test void dissectRemovePublicationCleanup() { final int offset = 12; internalEncodeLogHeader(buffer, offset, 22, 88, () -> 2_500_000_000L); buffer.putInt(offset + LOG_HEADER_LENGTH, 42, LITTLE_ENDIAN); buffer.putInt(offset + LOG_HEADER_LENGTH + SIZE_OF_INT, 11, LITTLE_ENDIAN); buffer.putStringAscii(offset + LOG_HEADER_LENGTH + SIZE_OF_INT * 2, "channel uri"); DriverEventDissector.dissectRemovePublicationCleanup(buffer, offset, builder); assertEquals("[2.500000000] " + CONTEXT + ": " + REMOVE_PUBLICATION_CLEANUP.name() + " [22/88]: sessionId=42 streamId=11 channel=channel uri", builder.toString()); }
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testCpuPercentageMemoryAbsoluteCpuNegative() throws Exception { expectMissingResource("memory"); parseResourceConfigValue("-50% cpu, 1024 mb"); }
public boolean getBoolean(@NotNull final String key) throws InvalidSettingException { return Boolean.parseBoolean(getString(key)); }
@Test public void testGetBoolean() throws InvalidSettingException { String key = "SomeBoolean"; getSettings().setString(key, "false"); boolean expResult = false; boolean result = getSettings().getBoolean(key); Assert.assertEquals(expResult, result); key = "something that does not exist"; expResult = true; result = getSettings().getBoolean(key, true); Assert.assertEquals(expResult, result); }
public static String getContent(String content) { int index = content.indexOf(WORD_SEPARATOR); if (index == -1) { throw new IllegalArgumentException("content does not contain separator"); } return content.substring(index + 1); }
@Test void testGetContentFail() { assertThrows(IllegalArgumentException.class, () -> { String content = "aabbb"; ContentUtils.getContent(content); }); }
public static <K, V> AsMap<K, V> asMap() { return new AsMap<>(false); }
@Test @Category(ValidatesRunner.class) public void testWindowedMapSideInput() { final PCollectionView<Map<String, Integer>> view = pipeline .apply( "CreateSideInput", Create.timestamped( TimestampedValue.of(KV.of("a", 1), new Instant(1)), TimestampedValue.of(KV.of("b", 2), new Instant(4)), TimestampedValue.of(KV.of("b", 3), new Instant(18)))) .apply("SideWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) .apply(View.asMap()); PCollection<KV<String, Integer>> output = pipeline .apply( "CreateMainInput", Create.timestamped( TimestampedValue.of("apple", new Instant(5)), TimestampedValue.of("banana", new Instant(4)), TimestampedValue.of("blackberry", new Instant(16)))) .apply("MainWindowInto", Window.into(FixedWindows.of(Duration.millis(10)))) .apply( "OutputSideInputs", ParDo.of( new DoFn<String, KV<String, Integer>>() { @ProcessElement public void processElement(ProcessContext c) { c.output( KV.of( c.element(), c.sideInput(view).get(c.element().substring(0, 1)))); } }) .withSideInputs(view)); PAssert.that(output) .containsInAnyOrder(KV.of("apple", 1), KV.of("banana", 2), KV.of("blackberry", 3)); pipeline.run(); }
public SchemaWriter(String typeName) { this.typeName = typeName; }
@Test public void testSchemaWriter() { SchemaWriter writer = new SchemaWriter("foo"); writer.writeBoolean(FieldKind.BOOLEAN.name(), true); writer.writeArrayOfBoolean(FieldKind.ARRAY_OF_BOOLEAN.name(), null); writer.writeInt8(FieldKind.INT8.name(), (byte) 0); writer.writeArrayOfInt8(FieldKind.ARRAY_OF_INT8.name(), null); writer.writeInt16(FieldKind.INT16.name(), (short) 0); writer.writeArrayOfInt16(FieldKind.ARRAY_OF_INT16.name(), null); writer.writeInt32(FieldKind.INT32.name(), 0); writer.writeArrayOfInt32(FieldKind.ARRAY_OF_INT32.name(), null); writer.writeInt64(FieldKind.INT64.name(), 0); writer.writeArrayOfInt64(FieldKind.ARRAY_OF_INT64.name(), null); writer.writeFloat32(FieldKind.FLOAT32.name(), 0); writer.writeArrayOfFloat32(FieldKind.ARRAY_OF_FLOAT32.name(), null); writer.writeFloat64(FieldKind.FLOAT64.name(), 0); writer.writeArrayOfFloat64(FieldKind.ARRAY_OF_FLOAT64.name(), null); writer.writeString(FieldKind.STRING.name(), null); writer.writeArrayOfString(FieldKind.ARRAY_OF_STRING.name(), null); writer.writeDecimal(FieldKind.DECIMAL.name(), null); writer.writeArrayOfDecimal(FieldKind.ARRAY_OF_DECIMAL.name(), null); writer.writeTime(FieldKind.TIME.name(), null); writer.writeArrayOfTime(FieldKind.ARRAY_OF_TIME.name(), null); writer.writeDate(FieldKind.DATE.name(), null); writer.writeArrayOfDate(FieldKind.ARRAY_OF_DATE.name(), null); writer.writeTimestamp(FieldKind.TIMESTAMP.name(), null); writer.writeArrayOfTimestamp(FieldKind.ARRAY_OF_TIMESTAMP.name(), null); writer.writeTimestampWithTimezone(FieldKind.TIMESTAMP_WITH_TIMEZONE.name(), null); writer.writeArrayOfTimestampWithTimezone(FieldKind.ARRAY_OF_TIMESTAMP_WITH_TIMEZONE.name(), null); writer.writeCompact(FieldKind.COMPACT.name(), null); writer.writeArrayOfCompact(FieldKind.ARRAY_OF_COMPACT.name(), null); writer.writeNullableBoolean(FieldKind.NULLABLE_BOOLEAN.name(), null); writer.writeArrayOfNullableBoolean(FieldKind.ARRAY_OF_NULLABLE_BOOLEAN.name(), null); writer.writeNullableInt8(FieldKind.NULLABLE_INT8.name(), null); writer.writeArrayOfNullableInt8(FieldKind.ARRAY_OF_NULLABLE_INT8.name(), null); writer.writeNullableInt16(FieldKind.NULLABLE_INT16.name(), null); writer.writeArrayOfNullableInt16(FieldKind.ARRAY_OF_NULLABLE_INT16.name(), null); writer.writeNullableInt32(FieldKind.NULLABLE_INT32.name(), null); writer.writeArrayOfNullableInt32(FieldKind.ARRAY_OF_NULLABLE_INT32.name(), null); writer.writeNullableInt64(FieldKind.NULLABLE_INT64.name(), null); writer.writeArrayOfNullableInt64(FieldKind.ARRAY_OF_NULLABLE_INT64.name(), null); writer.writeNullableFloat32(FieldKind.NULLABLE_FLOAT32.name(), null); writer.writeArrayOfNullableFloat32(FieldKind.ARRAY_OF_NULLABLE_FLOAT32.name(), null); writer.writeNullableFloat64(FieldKind.NULLABLE_FLOAT64.name(), null); writer.writeArrayOfNullableFloat64(FieldKind.ARRAY_OF_NULLABLE_FLOAT64.name(), null); Schema schema = writer.build(); for (FieldKind kind : FieldKind.values()) { if (!isSupportedByCompact(kind)) { continue; } FieldDescriptor field = schema.getField(kind.name()); assertNotNull(field); assertEquals(kind.name(), field.getFieldName()); assertEquals(kind, field.getKind()); } }
@Override public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception { //Unlike when adding a producer, consumers must specify the destination at creation time, so we can rely on //a destination being available to perform the authz check: DestinationAction action = new DestinationAction(context, info.getDestination(), "read"); assertAuthorized(action, "read from"); return super.addConsumer(context, info); }
@Test(expected=UnauthorizedException.class) public void testAddConsumerNotAuthorized() throws Exception { String name = "myTopic"; ActiveMQDestination dest = new ActiveMQTopic(name); Subject subject = new PermsSubject(); ConnectionContext context = createContext(subject); ConsumerInfo info = new ConsumerInfo(null); info.setDestination(dest); filter.addConsumer(context, info); }
public StepDataInterface getStepData() { return new DetectLastRowData(); }
@Test public void testGetData() { DetectLastRowMeta meta = new DetectLastRowMeta(); assertTrue( meta.getStepData() instanceof DetectLastRowData ); }
public String getRole() { return role; }
@Test public void testGetRole() { // Test the getRole method assertEquals("tc", event.getRole()); }
public static <K, V> Cache<K, V> fromOptions(PipelineOptions options) { return forMaximumBytes( ((long) options.as(SdkHarnessOptions.class).getMaxCacheMemoryUsageMb()) << 20); }
@Test public void testDefaultCache() throws Exception { testCache(Caches.fromOptions(PipelineOptionsFactory.create())); }
@Override public long skip(long n) { long increase = Math.min(n, availableLong()); _currentOffset += increase; return increase; }
@Test void testSkip() { _dataBufferPinotInputStream.seek(1); long skip = _dataBufferPinotInputStream.skip(2); assertEquals(skip, 2); assertEquals(_dataBufferPinotInputStream.getCurrentOffset(), 3); }
public List<String> getUuids() { return this.stream().map(EnvironmentAgentConfig::getUuid).collect(toList()); }
@Test void shouldGetEmptyListOfUUIDsWhenThereAreNoAgentsAssociatedWithEnvironment(){ List<String> uuids = envAgentsConfig.getUuids(); assertThat(uuids.size(), is(0)); }
@Override public List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> history) { List<Interval> intervals = Interval.group(history, start, end, dateField); List<PurgeableAnalysisDto> result = new ArrayList<>(); for (Interval interval : intervals) { appendSnapshotsToDelete(interval, result); } return result; }
@Test void shouldOnlyOneSnapshotPerInterval() { Filter filter = new KeepOneFilter(DateUtils.parseDate("2011-03-25"), DateUtils.parseDate("2011-08-25"), Calendar.MONTH, "month"); List<PurgeableAnalysisDto> toDelete = filter.filter(Arrays.asList( DbCleanerTestUtils.createAnalysisWithDate("u1", "2010-01-01"), // out of scope -> keep DbCleanerTestUtils.createAnalysisWithDate("u2", "2011-05-01"), // may -> keep DbCleanerTestUtils.createAnalysisWithDate("u3", "2011-05-02"), // may -> to be deleted DbCleanerTestUtils.createAnalysisWithDate("u4", "2011-05-19"), // may -> to be deleted DbCleanerTestUtils.createAnalysisWithDate("u5", "2011-06-01"), // june -> keep DbCleanerTestUtils.createAnalysisWithDate("u6", "2012-01-01") // out of scope -> keep )); assertThat(toDelete).hasSize(2); assertThat(analysisUuids(toDelete)).containsOnly("u2", "u3"); }
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) { final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace(); final String importerDMNName = ((Definitions) importElement.getParent()).getName(); final String importNamespace = importElement.getNamespace(); final String importName = importElement.getName(); final String importLocationURI = importElement.getLocationURI(); // This is optional final String importModelName = importElement.getAdditionalAttributes().get(TImport.MODELNAME_QNAME); LOGGER.debug("Resolving an Import in DMN Model with name={} and namespace={}. " + "Importing a DMN model with namespace={} name={} locationURI={}, modelName={}", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName); List<T> matchingDMNList = dmns.stream() .filter(m -> idExtractor.apply(m).getNamespaceURI().equals(importNamespace)) .toList(); if (matchingDMNList.size() == 1) { T located = matchingDMNList.get(0); // Check if the located DMN Model in the NS, correspond for the import `drools:modelName`. if (importModelName == null || idExtractor.apply(located).getLocalPart().equals(importModelName)) { LOGGER.debug("DMN Model with name={} and namespace={} successfully imported a DMN " + "with namespace={} name={} locationURI={}, modelName={}", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName); return Either.ofRight(located); } else { LOGGER.error("DMN Model with name={} and namespace={} can't import a DMN with namespace={}, name={}, modelName={}, " + "located within namespace only {} but does not match for the actual modelName", importerDMNName, importerDMNNamespace, importNamespace, importName, importModelName, idExtractor.apply(located)); return Either.ofLeft(String.format( "DMN Model with name=%s and namespace=%s can't import a DMN with namespace=%s, name=%s, modelName=%s, " + "located within namespace only %s but does not match for the actual modelName", importerDMNName, importerDMNNamespace, importNamespace, importName, importModelName, idExtractor.apply(located))); } } else { List<T> usingNSandName = matchingDMNList.stream() .filter(dmn -> idExtractor.apply(dmn).getLocalPart().equals(importModelName)) .toList(); if (usingNSandName.size() == 1) { LOGGER.debug("DMN Model with name={} and namespace={} successfully imported a DMN " + "with namespace={} name={} locationURI={}, modelName={}", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName); return Either.ofRight(usingNSandName.get(0)); } else if (usingNSandName.isEmpty()) { LOGGER.error("DMN Model with name={} and namespace={} failed to import a DMN with namespace={} name={} locationURI={}, modelName={}.", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName); return Either.ofLeft(String.format( "DMN Model with name=%s and namespace=%s failed to import a DMN with namespace=%s name=%s locationURI=%s, modelName=%s. ", importerDMNName, importerDMNNamespace, importNamespace, importName, importLocationURI, importModelName)); } else { LOGGER.error("DMN Model with name={} and namespace={} detected a collision ({} elements) trying to import a DMN with namespace={} name={} locationURI={}, modelName={}", importerDMNName, importerDMNNamespace, usingNSandName.size(), importNamespace, importName, importLocationURI, importModelName); return Either.ofLeft(String.format( "DMN Model with name=%s and namespace=%s detected a collision trying to import a DMN with %s namespace, " + "%s name and modelName %s. There are %s DMN files with the same namespace in your project. " + "Please change the DMN namespaces and make them unique to fix this issue.", importerDMNName, importerDMNNamespace, importNamespace, importName, importModelName, usingNSandName.size())); } } }
@Test void locateInNS() { final Import i = makeImport("nsA", null, "m1"); final List<QName> available = Arrays.asList(new QName("nsA", "m1"), new QName("nsA", "m2"), new QName("nsB", "m3")); final Either<String, QName> result = ImportDMNResolverUtil.resolveImportDMN(i, available, Function.identity()); assertThat(result.isRight()).isTrue(); assertThat(result.getOrElse(null)).isEqualTo(new QName("nsA", "m1")); }
public HttpHeaders preflightResponseHeaders() { if (preflightHeaders.isEmpty()) { return EmptyHttpHeaders.INSTANCE; } final HttpHeaders preflightHeaders = new DefaultHttpHeaders(); for (Entry<CharSequence, Callable<?>> entry : this.preflightHeaders.entrySet()) { final Object value = getValue(entry.getValue()); if (value instanceof Iterable) { preflightHeaders.add(entry.getKey(), (Iterable<?>) value); } else { preflightHeaders.add(entry.getKey(), value); } } return preflightHeaders; }
@Test public void defaultPreflightResponseHeaders() { final CorsConfig cors = forAnyOrigin().build(); assertThat(cors.preflightResponseHeaders().get(HttpHeaderNames.DATE), is(notNullValue())); assertThat(cors.preflightResponseHeaders().get(HttpHeaderNames.CONTENT_LENGTH), is("0")); }
public <T extends Tuple> DataSource<T> tupleType(Class<T> targetType) { Preconditions.checkNotNull(targetType, "The target type class must not be null."); if (!Tuple.class.isAssignableFrom(targetType)) { throw new IllegalArgumentException( "The target type must be a subclass of " + Tuple.class.getName()); } @SuppressWarnings("unchecked") TupleTypeInfo<T> typeInfo = (TupleTypeInfo<T>) TypeExtractor.createTypeInfo(targetType); CsvInputFormat<T> inputFormat = new TupleCsvInputFormat<T>( path, this.lineDelimiter, this.fieldDelimiter, typeInfo, this.includedMask); Class<?>[] classes = new Class<?>[typeInfo.getArity()]; for (int i = 0; i < typeInfo.getArity(); i++) { classes[i] = typeInfo.getTypeAt(i).getTypeClass(); } configureInputFormat(inputFormat); return new DataSource<T>( executionContext, inputFormat, typeInfo, Utils.getCallLocationName()); }
@Test void testReturnType() { CsvReader reader = getCsvReader(); DataSource<Item> items = reader.tupleType(Item.class); assertThat(items.getType().getTypeClass()).isSameAs(Item.class); }
@Override public String toString() { StringBuilder sb = new StringBuilder("jmx:").append(getServerName()); if (!mQueryProps.isEmpty()) { sb.append('?'); String delim = ""; for (Entry<String, String> entry : mQueryProps.entrySet()) { sb.append(delim); sb.append(entry.getKey()).append('=').append(entry.getValue()); delim = "&"; } } return sb.toString(); }
@Test public void remote() { assertEquals("jmx:service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi", new JMXUriBuilder("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi").toString()); }
static void validate(KafkaConsumer<byte[], byte[]> consumer, byte[] message, ConsumerRecords<byte[], byte[]> records) { if (records.isEmpty()) { consumer.commitSync(); throw new RuntimeException("poll() timed out before finding a result (timeout:[" + POLL_TIMEOUT_MS + "])"); } //Check result matches the original record String sent = new String(message, StandardCharsets.UTF_8); String read = new String(records.iterator().next().value(), StandardCharsets.UTF_8); if (!read.equals(sent)) { consumer.commitSync(); throw new RuntimeException("The message read [" + read + "] did not match the message sent [" + sent + "]"); } //Check we only got the one message if (records.count() != 1) { int count = records.count(); consumer.commitSync(); throw new RuntimeException("Only one result was expected during this test. We found [" + count + "]"); } }
@Test @SuppressWarnings("unchecked") public void shouldFailWhenReceivedMoreThanOneRecord() { Iterator<ConsumerRecord<byte[], byte[]>> iterator = mock(Iterator.class); ConsumerRecord<byte[], byte[]> record = mock(ConsumerRecord.class); when(records.isEmpty()).thenReturn(false); when(records.iterator()).thenReturn(iterator); when(iterator.next()).thenReturn(record); when(record.value()).thenReturn("kafkaa".getBytes(StandardCharsets.UTF_8)); when(records.count()).thenReturn(2); assertThrows(RuntimeException.class, () -> EndToEndLatency.validate(consumer, "kafkaa".getBytes(StandardCharsets.UTF_8), records)); }
@PublicAPI(usage = ACCESS) public JavaClass importClass(Class<?> clazz) { return getOnlyElement(importClasses(clazz)); }
@Test public void class_has_source_of_import() throws Exception { ArchConfiguration.get().setMd5InClassSourcesEnabled(true); JavaClass clazzFromFile = new ClassFileImporter().importClass(ClassToImportOne.class); Source source = clazzFromFile.getSource().get(); assertThat(source.getUri()).isEqualTo(uriOf(ClassToImportOne.class)); assertThat(source.getFileName()).contains(ClassToImportOne.class.getSimpleName() + ".java"); assertThat(source.getMd5sum()).isEqualTo(md5sumOf(bytesAt(urlOf(ClassToImportOne.class)))); clazzFromFile = new ClassFileImporter().importClass(ClassWithInnerClass.Inner.class); source = clazzFromFile.getSource().get(); assertThat(source.getUri()).isEqualTo(uriOf(ClassWithInnerClass.Inner.class)); assertThat(source.getFileName()).contains(ClassWithInnerClass.class.getSimpleName() + ".java"); assertThat(source.getMd5sum()).isEqualTo(md5sumOf(bytesAt(urlOf(ClassWithInnerClass.Inner.class)))); JavaClass clazzFromJar = new ClassFileImporter().importClass(Rule.class); source = clazzFromJar.getSource().get(); assertThat(source.getUri()).isEqualTo(uriOf(Rule.class)); assertThat(source.getFileName()).contains(Rule.class.getSimpleName() + ".java"); assertThat(source.getMd5sum()).isEqualTo(md5sumOf(bytesAt(urlOf(Rule.class)))); ArchConfiguration.get().setMd5InClassSourcesEnabled(false); source = new ClassFileImporter().importClass(ClassToImportOne.class).getSource().get(); assertThat(source.getMd5sum()).isEqualTo(MD5_SUM_DISABLED); }
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException { final List<MavenArtifact> result = new ArrayList<>(); try (InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); JsonParser parser = objectReader.getFactory().createParser(streamReader)) { if (init(parser) && parser.nextToken() == com.fasterxml.jackson.core.JsonToken.START_OBJECT) { // at least one result do { final FileImpl file = objectReader.readValue(parser); checkHashes(dependency, file.getChecksums()); final Matcher pathMatcher = PATH_PATTERN.matcher(file.getPath()); if (!pathMatcher.matches()) { throw new IllegalStateException("Cannot extract the Maven information from the path " + "retrieved in Artifactory " + file.getPath()); } final String groupId = pathMatcher.group("groupId").replace('/', '.'); final String artifactId = pathMatcher.group("artifactId"); final String version = pathMatcher.group("version"); result.add(new MavenArtifact(groupId, artifactId, version, file.getDownloadUri(), MavenArtifact.derivePomUrl(artifactId, version, file.getDownloadUri()))); } while (parser.nextToken() == com.fasterxml.jackson.core.JsonToken.START_OBJECT); } else { throw new FileNotFoundException("Artifact " + dependency + " not found in Artifactory"); } } return result; }
@Test public void shouldProcessCorrectlyArtifactoryAnswerMisMatchSha1() throws IOException { // Given Dependency dependency = new Dependency(); dependency.setSha1sum("c5b4c491aecb72e7c32a78da0b5c6b9cda8dee0e"); dependency.setSha256sum("512b4bf6927f4864acc419b8c5109c23361c30ed1f5798170248d33040de068e"); dependency.setMd5sum("2d1dd0fc21ee96bccfab4353d5379649"); final HttpURLConnection urlConnection = mock(HttpURLConnection.class); final byte[] payload = payloadWithSha256().getBytes(StandardCharsets.UTF_8); when(urlConnection.getInputStream()).thenReturn(new ByteArrayInputStream(payload)); // When try { searcher.processResponse(dependency, urlConnection); fail("SHA1 mismatching should throw an exception!"); } catch (FileNotFoundException e) { // Then assertEquals("Artifact found by API is not matching the SHA1 of the artifact (repository hash is c5b4c491aecb72e7c32a78da0b5c6b9cda8dee0f while actual is c5b4c491aecb72e7c32a78da0b5c6b9cda8dee0e) !", e.getMessage()); } }
public static SqlArgument of(final SqlType type) { return new SqlArgument(type, null, null); }
@Test public void shouldThrowWhenLambdaNotPresentGettingLambda() { final SqlArgument argument = SqlArgument.of(null, null); final Exception e = assertThrows( RuntimeException.class, argument::getSqlLambdaOrThrow ); assertThat(e.getMessage(), containsString("Was expecting lambda as a function argument")); }
public boolean isActiveVersionPath(final String path) { Matcher matcher = activeVersionPathPattern.matcher(path); return matcher.find(); }
@Test void assertIsActiveVersionPath() { UniqueRuleItemNodePath uniqueRuleItemNodePath = new UniqueRuleItemNodePath(new RuleRootNodePath("foo"), "test_path"); assertTrue(uniqueRuleItemNodePath.isActiveVersionPath("/word1-/word2/rules/foo/test_path/active_version")); }
@Override protected void doStart() throws Exception { super.doStart(); LOG.debug("Creating connection to Azure ServiceBus"); client = getEndpoint().getServiceBusClientFactory().createServiceBusProcessorClient(getConfiguration(), this::processMessage, this::processError); client.start(); }
@Test void consumerFiltersApplicationPropertiesFromMessageHeaders() throws Exception { try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) { consumer.doStart(); verify(client).start(); verify(clientFactory).createServiceBusProcessorClient(any(), any(), any()); when(messageContext.getMessage()).thenReturn(message); configureMockMessage(); message.getApplicationProperties().put(PROPAGATED_HEADER_KEY, PROPAGATED_HEADER_VALUE); when(headerFilterStrategy.applyFilterToExternalHeaders(anyString(), any(), any(Exchange.class))).thenReturn(true); processMessageCaptor.getValue().accept(messageContext); verify(headerFilterStrategy, atLeastOnce()).applyFilterToExternalHeaders(anyString(), any(), any(Exchange.class)); verifyNoMoreInteractions(headerFilterStrategy); verify(processor).process(any(Exchange.class), any(AsyncCallback.class)); Exchange exchange = exchangeCaptor.getValue(); assertThat(exchange).isNotNull(); Message inMessage = exchange.getIn(); assertThat(inMessage).isNotNull(); assertThat(inMessage.getHeaders()).doesNotContainKey(PROPAGATED_HEADER_KEY); } }
public void setSyncDelayMillis(long syncDelayMillis) { this.syncDelayMillis = syncDelayMillis; }
@Test void testSetSyncDelayMillis() { distroConfig.setSyncDelayMillis(syncDelayMillis); assertEquals(syncDelayMillis, distroConfig.getSyncDelayMillis()); }
public String getFormattedMessage() { if (formattedMessage != null) { return formattedMessage; } if (argumentArray != null) { formattedMessage = MessageFormatter.arrayFormat(message, argumentArray).getMessage(); } else { formattedMessage = message; } return formattedMessage; }
@Test public void testNoFormattingWithArgs() { String message = "testNoFormatting"; Throwable throwable = null; Object[] argArray = new Object[] { 12, 13 }; LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); assertNull(event.formattedMessage); assertEquals(message, event.getFormattedMessage()); }
@Override public void trash(final Local file) throws LocalAccessDeniedException { synchronized(NSWorkspace.class) { if(log.isDebugEnabled()) { log.debug(String.format("Move %s to Trash", file)); } // Asynchronous operation. 0 if the operation is performed synchronously and succeeds, and a positive // integer if the operation is performed asynchronously and succeeds if(!workspace.performFileOperation( NSWorkspace.RecycleOperation, new NFDNormalizer().normalize(file.getParent().getAbsolute()).toString(), StringUtils.EMPTY, NSArray.arrayWithObject(new NFDNormalizer().normalize(file.getName()).toString()))) { throw new LocalAccessDeniedException(String.format("Failed to move %s to Trash", file.getName())); } } }
@Test public void testTrashOpenDirectoryEnumeration() throws Exception { final Trash trash = new WorkspaceTrashFeature(); final SupportDirectoryFinder finder = new TemporarySupportDirectoryFinder(); final Local temp = finder.find(); final Local directory = LocalFactory.get(temp, UUID.randomUUID().toString()); directory.mkdir(); final Local sub = LocalFactory.get(directory, UUID.randomUUID().toString()); sub.mkdir(); final Local file = LocalFactory.get(sub, UUID.randomUUID().toString()); final Touch touch = LocalTouchFactory.get(); touch.touch(file); try (final DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(sub.getAbsolute()))) { trash.trash(directory); } }
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@TestTemplate public void testPartitionedBucketString() throws Exception { createPartitionedTable(spark, tableName, "bucket(5, data)"); SparkScanBuilder builder = scanBuilder(); BucketFunction.BucketString function = new BucketFunction.BucketString(); UserDefinedScalarFunc udf = toUDF(function, expressions(intLit(5), fieldRef("data"))); Predicate predicate = new Predicate("<=", expressions(udf, intLit(2))); pushFilters(builder, predicate); Batch scan = builder.build().toBatch(); assertThat(scan.planInputPartitions().length).isEqualTo(6); // NOT LTEQ builder = scanBuilder(); predicate = new Not(predicate); pushFilters(builder, predicate); scan = builder.build().toBatch(); assertThat(scan.planInputPartitions().length).isEqualTo(4); }
@Override public void handle(final RoutingContext routingContext) { if (routingContext.request().isSSL()) { final String indicatedServerName = routingContext.request().connection() .indicatedServerName(); final String requestHost = routingContext.request().host(); if (indicatedServerName != null && requestHost != null) { // sometimes the port is present in the host header, remove it final String requestHostNoPort = requestHost.replaceFirst(":\\d+", ""); if (!requestHostNoPort.equals(indicatedServerName)) { log.error(String.format( "Sni check failed, host header: %s, sni value %s", requestHostNoPort, indicatedServerName) ); routingContext.fail(MISDIRECTED_REQUEST.code(), new KsqlApiException("This request was incorrectly sent to this ksqlDB server", Errors.ERROR_CODE_MISDIRECTED_REQUEST)); return; } } } routingContext.next(); }
@Test public void shouldCheckOnlyIfTls() { // Given: when(routingContext.request()).thenReturn(serverRequest); when(serverRequest.isSSL()).thenReturn(false); // When: new SniHandler().handle(routingContext); // Then: verify(routingContext, never()).fail(anyInt(), any()); verify(routingContext).next(); }
public void setBuildFile(String buildFile) { this.buildFile = buildFile; }
@Test public void rakeTaskShouldNormalizeBuildFile() { RakeTask task = new RakeTask(); task.setBuildFile("pavan\\build.xml"); assertThat(task.arguments(), containsString("\"pavan/build.xml\"")); }
@Override public void execute(Context context) { Collection<CeTaskMessages.Message> warnings = new ArrayList<>(); try (CloseableIterator<ScannerReport.AnalysisWarning> it = reportReader.readAnalysisWarnings()) { it.forEachRemaining(w -> warnings.add(new CeTaskMessages.Message(w.getText(), w.getTimestamp()))); } if (!warnings.isEmpty()) { ceTaskMessages.addAll(warnings); } }
@Test public void execute_does_not_persist_warnings_from_reportReader_when_empty() { reportReader.setScannerLogs(emptyList()); underTest.execute(new TestComputationStepContext()); verifyNoInteractions(ceTaskMessages); }
protected boolean identifierMatches(PropertyType suppressionEntry, Identifier identifier) { if (identifier instanceof PurlIdentifier) { final PurlIdentifier purl = (PurlIdentifier) identifier; return suppressionEntry.matches(purl.toGav()); } else if (identifier instanceof CpeIdentifier) { //TODO check for regex - not just type final Cpe cpeId = ((CpeIdentifier) identifier).getCpe(); if (suppressionEntry.isRegex()) { try { return suppressionEntry.matches(cpeId.toCpe22Uri()); } catch (CpeEncodingException ex) { LOGGER.debug("Unable to convert CPE to 22 URI?" + cpeId); } } else if (suppressionEntry.isCaseSensitive()) { try { return cpeId.toCpe22Uri().startsWith(suppressionEntry.getValue()); } catch (CpeEncodingException ex) { LOGGER.debug("Unable to convert CPE to 22 URI?" + cpeId); } } else { final String id; try { id = cpeId.toCpe22Uri().toLowerCase(); } catch (CpeEncodingException ex) { LOGGER.debug("Unable to convert CPE to 22 URI?" + cpeId); return false; } final String check = suppressionEntry.getValue().toLowerCase(); return id.startsWith(check); } } return suppressionEntry.matches(identifier.getValue()); }
@Test public void testCpeMatches() throws CpeValidationException, MalformedPackageURLException { CpeIdentifier identifier = new CpeIdentifier("microsoft", ".net_framework", "4.5", Confidence.HIGHEST); PropertyType cpe = new PropertyType(); cpe.setValue("cpe:/a:microsoft:.net_framework:4.5"); SuppressionRule instance = new SuppressionRule(); boolean expResult = true; boolean result = instance.identifierMatches(cpe, identifier); assertEquals(expResult, result); cpe.setValue("cpe:/a:microsoft:.net_framework:4.0"); expResult = false; result = instance.identifierMatches(cpe, identifier); assertEquals(expResult, result); cpe.setValue("CPE:/a:microsoft:.net_framework:4.5"); cpe.setCaseSensitive(true); expResult = false; result = instance.identifierMatches(cpe, identifier); assertEquals(expResult, result); cpe.setValue("cpe:/a:microsoft:.net_framework"); cpe.setCaseSensitive(false); expResult = true; result = instance.identifierMatches(cpe, identifier); assertEquals(expResult, result); cpe.setValue("cpe:/a:microsoft:.*"); cpe.setRegex(true); expResult = true; result = instance.identifierMatches(cpe, identifier); assertEquals(expResult, result); cpe.setValue("CPE:/a:microsoft:.*"); cpe.setRegex(true); cpe.setCaseSensitive(true); expResult = false; result = instance.identifierMatches(cpe, identifier); assertEquals(expResult, result); cpe.setValue("cpe:/a:apache:.*"); cpe.setRegex(true); cpe.setCaseSensitive(false); expResult = false; result = instance.identifierMatches(cpe, identifier); assertEquals(expResult, result); identifier = new CpeIdentifier("apache", "tomcat", "7.0", Confidence.HIGH); cpe.setValue("cpe:/a:apache:tomcat"); cpe.setRegex(false); cpe.setCaseSensitive(false); expResult = true; result = instance.identifierMatches(cpe, identifier); assertEquals(expResult, result); PurlIdentifier pid = new PurlIdentifier("maven", "org.springframework", "spring-core", "2.5.5", Confidence.HIGH); cpe.setValue("org.springframework:spring-core:2.5.5"); cpe.setRegex(false); cpe.setCaseSensitive(false); expResult = true; result = instance.identifierMatches(cpe, pid); assertEquals(expResult, result); cpe.setValue("org\\.springframework\\.security:spring.*"); cpe.setRegex(true); cpe.setCaseSensitive(false); expResult = false; result = instance.identifierMatches(cpe, pid); assertEquals(expResult, result); }
@Override public void execute(ComputationStep.Context context) { Metric qProfilesMetric = metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY); new PathAwareCrawler<>(new QProfileAggregationComponentVisitor(qProfilesMetric)) .visit(treeRootHolder.getRoot()); }
@Test public void nothing_to_add_when_no_files() { ReportComponent project = ReportComponent.builder(PROJECT, PROJECT_REF).build(); treeRootHolder.setRoot(project); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasures(PROJECT_REF)).isEmpty(); }
public Set<String> indexNamesForStreamsInTimeRange(final Set<String> streamIds, final TimeRange timeRange) { Set<String> dataStreamIndices = streamIds.stream() .filter(s -> s.startsWith(Stream.DATASTREAM_PREFIX)) .map(s -> s.substring(Stream.DATASTREAM_PREFIX.length())) .collect(Collectors.toSet()); final Set<String> candidateIndices = indexRangesForStreamsInTimeRange(streamIds, timeRange).stream().map(IndexRange::indexName).collect(Collectors.toSet()); return Sets.union(dataStreamIndices, candidateIndices); }
@Test void returnsEmptySetIfNoIndicesFound() { final IndexLookup sut = new IndexLookup(mock(IndexRangeService.class), mockStreamService(streamIds), mock(IndexRangeContainsOneOfStreams.class)); Set<String> result = sut.indexNamesForStreamsInTimeRange(streamIds, timeRangeWithNoIndexRanges); assertThat(result).isEmpty(); }
public static UriTemplate create(String template, Charset charset) { return new UriTemplate(template, true, charset); }
@Test void skipSlashes() { String template = "https://www.example.com/{path}"; UriTemplate uriTemplate = UriTemplate.create(template, false, Util.UTF_8); Map<String, Object> variables = new LinkedHashMap<>(); variables.put("path", "me/you/first"); String encoded = uriTemplate.expand(variables); assertThat(encoded).isEqualToIgnoringCase("https://www.example.com/me/you/first"); }
@Override public AllocatedSlotsAndReservationStatus removeSlots(ResourceID owner) { final Set<AllocationID> slotsOfTaskExecutor = slotsPerTaskExecutor.remove(owner); if (slotsOfTaskExecutor != null) { final Collection<AllocatedSlot> removedSlots = new ArrayList<>(); final Map<AllocationID, ReservationStatus> removedSlotsReservationStatus = new HashMap<>(); for (AllocationID allocationId : slotsOfTaskExecutor) { final ReservationStatus reservationStatus = containsFreeSlot(allocationId) ? ReservationStatus.FREE : ReservationStatus.RESERVED; final AllocatedSlot removedSlot = Preconditions.checkNotNull(removeSlotInternal(allocationId)); removedSlots.add(removedSlot); removedSlotsReservationStatus.put(removedSlot.getAllocationId(), reservationStatus); } return new DefaultAllocatedSlotsAndReservationStatus( removedSlots, removedSlotsReservationStatus); } else { return new DefaultAllocatedSlotsAndReservationStatus( Collections.emptyList(), Collections.emptyMap()); } }
@Test void testRemoveSlots() { final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool(); final ResourceID owner = ResourceID.generate(); final Collection<AllocatedSlot> slots = createAllocatedSlotsWithOwner(owner); final AllocatedSlot otherSlot = createAllocatedSlot(ResourceID.generate()); slots.add(otherSlot); slotPool.addSlots(slots, 0); slotPool.removeSlots(owner); assertSlotPoolContainsSlots(slotPool, Collections.singleton(otherSlot)); }
private static String transFromCamel(String key) { Matcher matcher = PATTERN.matcher(key); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, "." + matcher.group(0).toLowerCase(Locale.ROOT)); } matcher.appendTail(sb); return sb.toString(); }
@Test public void testReadEnv() throws Exception { testKey(CONFIG_KEY); testKey(CONFIG_KEY.replace('.', '_')); testKey(CONFIG_KEY.replace('.', '-')); testKey(CONFIG_KEY.toLowerCase(Locale.ROOT).replace('.', '-')); testKey(CONFIG_KEY.toLowerCase(Locale.ROOT).replace('.', '_')); testKey(CONFIG_KEY.toLowerCase(Locale.ROOT)); testKey(CONFIG_KEY.toUpperCase(Locale.ROOT).replace('.', '-')); testKey(CONFIG_KEY.toUpperCase(Locale.ROOT).replace('.', '_')); testKey(CONFIG_KEY.toUpperCase(Locale.ROOT)); testKey(transFromCamel(CONFIG_KEY)); testKey(transFromCamel(CONFIG_KEY).replace('.', '_')); testKey(transFromCamel(CONFIG_KEY).replace('.', '-')); testKey(transFromCamel(CONFIG_KEY).toUpperCase(Locale.ROOT)); testKey(transFromCamel(CONFIG_KEY).toUpperCase(Locale.ROOT).replace('.', '_')); testKey(transFromCamel(CONFIG_KEY).toUpperCase(Locale.ROOT).replace('.', '-')); }
public Node pop() { return nodes.poll(); }
@Test void require_NameProviders_before_SearcherNodes() { NameProvider nameProvider = createDummyNameProvider(100); ComponentNode componentNode = new ComponentNode<>(createFakeComponentA("a"), 1); addNodes(nameProvider, componentNode); assertEquals(nameProvider, pop()); assertEquals(componentNode, pop()); }
public static boolean testURLPassesExclude(String url, String exclude) { // If the url doesn't decode to UTF-8 then return false, it could be trying to get around our rules with nonstandard encoding // If the exclude rule includes a "?" character, the url must exactly match the exclude rule. // If the exclude rule does not contain the "?" character, we chop off everything starting at the first "?" // in the URL and then the resulting url must exactly match the exclude rule. If the exclude ends with a "*" // (wildcard) character, and wildcards are allowed in excludes, then the URL is allowed if it exactly // matches everything before the * and there are no ".." even encoded ones characters after the "*". String decodedUrl = null; try { decodedUrl = URLDecoder.decode(url, "UTF-8"); } catch (Exception e) { return false; } if (exclude.endsWith("*") && ALLOW_WILDCARDS_IN_EXCLUDES.getValue()) { if (url.startsWith(exclude.substring(0, exclude.length()-1))) { // Now make sure that there are no ".." characters in the rest of the URL. if (!decodedUrl.contains("..")) { return true; } } } else if (exclude.contains("?")) { if (url.equals(exclude)) { return true; } } else { int paramIndex = url.indexOf("?"); if (paramIndex != -1) { url = url.substring(0, paramIndex); } if (url.equals(exclude)) { return true; } } return false; }
@Test public void testExcludeRules() { assertFalse(AuthCheckFilter.testURLPassesExclude("blahblah/login.jsp", "login.jsp")); assertTrue(AuthCheckFilter.testURLPassesExclude("login.jsp", "login.jsp")); assertTrue(AuthCheckFilter.testURLPassesExclude("login.jsp?yousuck&blah", "login.jsp")); assertTrue(AuthCheckFilter.testURLPassesExclude("login.jsp?another=true&login.jsp?true", "login.jsp")); assertFalse(AuthCheckFilter.testURLPassesExclude("blahblah/login.jsp", "login.jsp?logout=false")); assertTrue(AuthCheckFilter.testURLPassesExclude("login.jsp?logout=false", "login.jsp?logout=false")); assertFalse(AuthCheckFilter.testURLPassesExclude("login.jsp?logout=false&another=true", "login.jsp?logout=false")); assertFalse(AuthCheckFilter.testURLPassesExclude("login.jsp?logout=false&another=true", "login.jsp?logout=false")); assertFalse(AuthCheckFilter.testURLPassesExclude("another.jsp?login.jsp", "login.jsp")); }
private static boolean visitTerminal(final SchemaVisitor visitor, final Schema schema, final Deque<Object> dq) { SchemaVisitorAction action = visitor.visitTerminal(schema); switch (action) { case CONTINUE: break; case SKIP_SUBTREE: throw new UnsupportedOperationException("Invalid action " + action + " for " + schema); case SKIP_SIBLINGS: while (!dq.isEmpty() && dq.getLast() instanceof Schema) { dq.removeLast(); } break; case TERMINATE: return true; default: throw new UnsupportedOperationException("Invalid action " + action + " for " + schema); } return false; }
@Test void cloningError1() { assertThrows(IllegalStateException.class, () -> { // Visit Terminal with union Schema recordSchema = new Schema.Parser().parse( "{\"type\": \"record\", \"name\": \"R\", \"fields\":[{\"name\": \"f1\", \"type\": [\"int\", \"long\"]}]}"); new CloningVisitor(recordSchema).visitTerminal(recordSchema.getField("f1").schema()); }); }
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthGetTransactionCount() throws Exception { web3j.ethGetTransactionCount( "0x407d73d8a49eeb85d32cf465507dd71d507100c1", DefaultBlockParameterName.LATEST) .send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionCount\"," + "\"params\":[\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\",\"latest\"]," + "\"id\":1}"); }
public static YamlScalar asScalar(YamlNode node) { if (node != null && !(node instanceof YamlScalar)) { String nodeName = node.nodeName(); throw new YamlException(String.format("Child %s is not a scalar, it's actual type is %s", nodeName, node.getClass())); } return (YamlScalar) node; }
@Test(expected = YamlException.class) public void asScalarThrowsIfNonScalarPassed() { YamlNode genericNode = new YamlMappingImpl(null, "mapping"); YamlUtil.asScalar(genericNode); }
@Override public String service() { return DubboParser.service(invoker); }
@Test void service() { when(invocation.getInvoker()).thenReturn(invoker); when(invoker.getUrl()).thenReturn(url); assertThat(request.service()) .isEqualTo("brave.dubbo.GreeterService"); }
public ConvertedTime getConvertedTime(long duration) { Set<Seconds> keys = RULES.keySet(); for (Seconds seconds : keys) { if (duration <= seconds.getSeconds()) { return RULES.get(seconds).getConvertedTime(duration); } } return new TimeConverter.OverTwoYears().getConvertedTime(duration); }
@Test public void testShouldReturnTimeUnitAsYearsWhenDurationIsLargerThan3Years() throws Exception { assertEquals(TimeConverter.OVER_X_YEARS_AGO.argument(3), timeConverter .getConvertedTime(3 * 365 * TimeConverter.DAY_IN_SECONDS + 2 * TimeConverter.DAY_IN_SECONDS)); }
@Override public long getVersion() { return record.getVersion(); }
@Test public void test_getVersion() { assertEquals(0, view.getVersion()); }