focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Object read(final MySQLPacketPayload payload, final boolean unsigned) { return payload.getByteBuf().readDoubleLE(); }
@Test void assertRead() { when(byteBuf.readDoubleLE()).thenReturn(1.0D); assertThat(new MySQLDoubleBinaryProtocolValue().read(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8), false), is(1.0D)); }
public void setProfile(final Set<String> indexSetsIds, final String profileId, final boolean rotateImmediately) { checkProfile(profileId); checkAllIndicesSupportProfileChange(indexSetsIds); for (String indexSetId : indexSetsIds) { try { indexSetService.get(indexSetId).ifPresent(indexSetConfig -> { var updatedIndexSetConfig = setProfileForIndexSet(profileId, indexSetConfig); if (rotateImmediately) { updatedIndexSetConfig.ifPresent(this::cycleIndexSet); } }); } catch (Exception ex) { LOG.error("Failed to update field type in index set : " + indexSetId, ex); throw ex; } } }
@Test void testThrowsExceptionWhenTryingToSetUnExistingProfile() { assertThrows(NotFoundException.class, () -> toTest.setProfile(Set.of(), "000000000000000000000042", false)); }
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .precision(column.getColumnLength()) .length(column.getColumnLength()) .nullable(column.isNullable()) .comment(column.getComment()) .scale(column.getScale()) .defaultValue(column.getDefaultValue()); switch (column.getDataType().getSqlType()) { case NULL: builder.columnType(IRIS_NULL); builder.dataType(IRIS_NULL); break; case STRING: if (column.getColumnLength() == null || column.getColumnLength() <= 0) { builder.columnType(String.format("%s(%s)", IRIS_VARCHAR, MAX_VARCHAR_LENGTH)); builder.dataType(IRIS_VARCHAR); } else if (column.getColumnLength() < MAX_VARCHAR_LENGTH) { builder.columnType( String.format("%s(%s)", IRIS_VARCHAR, column.getColumnLength())); builder.dataType(IRIS_VARCHAR); } else { builder.columnType(IRIS_LONG_VARCHAR); builder.dataType(IRIS_LONG_VARCHAR); } break; case BOOLEAN: builder.columnType(IRIS_BIT); builder.dataType(IRIS_BIT); break; case TINYINT: builder.columnType(IRIS_TINYINT); builder.dataType(IRIS_TINYINT); break; case SMALLINT: builder.columnType(IRIS_SMALLINT); builder.dataType(IRIS_SMALLINT); break; case INT: builder.columnType(IRIS_INTEGER); builder.dataType(IRIS_INTEGER); break; case BIGINT: builder.columnType(IRIS_BIGINT); builder.dataType(IRIS_BIGINT); break; case FLOAT: builder.columnType(IRIS_FLOAT); builder.dataType(IRIS_FLOAT); break; case DOUBLE: builder.columnType(IRIS_DOUBLE); builder.dataType(IRIS_DOUBLE); break; case DECIMAL: DecimalType decimalType = (DecimalType) column.getDataType(); long precision = decimalType.getPrecision(); int scale = decimalType.getScale(); 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); } if (precision < scale) { precision = scale; } 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 = MAX_SCALE; 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); } builder.columnType(String.format("%s(%s,%s)", IRIS_DECIMAL, precision, scale)); builder.dataType(IRIS_DECIMAL); builder.precision(precision); builder.scale(scale); break; case BYTES: if (column.getColumnLength() == null || column.getColumnLength() <= 0) { builder.columnType(IRIS_LONG_BINARY); builder.dataType(IRIS_LONG_BINARY); } else if (column.getColumnLength() < MAX_BINARY_LENGTH) { builder.dataType(IRIS_BINARY); builder.columnType( String.format("%s(%s)", IRIS_BINARY, column.getColumnLength())); } else { builder.columnType(IRIS_LONG_BINARY); builder.dataType(IRIS_LONG_BINARY); } break; case DATE: builder.columnType(IRIS_DATE); builder.dataType(IRIS_DATE); break; case TIME: builder.dataType(IRIS_TIME); if (Objects.nonNull(column.getScale()) && column.getScale() > 0) { Integer 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_TIME_SCALE, timeScale); } builder.columnType(String.format("%s(%s)", IRIS_TIME, timeScale)); builder.scale(timeScale); } else { builder.columnType(IRIS_TIME); } break; case TIMESTAMP: builder.columnType(IRIS_TIMESTAMP2); builder.dataType(IRIS_TIMESTAMP2); break; default: throw CommonError.convertToConnectorTypeError( DatabaseIdentifier.IRIS, column.getDataType().getSqlType().name(), column.getName()); } return builder.build(); }
@Test public void testReconvertString() { Column column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(null) .build(); BasicTypeDefine typeDefine = IrisTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.assertEquals("VARCHAR(" + Integer.MAX_VALUE + ")", typeDefine.getColumnType()); Assertions.assertEquals(IrisTypeConverter.IRIS_VARCHAR, typeDefine.getDataType()); column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(1L) .build(); typeDefine = IrisTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.assertEquals( String.format("%s(%s)", IrisTypeConverter.IRIS_VARCHAR, column.getColumnLength()), typeDefine.getColumnType()); Assertions.assertEquals(IrisTypeConverter.IRIS_VARCHAR, typeDefine.getDataType()); column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(60000L) .build(); typeDefine = IrisTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.assertEquals( String.format("%s(%s)", IrisTypeConverter.IRIS_VARCHAR, column.getColumnLength()), typeDefine.getColumnType()); Assertions.assertEquals(IrisTypeConverter.IRIS_VARCHAR, typeDefine.getDataType()); column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(60001L) .build(); typeDefine = IrisTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.assertEquals( String.format("%s(%s)", IrisTypeConverter.IRIS_VARCHAR, column.getColumnLength()), typeDefine.getColumnType()); Assertions.assertEquals(IrisTypeConverter.IRIS_VARCHAR, typeDefine.getDataType()); }
@Override public KeyValueIterator<Windowed<K>, V> fetchAll(final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { return new KeyValueIteratorFacade<>(inner.fetchAll(timeFrom, timeTo)); }
@Test public void shouldReturnPlainKeyValuePairsOnFetchAllInstantParameters() { when(mockedKeyValueWindowTimestampIterator.next()) .thenReturn(KeyValue.pair( new Windowed<>("key1", new TimeWindow(21L, 22L)), ValueAndTimestamp.make("value1", 22L))) .thenReturn(KeyValue.pair( new Windowed<>("key2", new TimeWindow(42L, 43L)), ValueAndTimestamp.make("value2", 100L))); when(mockedWindowTimestampStore.fetchAll(Instant.ofEpochMilli(21L), Instant.ofEpochMilli(42L))) .thenReturn(mockedKeyValueWindowTimestampIterator); final KeyValueIterator<Windowed<String>, String> iterator = readOnlyWindowStoreFacade.fetchAll(Instant.ofEpochMilli(21L), Instant.ofEpochMilli(42L)); assertThat(iterator.next(), is(KeyValue.pair(new Windowed<>("key1", new TimeWindow(21L, 22L)), "value1"))); assertThat(iterator.next(), is(KeyValue.pair(new Windowed<>("key2", new TimeWindow(42L, 43L)), "value2"))); }
public static boolean isServiceNameCompatibilityMode(final String serviceName) { return !StringUtils.isBlank(serviceName) && serviceName.contains(Constants.SERVICE_INFO_SPLITER); }
@Test void testIsServiceNameCompatibilityMode() { String serviceName1 = "group@@serviceName"; assertTrue(NamingUtils.isServiceNameCompatibilityMode(serviceName1)); String serviceName2 = "serviceName"; assertFalse(NamingUtils.isServiceNameCompatibilityMode(serviceName2)); String serviceName3 = null; assertFalse(NamingUtils.isServiceNameCompatibilityMode(serviceName3)); }
public void startAsync() { try { udfLoader.load(); ProcessingLogServerUtils.maybeCreateProcessingLogTopic( serviceContext.getTopicClient(), processingLogConfig, ksqlConfig); if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) { log.warn("processing log auto-create is enabled, but this is not supported " + "for headless mode."); } rocksDBConfigSetterHandler.accept(ksqlConfig); processesQueryFile(readQueriesFile(queriesFile)); showWelcomeMessage(); final Properties properties = new Properties(); ksqlConfig.originals().forEach((key, value) -> { if (nonNull(value)) { properties.put(key, value.toString()); } }); versionChecker.start(KsqlModuleType.SERVER, properties); } catch (final Exception e) { log.error("Failed to start KSQL Server with query file: " + queriesFile, e); throw e; } }
@Test public void shouldSetPropertyOnlyOnCommandsFollowingTheSetStatement() { // Given: final PreparedStatement<SetProperty> setProp = PreparedStatement.of("SET PROP", new SetProperty(Optional.empty(), ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")); final PreparedStatement<CreateStream> cs = PreparedStatement.of("CS", new CreateStream(SOME_NAME, SOME_ELEMENTS, false, false, JSON_PROPS, false)); givenQueryFileParsesTo(cs, setProp); // When: standaloneExecutor.startAsync(); // Then: verify(ksqlEngine).execute(serviceContext, ConfiguredStatement .of(cs, SessionConfig.of(ksqlConfig, ImmutableMap.of()))); }
public RouterQuotaUsage getQuotaUsage(String path) { readLock.lock(); try { RouterQuotaUsage quotaUsage = this.cache.get(path); if (quotaUsage != null && isQuotaSet(quotaUsage)) { return quotaUsage; } // If not found, look for its parent path usage value. int pos = path.lastIndexOf(Path.SEPARATOR); if (pos != -1) { String parentPath = path.substring(0, pos); return getQuotaUsage(parentPath); } } finally { readLock.unlock(); } return null; }
@Test public void testGetQuotaUsage() { RouterQuotaUsage quotaGet; // test case1: get quota with a non-exist path quotaGet = manager.getQuotaUsage("/non-exist-path"); assertNull(quotaGet); // test case2: get quota from a no-quota set path RouterQuotaUsage.Builder quota = new RouterQuotaUsage.Builder() .quota(HdfsConstants.QUOTA_RESET) .spaceQuota(HdfsConstants.QUOTA_RESET); manager.put("/noQuotaSet", quota.build()); quotaGet = manager.getQuotaUsage("/noQuotaSet"); // it should return null assertNull(quotaGet); // test case3: get quota from a quota-set path quota.quota(1); quota.spaceQuota(HdfsConstants.QUOTA_RESET); manager.put("/hasQuotaSet", quota.build()); quotaGet = manager.getQuotaUsage("/hasQuotaSet"); assertEquals(1, quotaGet.getQuota()); assertEquals(HdfsConstants.QUOTA_RESET, quotaGet.getSpaceQuota()); // test case4: get quota with a non-exist child path quotaGet = manager.getQuotaUsage("/hasQuotaSet/file"); // it will return the nearest ancestor which quota was set assertEquals(1, quotaGet.getQuota()); assertEquals(HdfsConstants.QUOTA_RESET, quotaGet.getSpaceQuota()); // test case5: get quota with a child path which its parent // wasn't quota set quota.quota(HdfsConstants.QUOTA_RESET); quota.spaceQuota(HdfsConstants.QUOTA_RESET); manager.put("/hasQuotaSet/noQuotaSet", quota.build()); // here should return the quota of path /hasQuotaSet // (the nearest ancestor which quota was set) quotaGet = manager.getQuotaUsage("/hasQuotaSet/noQuotaSet/file"); assertEquals(1, quotaGet.getQuota()); assertEquals(HdfsConstants.QUOTA_RESET, quotaGet.getSpaceQuota()); // test case6: get quota with a child path which its parent was quota set quota.quota(2); quota.spaceQuota(HdfsConstants.QUOTA_RESET); manager.put("/hasQuotaSet/hasQuotaSet", quota.build()); // here should return the quota of path /hasQuotaSet/hasQuotaSet quotaGet = manager.getQuotaUsage("/hasQuotaSet/hasQuotaSet/file"); assertEquals(2, quotaGet.getQuota()); assertEquals(HdfsConstants.QUOTA_RESET, quotaGet.getSpaceQuota()); }
@Override public ExecutionState getState() { return stateSupplier.get(); }
@Test void testGetExecutionState() { for (ExecutionState state : ExecutionState.values()) { stateSupplier.setExecutionState(state); assertThat(producerVertex.getState()).isEqualTo(state); } }
public static boolean isUnclosedQuote(final String line) { // CHECKSTYLE_RULES.ON: CyclomaticComplexity int quoteStart = -1; for (int i = 0; i < line.length(); ++i) { if (quoteStart < 0 && isQuoteChar(line, i)) { quoteStart = i; } else if (quoteStart >= 0 && isTwoQuoteStart(line, i) && !isEscaped(line, i)) { // Together, two quotes are effectively an escaped quote and don't act as a quote character. // Skip the next quote char, since it's coupled with the first. i++; } else if (quoteStart >= 0 && isQuoteChar(line, i) && !isEscaped(line, i)) { quoteStart = -1; } } final int commentInd = line.indexOf(COMMENT); if (commentInd < 0) { return quoteStart >= 0; } else if (quoteStart < 0) { return false; } else { return commentInd > quoteStart; } }
@Test public void shouldFindUnclosedQuote_escapedEscape() { // Given: final String line = "some line 'this is in a quote\\\\'"; // Then: assertThat(UnclosedQuoteChecker.isUnclosedQuote(line), is(false)); }
public Stream<Hit> stream() { if (nPostingLists == 0) { return Stream.empty(); } return StreamSupport.stream(new PredicateSpliterator(), false); }
@Test void requireThatNoStreamsReturnNoResults() { PredicateSearch search = new PredicateSearch(new ArrayList<>(), new byte[0], new byte[0], new short[0], 1); assertEquals(0, search.stream().count()); }
@Override public Long createMailLog(Long userId, Integer userType, String toMail, MailAccountDO account, MailTemplateDO template, String templateContent, Map<String, Object> templateParams, Boolean isSend) { MailLogDO.MailLogDOBuilder logDOBuilder = MailLogDO.builder(); // 根据是否要发送,设置状态 logDOBuilder.sendStatus(Objects.equals(isSend, true) ? MailSendStatusEnum.INIT.getStatus() : MailSendStatusEnum.IGNORE.getStatus()) // 用户信息 .userId(userId).userType(userType).toMail(toMail) .accountId(account.getId()).fromMail(account.getMail()) // 模板相关字段 .templateId(template.getId()).templateCode(template.getCode()).templateNickname(template.getNickname()) .templateTitle(template.getTitle()).templateContent(templateContent).templateParams(templateParams); // 插入数据库 MailLogDO logDO = logDOBuilder.build(); mailLogMapper.insert(logDO); return logDO.getId(); }
@Test public void testCreateMailLog() { // 准备参数 Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); String toMail = randomEmail(); MailAccountDO account = randomPojo(MailAccountDO.class); MailTemplateDO template = randomPojo(MailTemplateDO.class); String templateContent = randomString(); Map<String, Object> templateParams = randomTemplateParams(); Boolean isSend = true; // mock 方法 // 调用 Long logId = mailLogService.createMailLog(userId, userType, toMail, account, template, templateContent, templateParams, isSend); // 断言 MailLogDO log = mailLogMapper.selectById(logId); assertNotNull(log); assertEquals(MailSendStatusEnum.INIT.getStatus(), log.getSendStatus()); assertEquals(userId, log.getUserId()); assertEquals(userType, log.getUserType()); assertEquals(toMail, log.getToMail()); assertEquals(account.getId(), log.getAccountId()); assertEquals(account.getMail(), log.getFromMail()); assertEquals(template.getId(), log.getTemplateId()); assertEquals(template.getCode(), log.getTemplateCode()); assertEquals(template.getNickname(), log.getTemplateNickname()); assertEquals(template.getTitle(), log.getTemplateTitle()); assertEquals(templateContent, log.getTemplateContent()); assertEquals(templateParams, log.getTemplateParams()); }
@Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { if (args.isEmpty()) { printHelp(out); return 0; } OutputStream output = out; if (args.size() > 1) { output = Util.fileOrStdout(args.get(args.size() - 1), out); args = args.subList(0, args.size() - 1); } DataFileWriter<GenericRecord> writer = new DataFileWriter<>(new GenericDatumWriter<>()); Schema schema = null; Map<String, byte[]> metadata = new TreeMap<>(); String inputCodec = null; for (String inFile : expandsInputFiles(args)) { InputStream input = Util.fileOrStdin(inFile, in); DataFileStream<GenericRecord> reader = new DataFileStream<>(input, new GenericDatumReader<>()); if (schema == null) { // this is the first file - set up the writer, and store the // Schema & metadata we'll use. schema = reader.getSchema(); for (String key : reader.getMetaKeys()) { if (!DataFileWriter.isReservedMeta(key)) { byte[] metadatum = reader.getMeta(key); metadata.put(key, metadatum); writer.setMeta(key, metadatum); } } inputCodec = reader.getMetaString(DataFileConstants.CODEC); if (inputCodec == null) { inputCodec = DataFileConstants.NULL_CODEC; } writer.setCodec(CodecFactory.fromString(inputCodec)); writer.create(schema, output); } else { // check that we're appending to the same schema & metadata. if (!schema.equals(reader.getSchema())) { err.println("input files have different schemas"); reader.close(); return 1; } for (String key : reader.getMetaKeys()) { if (!DataFileWriter.isReservedMeta(key)) { byte[] metadatum = reader.getMeta(key); byte[] writersMetadatum = metadata.get(key); if (!Arrays.equals(metadatum, writersMetadatum)) { err.println("input files have different non-reserved metadata"); reader.close(); return 2; } } } String thisCodec = reader.getMetaString(DataFileConstants.CODEC); if (thisCodec == null) { thisCodec = DataFileConstants.NULL_CODEC; } if (!inputCodec.equals(thisCodec)) { err.println("input files have different codecs"); reader.close(); return 3; } } writer.appendAllFrom(reader, /* recompress */ false); reader.close(); } writer.close(); return 0; }
@Test void concat() throws Exception { Map<String, String> metadata = new HashMap<>(); metadata.put("myMetaKey", "myMetaValue"); File input1 = generateData(name.getMethodName() + "-1.avro", Type.STRING, metadata, DEFLATE); File input2 = generateData(name.getMethodName() + "-2.avro", Type.STRING, metadata, DEFLATE); File input3 = generateData(name.getMethodName() + "-3.avro", Type.STRING, metadata, DEFLATE); File output = new File(OUTPUT_DIR, name.getMethodName() + ".avro"); List<String> args = asList(input1.getAbsolutePath(), input2.getAbsolutePath(), input3.getAbsolutePath(), output.getAbsolutePath()); int returnCode = new ConcatTool().run(System.in, System.out, System.err, args); assertEquals(0, returnCode); assertEquals(ROWS_IN_INPUT_FILES * 3, numRowsInFile(output)); assertEquals(getCodec(input1).getClass(), getCodec(output).getClass()); }
@Override public void close() throws Exception { handlesToClose.forEach(IOUtils::closeQuietly); handlesToClose.clear(); if (sharedResources != null) { sharedResources.close(); } cleanRelocatedDbLogs(); }
@Test public void testFreeSharedResourcesAfterClose() throws Exception { LRUCache cache = new LRUCache(1024L); WriteBufferManager wbm = new WriteBufferManager(1024L, cache); RocksDBSharedResources sharedResources = new RocksDBSharedResources(cache, wbm, 1024L, false); final ThrowingRunnable<Exception> disposer = sharedResources::close; OpaqueMemoryResource<RocksDBSharedResources> opaqueResource = new OpaqueMemoryResource<>(sharedResources, 1024L, disposer); RocksDBResourceContainer container = new RocksDBResourceContainer(PredefinedOptions.DEFAULT, null, opaqueResource); container.close(); assertThat(cache.isOwningHandle(), is(false)); assertThat(wbm.isOwningHandle(), is(false)); }
@ConstantFunction(name = "url_extract_parameter", argTypes = {VARCHAR, VARCHAR}, returnType = VARCHAR) public static ConstantOperator urlExtractParameter(ConstantOperator url, ConstantOperator parameter) { List<NameValuePair> parametersAndValues = null; try { parametersAndValues = URLEncodedUtils.parse(new URI(url.getVarchar()), Charset.forName("UTF-8")); String parameterName = parameter.getVarchar(); for (NameValuePair nv : parametersAndValues) { if (nv.getName().equals(parameterName)) { return ConstantOperator.createVarchar(nv.getValue()); } } } catch (URISyntaxException e) { return ConstantOperator.createNull(Type.VARCHAR); } return ConstantOperator.createNull(Type.VARCHAR); }
@Test public void testUrlExtractParameter() { assertEquals("100", ScalarOperatorFunctions.urlExtractParameter( new ConstantOperator("https://starrocks.com/doc?k1=100&k2=3", Type.VARCHAR), new ConstantOperator("k1", Type.VARCHAR) ).getVarchar()); assertEquals(ScalarOperatorFunctions.urlExtractParameter( new ConstantOperator("1234i5", Type.VARCHAR), new ConstantOperator("k1", Type.VARCHAR)), ConstantOperator.createNull(Type.VARCHAR)); assertEquals(ScalarOperatorFunctions.urlExtractParameter( new ConstantOperator("https://starrocks.com/doc?k1=100&k2=3", Type.VARCHAR), new ConstantOperator("k3", Type.VARCHAR)), ConstantOperator.createNull(Type.VARCHAR)); }
public String toRegexForFixedDate(Date date) { StringBuilder buf = new StringBuilder(); Converter<Object> p = headTokenConverter; while (p != null) { if (p instanceof LiteralConverter) { buf.append(p.convert(null)); } else if (p instanceof IntegerTokenConverter) { buf.append("(\\d+)"); } else if (p instanceof DateTokenConverter) { buf.append(p.convert(date)); } p = p.getNext(); } return buf.toString(); }
@Test public void asRegexByDate() { Calendar cal = Calendar.getInstance(); cal.set(2003, 4, 20, 17, 55); { FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", context); String regex = fnp.toRegexForFixedDate(cal.getTime()); assertEquals("foo-2003.05.20-(\\d+).txt", regex); } { FileNamePattern fnp = new FileNamePattern("\\toto\\foo-%d{yyyy\\MM\\dd}-%i.txt", context); String regex = fnp.toRegexForFixedDate(cal.getTime()); assertEquals("/toto/foo-2003/05/20-(\\d+).txt", regex); } }
@Override public UseDefaultInsertColumnsToken generateSQLToken(final InsertStatementContext insertStatementContext) { String tableName = Optional.ofNullable(insertStatementContext.getSqlStatement().getTable()).map(optional -> optional.getTableName().getIdentifier().getValue()).orElse(""); Optional<UseDefaultInsertColumnsToken> previousSQLToken = findInsertColumnsToken(); if (previousSQLToken.isPresent()) { processPreviousSQLToken(previousSQLToken.get(), insertStatementContext, tableName); return previousSQLToken.get(); } return generateNewSQLToken(insertStatementContext, tableName); }
@Test void assertGenerateSQLTokensWhenInsertColumnsUseDifferentEncryptorWithSelectProjection() { generator.setPreviousSQLTokens(EncryptGeneratorFixtureBuilder.getPreviousSQLTokens()); assertThrows(UnsupportedSQLOperationException.class, () -> generator.generateSQLToken(EncryptGeneratorFixtureBuilder.createInsertSelectStatementContext(Collections.emptyList(), false))); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> children = new AttributedList<>(); for(List<DavResource> list : ListUtils.partition(this.list(directory), new HostPreferences(session.getHost()).getInteger("webdav.listing.chunksize"))) { for(final DavResource resource : list) { if(new SimplePathPredicate(new Path(resource.getHref().getPath(), EnumSet.of(Path.Type.directory))).test(directory)) { log.warn(String.format("Ignore resource %s", resource)); // Do not include self if(resource.isDirectory()) { continue; } throw new NotfoundException(directory.getAbsolute()); } final PathAttributes attr = attributes.toAttributes(resource); final Path file = new Path(directory, PathNormalizer.name(resource.getHref().getPath()), resource.isDirectory() ? EnumSet.of(Path.Type.directory) : EnumSet.of(Path.Type.file), attr); children.add(file); listener.chunk(directory, children); } } return children; } catch(SardineException e) { throw new DAVExceptionMappingService().map("Listing directory {0} failed", e, directory); } catch(IOException e) { throw new HttpExceptionMappingService().map(e, directory); } }
@Test(expected = NotfoundException.class) public void testListNotfound() throws Exception { new DAVListService(session).list(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new DisabledListProgressListener()); }
public static IpPrefix valueOf(int address, int prefixLength) { return new IpPrefix(IpAddress.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfAddressNegativePrefixLengthIPv4() { IpAddress ipAddress; IpPrefix ipPrefix; ipAddress = IpAddress.valueOf("1.2.3.4"); ipPrefix = IpPrefix.valueOf(ipAddress, -1); }
public static Iterator<String> lineIterator(String input) { return new LineIterator(input); }
@Test public void lines() { assertThat(ImmutableList.copyOf(Newlines.lineIterator("foo\nbar\n"))) .containsExactly("foo\n", "bar\n"); assertThat(ImmutableList.copyOf(Newlines.lineIterator("foo\nbar"))) .containsExactly("foo\n", "bar"); assertThat(ImmutableList.copyOf(Newlines.lineIterator("foo\rbar\r"))) .containsExactly("foo\r", "bar\r"); assertThat(ImmutableList.copyOf(Newlines.lineIterator("foo\rbar"))) .containsExactly("foo\r", "bar"); assertThat(ImmutableList.copyOf(Newlines.lineIterator("foo\r\nbar\r\n"))) .containsExactly("foo\r\n", "bar\r\n"); assertThat(ImmutableList.copyOf(Newlines.lineIterator("foo\r\nbar"))) .containsExactly("foo\r\n", "bar"); }
@Override public EventNotificationConfigEntity toContentPackEntity(EntityDescriptorIds entityDescriptorIds) { return TeamsEventNotificationConfigEntity.builder() .color(ValueReference.of(color())) .webhookUrl(ValueReference.of(webhookUrl())) .customMessage(ValueReference.of(customMessage())) .iconUrl(ValueReference.of(iconUrl())) .timeZone(ValueReference.of(timeZone().getID())) .build(); }
@Test(expected = NullPointerException.class) public void toContentPackEntity() { final TeamsEventNotificationConfig teamsEventNotificationConfig = TeamsEventNotificationConfig.builder().build(); teamsEventNotificationConfig.toContentPackEntity(EntityDescriptorIds.empty()); }
@Override public <KEY> URIMappingResult<KEY> mapUris(List<URIKeyPair<KEY>> requestUriKeyPairs) throws ServiceUnavailableException { if (requestUriKeyPairs == null || requestUriKeyPairs.isEmpty()) { return new URIMappingResult<>(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap()); } // API assumes that all requests will be made to the same service, just use the first request to get the service name and act as sample uri URI sampleURI = requestUriKeyPairs.get(0).getRequestUri(); String serviceName = LoadBalancerUtil.getServiceNameFromUri(sampleURI); // To achieve scatter-gather, we require the following information PartitionAccessor accessor = _partitionInfoProvider.getPartitionAccessor(serviceName); Map<Integer, Ring<URI>> rings = _hashRingProvider.getRings(sampleURI); HashFunction<Request> hashFunction = _hashRingProvider.getRequestHashFunction(serviceName); Map<Integer, Set<KEY>> unmapped = new HashMap<>(); // Pass One Map<Integer, List<URIKeyPair<KEY>>> requestsByPartition = distributeToPartitions(requestUriKeyPairs, accessor, unmapped); // Pass Two Map<URI, Integer> hostToParitionId = new HashMap<>(); Map<URI, Set<KEY>> hostToKeySet = distributeToHosts(requestsByPartition, rings, hashFunction, hostToParitionId, unmapped); return new URIMappingResult<>(hostToKeySet, unmapped, hostToParitionId); }
@Test(dataProvider = "stickyPartitionPermutation") public void testUnmappedKeys(boolean sticky, boolean partitioned) throws Exception { int partitionCount = partitioned ? 10 : 1; int requestPerPartition = 100; List<Ring<URI>> rings = new ArrayList<>(); IntStream.range(0, partitionCount).forEach(i -> rings.add(new MPConsistentHashRing<>(Collections.emptyMap()))); StaticRingProvider ringProvider = new StaticRingProvider(rings); ringProvider.setHashFunction(getHashFunction(sticky)); PartitionInfoProvider infoProvider = createRangeBasedPartitionInfoProvider(partitionCount); URIMapper mapper = new RingBasedUriMapper(ringProvider, infoProvider); List<URIKeyPair<Integer>> requests = testUtil.generateRequests(partitionCount, requestPerPartition); URIMappingResult<Integer> uriMapperResultNormal = mapper.mapUris(requests); Assert.assertTrue(uriMapperResultNormal.getUnmappedKeys().size() == partitionCount); uriMapperResultNormal.getUnmappedKeys() .forEach((key, value) -> Assert.assertTrue(value.size() == requestPerPartition)); URIKeyPair<Integer> request = new URIKeyPair<>(new URI("d2://testService/1"), IntStream.range(0, partitionCount).boxed().collect(Collectors.toSet())); URIMappingResult<Integer> uriMapperResultCustom = mapper.mapUris(Collections.singletonList(request)); Assert.assertTrue(uriMapperResultCustom.getUnmappedKeys().size() == partitionCount); uriMapperResultCustom.getUnmappedKeys() .forEach((key, value) -> Assert.assertTrue(value.isEmpty())); }
@Override public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { final BrickApiClient client = new BrickApiClient(session); if(status.isExists()) { if(log.isWarnEnabled()) { log.warn(String.format("Delete file %s to be replaced with %s", target, file)); } new BrickDeleteFeature(session).delete(Collections.singletonList(target), callback, new Delete.DisabledCallback()); } final FileActionEntity entity = new FileActionsApi(client) .copy(new CopyPathBody().destination(StringUtils.removeStart(target.getAbsolute(), String.valueOf(Path.DELIMITER))), StringUtils.removeStart(file.getAbsolute(), String.valueOf(Path.DELIMITER))); listener.sent(status.getLength()); if(entity.getFileMigrationId() != null) { this.poll(client, entity); } return target.withAttributes(file.attributes()); } catch(ApiException e) { throw new BrickExceptionMappingService().map("Cannot copy {0}", e, file); } }
@Test public void testCopyFile() throws Exception { final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final Local local = new Local(System.getProperty("java.io.tmpdir"), test.getName()); final byte[] random = RandomUtils.nextBytes(2547); IOUtils.write(random, local.getOutputStream(false)); final TransferStatus status = new TransferStatus().withLength(random.length); new BrickUploadFeature(session, new BrickWriteFeature(session)).upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), status, new DisabledLoginCallback()); local.delete(); assertTrue(new BrickFindFeature(session).find(test)); final Path copy = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new BrickCopyFeature(session).copy(test, copy, new TransferStatus(), new DisabledConnectionCallback(), new DisabledStreamListener()); assertTrue(new BrickFindFeature(session).find(test)); assertTrue(new BrickFindFeature(session).find(copy)); new BrickDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); new BrickDeleteFeature(session).delete(Collections.<Path>singletonList(copy), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public abstract Map<String, String> properties(final Map<String, String> defaultProperties, final long additionalRetentionMs);
@Test public void shouldSetCreateTimeByDefaultForUnwindowedUnversionedChangelog() { final UnwindowedUnversionedChangelogTopicConfig topicConfig = new UnwindowedUnversionedChangelogTopicConfig("name", Collections.emptyMap()); final Map<String, String> properties = topicConfig.properties(Collections.emptyMap(), 0); assertEquals("CreateTime", properties.get(TopicConfig.MESSAGE_TIMESTAMP_TYPE_CONFIG)); }
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final Map<Path, List<ObjectKeyAndVersion>> map = new HashMap<>(); final List<Path> containers = new ArrayList<>(); for(Path file : files.keySet()) { if(containerService.isContainer(file)) { containers.add(file); continue; } callback.delete(file); final Path bucket = containerService.getContainer(file); if(file.getType().contains(Path.Type.upload)) { // In-progress multipart upload try { multipartService.delete(new MultipartUpload(file.attributes().getVersionId(), bucket.isRoot() ? StringUtils.EMPTY : bucket.getName(), containerService.getKey(file))); } catch(NotfoundException ignored) { log.warn(String.format("Ignore failure deleting multipart upload %s", file)); } } else { final List<ObjectKeyAndVersion> keys = new ArrayList<>(); // Always returning 204 even if the key does not exist. Does not return 404 for non-existing keys keys.add(new ObjectKeyAndVersion(containerService.getKey(file), file.attributes().getVersionId())); if(map.containsKey(bucket)) { map.get(bucket).addAll(keys); } else { map.put(bucket, keys); } } } // Iterate over all containers and delete list of keys for(Map.Entry<Path, List<ObjectKeyAndVersion>> entry : map.entrySet()) { final Path container = entry.getKey(); final List<ObjectKeyAndVersion> keys = entry.getValue(); this.delete(container, keys, prompt); } for(Path file : containers) { callback.delete(file); // Finally delete bucket itself try { final String bucket = containerService.getContainer(file).getName(); session.getClient().deleteBucket(bucket); session.getClient().getRegionEndpointCache().removeRegionForBucketName(bucket); } catch(ServiceException e) { throw new S3ExceptionMappingService().map("Cannot delete {0}", e, file); } } }
@Test public void testDeleteFile() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new S3TouchFeature(session, new S3AccessControlListFeature(session)).touch(test, new TransferStatus()); assertTrue(new S3FindFeature(session, new S3AccessControlListFeature(session)).find(test)); new S3MultipleDeleteFeature(session, new S3AccessControlListFeature(session)).delete(Arrays.asList(test, test), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(new S3FindFeature(session, new S3AccessControlListFeature(session)).find(test)); }
public static BigInteger signedMessageToKey(byte[] message, SignatureData signatureData) throws SignatureException { return signedMessageHashToKey(Hash.sha3(message), signatureData); }
@Test public void testInvalidSignature() { assertThrows( RuntimeException.class, () -> Sign.signedMessageToKey( TEST_MESSAGE, new Sign.SignatureData((byte) 27, new byte[] {1}, new byte[] {0}))); }
@Override @Nullable public boolean[] readBooleanArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { boolean[] values = new boolean[len]; for (int i = 0; i < len; i++) { values[i] = readBoolean(); } return values; } return new boolean[0]; }
@Test public void testReadBooleanArray() throws Exception { byte[] bytesBE = {0, 0, 0, 0, 0, 0, 0, 1, 1, 9, -1, -1, -1, -1}; byte[] bytesLE = {0, 0, 0, 0, 1, 0, 0, 0, 1, 9, -1, -1, -1, -1}; in.init((byteOrder == BIG_ENDIAN ? bytesBE : bytesLE), 0); in.position(10); boolean[] theNullArray = in.readBooleanArray(); in.position(0); boolean[] theZeroLengthArray = in.readBooleanArray(); in.position(4); boolean[] booleanArray = in.readBooleanArray(); assertNull(theNullArray); assertArrayEquals(new boolean[0], theZeroLengthArray); assertArrayEquals(new boolean[]{true}, booleanArray); }
double getErrorRateToDegrade() { Map<ErrorType, Integer> errorTypeCounts = _callTrackerStats.getErrorTypeCounts(); Integer connectExceptionCount = errorTypeCounts.getOrDefault(ErrorType.CONNECT_EXCEPTION, 0); Integer closedChannelExceptionCount = errorTypeCounts.getOrDefault(ErrorType.CLOSED_CHANNEL_EXCEPTION, 0); Integer serverErrorCount = errorTypeCounts.getOrDefault(ErrorType.SERVER_ERROR, 0); Integer timeoutExceptionCount = errorTypeCounts.getOrDefault(ErrorType.TIMEOUT_EXCEPTION, 0); Integer streamErrorCount = errorTypeCounts.getOrDefault(ErrorType.STREAM_ERROR, 0); double validExceptionCount = connectExceptionCount + closedChannelExceptionCount + serverErrorCount + timeoutExceptionCount; if (_config.getLoadBalanceStreamException()) { validExceptionCount += streamErrorCount; } return safeDivide(validExceptionCount, _callTrackerStats.getCallCount()); }
@Test(dataProvider = "loadBalanceStreamExceptionDataProvider") public void testGetErrorRateToDegrade(Boolean loadBalancerStreamException) { Map<ErrorType, Integer> errorTypeCounts = ImmutableMap.of( ErrorType.CONNECT_EXCEPTION, 1, ErrorType.CLOSED_CHANNEL_EXCEPTION, 1, ErrorType.SERVER_ERROR, 1, ErrorType.TIMEOUT_EXCEPTION, 1, ErrorType.STREAM_ERROR, 1 ); DegraderImpl degrader = new DegraderImplTestFixture().getDegraderImpl(loadBalancerStreamException, errorTypeCounts, 10); assertEquals(degrader.getErrorRateToDegrade(), loadBalancerStreamException ? 0.5 : 0.4); }
@Override public void registerInstance(String serviceName, String ip, int port) throws NacosException { registerInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME); }
@Test void testRegisterInstance1() throws NacosException { //given String serviceName = "service1"; String ip = "1.1.1.1"; int port = 10000; //when client.registerInstance(serviceName, ip, port); //then verify(proxy, times(1)).registerService(eq(serviceName), eq(Constants.DEFAULT_GROUP), argThat(instance -> instance.getIp().equals(ip) && instance.getPort() == port && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(Constants.DEFAULT_CLUSTER_NAME))); }
public Path getTargetPath() { return targetPath; }
@Test public void testTargetPath() { final DistCpOptions options = new DistCpOptions.Builder( new Path("hdfs://localhost:8020/source/first"), new Path("hdfs://localhost:8020/target/")).build(); Assert.assertEquals(new Path("hdfs://localhost:8020/target/"), options.getTargetPath()); }
public int[] get(int intervalRef) { assert intervalRef < intervalsList.length; return intervalsList[intervalRef]; }
@Test void requireThatEqualIntervalListsReturnsSameReference() { PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder(); List<Integer> intervals1 = List.of(0x00010001, 0x00020002); List<Integer> intervals2 = List.of(0x00010001, 0x00020002); int ref1 = builder.insert(intervals1); int ref2 = builder.insert(intervals2); PredicateIntervalStore store = builder.build(); int[] a1 = store.get(ref1); int[] a2 = store.get(ref2); assertEquals(a1, a2); }
@Override @PublicAPI(usage = ACCESS) public String getDescription() { String description = origin.getDescription() + " " + descriptionVerb() + " " + getTarget().getDescription(); return description + " in " + getSourceCodeLocation(); }
@Test public void when_the_origin_is_an_inner_class_the_toplevel_class_is_displayed_as_location() { TestJavaAccess access = javaAccessFrom(importClassWithContext(SomeClass.Inner.class), "foo") .to(SomeEnum.class, "bar") .inLineNumber(7); assertThat(access.getDescription()).contains("(SomeClass.java:7)"); }
@Override protected void encodeInitialLine(ByteBuf buf, HttpRequest request) throws Exception { ByteBufUtil.copy(request.method().asciiName(), buf); String uri = request.uri(); if (uri.isEmpty()) { // Add " / " as absolute path if uri is not present. // See https://tools.ietf.org/html/rfc2616#section-5.1.2 ByteBufUtil.writeMediumBE(buf, SPACE_SLASH_AND_SPACE_MEDIUM); } else { CharSequence uriCharSequence = uri; boolean needSlash = false; int start = uri.indexOf("://"); if (start != -1 && uri.charAt(0) != SLASH) { start += 3; // Correctly handle query params. // See https://github.com/netty/netty/issues/2732 int index = uri.indexOf(QUESTION_MARK, start); if (index == -1) { if (uri.lastIndexOf(SLASH) < start) { needSlash = true; } } else { if (uri.lastIndexOf(SLASH, index) < start) { uriCharSequence = new StringBuilder(uri).insert(index, SLASH); } } } buf.writeByte(SP).writeCharSequence(uriCharSequence, CharsetUtil.UTF_8); if (needSlash) { // write "/ " after uri ByteBufUtil.writeShortBE(buf, SLASH_AND_SPACE_SHORT); } else { buf.writeByte(SP); } } request.protocolVersion().encode(buf); ByteBufUtil.writeShortBE(buf, CRLF_SHORT); }
@Test public void testUriWithPath() throws Exception { for (ByteBuf buffer : getBuffers()) { HttpRequestEncoder encoder = new HttpRequestEncoder(); encoder.encodeInitialLine(buffer, new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/")); String req = buffer.toString(Charset.forName("US-ASCII")); assertEquals("GET http://localhost/ HTTP/1.1\r\n", req); buffer.release(); } }
@Udf(description = "Returns the inverse (arc) tangent of y / x") public Double atan2( @UdfParameter( value = "y", description = "The ordinate (y) coordinate." ) final Integer y, @UdfParameter( value = "x", description = "The abscissa (x) coordinate." ) final Integer x ) { return atan2(y == null ? null : y.doubleValue(), x == null ? null : x.doubleValue()); }
@Test public void shouldHandleZeroYNegativeX() { assertThat(udf.atan2(0.0, -0.24), closeTo(3.141592653589793, 0.000000000000001)); assertThat(udf.atan2(0.0, -7.1), closeTo(3.141592653589793, 0.000000000000001)); assertThat(udf.atan2(0, -3), closeTo(3.141592653589793, 0.000000000000001)); assertThat(udf.atan2(0L, -2L), closeTo(3.141592653589793, 0.000000000000001)); }
@Override public boolean isExisted(final String originalName) { return encryptTable.isCipherColumn(originalName) || !encryptTable.isAssistedQueryColumn(originalName) && !encryptTable.isLikeQueryColumn(originalName); }
@Test void assertIsExistedWithNormalColumn() { EncryptTable encryptTable = mock(EncryptTable.class); EncryptColumnExistedReviser reviser = new EncryptColumnExistedReviser(encryptTable); assertTrue(reviser.isExisted("normal_column")); }
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchSctpSrcMaskedTest() { Criterion criterion = Criteria.matchSctpSrcMasked(tpPort, tpPortMask); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
public static Result find(List<Path> files, Consumer<LogEvent> logger) { List<String> mainClasses = new ArrayList<>(); for (Path file : files) { // Makes sure classFile is valid. if (!Files.exists(file)) { logger.accept(LogEvent.debug("MainClassFinder: " + file + " does not exist; ignoring")); continue; } if (!Files.isRegularFile(file)) { logger.accept( LogEvent.debug("MainClassFinder: " + file + " is not a regular file; skipping")); continue; } if (!file.toString().endsWith(".class")) { logger.accept( LogEvent.debug("MainClassFinder: " + file + " is not a class file; skipping")); continue; } MainClassVisitor mainClassVisitor = new MainClassVisitor(); try (InputStream classFileInputStream = Files.newInputStream(file)) { ClassReader reader = new ClassReader(classFileInputStream); reader.accept(mainClassVisitor, 0); if (mainClassVisitor.visitedMainClass) { mainClasses.add(reader.getClassName().replace('/', '.')); } } catch (IllegalArgumentException ex) { throw new UnsupportedOperationException( "Check the full stace trace, and if the root cause is from ASM ClassReader about " + "unsupported class file version, see " + "https://github.com/GoogleContainerTools/jib/blob/master/docs/faq.md" + "#i-am-seeing-unsupported-class-file-major-version-when-building", ex); } catch (ArrayIndexOutOfBoundsException ignored) { // Not a valid class file (thrown by ClassReader if it reads an invalid format) logger.accept(LogEvent.warn("Invalid class file found: " + file)); } catch (IOException ignored) { // Could not read class file. logger.accept(LogEvent.warn("Could not read file: " + file)); } } if (mainClasses.size() == 1) { // Valid class found. return Result.success(mainClasses.get(0)); } if (mainClasses.isEmpty()) { // No main class found anywhere. return Result.mainClassNotFound(); } // More than one main class found. return Result.multipleMainClasses(mainClasses); }
@Test public void testFindMainClass_extension() throws URISyntaxException, IOException { Path rootDirectory = Paths.get(Resources.getResource("core/class-finder-tests/extension").toURI()); MainClassFinder.Result mainClassFinderResult = MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEventConsumer); Assert.assertSame(Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType()); MatcherAssert.assertThat( mainClassFinderResult.getFoundMainClass(), CoreMatchers.containsString("main.MainClass")); }
@Override public DeleteConsumerGroupsResult deleteConsumerGroups(Collection<String> groupIds, DeleteConsumerGroupsOptions options) { SimpleAdminApiFuture<CoordinatorKey, Void> future = DeleteConsumerGroupsHandler.newFuture(groupIds); DeleteConsumerGroupsHandler handler = new DeleteConsumerGroupsHandler(logContext); invokeDriver(handler, future, options.timeoutMs); return new DeleteConsumerGroupsResult(future.all().entrySet().stream() .collect(Collectors.toMap(entry -> entry.getKey().idValue, Map.Entry::getValue))); }
@Test public void testDeleteMultipleConsumerGroupsWithOlderBroker() throws Exception { final List<String> groupIds = asList("group1", "group2"); ApiVersion findCoordinatorV3 = new ApiVersion() .setApiKey(ApiKeys.FIND_COORDINATOR.id) .setMinVersion((short) 0) .setMaxVersion((short) 3); ApiVersion describeGroups = new ApiVersion() .setApiKey(ApiKeys.DESCRIBE_GROUPS.id) .setMinVersion((short) 0) .setMaxVersion(ApiKeys.DELETE_GROUPS.latestVersion()); try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) { env.kafkaClient().setNodeApiVersions( NodeApiVersions.create(asList(findCoordinatorV3, describeGroups))); // Dummy response for MockClient to handle the UnsupportedVersionException correctly to switch from batched to un-batched env.kafkaClient().prepareResponse(null); // Retriable FindCoordinatorResponse errors should be retried for (int i = 0; i < groupIds.size(); i++) { env.kafkaClient().prepareResponse( prepareOldFindCoordinatorResponse(Errors.COORDINATOR_NOT_AVAILABLE, Node.noNode())); } for (int i = 0; i < groupIds.size(); i++) { env.kafkaClient().prepareResponse( prepareOldFindCoordinatorResponse(Errors.NONE, env.cluster().controller())); } final DeletableGroupResultCollection validResponse = new DeletableGroupResultCollection(); validResponse.add(new DeletableGroupResult() .setGroupId("group1") .setErrorCode(Errors.NONE.code())); validResponse.add(new DeletableGroupResult() .setGroupId("group2") .setErrorCode(Errors.NONE.code())); env.kafkaClient().prepareResponse(new DeleteGroupsResponse( new DeleteGroupsResponseData() .setResults(validResponse) )); final DeleteConsumerGroupsResult result = env.adminClient() .deleteConsumerGroups(groupIds); final KafkaFuture<Void> results = result.deletedGroups().get("group1"); assertNull(results.get(5, TimeUnit.SECONDS)); } }
synchronized void add(int splitCount) { int pos = count % history.length; history[pos] = splitCount; count += 1; }
@Test public void testOneMoreThanFullHistory() { EnumerationHistory history = new EnumerationHistory(3); history.add(1); history.add(2); history.add(3); history.add(4); int[] expectedHistorySnapshot = {2, 3, 4}; testHistory(history, expectedHistorySnapshot); }
public static Area getArea(String ip) { return AreaUtils.getArea(getAreaId(ip)); }
@Test public void testGetArea_long() throws Exception { // 120.203.123.0|120.203.133.255|360900 long ip = Searcher.checkIP("120.203.123.252"); Area area = IPUtils.getArea(ip); assertEquals("宜春市", area.getName()); }
@Override public boolean equals(Object o) { if (o == this) { return true; } else if (!(o instanceof ExpiryPolicy)) { return false; } var policy = (ExpiryPolicy) o; return Objects.equals(creation, policy.getExpiryForCreation()) && Objects.equals(update, policy.getExpiryForUpdate()) && Objects.equals(access, policy.getExpiryForAccess()); }
@Test public void equals_wrongType() { assertThat(eternal.equals(new Object())).isFalse(); }
@Override public void failover(NamedNode master) { connection.sync(RedisCommands.SENTINEL_FAILOVER, master.getName()); }
@Test public void testFailover() throws InterruptedException { Collection<RedisServer> masters = connection.masters(); connection.failover(masters.iterator().next()); Thread.sleep(10000); RedisServer newMaster = connection.masters().iterator().next(); assertThat(masters.iterator().next().getPort()).isNotEqualTo(newMaster.getPort()); }
@Override public JWKSet getJWKSet(JWKSetCacheRefreshEvaluator refreshEvaluator, long currentTime, T context) throws KeySourceException { var jwksUrl = discoverJwksUrl(); try (var jwkSetSource = new URLBasedJWKSetSource<>(jwksUrl, new HttpRetriever(httpClient))) { return jwkSetSource.getJWKSet(null, 0, context); } catch (IOException e) { throw new RemoteKeySourceException( "failed to fetch jwks from discovery document '%s'".formatted(discoveryUrl), e); } }
@Test void getJWKSet_noKeys(WireMockRuntimeInfo wm) throws KeySourceException { var jwks = "{\"keys\": []}"; var discoveryUrl = URI.create(wm.getHttpBaseUrl()).resolve(DISCOVERY_PATH); var jwksUrl = URI.create(wm.getHttpBaseUrl()).resolve(JWKS_PATH); stubFor(get(DISCOVERY_PATH).willReturn(okJson("{\"jwks_uri\": \"%s\"}".formatted(jwksUrl)))); stubFor(get(JWKS_PATH).willReturn(okJson(jwks))); var sut = new DiscoveryJwkSetSource<>(HttpClient.newHttpClient(), discoveryUrl); var gotJwks = sut.getJWKSet(null, 0, null); assertTrue(gotJwks.getKeys().isEmpty()); }
@Override public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter) throws IOException { EthCall ethCall = web3j.ethCall( Transaction.createEthCallTransaction(getFromAddress(), to, data), defaultBlockParameter) .send(); assertCallNotReverted(ethCall); return ethCall.getValue() != null ? ethCall.getValue() : ethCall.getError() != null ? ethCall.getError().getData() : null; }
@Test void sendCallErrorSuccess() throws IOException { EthCall lookupDataHex = new EthCall(); lookupDataHex.setResult(responseData); Request request = mock(Request.class); when(request.send()).thenReturn(lookupDataHex); when(web3j.ethCall(any(Transaction.class), any(DefaultBlockParameter.class))) .thenReturn(request); String result = clientTransactionManager.sendCall( "0xAdress", "data", DefaultBlockParameter.valueOf("latest")); assertEquals(responseData, result); }
@Override public ConfigInfo findConfigInfo(long id) { try { ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); return this.jt.queryForObject(configInfoMapper.select( Arrays.asList("id", "data_id", "group_id", "tenant_id", "app_name", "content"), Collections.singletonList("id")), new Object[] {id}, CONFIG_INFO_ROW_MAPPER); } catch (EmptyResultDataAccessException e) { // Indicates that the data does not exist, returns null. return null; } catch (CannotGetJdbcConnectionException e) { LogUtil.FATAL_LOG.error("[db-error] " + e, e); throw e; } }
@Test void testFindConfigInfoByIdNull() { long id = 1234567890876L; ConfigInfo configInfo = new ConfigInfo(); configInfo.setId(id); Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {id}), eq(CONFIG_INFO_ROW_MAPPER))) .thenThrow(new EmptyResultDataAccessException(1)); ConfigInfo configReturn = externalConfigInfoPersistService.findConfigInfo(id); assertNull(configReturn); }
public void setIncludeCallerData(boolean includeCallerData) { this.includeCallerData = includeCallerData; }
@Test public void settingIncludeCallerDataPropertyCausedCallerDataToBeIncluded() { asyncAppender.addAppender(listAppender); asyncAppender.setIncludeCallerData(true); asyncAppender.start(); asyncAppender.doAppend(builder.build(diff)); asyncAppender.stop(); // check the event assertEquals(1, listAppender.list.size()); ILoggingEvent e = listAppender.list.get(0); assertTrue(e.hasCallerData()); StackTraceElement ste = e.getCallerData()[0]; assertEquals(thisClassName, ste.getClassName()); }
@Override public <E extends Extension> E convertFrom(Class<E> type, ExtensionStore extensionStore) { try { var extension = objectMapper.readValue(extensionStore.getData(), type); extension.getMetadata().setVersion(extensionStore.getVersion()); return extension; } catch (IOException e) { throw new ExtensionConvertException("Failed to read Extension " + type + " from bytes", e); } }
@Test void shouldThrowConvertExceptionWhenDataIsInvalid() { var store = new ExtensionStore(); store.setName("/registry/fake.halo.run/fakes/fake"); store.setVersion(20L); store.setData("{".getBytes()); assertThrows(ExtensionConvertException.class, () -> converter.convertFrom(FakeExtension.class, store)); }
@Restricted(NoExternalUse.class) public static void skip(@NonNull Iterator<?> iterator, int count) { if (count < 0) { throw new IllegalArgumentException(); } while (iterator.hasNext() && count-- > 0) { iterator.next(); } }
@Issue("JENKINS-51779") @Test public void skip() { List<Integer> lst = Iterators.sequence(1, 4); Iterator<Integer> it = lst.iterator(); Iterators.skip(it, 0); assertEquals("[1, 2, 3]", com.google.common.collect.Iterators.toString(it)); it = lst.iterator(); Iterators.skip(it, 1); assertEquals("[2, 3]", com.google.common.collect.Iterators.toString(it)); it = lst.iterator(); Iterators.skip(it, 2); assertEquals("[3]", com.google.common.collect.Iterators.toString(it)); it = lst.iterator(); Iterators.skip(it, 3); assertEquals("[]", com.google.common.collect.Iterators.toString(it)); it = lst.iterator(); Iterators.skip(it, 4); assertEquals("[]", com.google.common.collect.Iterators.toString(it)); }
@Override public void afterPropertiesSet() throws Exception { if (dataSource == null) { throw new IllegalArgumentException("datasource required not null!"); } dbType = getDbTypeFromDataSource(dataSource); if (getStateLogStore() == null) { DbAndReportTcStateLogStore dbStateLogStore = new DbAndReportTcStateLogStore(); dbStateLogStore.setDataSource(dataSource); dbStateLogStore.setTablePrefix(tablePrefix); dbStateLogStore.setDbType(dbType); dbStateLogStore.setDefaultTenantId(getDefaultTenantId()); dbStateLogStore.setSeqGenerator(getSeqGenerator()); if (StringUtils.hasLength(getSagaJsonParser())) { ParamsSerializer paramsSerializer = new ParamsSerializer(); paramsSerializer.setJsonParserName(getSagaJsonParser()); dbStateLogStore.setParamsSerializer(paramsSerializer); } if (sagaTransactionalTemplate == null) { DefaultSagaTransactionalTemplate defaultSagaTransactionalTemplate = new DefaultSagaTransactionalTemplate(); defaultSagaTransactionalTemplate.setApplicationContext(getApplicationContext()); defaultSagaTransactionalTemplate.setApplicationId(applicationId); defaultSagaTransactionalTemplate.setTxServiceGroup(txServiceGroup); defaultSagaTransactionalTemplate.setAccessKey(accessKey); defaultSagaTransactionalTemplate.setSecretKey(secretKey); defaultSagaTransactionalTemplate.afterPropertiesSet(); sagaTransactionalTemplate = defaultSagaTransactionalTemplate; } dbStateLogStore.setSagaTransactionalTemplate(sagaTransactionalTemplate); setStateLogStore(dbStateLogStore); } if (getStateLangStore() == null) { DbStateLangStore dbStateLangStore = new DbStateLangStore(); dbStateLangStore.setDataSource(dataSource); dbStateLangStore.setTablePrefix(tablePrefix); dbStateLangStore.setDbType(dbType); setStateLangStore(dbStateLangStore); } //must execute after StateLangStore initialized super.afterPropertiesSet(); }
@Test public void testAfterPropertiesSet() throws Exception { DbStateMachineConfig dbStateMachineConfig = new DbStateMachineConfig(); Connection connection = Mockito.mock(Connection.class); DatabaseMetaData databaseMetaData = Mockito.mock(DatabaseMetaData.class); when(connection.getMetaData()).thenReturn(databaseMetaData); when(databaseMetaData.getDatabaseProductName()).thenReturn("test"); MockDataSource mockDataSource = new MockDataSource(); mockDataSource.setConnection(connection); dbStateMachineConfig.setDataSource(mockDataSource); dbStateMachineConfig.setApplicationId("test"); dbStateMachineConfig.setTxServiceGroup("test"); Assertions.assertDoesNotThrow(dbStateMachineConfig::afterPropertiesSet); }
@Override public TableEntryByTypeTransformer tableEntryByTypeTransformer() { return transformer; }
@Test void transforms_nulls_with_correct_method() throws Throwable { Map<String, String> fromValue = singletonMap("key", null); Method method = JavaDefaultDataTableEntryTransformerDefinitionTest.class.getMethod("correct_method", Map.class, Type.class); JavaDefaultDataTableEntryTransformerDefinition definition = new JavaDefaultDataTableEntryTransformerDefinition( method, lookup, false, new String[] { "[empty]" }); assertThat(definition.tableEntryByTypeTransformer() .transform(fromValue, String.class, cellTransformer), is("key=null")); }
public ProcessingNodesState calculateProcessingState(TimeRange timeRange) { final DateTime updateThresholdTimestamp = clock.nowUTC().minus(updateThreshold.toMilliseconds()); try (DBCursor<ProcessingStatusDto> statusCursor = db.find(activeNodes(updateThresholdTimestamp))) { if (!statusCursor.hasNext()) { return ProcessingNodesState.NONE_ACTIVE; } int activeNodes = 0; int idleNodes = 0; while (statusCursor.hasNext()) { activeNodes++; ProcessingStatusDto nodeProcessingStatus = statusCursor.next(); DateTime lastIndexedMessage = nodeProcessingStatus.receiveTimes().postIndexing(); // If node is behind and is busy, it is overloaded. if (lastIndexedMessage.isBefore(timeRange.getTo()) && isBusy(nodeProcessingStatus)) { return ProcessingNodesState.SOME_OVERLOADED; } // If a node did not index a message that is at least at the start of the time range, // we consider it idle. if (lastIndexedMessage.isBefore(timeRange.getFrom())) { idleNodes++; } } // Only if all nodes are idle, we stop the processing. if (activeNodes == idleNodes) { return ProcessingNodesState.ALL_IDLE; } } // If none of the above checks return, we can assume that some nodes have already indexed the given timerange. return ProcessingNodesState.SOME_UP_TO_DATE; }
@Test @MongoDBFixtures("processing-status-no-nodes.json") public void processingStateNoActiveNodesBecauseNoNodesExists() { TimeRange timeRange = AbsoluteRange.create("2019-01-01T00:00:00.000Z", "2019-01-01T00:00:30.000Z"); assertThat(dbService.calculateProcessingState(timeRange)).isEqualTo(ProcessingNodesState.NONE_ACTIVE); }
public String getFileContentInsideZip(ZipInputStream zipInputStream, String file) throws IOException { ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { if (new File(zipEntry.getName()).getName().equals(file)) { return IOUtils.toString(zipInputStream, UTF_8); } zipEntry = zipInputStream.getNextEntry(); } return null; }
@Test void shouldReturnNullIfTheFileByTheNameDoesNotExistInsideZip() throws IOException, URISyntaxException { try (ZipInputStream zip = new ZipInputStream(new FileInputStream(new File(getClass().getResource("/dummy-plugins.zip").toURI())))) { String contents = zipUtil.getFileContentInsideZip(zip, "does_not_exist.txt"); assertThat(contents).isNull(); } }
@Transactional public ConsumerToken createConsumerToken(ConsumerToken entity) { entity.setId(0); //for protection return consumerTokenRepository.save(entity); }
@Test public void testCreateConsumerToken() throws Exception { ConsumerToken someConsumerToken = mock(ConsumerToken.class); ConsumerToken savedConsumerToken = mock(ConsumerToken.class); when(consumerTokenRepository.save(someConsumerToken)).thenReturn(savedConsumerToken); assertEquals(savedConsumerToken, consumerService.createConsumerToken(someConsumerToken)); }
@Bean("CiConfiguration") public CiConfiguration provide(Configuration configuration, CiVendor[] ciVendors) { boolean disabled = configuration.getBoolean(PROP_DISABLED).orElse(false); if (disabled) { return new EmptyCiConfiguration(); } List<CiVendor> detectedVendors = Arrays.stream(ciVendors) .filter(CiVendor::isDetected) .toList(); if (detectedVendors.size() > 1) { List<String> names = detectedVendors.stream().map(CiVendor::getName).toList(); throw MessageException.of("Multiple CI environments are detected: " + names + ". Please check environment variables or set property " + PROP_DISABLED + " to true."); } if (detectedVendors.size() == 1) { CiVendor vendor = detectedVendors.get(0); LOG.info("Auto-configuring with CI '{}'", vendor.getName()); return vendor.loadConfiguration(); } return new EmptyCiConfiguration(); }
@Test public void fail_if_multiple_ci_vendor_are_detected() { Throwable thrown = catchThrowable(() -> underTest.provide(cli.asConfig(), new CiVendor[]{new EnabledCiVendor("vendor1"), new EnabledCiVendor("vendor2")})); assertThat(thrown) .isInstanceOf(MessageException.class) .hasMessage("Multiple CI environments are detected: [vendor1, vendor2]. Please check environment variables or set property sonar.ci.autoconfig.disabled to true."); }
public MethodBuilder deprecated(Boolean deprecated) { this.deprecated = deprecated; return getThis(); }
@Test void deprecated() { MethodBuilder builder = MethodBuilder.newBuilder(); builder.deprecated(true); Assertions.assertTrue(builder.build().getDeprecated()); }
@Override public long read() { return gaugeSource.read(); }
@Test public void whenCacheDynamicMetricSourceGcdReadsDefault() { NullableDynamicMetricsProvider metricsProvider = new NullableDynamicMetricsProvider(); WeakReference<SomeObject> someObjectWeakRef = new WeakReference<>(metricsProvider.someObject); metricsProvider.someObject.longField = 42; metricsRegistry.registerDynamicMetricsProvider(metricsProvider); LongGaugeImpl longGauge = metricsRegistry.newLongGauge("foo.longField"); // needed to collect dynamic metrics and update the gauge created from them metricsRegistry.collect(mock(MetricsCollector.class)); assertEquals(42, longGauge.read()); metricsProvider.someObject = null; System.gc(); // wait for someObject to get GCd - should have already happened assertTrueEventually(() -> assertNull(someObjectWeakRef.get())); assertEquals(LongGaugeImpl.DEFAULT_VALUE, longGauge.read()); }
public static boolean isPrimitiveTypeName(final String name) { return PRIMITIVE_TYPE_NAMES.contains(name.toUpperCase()); }
@Test public void shouldNotSupportRandomTypeName() { // When: final boolean isPrimitive = SqlPrimitiveType.isPrimitiveTypeName("WILL ROBINSON"); // Then: assertThat("expected not primitive!", !isPrimitive); }
public void applyConfig(ClientBwListDTO configDTO) { requireNonNull(configDTO, "Client filtering config must not be null"); requireNonNull(configDTO.mode, "Config mode must not be null"); requireNonNull(configDTO.entries, "Config entries must not be null"); ClientSelector selector; switch (configDTO.mode) { case DISABLED: selector = ClientSelectors.any(); break; case WHITELIST: selector = createSelector(configDTO.entries); break; case BLACKLIST: selector = ClientSelectors.inverse(createSelector(configDTO.entries)); break; default: throw new IllegalArgumentException("Unknown client B/W list mode: " + configDTO.mode); } clientEngine.applySelector(selector); }
@Test public void testApplyConfig_whitelist() { ClientBwListDTO config = createConfig(Mode.WHITELIST, new ClientBwListEntryDTO(Type.IP_ADDRESS, "127.0.0.*"), new ClientBwListEntryDTO(Type.IP_ADDRESS, "192.168.0.1"), new ClientBwListEntryDTO(Type.IP_ADDRESS, "192.168.0.42-43"), new ClientBwListEntryDTO(Type.IP_ADDRESS, "fe80:0:0:0:45c5:47ee:fe15:493a"), new ClientBwListEntryDTO(Type.INSTANCE_NAME, "client*"), new ClientBwListEntryDTO(Type.LABEL, "label*")); handler.applyConfig(config); Client[] allowed = { createClient("127.0.0.3", "a_name"), createClient("192.168.0.1", "a_name"), createClient("192.168.0.42", "a_name"), createClient("fe80:0:0:0:45c5:47ee:fe15:493a", "a_name"), createClient("192.168.0.101", "client4"), createClient("192.168.0.101", "a_name", "label") }; for (Client client : allowed) { assertTrue(clientEngine.isClientAllowed(client)); } Client[] denied = { createClient("192.168.0.101", "a_name", "random"), createClient("fe70:0:0:0:35c5:16ee:fe15:491a", "a_name", "random") }; for (Client client : denied) { assertFalse(clientEngine.isClientAllowed(client)); } }
@Override public void clear() { if (!isEmpty()) { notifyRemoval(0, size()); super.clear(); } }
@Test public void testClearWhenAlreadyEmpty() { modelList.clear(); modelList.clear(); verify(observer).onItemRangeRemoved(0, 3); verifyNoMoreInteractions(observer); }
@Override protected Object createBody() { if (command instanceof MessageRequest) { MessageRequest msgRequest = (MessageRequest) command; byte[] shortMessage = msgRequest.getShortMessage(); if (shortMessage == null || shortMessage.length == 0) { return null; } Alphabet alphabet = Alphabet.parseDataCoding(msgRequest.getDataCoding()); if (SmppUtils.is8Bit(alphabet)) { return shortMessage; } String encoding = ExchangeHelper.getCharsetName(getExchange(), false); if (ObjectHelper.isEmpty(encoding) || !Charset.isSupported(encoding)) { encoding = configuration.getEncoding(); } try { return new String(shortMessage, encoding); } catch (UnsupportedEncodingException e) { LOG.info("Unsupported encoding \"{}\". Using system default encoding.", encoding); } return new String(shortMessage); } return null; }
@Test public void createBodyShouldNotMangle8bitDataCodingShortMessage() { final Set<String> encodings = Charset.availableCharsets().keySet(); final byte[] dataCodings = { (byte) 0x02, (byte) 0x04, (byte) 0xF6, (byte) 0xF4 }; byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; DeliverSm command = new DeliverSm(); SmppConfiguration config = new SmppConfiguration(); for (byte dataCoding : dataCodings) { command.setDataCoding(dataCoding); command.setShortMessage(body); for (String encoding : encodings) { config.setEncoding(encoding); message = new SmppMessage(camelContext, command, config); assertArrayEquals( body, (byte[]) message.createBody(), String.format("data coding=0x%02X; encoding=%s", dataCoding, encoding)); } } }
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return true; } try { final SMBSession.DiskShareWrapper share = session.openShare(file); try { if(new SMBPathContainerService(session).isContainer(file)) { return true; } if(file.isDirectory()) { return share.get().folderExists(new SMBPathContainerService(session).getKey(file)); } return share.get().fileExists(new SMBPathContainerService(session).getKey(file)); } catch(SMBRuntimeException e) { throw new SMBExceptionMappingService().map("Failure to read attributes of {0}", e, file); } finally { session.releaseShare(share); } } catch(NotfoundException e) { return false; } }
@Test public void testFindDirectory() throws Exception { assertTrue(new SMBFindFeature(session).find(new DefaultHomeFinderService(session).find())); }
public static TimestampRange of(Timestamp from, Timestamp to) { return new TimestampRange(from, to); }
@Test public void testTimestampRangeWhenFromIsEqualToTo() { assertEquals( new TimestampRange(Timestamp.ofTimeMicroseconds(10L), Timestamp.ofTimeMicroseconds(10L)), TimestampRange.of(Timestamp.ofTimeMicroseconds(10L), Timestamp.ofTimeMicroseconds(10L))); }
@Override public void updateLevel(int level) { Preconditions.checkArgument( level >= 0 && level <= MAX_LEVEL, "level(" + level + ") must be non-negative and no more than " + MAX_LEVEL); Preconditions.checkArgument( level <= this.topLevel + 1, "top level " + topLevel + " must be updated level by level, but new level is " + level); if (levelIndex.length < level) { long[] newLevelIndex = new long[this.levelIndex.length * 2]; initLevelIndex(newLevelIndex); System.arraycopy(this.levelIndex, 0, newLevelIndex, 0, this.levelIndex.length); this.levelIndex = newLevelIndex; } if (topLevel < level) { topLevel = level; } }
@Test void testUpdateToMoreThanMaximumAllowed() { assertThatThrownBy(() -> heapHeadIndex.updateLevel(MAX_LEVEL + 1)) .isInstanceOf(IllegalArgumentException.class); }
@Override public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (TokenReloadAction.tokenReloadEnabled()) { String pathInfo = request.getPathInfo(); if (pathInfo != null && pathInfo.equals("/" + TokenReloadAction.URL_NAME + "/")) { chain.doFilter(request, response); return true; } } return false; }
@Test public void crumbExclustionAllowsReloadIfEnabledAndRequestPathMatch() throws Exception { System.setProperty("casc.reload.token", "someSecretValue"); TokenReloadCrumbExclusion crumbExclusion = new TokenReloadCrumbExclusion(); AtomicBoolean callProcessed = new AtomicBoolean(false); assertTrue(crumbExclusion.process( new MockHttpServletRequest("/reload-configuration-as-code/"), null, (request, response) -> callProcessed.set(true))); assertTrue(callProcessed.get()); }
public static <T> T execute(Single<T> apiCall) { try { return apiCall.blockingGet(); } catch (HttpException e) { try { if (e.response() == null || e.response().errorBody() == null) { throw e; } String errorBody = e.response().errorBody().string(); OpenAiError error = mapper.readValue(errorBody, OpenAiError.class); throw new OpenAiHttpException(error, e, e.code()); } catch (IOException ex) { // couldn't parse OpenAI error throw e; } } }
@Test void executeParseUnknownProperties() { // error body contains one unknown property and no message String errorBody = "{\"error\":{\"unknown\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}"; HttpException httpException = createException(errorBody, 401); Single<CompletionResult> single = Single.error(httpException); OpenAiHttpException exception = assertThrows(OpenAiHttpException.class, () -> OpenAiService.execute(single)); assertNull(exception.getMessage()); assertEquals("type", exception.type); assertEquals("param", exception.param); assertEquals("code", exception.code); assertEquals(401, exception.statusCode); }
@POST @Path("{networkId}/hosts") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createVirtualHost(@PathParam("networkId") long networkId, InputStream stream) { try { ObjectNode jsonTree = readTreeFromStream(mapper(), stream); JsonNode specifiedNetworkId = jsonTree.get("networkId"); if (specifiedNetworkId == null || specifiedNetworkId.asLong() != (networkId)) { throw new IllegalArgumentException(INVALID_FIELD + "networkId"); } final VirtualHost vhostReq = codec(VirtualHost.class).decode(jsonTree, this); vnetAdminService.createVirtualHost(vhostReq.networkId(), vhostReq.id(), vhostReq.mac(), vhostReq.vlan(), vhostReq.location(), vhostReq.ipAddresses()); UriBuilder locationBuilder = uriInfo.getBaseUriBuilder() .path("vnets").path(specifiedNetworkId.asText()) .path("hosts"); return Response .created(locationBuilder.build()) .build(); } catch (IOException e) { throw new IllegalArgumentException(e); } }
@Test public void testPostVirtualHost() { NetworkId networkId = networkId3; expect(mockVnetAdminService.createVirtualHost(networkId, hId1, mac1, vlan1, loc1, ipSet1)) .andReturn(vhost1); replay(mockVnetAdminService); WebTarget wt = target(); InputStream jsonStream = VirtualNetworkWebResourceTest.class .getResourceAsStream("post-virtual-host.json"); String reqLocation = "vnets/" + networkId.toString() + "/hosts"; Response response = wt.path(reqLocation).request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(jsonStream)); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED)); String location = response.getLocation().getPath(); assertThat(location, Matchers.startsWith("/" + reqLocation)); verify(mockVnetAdminService); }
@Override public Optional<Asset> findAssetsByTenantIdAndName(UUID tenantId, String name) { Asset asset = DaoUtil.getData(assetRepository.findByTenantIdAndName(tenantId, name)); return Optional.ofNullable(asset); }
@Test public void testFindAssetsByTenantIdAndName() { UUID assetId = Uuids.timeBased(); String name = "TEST_ASSET"; assets.add(saveAsset(assetId, tenantId2, customerId2, name)); Optional<Asset> assetOpt1 = assetDao.findAssetsByTenantIdAndName(tenantId2, name); assertTrue("Optional expected to be non-empty", assetOpt1.isPresent()); assertEquals(assetId, assetOpt1.get().getId().getId()); Optional<Asset> assetOpt2 = assetDao.findAssetsByTenantIdAndName(tenantId2, "NON_EXISTENT_NAME"); assertFalse("Optional expected to be empty", assetOpt2.isPresent()); }
@NonNull @Override public Object configure(CNode config, ConfigurationContext context) throws ConfiguratorException { return Stapler.lookupConverter(target) .convert( target, context.getSecretSourceResolver() .resolve(config.asScalar().toString())); }
@Test public void _Integer_env() throws Exception { environment.set("ENV_FOR_TEST", "123"); Configurator c = registry.lookupOrFail(Integer.class); final Object value = c.configure(new Scalar("${ENV_FOR_TEST}"), context); assertEquals(123, (int) value); }
@Override @Nullable public byte[] readByteArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, BYTE_ARRAY, super::readByteArray); }
@Test(expected = IncompatibleClassChangeError.class) public void testReadShortArray_IncompatibleClass() throws Exception { reader.readByteArray("byte"); }
@Override public Object convert(String value) { if (value == null || value.isEmpty()) { return 0; } return value.split(splitByEscaped).length; }
@Test public void testConvert() throws Exception { assertEquals(0, new SplitAndCountConverter(config("x")).convert("")); assertEquals(1, new SplitAndCountConverter(config("_")).convert("foo-bar-baz")); assertEquals(1, new SplitAndCountConverter(config("-")).convert("foo")); assertEquals(2, new SplitAndCountConverter(config("-")).convert("foo-bar")); assertEquals(3, new SplitAndCountConverter(config("-")).convert("foo-bar-baz")); assertEquals(3, new SplitAndCountConverter(config(".")).convert("foo.bar.baz")); // Regex. Must be escaped. }
public void processOnce() throws IOException { // set status of query to OK. ctx.getState().reset(); executor = null; // reset sequence id of MySQL protocol final MysqlChannel channel = ctx.getMysqlChannel(); channel.setSequenceId(0); // read packet from channel try { packetBuf = channel.fetchOnePacket(); if (packetBuf == null) { throw new RpcException(ctx.getRemoteIP(), "Error happened when receiving packet."); } } catch (AsynchronousCloseException e) { // when this happened, timeout checker close this channel // killed flag in ctx has been already set, just return return; } // dispatch dispatch(); // finalize finalizeCommand(); ctx.setCommand(MysqlCommand.COM_SLEEP); }
@Test public void testFieldListFailNoTable() throws Exception { MysqlSerializer serializer = MysqlSerializer.newInstance(); serializer.writeInt1(4); serializer.writeNulTerminateString("emptyTable"); serializer.writeEofString(""); myContext.setDatabase("testDb1"); ConnectContext ctx = initMockContext(mockChannel(serializer.toByteBuffer()), GlobalStateMgr.getCurrentState()); ConnectProcessor processor = new ConnectProcessor(ctx); processor.processOnce(); Assert.assertEquals(MysqlCommand.COM_FIELD_LIST, myContext.getCommand()); Assert.assertTrue(myContext.getState().toResponsePacket() instanceof MysqlErrPacket); Assert.assertEquals("Unknown table(emptyTable)", myContext.getState().getErrorMessage()); }
public abstract byte[] encode(MutableSpan input);
@Test void span_noLocalServiceName_JSON_V2() { clientSpan.localServiceName(null); assertThat(new String(encoder.encode(clientSpan), UTF_8)) .isEqualTo( "{\"traceId\":\"7180c278b62e8f6a216a2aea45d08fc9\",\"parentId\":\"6b221d5bc9e6496c\",\"id\":\"5b4185666d50f68b\",\"kind\":\"CLIENT\",\"name\":\"get\",\"timestamp\":1472470996199000,\"duration\":207000,\"localEndpoint\":{\"ipv4\":\"127.0.0.1\"},\"remoteEndpoint\":{\"serviceName\":\"backend\",\"ipv4\":\"192.168.99.101\",\"port\":9000},\"annotations\":[{\"timestamp\":1472470996238000,\"value\":\"foo\"},{\"timestamp\":1472470996403000,\"value\":\"bar\"}],\"tags\":{\"clnt/finagle.version\":\"6.45.0\",\"http.path\":\"/api\"}}"); }
@Udf public String lpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (padding == null || padding.isEmpty() || targetLen == null || targetLen < 0) { return null; } final StringBuilder sb = new StringBuilder(targetLen + padding.length()); final int padUpTo = Math.max(targetLen - input.length(), 0); for (int i = 0; i < padUpTo; i += padding.length()) { sb.append(padding); } sb.setLength(padUpTo); sb.append(input); sb.setLength(targetLen); return sb.toString(); }
@Test public void shouldAppendPartialPaddingString() { final String result = udf.lpad("foo", 4, "Bar"); assertThat(result, is("Bfoo")); }
@Bean public PluginDataHandler jwtPluginDataHandler() { return new JwtPluginDataHandler(); }
@Test public void testJwtPluginDataHandler() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JwtPluginConfiguration.class)) .withBean(JwtPluginConfigurationTest.class) .withPropertyValues("debug=true") .run(context -> { PluginDataHandler handler = context.getBean("jwtPluginDataHandler", PluginDataHandler.class); assertNotNull(handler); }); }
@VisibleForTesting static String extractTableName(MultivaluedMap<String, String> pathParameters, MultivaluedMap<String, String> queryParameters) { String tableName = extractTableName(pathParameters); if (tableName != null) { return tableName; } return extractTableName(queryParameters); }
@Test public void testExtractTableNameWithSchemaNameInQueryParams() { MultivaluedMap<String, String> pathParams = new MultivaluedHashMap<>(); MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>(); queryParams.putSingle("schemaName", "F"); assertEquals(AuthenticationFilter.extractTableName(pathParams, queryParams), "F"); }
public static <T> T createInstance(String userClassName, Class<T> xface, ClassLoader classLoader) { Class<?> theCls; try { theCls = Class.forName(userClassName, true, classLoader); } catch (ClassNotFoundException | NoClassDefFoundError cnfe) { throw new RuntimeException("User class must be in class path", cnfe); } if (!xface.isAssignableFrom(theCls)) { throw new RuntimeException(userClassName + " does not implement " + xface.getName()); } Class<T> tCls = (Class<T>) theCls.asSubclass(xface); T result; try { Constructor<T> meth = (Constructor<T>) constructorCache.get(theCls); if (null == meth) { meth = tCls.getDeclaredConstructor(); meth.setAccessible(true); constructorCache.put(theCls, meth); } result = meth.newInstance(); } catch (InstantiationException ie) { throw new RuntimeException("User class must be concrete", ie); } catch (NoSuchMethodException e) { throw new RuntimeException("User class must have a no-arg constructor", e); } catch (IllegalAccessException e) { throw new RuntimeException("User class must have a public constructor", e); } catch (InvocationTargetException e) { throw new RuntimeException("User class constructor throws exception", e); } return result; }
@Test public void testCreateInstanceAbstractClass() { try { createInstance(AbstractClass.class.getName(), classLoader); fail("Should fail to load abstract class"); } catch (RuntimeException re) { assertTrue(re.getCause() instanceof InstantiationException); } }
public static String dateToStr(Date date) { return dateToStr(date, DATE_FORMAT_TIME); }
@Test public void dateToStr1() throws Exception { long d0 = 0l; long d1 = 1501127802975l; // 2017-07-27 11:56:42:975 +8 long d2 = 1501127835658l; // 2017-07-27 11:57:15:658 +8 TimeZone timeZone = TimeZone.getDefault(); Date date0 = new Date(d0 - timeZone.getOffset(d0)); Date date1 = new Date(d1 - timeZone.getOffset(d1)); Date date2 = new Date(d2 - timeZone.getOffset(d2)); Assert.assertEquals(DateUtils.dateToStr(date0, DateUtils.DATE_FORMAT_MILLS_TIME), "1970-01-01 00:00:00.000"); Assert.assertEquals(DateUtils.dateToStr(date1, DateUtils.DATE_FORMAT_MILLS_TIME), "2017-07-27 03:56:42.975"); Assert.assertEquals(DateUtils.dateToStr(date2, DateUtils.DATE_FORMAT_MILLS_TIME), "2017-07-27 03:57:15.658"); }
@SuppressWarnings("checkstyle:BooleanExpressionComplexity") public static Optional<KeyStoreOptions> getBcfksTrustStoreOptions( final Map<String, String> props) { final String location = getTrustStoreLocation(props); final String password = getTrustStorePassword(props); final String trustManagerAlgorithm = getTrustManagerAlgorithm(props); final String securityProviders = getSecurityProviders(props); if (Strings.isNullOrEmpty(location) || Strings.isNullOrEmpty(password) || Strings.isNullOrEmpty(trustManagerAlgorithm) || Strings.isNullOrEmpty(securityProviders)) { return Optional.empty(); } specifySecurityProperties(securityProviders, trustManagerAlgorithm, false); return Optional.of(buildBcfksOptions(location, password, "")); }
@Test public void shouldReturnEmptyTrustStoreBCFKSOptionsIfPasswordIsEmpty() { // When final Optional<KeyStoreOptions> keyStoreOptions = VertxSslOptionsFactory.getBcfksTrustStoreOptions( ImmutableMap.of() ); // Then assertThat(keyStoreOptions, is(Optional.empty())); }
@Override @Nonnull public <T> T invokeAny(@Nonnull Collection<? extends Callable<T>> tasks) throws ExecutionException { throwRejectedExecutionExceptionIfShutdown(); Exception exception = null; for (Callable<T> task : tasks) { try { return task.call(); } catch (Exception e) { // try next task exception = e; } } throw new ExecutionException("No tasks finished successfully.", exception); }
@Test void testInvokeAnyWithTimeoutAndNoopShutdown() { final CompletableFuture<Thread> future = new CompletableFuture<>(); testWithNoopShutdown( testInstance -> testInstance.invokeAny( callableCollectionFromFuture(future), 1, TimeUnit.DAYS)); assertThat(future).isCompletedWithValue(Thread.currentThread()); }
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testLambdaCapture() { analyze("SELECT apply(c1, x -> x + c2) FROM (VALUES (1, 2), (3, 4), (5, 6)) t(c1, c2)"); analyze("SELECT apply(c1 + 10, x -> apply(x + 100, y -> c1)) FROM (VALUES 1) t(c1)"); // reference lambda variable of the not-immediately-enclosing lambda analyze("SELECT apply(1, x -> apply(10, y -> x)) FROM (VALUES 1000) t(x)"); analyze("SELECT apply(1, x -> apply(10, y -> x)) FROM (VALUES 'abc') t(x)"); analyze("SELECT apply(1, x -> apply(10, y -> apply(100, z -> x))) FROM (VALUES 1000) t(x)"); analyze("SELECT apply(1, x -> apply(10, y -> apply(100, z -> x))) FROM (VALUES 'abc') t(x)"); }
@Override public void callback(CallbackContext context) { try { onCallback(context); } catch (IOException | ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); } }
@Test public void callback_whenOrganizationsAreDefinedAndUserBelongsToOne_shouldAuthenticateAndRedirect() throws IOException, ExecutionException, InterruptedException { UserIdentity userIdentity = mock(UserIdentity.class); CallbackContext context = mockUserBelongingToOrganization(userIdentity); settings.setProperty(GITHUB_ORGANIZATIONS, "organization1,organization2"); underTest.callback(context); verify(context).authenticate(userIdentity); verify(context).redirectToRequestedPage(); }
public static boolean isTimeoutException(Throwable exception) { if (exception == null) return false; if (exception instanceof ExecutionException) { exception = exception.getCause(); if (exception == null) return false; } return exception instanceof TimeoutException; }
@Test public void testTimeoutExceptionIsTimeoutException() { assertTrue(isTimeoutException(new TimeoutException())); }
public Result parse(final String string) throws DateNotParsableException { return this.parse(string, new Date()); }
@Test public void testThisMonth() throws Exception { DateTime reference = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("12.06.2021 09:45:23"); NaturalDateParser.Result result = naturalDateParser.parse("this month", reference.toDate()); DateTime first = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("01.06.2021 00:00:00"); DateTime firstNextMonth = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("01.07.2021 00:00:00"); assertThat(result.getFrom()).as("should start at the beginning of the month").isEqualTo(first); assertThat(result.getTo()).as("should be the 1st day of the following month").isEqualTo(firstNextMonth); }
@Override public int read() throws IOException { return ( (SnappyInputStream) delegate ).read(); }
@Test public void testRead() throws IOException { assertEquals( inStream.available(), inStream.read( new byte[100], 0, inStream.available() ) ); }
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { Registration<T> registration = PipelineOptionsFactory.CACHE .get() .validateWellFormed(iface, computedProperties.knownInterfaces); List<PropertyDescriptor> propertyDescriptors = registration.getPropertyDescriptors(); Class<T> proxyClass = registration.getProxyClass(); existingOption = InstanceBuilder.ofType(proxyClass) .fromClass(proxyClass) .withArg(InvocationHandler.class, this) .build(); computedProperties = computedProperties.updated(iface, existingOption, propertyDescriptors); } } } return existingOption; }
@Test public void testJsonConversionForSimpleTypes() throws Exception { SimpleTypes options = PipelineOptionsFactory.as(SimpleTypes.class); options.setString("TestValue"); options.setInteger(5); SimpleTypes options2 = serializeDeserialize(SimpleTypes.class, options); assertEquals(5, options2.getInteger()); assertEquals("TestValue", options2.getString()); }
@Override public void start() { initHealthChecker(); NamespacedPodListInformer.INFORMER.init(config, new K8sResourceEventHandler()); }
@Test public void queryRemoteNodesWhenInformerNotwork() throws Exception { withEnvironmentVariable(SELF_UID, SELF_UID + "0").execute(() -> { providerA = createProvider(SELF_UID); coordinatorA = getClusterCoordinator(providerA); coordinatorA.start(); }); KubernetesCoordinator coordinator = getClusterCoordinator(providerA); doReturn(Optional.empty()).when(NamespacedPodListInformer.INFORMER).listPods(); List<RemoteInstance> remoteInstances = Whitebox.invokeMethod(coordinator, "queryRemoteNodes"); Assertions.assertEquals(1, remoteInstances.size()); Assertions.assertEquals(addressA, remoteInstances.get(0).getAddress()); }
@Override public void deleteDiscountActivity(Long id) { // 校验存在 DiscountActivityDO activity = validateDiscountActivityExists(id); if (CommonStatusEnum.isEnable(activity.getStatus())) { // 未关闭的活动,不能删除噢 throw exception(DISCOUNT_ACTIVITY_DELETE_FAIL_STATUS_NOT_CLOSED); } // 删除 discountActivityMapper.deleteById(id); }
@Test public void testDeleteDiscountActivity_success() { // mock 数据 DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus())); discountActivityMapper.insert(dbDiscountActivity);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbDiscountActivity.getId(); // 调用 discountActivityService.deleteDiscountActivity(id); // 校验数据不存在了 assertNull(discountActivityMapper.selectById(id)); }
@Override public int getColumnLength(final Object value) { return 4; }
@Test void assertGetColumnLength() { assertThat(new PostgreSQLDateBinaryProtocolValue().getColumnLength(""), is(4)); }
public List<QueuedCommand> getRestoreCommands(final Duration duration) { if (commandTopicBackup.commandTopicCorruption()) { log.warn("Corruption detected. " + "Use backup to restore command topic."); return Collections.emptyList(); } return getAllCommandsInCommandTopic( commandConsumer, commandTopicPartition, Optional.of(commandTopicBackup), duration ); }
@Test public void shouldGetRestoreCommandsCorrectlyWithDuplicateKeys() { // Given: when(commandConsumer.poll(any(Duration.class))) .thenReturn(someConsumerRecords( new ConsumerRecord<>("topic", 0, 0, commandId1, command1), new ConsumerRecord<>("topic", 0, 1, commandId2, command2))) .thenReturn(someConsumerRecords( new ConsumerRecord<>("topic", 0, 2, commandId2, command3), new ConsumerRecord<>("topic", 0, 3, commandId3, command3))); when(commandConsumer.endOffsets(any())).thenReturn(ImmutableMap.of(TOPIC_PARTITION, 4L)); when(commandConsumer.position(TOPIC_PARTITION)).thenReturn(0L, 2L, 4L); // When: final List<QueuedCommand> queuedCommandList = commandTopic .getRestoreCommands(Duration.ofMillis(1)); // Then: assertThat(queuedCommandList, equalTo(ImmutableList.of( new QueuedCommand(commandId1, command1, Optional.empty(), 0L), new QueuedCommand(commandId2, command2, Optional.empty(), 1L), new QueuedCommand(commandId2, command3, Optional.empty(), 2L), new QueuedCommand(commandId3, command3, Optional.empty(), 3L)))); }
static URI determineClasspathResourceUri(Path baseDir, String basePackagePath, Path resource) { String subPackageName = determineSubpackagePath(baseDir, resource); String resourceName = resource.getFileName().toString(); String classpathResourcePath = of(basePackagePath, subPackageName, resourceName) .filter(value -> !value.isEmpty()) // default package . .collect(joining(RESOURCE_SEPARATOR_STRING)); return classpathResourceUri(classpathResourcePath); }
@Test void determineFullyQualifiedResourceNameFromComPackage() { Path baseDir = Paths.get("path", "to", "com"); String basePackageName = "com"; Path resourceFile = Paths.get("path", "to", "com", "example", "app", "app.feature"); URI fqn = ClasspathSupport.determineClasspathResourceUri(baseDir, basePackageName, resourceFile); assertEquals(URI.create("classpath:com/example/app/app.feature"), fqn); }
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { if(!session.getClient().makeDirectory(folder.getAbsolute())) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } return folder; } catch(FTPException e) { switch(e.getCode()) { case FTPReply.FILE_UNAVAILABLE: throw new ConflictException(folder.getAbsolute()); } throw new FTPExceptionMappingService().map("Cannot create folder {0}", e, folder); } catch(IOException e) { throw new FTPExceptionMappingService().map("Cannot create folder {0}", e, folder); } }
@Test public void testMakeDirectory() throws Exception { final Path test = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)); new FTPDirectoryFeature(session).mkdir(test, new TransferStatus()); assertTrue(session.getFeature(Find.class).find(test)); assertThrows(ConflictException.class, () -> new FTPDirectoryFeature(session).mkdir(test, new TransferStatus())); new FTPDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); assertFalse(session.getFeature(Find.class).find(test)); }
public Analysis analyze( final Query query, final Optional<Sink> sink ) { final Analysis analysis = analyzer.analyze(query, sink); if (query.isPullQuery()) { pullQueryValidator.validate(analysis); } else { pushQueryValidator.validate(analysis); } if (!analysis.getTableFunctions().isEmpty()) { final AliasedDataSource ds = analysis.getFrom(); if (ds.getDataSource().getDataSourceType() == DataSourceType.KTABLE) { throw new KsqlException("Table source is not supported with table functions"); } } return analysis; }
@Test public void shouldPreThenPostValidateContinuousQueries() { // Given: when(query.isPullQuery()).thenReturn(false); // When: queryAnalyzer.analyze(query, Optional.of(sink)); // Then: verify(continuousValidator).validate(analysis); verifyNoMoreInteractions(staticValidator); }
@Nullable public static URI normalizeURI(@Nullable final URI uri, String scheme, int port, String path) { return Optional.ofNullable(uri) .map(u -> getUriWithScheme(u, scheme)) .map(u -> getUriWithPort(u, port)) .map(u -> getUriWithDefaultPath(u, path)) .map(Tools::uriWithTrailingSlash) .map(URI::normalize) .orElse(null); }
@Test public void normalizeURIReturnsNullIfURIIsNull() { assertNull(Tools.normalizeURI(null, "http", 1234, "/baz")); }
@Override public MaskRule build(final MaskRuleConfiguration ruleConfig, final String databaseName, final DatabaseType protocolType, final ResourceMetaData resourceMetaData, final Collection<ShardingSphereRule> builtRules, final ComputeNodeInstanceContext computeNodeInstanceContext) { return new MaskRule(ruleConfig); }
@SuppressWarnings("unchecked") @Test void assertBuild() { MaskRuleConfiguration ruleConfig = mock(MaskRuleConfiguration.class); DatabaseRuleBuilder<MaskRuleConfiguration> builder = OrderedSPILoader.getServices(DatabaseRuleBuilder.class, Collections.singleton(ruleConfig)).get(ruleConfig); assertThat(builder.build(ruleConfig, "", new MySQLDatabaseType(), mock(ResourceMetaData.class), Collections.emptyList(), mock(ComputeNodeInstanceContext.class)), instanceOf(MaskRule.class)); }
public int countScimGroups(DbSession dbSession, ScimGroupQuery query) { return mapper(dbSession).countScimGroups(query); }
@Test void countScimGroups_shouldReturnTheTotalNumberOfScimGroups() { int totalScimGroups = 15; generateScimGroups(totalScimGroups); assertThat(scimGroupDao.countScimGroups(db.getSession(), ScimGroupQuery.ALL)).isEqualTo(totalScimGroups); }
public static int isBinary(String str) { if (str == null || str.isEmpty()) { return -1; } return str.matches("[01]+") ? MIN_RADIX : -1; }
@Test public void isBinary_Test() { Assertions.assertEquals(2, TbUtils.isBinary("1100110")); Assertions.assertEquals(-1, TbUtils.isBinary("2100110")); }
@Override public final boolean offer(int ordinal, @Nonnull Object item) { if (ordinal == -1) { return offerInternal(allEdges, item); } else { if (ordinal == bucketCount()) { // ordinal beyond bucketCount will add to snapshot queue, which we don't allow through this method throw new IllegalArgumentException("Illegal edge ordinal: " + ordinal); } singleEdge[0] = ordinal; return offerInternal(singleEdge, item); } }
@Test public void when_offer1_then_rateLimited() { do_when_offer_then_rateLimited(e -> outbox.offer(e)); }
public String format(Date then) { if (then == null) then = now(); Duration d = approximateDuration(then); return format(d); }
@Test public void testDecadesAgo() throws Exception { PrettyTime t = new PrettyTime(now); Assert.assertEquals("3 decades ago", t.format(now.minus(3, ChronoUnit.DECADES))); }
@Override public Destination createTemporaryDestination(final Session session, final boolean topic) throws JMSException { if (topic) { return session.createTemporaryTopic(); } else { return session.createTemporaryQueue(); } }
@Test public void testTemporaryTopicCreation() throws Exception { TemporaryTopic destination = (TemporaryTopic) strategy.createTemporaryDestination(getSession(), true); assertNotNull(destination); assertNotNull(destination.getTopicName()); }
public static MemorySegment wrapCopy(byte[] bytes, int start, int end) throws IllegalArgumentException { checkArgument(end >= start); checkArgument(end <= bytes.length); MemorySegment copy = allocateUnpooledSegment(end - start); copy.put(0, bytes, start, copy.size()); return copy; }
@Test void testWrapCopyWrongEnd() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> MemorySegmentFactory.wrapCopy(new byte[] {1, 2, 3}, 0, 10)); }
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "Handled in switchIfEmpty") @Override public HouseTable save(HouseTable entity) { CreateUpdateEntityRequestBodyUserTable requestBody = new CreateUpdateEntityRequestBodyUserTable().entity(houseTableMapper.toUserTable(entity)); return getHtsRetryTemplate(Arrays.asList(IllegalStateException.class)) .execute( context -> apiInstance .putUserTable(requestBody) .map(EntityResponseBodyUserTable::getEntity) .map(houseTableMapper::toHouseTable) .onErrorResume(this::handleHtsHttpError) .block(Duration.ofSeconds(REQUEST_TIMEOUT_SECONDS))); }
@Test public void testRepoSaveWithEmptyMono() { // Leave the entity as empty. EntityResponseBodyUserTable putResponse = new EntityResponseBodyUserTable(); mockHtsServer.enqueue( new MockResponse() .setResponseCode(200) .setBody((new Gson()).toJson(putResponse)) .addHeader("Content-Type", "application/json")); Assertions.assertThrowsExactly( RuntimeException.class, () -> htsRepo.save(HOUSE_TABLE), "Unexpected null value from publisher."); }