focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static <T> Window<T> into(WindowFn<? super T, ?> fn) { try { fn.windowCoder().verifyDeterministic(); } catch (NonDeterministicException e) { throw new IllegalArgumentException("Window coders must be deterministic.", e); } return Window.<T>configure().withWindowFn(fn); }
@Test @Category(ValidatesRunner.class) public void testTimestampCombinerDefault() { pipeline.enableAbandonedNodeEnforcement(true); pipeline .apply( Create.timestamped( TimestampedValue.of(KV.of(0, "hello"), new Instant(0)), TimestampedValue.of(KV.of(0, "goodbye"), new Instant(10)))) .apply(Window.into(FixedWindows.of(Duration.standardMinutes(10)))) .apply(GroupByKey.create()) .apply( ParDo.of( new DoFn<KV<Integer, Iterable<String>>, Void>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { assertThat( c.timestamp(), equalTo( new IntervalWindow( new Instant(0), new Instant(0).plus(Duration.standardMinutes(10))) .maxTimestamp())); } })); pipeline.run(); }
@Override public boolean revokeToken(String clientId, String accessToken) { // 先查询,保证 clientId 时匹配的 OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.getAccessToken(accessToken); if (accessTokenDO == null || ObjectUtil.notEqual(clientId, accessTokenDO.getClientId())) { return false; } // 再删除 return oauth2TokenService.removeAccessToken(accessToken) != null; }
@Test public void testRevokeToken_clientIdError() { // 准备参数 String clientId = randomString(); String accessToken = randomString(); // mock 方法 OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class); when(oauth2TokenService.getAccessToken(eq(accessToken))).thenReturn(accessTokenDO); // 调用,并断言 assertFalse(oauth2GrantService.revokeToken(clientId, accessToken)); }
@Override public Output run(RunContext runContext) throws Exception { String taskSpec = runContext.render(this.spec); try { Task task = OBJECT_MAPPER.readValue(taskSpec, Task.class); if (task instanceof TemplatedTask) { throw new IllegalArgumentException("The templated task cannot be of type 'io.kestra.plugin.core.templating.TemplatedTask'"); } if (task instanceof RunnableTask<?> runnableTask) { return runnableTask.run(runContext); } throw new IllegalArgumentException("The templated task must be a runnable task"); } catch (JsonProcessingException e) { throw new IllegalVariableEvaluationException(e); } }
@Test void templatedType() throws Exception { RunContext runContext = runContextFactory.of(Map.of("type", "io.kestra.plugin.core.debug.Return")); TemplatedTask templatedTask = TemplatedTask.builder() .id("template") .type(TemplatedTask.class.getName()) .spec(""" type: {{ type }} format: It's alive!""") .build(); Output output = templatedTask.run(runContext); assertThat(output, notNullValue()); assertThat(output, instanceOf(Return.Output.class)); assertThat(((Return.Output)output).getValue(), is("It's alive!")); }
@Override public void execute(ComputationStep.Context context) { new PathAwareCrawler<>( FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor(List.of(duplicationFormula))) .visit(treeRootHolder.getRoot()); }
@Test public void compute_and_aggregate_duplicated_lines_when_only_some_lines_have_changesets() { // 2 new duplicated lines in each, since only the first 2 lines are new addDuplicatedBlock(FILE_1_REF, 2); addDuplicatedBlock(FILE_3_REF, 10); addDuplicatedBlock(FILE_4_REF, 12); setFirstTwoLinesAsNew(FILE_1, FILE_2, FILE_3, FILE_4); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_DUPLICATED_LINES_KEY, 2); assertRawMeasureValue(FILE_2_REF, NEW_DUPLICATED_LINES_KEY, 0); assertRawMeasureValue(FILE_3_REF, NEW_DUPLICATED_LINES_KEY, 2); assertRawMeasureValue(FILE_4_REF, NEW_DUPLICATED_LINES_KEY, 2); assertRawMeasureValue(DIRECTORY_REF, NEW_DUPLICATED_LINES_KEY, 2); assertNoRawMeasure(DIRECTORY_2_REF, NEW_DUPLICATED_LINES_KEY); assertRawMeasureValue(ROOT_REF, NEW_DUPLICATED_LINES_KEY, 6); }
@Override public String generateSqlType(Dialect dialect) { switch (dialect.getId()) { case MsSql.ID: return format("NVARCHAR (%d)", columnSize); case Oracle.ID: return format("VARCHAR2 (%d%s)", columnSize, ignoreOracleUnit ? "" : " CHAR"); default: return format("VARCHAR (%d)", columnSize); } }
@Test public void generate_sql_type() { VarcharColumnDef def = new VarcharColumnDef.Builder() .setColumnName("issues") .setLimit(10) .setIsNullable(true) .build(); assertThat(def.generateSqlType(new H2())).isEqualTo("VARCHAR (10)"); assertThat(def.generateSqlType(new PostgreSql())).isEqualTo("VARCHAR (10)"); assertThat(def.generateSqlType(new MsSql())).isEqualTo("NVARCHAR (10)"); assertThat(def.generateSqlType(new Oracle())).isEqualTo("VARCHAR2 (10 CHAR)"); }
public ChmDirectoryListingSet getChmDirList() { return chmDirList; }
@Test public void testGetChmDirList() { assertNotNull(chmExtractor.getChmDirList()); }
@JsonProperty public SchemaTableName getSchemaTableName() { return schemaTableName; }
@Test public void testRoundTrip() { MongoTableHandle expected = new MongoTableHandle(new SchemaTableName("schema", "table")); String json = codec.toJson(expected); MongoTableHandle actual = codec.fromJson(json); assertEquals(actual.getSchemaTableName(), expected.getSchemaTableName()); }
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@TestTemplate public void testPartitionedIsNull() throws Exception { createPartitionedTable(spark, tableName, "truncate(4, data)"); SparkScanBuilder builder = scanBuilder(); TruncateFunction.TruncateString function = new TruncateFunction.TruncateString(); UserDefinedScalarFunc udf = toUDF(function, expressions(intLit(4), fieldRef("data"))); Predicate predicate = new Predicate("IS_NULL", expressions(udf)); pushFilters(builder, predicate); Batch scan = builder.build().toBatch(); assertThat(scan.planInputPartitions().length).isEqualTo(0); // NOT IsNULL builder = scanBuilder(); predicate = new Not(predicate); pushFilters(builder, predicate); scan = builder.build().toBatch(); assertThat(scan.planInputPartitions().length).isEqualTo(10); }
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; } String message = chatMessage.getMessage(); Matcher matcher = KILLCOUNT_PATTERN.matcher(message); if (matcher.find()) { final String boss = matcher.group("boss"); final int kc = Integer.parseInt(matcher.group("kc")); final String pre = matcher.group("pre"); final String post = matcher.group("post"); if (Strings.isNullOrEmpty(pre) && Strings.isNullOrEmpty(post)) { unsetKc(boss); return; } String renamedBoss = KILLCOUNT_RENAMES .getOrDefault(boss, boss) // The config service doesn't support keys with colons in them .replace(":", ""); if (boss != renamedBoss) { // Unset old TOB kc unsetKc(boss); unsetPb(boss); unsetKc(boss.replace(":", ".")); unsetPb(boss.replace(":", ".")); // Unset old story mode unsetKc("Theatre of Blood Story Mode"); unsetPb("Theatre of Blood Story Mode"); } setKc(renamedBoss, kc); // We either already have the pb, or need to remember the boss for the upcoming pb if (lastPb > -1) { log.debug("Got out-of-order personal best for {}: {}", renamedBoss, lastPb); if (renamedBoss.contains("Theatre of Blood")) { // TOB team size isn't sent in the kill message, but can be computed from varbits int tobTeamSize = tobTeamSize(); lastTeamSize = tobTeamSize == 1 ? "Solo" : (tobTeamSize + " players"); } else if (renamedBoss.contains("Tombs of Amascut")) { // TOA team size isn't sent in the kill message, but can be computed from varbits int toaTeamSize = toaTeamSize(); lastTeamSize = toaTeamSize == 1 ? "Solo" : (toaTeamSize + " players"); } final double pb = getPb(renamedBoss); // If a raid with a team size, only update the pb if it is lower than the existing pb // so that the pb is the overall lowest of any team size if (lastTeamSize == null || pb == 0 || lastPb < pb) { log.debug("Setting overall pb (old: {})", pb); setPb(renamedBoss, lastPb); } if (lastTeamSize != null) { log.debug("Setting team size pb: {}", lastTeamSize); setPb(renamedBoss + " " + lastTeamSize, lastPb); } lastPb = -1; lastTeamSize = null; } else { lastBossKill = renamedBoss; lastBossTime = client.getTickCount(); } return; } matcher = DUEL_ARENA_WINS_PATTERN.matcher(message); if (matcher.find()) { final int oldWins = getKc("Duel Arena Wins"); final int wins = matcher.group(2).equals("one") ? 1 : Integer.parseInt(matcher.group(2).replace(",", "")); final String result = matcher.group(1); int winningStreak = getKc("Duel Arena Win Streak"); int losingStreak = getKc("Duel Arena Lose Streak"); if (result.equals("won") && wins > oldWins) { losingStreak = 0; winningStreak += 1; } else if (result.equals("were defeated")) { losingStreak += 1; winningStreak = 0; } else { log.warn("unrecognized duel streak chat message: {}", message); } setKc("Duel Arena Wins", wins); setKc("Duel Arena Win Streak", winningStreak); setKc("Duel Arena Lose Streak", losingStreak); } matcher = DUEL_ARENA_LOSSES_PATTERN.matcher(message); if (matcher.find()) { int losses = matcher.group(1).equals("one") ? 1 : Integer.parseInt(matcher.group(1).replace(",", "")); setKc("Duel Arena Losses", losses); } matcher = KILL_DURATION_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = NEW_PB_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = RAIDS_PB_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = RAIDS_DURATION_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = HS_PB_PATTERN.matcher(message); if (matcher.find()) { int floor = Integer.parseInt(matcher.group("floor")); String floortime = matcher.group("floortime"); String floorpb = matcher.group("floorpb"); String otime = matcher.group("otime"); String opb = matcher.group("opb"); String pb = MoreObjects.firstNonNull(floorpb, floortime); setPb("Hallowed Sepulchre Floor " + floor, timeStringToSeconds(pb)); if (otime != null) { pb = MoreObjects.firstNonNull(opb, otime); setPb("Hallowed Sepulchre", timeStringToSeconds(pb)); } } matcher = HS_KC_FLOOR_PATTERN.matcher(message); if (matcher.find()) { int floor = Integer.parseInt(matcher.group(1)); int kc = Integer.parseInt(matcher.group(2).replaceAll(",", "")); setKc("Hallowed Sepulchre Floor " + floor, kc); } matcher = HS_KC_GHC_PATTERN.matcher(message); if (matcher.find()) { int kc = Integer.parseInt(matcher.group(1).replaceAll(",", "")); setKc("Hallowed Sepulchre", kc); } matcher = HUNTER_RUMOUR_KC_PATTERN.matcher(message); if (matcher.find()) { int kc = Integer.parseInt(matcher.group(1).replaceAll(",", "")); setKc("Hunter Rumours", kc); } if (lastBossKill != null && lastBossTime != client.getTickCount()) { lastBossKill = null; lastBossTime = -1; } matcher = COLLECTION_LOG_ITEM_PATTERN.matcher(message); if (matcher.find()) { String item = matcher.group(1); int petId = findPet(item); if (petId != -1) { final List<Integer> petList = new ArrayList<>(getPetList()); if (!petList.contains(petId)) { log.debug("New pet added: {}/{}", item, petId); petList.add(petId); setPetList(petList); } } } matcher = GUARDIANS_OF_THE_RIFT_PATTERN.matcher(message); if (matcher.find()) { int kc = Integer.parseInt(matcher.group(1)); setKc("Guardians of the Rift", kc); } }
@Test public void testHsOverallNoPb_NoPb() { ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Floor 5 time: <col=ff0000>3:56</col>. Personal best: 3:05<br>Overall time: <col=ff0000>9:14</col>. Personal best: 7:49<br>", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration("personalbest", "hallowed sepulchre floor 5", 3 * 60 + 5.0); verify(configManager).setRSProfileConfiguration("personalbest", "hallowed sepulchre", 7 * 60 + 49.0); // Precise times chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Floor 5 time: <col=ff0000>3:56.40</col>. Personal best: 3:05.20<br>Overall time: <col=ff0000>9:14.20</col>. Personal best: 7:49.20<br>", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration("personalbest", "hallowed sepulchre floor 5", 3 * 60 + 5.2); verify(configManager).setRSProfileConfiguration("personalbest", "hallowed sepulchre", 7 * 60 + 49.2); }
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuffer buf = new StringBuffer(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_STATE: handleLiteralState(c, tokenList, buf); break; case FORMAT_MODIFIER_STATE: handleFormatModifierState(c, tokenList, buf); break; case OPTION_STATE: processOption(c, tokenList, buf); break; case KEYWORD_STATE: handleKeywordState(c, tokenList, buf); break; case RIGHT_PARENTHESIS_STATE: handleRightParenthesisState(c, tokenList, buf); break; default: } } // EOS switch (state) { case LITERAL_STATE: addValuedToken(Token.LITERAL, buf, tokenList); break; case KEYWORD_STATE: tokenList.add(new Token(Token.SIMPLE_KEYWORD, buf.toString())); break; case RIGHT_PARENTHESIS_STATE: tokenList.add(Token.RIGHT_PARENTHESIS_TOKEN); break; case FORMAT_MODIFIER_STATE: case OPTION_STATE: throw new ScanException("Unexpected end of pattern string"); } return tokenList; }
@Test public void testComplexNR() throws ScanException { List<Token> tl = new TokenStream("%d{1234} [%34.-67toto] %n").tokenize(); List<Token> witness = new ArrayList<Token>(); witness.add(Token.PERCENT_TOKEN); witness.add(new Token(Token.SIMPLE_KEYWORD, "d")); List<String> ol = new ArrayList<String>(); ol.add("1234"); witness.add(new Token(Token.OPTION, ol)); witness.add(new Token(Token.LITERAL, " [")); witness.add(Token.PERCENT_TOKEN); witness.add(new Token(Token.FORMAT_MODIFIER, "34.-67")); witness.add(new Token(Token.SIMPLE_KEYWORD, "toto")); witness.add(new Token(Token.LITERAL, "] ")); witness.add(Token.PERCENT_TOKEN); witness.add(new Token(Token.SIMPLE_KEYWORD, "n")); assertEquals(witness, tl); }
public List<String> build() { checkState(!columnDefs.isEmpty() || !pkColumnDefs.isEmpty(), "at least one column must be specified"); return Stream.concat(of(createTableStatement()), createOracleAutoIncrementStatements()) .toList(); }
@Test public void build_throws_ISE_if_no_column_has_been_set() { assertThatThrownBy(() -> underTest.build()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("at least one column must be specified"); }
@Override public Map<String, Collection<String>> getSystemDatabaseSchemaMap() { return SYSTEM_DATABASE_SCHEMA_MAP; }
@Test void assertGetSystemDatabases() { assertTrue(systemDatabase.getSystemDatabaseSchemaMap().containsKey("postgres")); }
@Override public int hashCode() { return key.hashCode(); }
@Test public void hashcode_uses_only_key() { int expected = new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.FLOAT).hashCode(); assertThat(new MetricImpl(SOME_UUID, SOME_KEY, "some other name", Metric.MetricType.FLOAT).hashCode()).isEqualTo(expected); assertThat(new MetricImpl(SOME_UUID, SOME_KEY, "some other name", Metric.MetricType.BOOL).hashCode()).isEqualTo(expected); }
@Override public int hashCode() { int result = Objects.hashCode(cpuCores); result = 31 * result + Objects.hashCode(taskHeapMemory); result = 31 * result + Objects.hashCode(taskOffHeapMemory); result = 31 * result + Objects.hashCode(managedMemory); result = 31 * result + extendedResources.hashCode(); return result; }
@Test void testHashCode() { ResourceSpec rs1 = ResourceSpec.newBuilder(1.0, 100).build(); ResourceSpec rs2 = ResourceSpec.newBuilder(1.0, 100).build(); assertThat(rs2).hasSameHashCodeAs(rs1); ResourceSpec rs3 = ResourceSpec.newBuilder(1.0, 100) .setExtendedResource(new ExternalResource(EXTERNAL_RESOURCE_NAME, 2.2)) .build(); ResourceSpec rs4 = ResourceSpec.newBuilder(1.0, 100) .setExtendedResource(new ExternalResource(EXTERNAL_RESOURCE_NAME, 1)) .build(); assertThat(rs4.hashCode()).isNotEqualTo(rs3.hashCode()); ResourceSpec rs5 = ResourceSpec.newBuilder(1.0, 100) .setExtendedResource(new ExternalResource(EXTERNAL_RESOURCE_NAME, 2.2)) .build(); assertThat(rs5).hasSameHashCodeAs(rs3); }
@Override public SymbolTable getRequestSymbolTable(URI requestUri) { // If the URI prefix doesn't match, return null. if (!requestUri.toString().startsWith(_uriPrefix)) { return null; } String serviceName = LoadBalancerUtil.getServiceNameFromUri(requestUri); // First check the cache. SymbolTable symbolTable = _serviceNameToSymbolTableCache.getIfPresent(serviceName); if (symbolTable != null) { // If we got a 404, we will cache an empty symbol table. For such cases, just return null, so that no // symbol table is used. return symbolTable == EmptySymbolTable.SHARED ? null : symbolTable; } try { URI symbolTableUri = new URI(_uriPrefix + serviceName + "/" + RestLiSymbolTableRequestHandler.SYMBOL_TABLE_URI_PATH); // // Fetch remote symbol table, configuring the fetch to return an empty table on 404. This will ensure that // for services that don't have symbol tables enabled yet, we will not use any symbol tables when encoding. // symbolTable = fetchRemoteSymbolTable(symbolTableUri, Collections.emptyMap(), true); if (symbolTable != null) { // Cache the retrieved table. _serviceNameToSymbolTableCache.put(serviceName, symbolTable); // If this symbol table is not the shared empty table, also cache it by symbol table name, else return null // to not use any symbol tables when encoding. if (symbolTable != EmptySymbolTable.SHARED) { _symbolTableNameToSymbolTableCache.put( _symbolTableNameHandler.extractMetadata(symbolTable.getName()).getSymbolTableName(), symbolTable); } else { return null; } } return symbolTable; } catch (URISyntaxException ex) { LOGGER.error("Failed to construct symbol table URI from request URI " + requestUri, ex); } return null; }
@Test public void testGetRemoteRequestSymbolTableFetch404Error() { RestResponseBuilder builder = new RestResponseBuilder(); builder.setStatus(404); Assert.assertNull(_provider.getRequestSymbolTable(URI.create("d2://serviceName"))); // Subsequent fetch should not trigger network fetch and get the table from the cache. when(_client.restRequest(any(RestRequest.class))).thenThrow(new IllegalStateException()); Assert.assertNull(_provider.getRequestSymbolTable(URI.create("d2://serviceName"))); }
private IcebergUUIDObjectInspector() { super(TypeInfoFactory.stringTypeInfo); }
@Test public void testIcebergUUIDObjectInspector() { IcebergUUIDObjectInspector oi = IcebergUUIDObjectInspector.get(); Assert.assertEquals(ObjectInspector.Category.PRIMITIVE, oi.getCategory()); Assert.assertEquals(PrimitiveObjectInspector.PrimitiveCategory.STRING, oi.getPrimitiveCategory()); Assert.assertEquals(TypeInfoFactory.stringTypeInfo, oi.getTypeInfo()); Assert.assertEquals(TypeInfoFactory.stringTypeInfo.getTypeName(), oi.getTypeName()); Assert.assertEquals(String.class, oi.getJavaPrimitiveClass()); Assert.assertEquals(Text.class, oi.getPrimitiveWritableClass()); Assert.assertNull(oi.copyObject(null)); Assert.assertNull(oi.getPrimitiveJavaObject(null)); Assert.assertNull(oi.getPrimitiveWritableObject(null)); Assert.assertNull(oi.convert(null)); UUID uuid = UUID.randomUUID(); String uuidStr = uuid.toString(); Text text = new Text(uuidStr); Assert.assertEquals(uuidStr, oi.getPrimitiveJavaObject(text)); Assert.assertEquals(text, oi.getPrimitiveWritableObject(uuidStr)); Assert.assertEquals(uuid, oi.convert(uuidStr)); Text copy = (Text) oi.copyObject(text); Assert.assertEquals(text, copy); Assert.assertNotSame(text, copy); Assert.assertFalse(oi.preferWritable()); }
@Override public int compareTo(Tag tag) { int keyResult = this.key.compareTo(tag.key); if (keyResult != 0) { return keyResult; } return this.value.compareTo(tag.value); }
@Test public void compareToTest() { Tag tag1 = new Tag(KEY, VALUE); Tag tag2 = new Tag(KEY, VALUE); Tag tag3 = new Tag(KEY, KEY); Tag tag4 = new Tag(VALUE, VALUE); Assert.assertTrue(tag1.compareTo(tag2) == 0); Assert.assertTrue(tag1.compareTo(tag3) < 0); Assert.assertTrue(tag1.compareTo(tag4) > 0); }
public void decode(ByteBuf buffer) { boolean last; int statusCode; while (true) { switch(state) { case READ_COMMON_HEADER: if (buffer.readableBytes() < SPDY_HEADER_SIZE) { return; } int frameOffset = buffer.readerIndex(); int flagsOffset = frameOffset + SPDY_HEADER_FLAGS_OFFSET; int lengthOffset = frameOffset + SPDY_HEADER_LENGTH_OFFSET; buffer.skipBytes(SPDY_HEADER_SIZE); boolean control = (buffer.getByte(frameOffset) & 0x80) != 0; int version; int type; if (control) { // Decode control frame common header version = getUnsignedShort(buffer, frameOffset) & 0x7FFF; type = getUnsignedShort(buffer, frameOffset + SPDY_HEADER_TYPE_OFFSET); streamId = 0; // Default to session Stream-ID } else { // Decode data frame common header version = spdyVersion; // Default to expected version type = SPDY_DATA_FRAME; streamId = getUnsignedInt(buffer, frameOffset); } flags = buffer.getByte(flagsOffset); length = getUnsignedMedium(buffer, lengthOffset); // Check version first then validity if (version != spdyVersion) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid SPDY Version"); } else if (!isValidFrameHeader(streamId, type, flags, length)) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid Frame Error"); } else { state = getNextState(type, length); } break; case READ_DATA_FRAME: if (length == 0) { state = State.READ_COMMON_HEADER; delegate.readDataFrame(streamId, hasFlag(flags, SPDY_DATA_FLAG_FIN), Unpooled.buffer(0)); break; } // Generate data frames that do not exceed maxChunkSize int dataLength = Math.min(maxChunkSize, length); // Wait until entire frame is readable if (buffer.readableBytes() < dataLength) { return; } ByteBuf data = buffer.alloc().buffer(dataLength); data.writeBytes(buffer, dataLength); length -= dataLength; if (length == 0) { state = State.READ_COMMON_HEADER; } last = length == 0 && hasFlag(flags, SPDY_DATA_FLAG_FIN); delegate.readDataFrame(streamId, last, data); break; case READ_SYN_STREAM_FRAME: if (buffer.readableBytes() < 10) { return; } int offset = buffer.readerIndex(); streamId = getUnsignedInt(buffer, offset); int associatedToStreamId = getUnsignedInt(buffer, offset + 4); byte priority = (byte) (buffer.getByte(offset + 8) >> 5 & 0x07); last = hasFlag(flags, SPDY_FLAG_FIN); boolean unidirectional = hasFlag(flags, SPDY_FLAG_UNIDIRECTIONAL); buffer.skipBytes(10); length -= 10; if (streamId == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid SYN_STREAM Frame"); } else { state = State.READ_HEADER_BLOCK; delegate.readSynStreamFrame(streamId, associatedToStreamId, priority, last, unidirectional); } break; case READ_SYN_REPLY_FRAME: if (buffer.readableBytes() < 4) { return; } streamId = getUnsignedInt(buffer, buffer.readerIndex()); last = hasFlag(flags, SPDY_FLAG_FIN); buffer.skipBytes(4); length -= 4; if (streamId == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid SYN_REPLY Frame"); } else { state = State.READ_HEADER_BLOCK; delegate.readSynReplyFrame(streamId, last); } break; case READ_RST_STREAM_FRAME: if (buffer.readableBytes() < 8) { return; } streamId = getUnsignedInt(buffer, buffer.readerIndex()); statusCode = getSignedInt(buffer, buffer.readerIndex() + 4); buffer.skipBytes(8); if (streamId == 0 || statusCode == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid RST_STREAM Frame"); } else { state = State.READ_COMMON_HEADER; delegate.readRstStreamFrame(streamId, statusCode); } break; case READ_SETTINGS_FRAME: if (buffer.readableBytes() < 4) { return; } boolean clear = hasFlag(flags, SPDY_SETTINGS_CLEAR); numSettings = getUnsignedInt(buffer, buffer.readerIndex()); buffer.skipBytes(4); length -= 4; // Validate frame length against number of entries. Each ID/Value entry is 8 bytes. if ((length & 0x07) != 0 || length >> 3 != numSettings) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid SETTINGS Frame"); } else { state = State.READ_SETTING; delegate.readSettingsFrame(clear); } break; case READ_SETTING: if (numSettings == 0) { state = State.READ_COMMON_HEADER; delegate.readSettingsEnd(); break; } if (buffer.readableBytes() < 8) { return; } byte settingsFlags = buffer.getByte(buffer.readerIndex()); int id = getUnsignedMedium(buffer, buffer.readerIndex() + 1); int value = getSignedInt(buffer, buffer.readerIndex() + 4); boolean persistValue = hasFlag(settingsFlags, SPDY_SETTINGS_PERSIST_VALUE); boolean persisted = hasFlag(settingsFlags, SPDY_SETTINGS_PERSISTED); buffer.skipBytes(8); --numSettings; delegate.readSetting(id, value, persistValue, persisted); break; case READ_PING_FRAME: if (buffer.readableBytes() < 4) { return; } int pingId = getSignedInt(buffer, buffer.readerIndex()); buffer.skipBytes(4); state = State.READ_COMMON_HEADER; delegate.readPingFrame(pingId); break; case READ_GOAWAY_FRAME: if (buffer.readableBytes() < 8) { return; } int lastGoodStreamId = getUnsignedInt(buffer, buffer.readerIndex()); statusCode = getSignedInt(buffer, buffer.readerIndex() + 4); buffer.skipBytes(8); state = State.READ_COMMON_HEADER; delegate.readGoAwayFrame(lastGoodStreamId, statusCode); break; case READ_HEADERS_FRAME: if (buffer.readableBytes() < 4) { return; } streamId = getUnsignedInt(buffer, buffer.readerIndex()); last = hasFlag(flags, SPDY_FLAG_FIN); buffer.skipBytes(4); length -= 4; if (streamId == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid HEADERS Frame"); } else { state = State.READ_HEADER_BLOCK; delegate.readHeadersFrame(streamId, last); } break; case READ_WINDOW_UPDATE_FRAME: if (buffer.readableBytes() < 8) { return; } streamId = getUnsignedInt(buffer, buffer.readerIndex()); int deltaWindowSize = getUnsignedInt(buffer, buffer.readerIndex() + 4); buffer.skipBytes(8); if (deltaWindowSize == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid WINDOW_UPDATE Frame"); } else { state = State.READ_COMMON_HEADER; delegate.readWindowUpdateFrame(streamId, deltaWindowSize); } break; case READ_HEADER_BLOCK: if (length == 0) { state = State.READ_COMMON_HEADER; delegate.readHeaderBlockEnd(); break; } if (!buffer.isReadable()) { return; } int compressedBytes = Math.min(buffer.readableBytes(), length); ByteBuf headerBlock = buffer.alloc().buffer(compressedBytes); headerBlock.writeBytes(buffer, compressedBytes); length -= compressedBytes; delegate.readHeaderBlock(headerBlock); break; case DISCARD_FRAME: int numBytes = Math.min(buffer.readableBytes(), length); buffer.skipBytes(numBytes); length -= numBytes; if (length == 0) { state = State.READ_COMMON_HEADER; break; } return; case FRAME_ERROR: buffer.skipBytes(buffer.readableBytes()); return; default: throw new Error("Shouldn't reach here."); } } }
@Test public void testIllegalSpdySynStreamFrameStreamId() throws Exception { short type = 1; byte flags = 0; int length = 10; int streamId = 0; // invalid stream identifier int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF; byte priority = (byte) (RANDOM.nextInt() & 0x07); ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length); encodeControlFrameHeader(buf, type, flags, length); buf.writeInt(streamId); buf.writeInt(associatedToStreamId); buf.writeByte(priority << 5); buf.writeByte(0); decoder.decode(buf); verify(delegate).readFrameError(anyString()); assertFalse(buf.isReadable()); buf.release(); }
@Override public void getBytes(int index, byte[] dst) { getBytes(index, dst, 0, dst.length); }
@Test void getDirectByteBufferBoundaryCheck() { Assertions.assertThrows( IndexOutOfBoundsException.class, () -> buffer.getBytes(-1, ByteBuffer.allocateDirect(0))); }
public List<DBObject> getIndexInfo() { return delegate.listIndexes(DBObject.class).into(new ArrayList<>()); }
@Test void getIndexInfo() { final var collection = jacksonCollection("simple", Simple.class); collection.createIndex(new BasicDBObject("name", 1)); collection.createIndex(new BasicDBObject("_id", 1).append("name", 1)); assertThat(collection.getIndexInfo()).containsExactlyInAnyOrder( new BasicDBObject("key", new Document("_id", 1)) .append("name", "_id_") .append("v", 2), new BasicDBObject("key", new Document("name", 1)) .append("name", "name_1") .append("v", 2), new BasicDBObject("key", new Document("_id", 1) .append("name", 1)) .append("name", "_id_1_name_1") .append("v", 2) ); }
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } boolean result = true; boolean containsNull = false; // Spec. definition: return false if any item is false, else true if all items are true, else null for ( final Object element : list ) { if (element != null && !(element instanceof Boolean)) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not a Boolean")); } else { if (element != null) { result &= (Boolean) element; } else if (!containsNull) { containsNull = true; } } } if (containsNull && result) { return FEELFnResult.ofResult( null ); } else { return FEELFnResult.ofResult( result ); } }
@Test void invokeArrayParamNull() { FunctionTestUtil.assertResultError(allFunction.invoke((Object[]) null), InvalidParametersEvent.class); }
@SuppressWarnings("checkstyle:trailingcomment") public long footprint() { return INT_SIZE_IN_BYTES * hashes.length // size of hashes array + REFERENCE_COST_IN_BYTES * table.length // size of table array + REFERENCE_COST_IN_BYTES // reference to hashes array + REFERENCE_COST_IN_BYTES // reference to table array + FLOAT_SIZE_IN_BYTES // loadFactor + INT_SIZE_IN_BYTES // resizeThreshold + INT_SIZE_IN_BYTES // capacity + INT_SIZE_IN_BYTES // mask + INT_SIZE_IN_BYTES // size + INT_SIZE_IN_BYTES; // version }
@Test public void testFootprintReflectsCapacityIncrease() { final OAHashSet<Integer> set = new OAHashSet<>(8); final long originalFootprint = set.footprint(); populateSet(set, 10); final long footprintAfterCapacityIncrease = set.footprint(); assertTrue(footprintAfterCapacityIncrease > originalFootprint); }
protected void waitForRunning(long interval) { if (hasNotified.compareAndSet(true, false)) { this.onWaitEnd(); return; } //entry to wait waitPoint.reset(); try { waitPoint.await(interval, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { log.error("Interrupted", e); } finally { hasNotified.set(false); this.onWaitEnd(); } }
@Test public void testWaitForRunning() { ServiceThread testServiceThread = startTestServiceThread(); // test waitForRunning testServiceThread.waitForRunning(1000); assertEquals(false, testServiceThread.hasNotified.get()); assertEquals(1, testServiceThread.waitPoint.getCount()); // test wake up testServiceThread.wakeup(); assertEquals(true, testServiceThread.hasNotified.get()); assertEquals(0, testServiceThread.waitPoint.getCount()); // repeat waitForRunning testServiceThread.waitForRunning(1000); assertEquals(false, testServiceThread.hasNotified.get()); assertEquals(0, testServiceThread.waitPoint.getCount()); // repeat waitForRunning again testServiceThread.waitForRunning(1000); assertEquals(false, testServiceThread.hasNotified.get()); assertEquals(1, testServiceThread.waitPoint.getCount()); }
public static String repeat(char value, int n) { return new String(new char[n]).replace("\0", String.valueOf(value)); }
@Test public void testRepeat() { assertEquals(repeat('0', 0), ("")); assertEquals(repeat('1', 3), ("111")); }
@Override public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception { OptionParser optionParser = new OptionParser(); OptionSet optionSet = optionParser.parse(args.toArray(new String[0])); List<String> nargs = (List<String>) optionSet.nonOptionArguments(); if (nargs.isEmpty()) { printHelp(err); err.println(); optionParser.printHelpOn(err); return 0; } long count = 0L; if (ImmutableList.of("-").equals(nargs)) { count = countRecords(stdin); } else { for (Path file : Util.getFiles(nargs)) { try (final InputStream inStream = Util.openFromFS(file)) { count += countRecords(inStream); } } } out.println(count); out.flush(); return 0; }
@Test void basic() throws Exception { final List<Integer> inputSizes = IntStream.range(0, 20).boxed().collect(Collectors.toList()); for (Integer inputSize : inputSizes) { File inputFile = generateData(inputSize); List<String> args = Collections.singletonList(inputFile.getAbsolutePath()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); int returnCode = new RecordCountTool().run(System.in, new PrintStream(out), System.err, args); assertEquals(0, returnCode); assertEquals(inputSize.toString() + System.lineSeparator(), out.toString()); } }
public static int validateToken(CharSequence token) { if (token instanceof AsciiString) { return validateAsciiStringToken((AsciiString) token); } return validateCharSequenceToken(token); }
@DisabledForJreRange(max = JRE.JAVA_17) // This test is much too slow on older Java versions. @Test void headerNameValidationMustRejectAllNamesRejectedByOldAlgorithm() throws Exception { byte[] array = new byte[4]; final ByteBuffer buffer = ByteBuffer.wrap(array); final AsciiString asciiString = new AsciiString(buffer, false); CharSequence charSequence = asCharSequence(asciiString); int i = Integer.MIN_VALUE; Supplier<String> failureMessageSupplier = new Supplier<String>() { @Override public String get() { return "validation mismatch on string '" + asciiString + "', iteration " + buffer.getInt(0); } }; do { buffer.putInt(0, i); try { oldHeaderNameValidationAlgorithmAsciiString(asciiString); } catch (IllegalArgumentException ignore) { assertNotEquals(-1, validateToken(asciiString), failureMessageSupplier); assertNotEquals(-1, validateToken(charSequence), failureMessageSupplier); } i++; } while (i != Integer.MIN_VALUE); }
public String doLayout(ILoggingEvent event) { if (!isStarted()) { return CoreConstants.EMPTY_STRING; } return writeLoopOnConverters(event); }
@Test public void testCompositePattern() { pl.setPattern("%-56(%d %lo{20}) - %m%n"); pl.start(); String val = pl.doLayout(getEventObject()); // 2008-03-18 21:55:54,250 c.q.l.c.pattern.ConverterTest - Some message String regex = ISO_REGEX + " c.q.l.c.p.ConverterTest - Some message\\s*"; assertTrue(val.matches(regex)); }
@GetMapping("/search") @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE) public List<String> searchUsersLikeUsername(@RequestParam String username) { return userDetailsService.findUserLikeUsername(username); }
@Test void testSearchUsersLikeUsername() { List<String> test = new ArrayList<>(1); when(userDetailsService.findUserLikeUsername(anyString())).thenReturn(test); List<String> list = userController.searchUsersLikeUsername("nacos"); assertEquals(test, list); }
TreePSet<E> underlying() { return underlying; }
@Test public void testUnderlying() { assertSame(SINGLETON_SET, new PCollectionsImmutableNavigableSet<>(SINGLETON_SET).underlying()); }
public final HttpClient cookie(Cookie cookie) { Objects.requireNonNull(cookie, "cookie"); if (!cookie.value().isEmpty()) { HttpClient dup = duplicate(); HttpHeaders headers = configuration().headers.copy(); headers.add(HttpHeaderNames.COOKIE, dup.configuration().cookieEncoder.encode(cookie)); dup.configuration().headers = headers; return dup; } return this; }
@Test @SuppressWarnings({"CollectionUndefinedEquality", "deprecation"}) void testCookie() { disposableServer = createServer() .host("localhost") .route(r -> r.get("/201", (req, res) -> res.addHeader("test", req.cookies() // Suppressed "CollectionUndefinedEquality", the CharSequence is String .get("test") .stream() .findFirst() .get() .value()) .status(HttpResponseStatus.CREATED) .sendHeaders())) .bindNow(); createHttpClientForContextWithAddress() .cookie("test", c -> c.setValue("lol")) .get() .uri("/201") .responseContent() .blockLast(Duration.ofSeconds(5)); }
@Override public void broadcastRecord(ByteBuffer record) throws IOException { broadcast(record, Buffer.DataType.DATA_BUFFER); }
@Test void testMetricsUpdateForBroadcastOnlyResultPartition() throws Exception { BufferPool bufferPool = globalPool.createBufferPool(3, 3); try (HsResultPartition partition = createHsResultPartition(2, bufferPool, true)) { partition.broadcastRecord(ByteBuffer.allocate(bufferSize)); assertThat(taskIOMetricGroup.getNumBuffersOutCounter().getCount()).isEqualTo(1); assertThat(taskIOMetricGroup.getNumBytesOutCounter().getCount()).isEqualTo(bufferSize); IOMetrics ioMetrics = taskIOMetricGroup.createSnapshot(); assertThat(ioMetrics.getResultPartitionBytes()).hasSize(1); ResultPartitionBytes partitionBytes = ioMetrics.getResultPartitionBytes().values().iterator().next(); assertThat(partitionBytes.getSubpartitionBytes()) .containsExactly((long) bufferSize, (long) bufferSize); } }
public HazelcastMemberBuilder setProcessId(ProcessId p) { if (p == ProcessId.ELASTICSEARCH) { throw new IllegalArgumentException("Hazelcast must not be enabled on Elasticsearch node"); } this.processId = p; return this; }
@Test public void fail_if_elasticsearch_process() { var builder = new HazelcastMemberBuilder(JoinConfigurationType.TCP_IP); assertThatThrownBy(() -> builder.setProcessId(ProcessId.ELASTICSEARCH)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Hazelcast must not be enabled on Elasticsearch node"); }
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } return results; }
@Test public void twilightForestOptiFineIncompatible() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/crash-report/mod/twilightforest_optifine_incompatibility.txt")), CrashReportAnalyzer.Rule.TWILIGHT_FOREST_OPTIFINE); }
public PluginRuntime addInfo(String name, Object value) { infoList.add(new Info(name, value)); return this; }
@Test public void test() { PluginRuntime runtime = new PluginRuntime("test"); Assert.assertEquals("test", runtime.getPluginId()); Assert.assertTrue(runtime.getInfoList().isEmpty()); runtime.addInfo("item", "item"); PluginRuntime.Info info = runtime.getInfoList().get(0); Assert.assertEquals("item", info.getName()); Assert.assertEquals("item", info.getValue()); }
@Override public int hashCode() { return label.hashCode(); }
@Test void requireThatHashCodeIsImplemented() { assertEquals(new RangePartition("foo=0-9").hashCode(), new RangePartition("foo=0-9").hashCode()); }
public synchronized <K, V> KStream<K, V> stream(final String topic) { return stream(Collections.singleton(topic)); }
@Test public void shouldThrowWhenSubscribedToAPatternWithDifferentResetPolicies() { builder.stream(Pattern.compile("some-regex"), Consumed.with(AutoOffsetReset.EARLIEST)); builder.stream(Pattern.compile("some-regex"), Consumed.with(AutoOffsetReset.LATEST)); assertThrows(TopologyException.class, builder::build); }
public int getLockRetryInterval() { return lockRetryInterval; }
@Test public void testGetLockRetryInterval() { GlobalLockConfig config = new GlobalLockConfig(); config.setLockRetryInterval(1000); assertEquals(1000, config.getLockRetryInterval()); }
@Udf(description = "Returns the correctly rounded positive square root of a DOUBLE value") public Double sqrt( @UdfParameter( value = "value", description = "The value to get the square root of." ) final Integer value ) { return sqrt(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleNegative() { assertThat(Double.isNaN(udf.sqrt(-6.0)), is(true)); }
@Override @Transactional(rollbackFor = Exception.class) @LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_CREATE_SUB_TYPE, bizNo = "{{#role.id}}", success = SYSTEM_ROLE_CREATE_SUCCESS) public Long createRole(RoleSaveReqVO createReqVO, Integer type) { // 1. 校验角色 validateRoleDuplicate(createReqVO.getName(), createReqVO.getCode(), null); // 2. 插入到数据库 RoleDO role = BeanUtils.toBean(createReqVO, RoleDO.class) .setType(ObjectUtil.defaultIfNull(type, RoleTypeEnum.CUSTOM.getType())) .setStatus(CommonStatusEnum.ENABLE.getStatus()) .setDataScope(DataScopeEnum.ALL.getScope()); // 默认可查看所有数据。原因是,可能一些项目不需要项目权限 roleMapper.insert(role); // 3. 记录操作日志上下文 LogRecordContext.putVariable("role", role); return role.getId(); }
@Test public void testCreateRole() { // 准备参数 RoleSaveReqVO reqVO = randomPojo(RoleSaveReqVO.class) .setId(null); // 防止 id 被赋值 // 调用 Long roleId = roleService.createRole(reqVO, null); // 断言 RoleDO roleDO = roleMapper.selectById(roleId); assertPojoEquals(reqVO, roleDO, "id"); assertEquals(RoleTypeEnum.CUSTOM.getType(), roleDO.getType()); assertEquals(CommonStatusEnum.ENABLE.getStatus(), roleDO.getStatus()); assertEquals(DataScopeEnum.ALL.getScope(), roleDO.getDataScope()); }
protected final void ensureCapacity(final int index, final int length) { if (index < 0 || length < 0) { throw new IndexOutOfBoundsException("negative value: index=" + index + " length=" + length); } final long resultingPosition = index + (long)length; final int currentCapacity = capacity; if (resultingPosition > currentCapacity) { if (resultingPosition > MAX_BUFFER_LENGTH) { throw new IndexOutOfBoundsException( "index=" + index + " length=" + length + " maxCapacity=" + MAX_BUFFER_LENGTH); } final int newCapacity = calculateExpansion(currentCapacity, resultingPosition); final ByteBuffer newBuffer = ByteBuffer.allocateDirect(newCapacity); final long newAddress = address(newBuffer); getBytes(0, newBuffer, 0, currentCapacity); byteBuffer = newBuffer; addressOffset = newAddress; capacity = newCapacity; } }
@Test void ensureCapacityThrowsIndexOutOfBoundsExceptionIfLengthIsNegative() { final ExpandableDirectByteBuffer buffer = new ExpandableDirectByteBuffer(1); final IndexOutOfBoundsException exception = assertThrowsExactly(IndexOutOfBoundsException.class, () -> buffer.ensureCapacity(8, -100)); assertEquals("negative value: index=8 length=-100", exception.getMessage()); }
public Optional<Column> findValueColumn(final ColumnName columnName) { return findColumnMatching(withNamespace(VALUE).and(withName(columnName))); }
@Test public void shouldNotGetMetaColumnFromValue() { assertThat(SOME_SCHEMA.findValueColumn(ROWTIME_NAME), is(Optional.empty())); assertThat(SOME_SCHEMA.findValueColumn(ROWPARTITION_NAME), is(Optional.empty())); assertThat(SOME_SCHEMA.findValueColumn(ROWOFFSET_NAME), is(Optional.empty())); }
public List<String> getAllAclFiles(String path) { if (!new File(path).exists()) { log.info("The default acl dir {} is not exist", path); return new ArrayList<>(); } List<String> allAclFileFullPath = new ArrayList<>(); File file = new File(path); File[] files = file.listFiles(); for (int i = 0; files != null && i < files.length; i++) { String fileName = files[i].getAbsolutePath(); File f = new File(fileName); if (fileName.equals(fileHome + MixAll.ACL_CONF_TOOLS_FILE)) { continue; } else if (fileName.endsWith(".yml") || fileName.endsWith(".yaml")) { allAclFileFullPath.add(fileName); } else if (f.isDirectory()) { allAclFileFullPath.addAll(getAllAclFiles(fileName)); } } return allAclFileFullPath; }
@Test public void getAllAclFilesTest() { final List<String> notExistList = plainPermissionManager.getAllAclFiles("aa/bb"); Assertions.assertThat(notExistList).isEmpty(); final List<String> files = plainPermissionManager.getAllAclFiles(confHome.getAbsolutePath()); Assertions.assertThat(files).isNotEmpty(); }
@Override protected long getSleepTime() { int count = getAttemptCount(); if (count >= 30) { // current logic overflows at 30, so set value to max return mMaxSleepMs; } else { // use randomness to avoid contention between many operations using the same retry policy int sleepMs = mBaseSleepTimeMs * (ThreadLocalRandom.current().nextInt(1 << count, 1 << (count + 1))); return Math.min(Math.abs(sleepMs), mMaxSleepMs); } }
@Test public void largeRetriesProducePositiveTime() { int max = 1000; MockExponentialBackoffRetry backoff = new MockExponentialBackoffRetry(50, Integer.MAX_VALUE, max); for (int i = 0; i < max; i++) { backoff.setRetryCount(i); long time = backoff.getSleepTime(); assertTrue("Time must always be positive: " + time, time > 0); } }
@Override public OutputStream getOutputStream(boolean append) throws AccessDeniedException { final NSURL resolved; try { resolved = this.lock(this.exists()); if(null == resolved) { return super.getOutputStream(append); } } catch(LocalAccessDeniedException e) { log.warn(String.format("Failure obtaining lock for %s. %s", this, e)); return super.getOutputStream(append); } return new LockReleaseProxyOutputStream(super.getOutputStream(resolved.path(), append), resolved, append); }
@Test public void testWriteExistingFile() throws Exception { final FinderLocal file = new FinderLocal(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random()); new DefaultLocalTouchFeature().touch(file); final OutputStream out = file.getOutputStream(false); out.close(); file.delete(); }
protected static boolean isMissingKey( final String string ) { return string == null || ( string.trim().startsWith( "!" ) && string.trim().endsWith( "!" ) && !string.trim().equals( "!" ) ); }
@Test public void isMissingKey() { Assert.assertTrue( GlobalMessageUtil.isMissingKey( null ) ); Assert.assertFalse( GlobalMessageUtil.isMissingKey( "" ) ); Assert.assertFalse( GlobalMessageUtil.isMissingKey( " " ) ); Assert.assertTrue( GlobalMessageUtil.isMissingKey( "!foo!" ) ); Assert.assertTrue( GlobalMessageUtil.isMissingKey( "!foo! " ) ); Assert.assertTrue( GlobalMessageUtil.isMissingKey( " !foo!" ) ); Assert.assertFalse( GlobalMessageUtil.isMissingKey( "!foo" ) ); Assert.assertFalse( GlobalMessageUtil.isMissingKey( "foo!" ) ); Assert.assertFalse( GlobalMessageUtil.isMissingKey( "foo" ) ); Assert.assertFalse( GlobalMessageUtil.isMissingKey( "!" ) ); Assert.assertFalse( GlobalMessageUtil.isMissingKey( " !" ) ); }
@Override public PipelineDef parse(Path pipelineDefPath, Configuration globalPipelineConfig) throws Exception { return parse(mapper.readTree(pipelineDefPath.toFile()), globalPipelineConfig); }
@Test void testMinimizedDefinition() throws Exception { URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml"); YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser(); PipelineDef pipelineDef = parser.parse(Paths.get(resource.toURI()), new Configuration()); assertThat(pipelineDef).isEqualTo(minimizedDef); }
public static List<AuthMethodConfig> parse(final String methods, final Map<String, String> replacements) { try { if (methods == null || methods.isEmpty()) { return Collections.emptyList(); } final List<AuthMethodConfig> ret = new ArrayList<AuthMethodConfig>(); String[] parts = methods.split(","); for (String part : parts) { if (part.isEmpty()) { continue; } int index = part.indexOf('?'); if (index == -1) { ret.add(createAuthMethodConfig(part, replacements)); } else { final String name = part.substring(0, index); Map<String, Deque<String>> props = QueryParameterUtils.parseQueryString(part.substring(index + 1), UTF_8); final AuthMethodConfig authMethodConfig = createAuthMethodConfig(name, replacements); for (Map.Entry<String, Deque<String>> entry : props.entrySet()) { Deque<String> val = entry.getValue(); if (val.isEmpty()) { authMethodConfig.getProperties().put(entry.getKey(), ""); } else { authMethodConfig.getProperties().put(entry.getKey(), val.getFirst()); } } ret.add(authMethodConfig); } } return ret; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
@Test public void testPEMEncoded() throws Exception { String pemOrig = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClH5+52mqHLdChbOfzuyue5FSDl2n1mOkpMlF1676NT79AScHVMi1Io" + "hWkuSe3W+oPLE+GAwyyr0DyolUmTkrhrMID6LamgmH8IzhOeyaxDOjwbCIUeGM1V9Qht+nTneRMhGa/oL687XioZiE1Ev52D8kMa" + "KMNMHprL9oOZ/QM4wIDAQAB"; String pemEnc = URLEncoder.encode(pemOrig, "UTF-8"); HashMap<String, String> props = new HashMap<>(); List<AuthMethodConfig> authMethodConfigs = AuthMethodParser.parse("CUSTOM?publicKey="+pemEnc, props); AuthMethodConfig authMethodConfig = authMethodConfigs.get(0); String pemDecode = authMethodConfig.getProperties().get("publicKey"); Assert.assertEquals("publicKey = pemOrig; failed probably due https://issues.jboss.org/browse/WFLY-9135", pemOrig, pemDecode); }
@GetMapping("/config") public Result<ConfigInfo> getConfig(ConfigInfo configInfo) { if (StringUtils.isEmpty(configInfo.getGroup()) || StringUtils.isEmpty(configInfo.getKey())) { return new Result<>(ResultCodeType.MISS_PARAM.getCode(), ResultCodeType.MISS_PARAM.getMessage()); } return configService.getConfig(configInfo); }
@Test public void getConfig() { Result<ConfigInfo> result = configController.getConfig(configInfo); Assert.assertTrue(result.isSuccess()); Assert.assertNotNull(result.getData()); ConfigInfo info = result.getData(); Assert.assertEquals(info.getKey(), KEY); Assert.assertEquals(info.getGroup(), GROUP); Assert.assertEquals(info.getServiceName(), SERVICE_NAME); Assert.assertEquals(info.getContent(), CONTENT); }
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = DODGY_PROTECT_PATTERN.matcher(message); Matcher dodgyBreakMatcher = DODGY_BREAK_PATTERN.matcher(message); Matcher bindingNecklaceCheckMatcher = BINDING_CHECK_PATTERN.matcher(message); Matcher bindingNecklaceUsedMatcher = BINDING_USED_PATTERN.matcher(message); Matcher ringOfForgingCheckMatcher = RING_OF_FORGING_CHECK_PATTERN.matcher(message); Matcher amuletOfChemistryCheckMatcher = AMULET_OF_CHEMISTRY_CHECK_PATTERN.matcher(message); Matcher amuletOfChemistryUsedMatcher = AMULET_OF_CHEMISTRY_USED_PATTERN.matcher(message); Matcher amuletOfChemistryBreakMatcher = AMULET_OF_CHEMISTRY_BREAK_PATTERN.matcher(message); Matcher amuletOfBountyCheckMatcher = AMULET_OF_BOUNTY_CHECK_PATTERN.matcher(message); Matcher amuletOfBountyUsedMatcher = AMULET_OF_BOUNTY_USED_PATTERN.matcher(message); Matcher chronicleAddMatcher = CHRONICLE_ADD_PATTERN.matcher(message); Matcher chronicleUseAndCheckMatcher = CHRONICLE_USE_AND_CHECK_PATTERN.matcher(message); Matcher slaughterActivateMatcher = BRACELET_OF_SLAUGHTER_ACTIVATE_PATTERN.matcher(message); Matcher slaughterCheckMatcher = BRACELET_OF_SLAUGHTER_CHECK_PATTERN.matcher(message); Matcher expeditiousActivateMatcher = EXPEDITIOUS_BRACELET_ACTIVATE_PATTERN.matcher(message); Matcher expeditiousCheckMatcher = EXPEDITIOUS_BRACELET_CHECK_PATTERN.matcher(message); Matcher bloodEssenceCheckMatcher = BLOOD_ESSENCE_CHECK_PATTERN.matcher(message); Matcher bloodEssenceExtractMatcher = BLOOD_ESSENCE_EXTRACT_PATTERN.matcher(message); Matcher braceletOfClayCheckMatcher = BRACELET_OF_CLAY_CHECK_PATTERN.matcher(message); if (message.contains(RING_OF_RECOIL_BREAK_MESSAGE)) { notifier.notify(config.recoilNotification(), "Your Ring of Recoil has shattered"); } else if (dodgyBreakMatcher.find()) { notifier.notify(config.dodgyNotification(), "Your dodgy necklace has crumbled to dust."); updateDodgyNecklaceCharges(MAX_DODGY_CHARGES); } else if (dodgyCheckMatcher.find()) { updateDodgyNecklaceCharges(Integer.parseInt(dodgyCheckMatcher.group(1))); } else if (dodgyProtectMatcher.find()) { updateDodgyNecklaceCharges(Integer.parseInt(dodgyProtectMatcher.group(1))); } else if (amuletOfChemistryCheckMatcher.find()) { updateAmuletOfChemistryCharges(Integer.parseInt(amuletOfChemistryCheckMatcher.group(1))); } else if (amuletOfChemistryUsedMatcher.find()) { final String match = amuletOfChemistryUsedMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateAmuletOfChemistryCharges(charges); } else if (amuletOfChemistryBreakMatcher.find()) { notifier.notify(config.amuletOfChemistryNotification(), "Your amulet of chemistry has crumbled to dust."); updateAmuletOfChemistryCharges(MAX_AMULET_OF_CHEMISTRY_CHARGES); } else if (amuletOfBountyCheckMatcher.find()) { updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyCheckMatcher.group(1))); } else if (amuletOfBountyUsedMatcher.find()) { updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyUsedMatcher.group(1))); } else if (message.equals(AMULET_OF_BOUNTY_BREAK_TEXT)) { updateAmuletOfBountyCharges(MAX_AMULET_OF_BOUNTY_CHARGES); } else if (message.contains(BINDING_BREAK_TEXT)) { notifier.notify(config.bindingNotification(), BINDING_BREAK_TEXT); // This chat message triggers before the used message so add 1 to the max charges to ensure proper sync updateBindingNecklaceCharges(MAX_BINDING_CHARGES + 1); } else if (bindingNecklaceUsedMatcher.find()) { final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); if (equipment.contains(ItemID.BINDING_NECKLACE)) { updateBindingNecklaceCharges(getItemCharges(ItemChargeConfig.KEY_BINDING_NECKLACE) - 1); } } else if (bindingNecklaceCheckMatcher.find()) { final String match = bindingNecklaceCheckMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateBindingNecklaceCharges(charges); } else if (ringOfForgingCheckMatcher.find()) { final String match = ringOfForgingCheckMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateRingOfForgingCharges(charges); } else if (message.equals(RING_OF_FORGING_USED_TEXT) || message.equals(RING_OF_FORGING_VARROCK_PLATEBODY)) { final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY); final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); // Determine if the player smelted with a Ring of Forging equipped. if (equipment == null) { return; } if (equipment.contains(ItemID.RING_OF_FORGING) && (message.equals(RING_OF_FORGING_USED_TEXT) || inventory.count(ItemID.IRON_ORE) > 1)) { int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_RING_OF_FORGING) - 1, 0, MAX_RING_OF_FORGING_CHARGES); updateRingOfForgingCharges(charges); } } else if (message.equals(RING_OF_FORGING_BREAK_TEXT)) { notifier.notify(config.ringOfForgingNotification(), "Your ring of forging has melted."); // This chat message triggers before the used message so add 1 to the max charges to ensure proper sync updateRingOfForgingCharges(MAX_RING_OF_FORGING_CHARGES + 1); } else if (chronicleAddMatcher.find()) { final String match = chronicleAddMatcher.group(1); if (match.equals("one")) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1); } else { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(match)); } } else if (chronicleUseAndCheckMatcher.find()) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(chronicleUseAndCheckMatcher.group(1))); } else if (message.equals(CHRONICLE_ONE_CHARGE_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1); } else if (message.equals(CHRONICLE_EMPTY_TEXT) || message.equals(CHRONICLE_NO_CHARGES_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 0); } else if (message.equals(CHRONICLE_FULL_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1000); } else if (slaughterActivateMatcher.find()) { final String found = slaughterActivateMatcher.group(1); if (found == null) { updateBraceletOfSlaughterCharges(MAX_SLAYER_BRACELET_CHARGES); notifier.notify(config.slaughterNotification(), BRACELET_OF_SLAUGHTER_BREAK_TEXT); } else { updateBraceletOfSlaughterCharges(Integer.parseInt(found)); } } else if (slaughterCheckMatcher.find()) { updateBraceletOfSlaughterCharges(Integer.parseInt(slaughterCheckMatcher.group(1))); } else if (expeditiousActivateMatcher.find()) { final String found = expeditiousActivateMatcher.group(1); if (found == null) { updateExpeditiousBraceletCharges(MAX_SLAYER_BRACELET_CHARGES); notifier.notify(config.expeditiousNotification(), EXPEDITIOUS_BRACELET_BREAK_TEXT); } else { updateExpeditiousBraceletCharges(Integer.parseInt(found)); } } else if (expeditiousCheckMatcher.find()) { updateExpeditiousBraceletCharges(Integer.parseInt(expeditiousCheckMatcher.group(1))); } else if (bloodEssenceCheckMatcher.find()) { updateBloodEssenceCharges(Integer.parseInt(bloodEssenceCheckMatcher.group(1))); } else if (bloodEssenceExtractMatcher.find()) { updateBloodEssenceCharges(getItemCharges(ItemChargeConfig.KEY_BLOOD_ESSENCE) - Integer.parseInt(bloodEssenceExtractMatcher.group(1))); } else if (message.contains(BLOOD_ESSENCE_ACTIVATE_TEXT)) { updateBloodEssenceCharges(MAX_BLOOD_ESSENCE_CHARGES); } else if (braceletOfClayCheckMatcher.find()) { updateBraceletOfClayCharges(Integer.parseInt(braceletOfClayCheckMatcher.group(1))); } else if (message.equals(BRACELET_OF_CLAY_USE_TEXT) || message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN)) { final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); // Determine if the player mined with a Bracelet of Clay equipped. if (equipment != null && equipment.contains(ItemID.BRACELET_OF_CLAY)) { final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY); // Charge is not used if only 1 inventory slot is available when mining in Prifddinas boolean ignore = inventory != null && inventory.count() == 27 && message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN); if (!ignore) { int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_BRACELET_OF_CLAY) - 1, 0, MAX_BRACELET_OF_CLAY_CHARGES); updateBraceletOfClayCharges(charges); } } } else if (message.equals(BRACELET_OF_CLAY_BREAK_TEXT)) { notifier.notify(config.braceletOfClayNotification(), "Your bracelet of clay has crumbled to dust"); updateBraceletOfClayCharges(MAX_BRACELET_OF_CLAY_CHARGES); } } }
@Test public void testChemistry1() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_AMULET_OF_CHEMISTRY_1, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_AMULET_OF_CHEMISTRY, 1); }
static GlobalPhaseSetup maybeMakeSetup(RankProfilesConfig.Rankprofile rp, RankProfilesEvaluator modelEvaluator) { var model = modelEvaluator.modelForRankProfile(rp.name()); Map<String, RankProfilesConfig.Rankprofile.Normalizer> availableNormalizers = new HashMap<>(); for (var n : rp.normalizer()) { availableNormalizers.put(n.name(), n); } Supplier<FunctionEvaluator> functionEvaluatorSource = null; int rerankCount = -1; Set<String> namesToHide = new HashSet<>(); Set<String> matchFeatures = new HashSet<>(); Map<String, String> renameFeatures = new HashMap<>(); String toRename = null; for (var prop : rp.fef().property()) { if (prop.name().equals("vespa.globalphase.rerankcount")) { rerankCount = Integer.parseInt(prop.value()); } if (prop.name().equals("vespa.rank.globalphase")) { functionEvaluatorSource = () -> model.evaluatorOf("globalphase"); } if (prop.name().equals("vespa.hidden.matchfeature")) { namesToHide.add(prop.value()); } if (prop.name().equals("vespa.match.feature")) { matchFeatures.add(prop.value()); } if (prop.name().equals("vespa.feature.rename")) { if (toRename == null) { toRename = prop.value(); } else { renameFeatures.put(toRename, prop.value()); toRename = null; } } } if (rerankCount < 0) { rerankCount = 100; } if (functionEvaluatorSource != null) { var mainResolver = new InputResolver(matchFeatures, renameFeatures, availableNormalizers.keySet()); var evaluator = functionEvaluatorSource.get(); var allInputs = List.copyOf(evaluator.function().arguments()); mainResolver.resolve(allInputs); List<NormalizerSetup> normalizers = new ArrayList<>(); for (var input : mainResolver.usedNormalizers) { var cfg = availableNormalizers.get(input); String normInput = cfg.input(); if (matchFeatures.contains(normInput) || renameFeatures.containsValue(normInput)) { Supplier<Evaluator> normSource = () -> new DummyEvaluator(normInput); normalizers.add(makeNormalizerSetup(cfg, matchFeatures, renameFeatures, normSource, List.of(normInput), rerankCount)); } else { Supplier<FunctionEvaluator> normSource = () -> model.evaluatorOf(normInput); var normInputs = List.copyOf(normSource.get().function().arguments()); var normSupplier = SimpleEvaluator.wrap(normSource); normalizers.add(makeNormalizerSetup(cfg, matchFeatures, renameFeatures, normSupplier, normInputs, rerankCount)); } } Supplier<Evaluator> supplier = SimpleEvaluator.wrap(functionEvaluatorSource); var gfun = new FunEvalSpec(supplier, mainResolver.fromQuery, mainResolver.fromMF); var defaultValues = extraDefaultQueryFeatureValues(rp, mainResolver.fromQuery, normalizers); return new GlobalPhaseSetup(gfun, rerankCount, namesToHide, normalizers, defaultValues); } return null; }
@Test void mediumAdvancedSetup() { RankProfilesConfig rpCfg = readConfig("medium"); assertEquals(1, rpCfg.rankprofile().size()); RankProfilesEvaluator rpEvaluator = createEvaluator(rpCfg); var setup = GlobalPhaseSetup.maybeMakeSetup(rpCfg.rankprofile().get(0), rpEvaluator); assertNotNull(setup); assertEquals(42, setup.rerankCount); assertEquals(0, setup.normalizers.size()); assertEquals(9, setup.matchFeaturesToHide.size()); assertEquals(1, setup.globalPhaseEvalSpec.fromQuery().size()); var wantMF = setup.globalPhaseEvalSpec.fromMF(); assertEquals(8, wantMF.size()); wantMF.sort((a, b) -> a.matchFeatureName().compareTo(b.matchFeatureName())); assertEquals("attribute(t1)", wantMF.get(0).matchFeatureName()); assertEquals("attribute(t1)", wantMF.get(0).inputName()); assertEquals("myplus", wantMF.get(5).matchFeatureName()); assertEquals("rankingExpression(myplus)", wantMF.get(5).inputName()); }
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void literalVariableLiteral() throws ScanException { Tokenizer tokenizer = new Tokenizer("a${b}c"); Parser parser = new Parser(tokenizer.tokenize()); Node node = parser.parse(); Node witness = new Node(Node.Type.LITERAL, "a"); witness.next = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b")); witness.next.next = new Node(Node.Type.LITERAL, "c"); assertEquals(witness, node); }
@Override public CheckResult runCheck() { try { // Create an absolute range from the relative range to make sure it doesn't change during the two // search requests. (count and find messages) // This is needed because the RelativeRange computes the range from NOW on every invocation of getFrom() and // getTo(). // See: https://github.com/Graylog2/graylog2-server/issues/2382 final RelativeRange relativeRange = RelativeRange.create(time * 60); final AbsoluteRange range = AbsoluteRange.create(relativeRange.getFrom(), relativeRange.getTo()); final String filter = buildQueryFilter(stream.getId(), query); final CountResult result = searches.count("*", range, filter); final long count = result.count(); LOG.debug("Alert check <{}> result: [{}]", id, count); final boolean triggered; switch (thresholdType) { case MORE: triggered = count > threshold; break; case LESS: triggered = count < threshold; break; default: triggered = false; } if (triggered) { final List<MessageSummary> summaries = Lists.newArrayList(); if (getBacklog() > 0) { final SearchResult backlogResult = searches.search("*", filter, range, getBacklog(), 0, new Sorting(Message.FIELD_TIMESTAMP, Sorting.Direction.DESC)); for (ResultMessage resultMessage : backlogResult.getResults()) { final Message msg = resultMessage.getMessage(); summaries.add(new MessageSummary(resultMessage.getIndex(), msg)); } } final String resultDescription = "Stream had " + count + " messages in the last " + time + " minutes with trigger condition " + thresholdType.toString().toLowerCase(Locale.ENGLISH) + " than " + threshold + " messages. " + "(Current grace time: " + grace + " minutes)"; return new CheckResult(true, this, resultDescription, Tools.nowUTC(), summaries); } else { return new NegativeCheckResult(); } } catch (InvalidRangeParametersException e) { // cannot happen lol LOG.error("Invalid timerange.", e); return null; } }
@Test public void testRunCheckMoreNegative() throws Exception { final MessageCountAlertCondition.ThresholdType type = MessageCountAlertCondition.ThresholdType.MORE; final MessageCountAlertCondition messageCountAlertCondition = getConditionWithParameters(type, threshold); searchCountShouldReturn(threshold); final AlertCondition.CheckResult result = messageCountAlertCondition.runCheck(); assertNotTriggered(result); }
static ImmutableList<PushImageStep> makeListForManifestList( BuildContext buildContext, ProgressEventDispatcher.Factory progressEventDispatcherFactory, RegistryClient registryClient, ManifestTemplate manifestList, boolean manifestListAlreadyExists) throws IOException { Set<String> tags = buildContext.getAllTargetImageTags(); EventHandlers eventHandlers = buildContext.getEventHandlers(); try (TimerEventDispatcher ignored = new TimerEventDispatcher(eventHandlers, "Preparing manifest list pushers"); ProgressEventDispatcher progressEventDispatcher = progressEventDispatcherFactory.create("launching manifest list pushers", tags.size())) { boolean singlePlatform = buildContext.getContainerConfiguration().getPlatforms().size() == 1; if (singlePlatform) { return ImmutableList.of(); // single image; no need to push a manifest list } if (JibSystemProperties.skipExistingImages() && manifestListAlreadyExists) { eventHandlers.dispatch(LogEvent.info("Skipping pushing manifest list; already exists.")); return ImmutableList.of(); } DescriptorDigest manifestListDigest = Digests.computeJsonDigest(manifestList); return tags.stream() .map( tag -> new PushImageStep( buildContext, progressEventDispatcher.newChildProducer(), registryClient, manifestList, tag, manifestListDigest, // TODO: a manifest list digest isn't an "image id". Figure out the right // return value and type. manifestListDigest)) .collect(ImmutableList.toImmutableList()); } }
@Test public void testMakeListForManifestList() throws IOException, RegistryException { List<PushImageStep> pushImageStepList = PushImageStep.makeListForManifestList( buildContext, progressDispatcherFactory, registryClient, manifestList, false); assertThat(pushImageStepList).hasSize(2); for (PushImageStep pushImageStep : pushImageStepList) { BuildResult buildResult = pushImageStep.call(); assertThat(buildResult.getImageDigest().toString()) .isEqualTo("sha256:64303e82b8a80ef20475dc7f807b81f172cacce1a59191927f3a7ea5222f38ae"); assertThat(buildResult.getImageId().toString()) .isEqualTo("sha256:64303e82b8a80ef20475dc7f807b81f172cacce1a59191927f3a7ea5222f38ae"); } }
public static int getMaxMagicOffset() { return maxMagicOffset; }
@Test public void getMaxMagicOffset() throws Exception { }
@Override public void putTaskConfigs(final String connName, final List<Map<String, String>> configs, final Callback<Void> callback, InternalRequestSignature requestSignature) { log.trace("Submitting put task configuration request {}", connName); if (requestNotSignedProperly(requestSignature, callback)) { return; } addRequest( () -> { if (!isLeader()) callback.onCompletion(new NotLeaderException("Only the leader may write task configurations.", leaderUrl()), null); else if (!configState.contains(connName)) callback.onCompletion(new NotFoundException("Connector " + connName + " not found"), null); else { writeTaskConfigs(connName, configs); callback.onCompletion(null, null); } return null; }, forwardErrorAndTickThreadStages(callback) ); }
@Test public void testPutTaskConfigsMissingRequiredSignature() { when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V2); Callback<Void> taskConfigCb = mock(Callback.class); herder.putTaskConfigs(CONN1, TASK_CONFIGS, taskConfigCb, null); ArgumentCaptor<Throwable> errorCapture = ArgumentCaptor.forClass(Throwable.class); verify(taskConfigCb).onCompletion(errorCapture.capture(), isNull()); assertInstanceOf(BadRequestException.class, errorCapture.getValue()); verifyNoMoreInteractions(member, taskConfigCb); }
@Override public void completeRequest() { }
@Test public void completeRequest() { final InstanceStats stats = new InstanceStats(); stats.completeRequest(); Assert.assertEquals(stats.getActiveRequests(), 0); }
public static UriTemplate create(String template, Charset charset) { return new UriTemplate(template, true, charset); }
@Test void emptyRelativeTemplate() { String template = "/"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); assertThat(uriTemplate.expand(Collections.emptyMap())).isEqualToIgnoringCase("/"); }
public String migrate(String oldJSON, int targetVersion) { LOGGER.debug("Migrating to version {}: {}", targetVersion, oldJSON); Chainr transform = getTransformerFor(targetVersion); Object transformedObject = transform.transform(JsonUtils.jsonToMap(oldJSON), getContextMap(targetVersion)); String transformedJSON = JsonUtils.toJsonString(transformedObject); LOGGER.debug("After migration to version {}: {}", targetVersion, transformedJSON); return transformedJSON; }
@Test void migrateV2ToV3_shouldAddArtifactOriginOnAllFetchTasks() { ConfigRepoDocumentMother documentMother = new ConfigRepoDocumentMother(); String oldJSON = documentMother.v2WithFetchTask(); String newJson = documentMother.v3WithFetchTask(); String transformedJSON = migrator.migrate(oldJSON, 3); assertThatJson(newJson).isEqualTo(transformedJSON); }
public PrimitiveValue minValue() { return minValue; }
@Test void shouldReturnCorrectMinValueWhenSpecified() throws Exception { final String minVal = "10"; final String testXmlString = "<types>" + " <type name=\"testTypeInt8MinValue\" primitiveType=\"int8\" minValue=\"" + minVal + "\"/>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types/type", testXmlString); assertThat((((EncodedDataType)map.get("testTypeInt8MinValue")).minValue()), is(parse(minVal, PrimitiveType.INT8))); }
public static String mkString(Collection<?> collection, String sep) { return mkString(collection, "", sep, ""); }
@Test public void testMkString() { assertEquals("1, 2, 3, 4", CollectionUtil.mkString(List.of(1, 2, 3, 4), ", ")); }
public void add(final T node) { if ( this.firstNode == null ) { this.firstNode = node; this.lastNode = node; } else { this.lastNode.setNext( node ); node.setPrevious( this.lastNode ); this.lastNode = node; } this.size++; }
@Test public void testAdd() { this.list.add( this.node1 ); assertThat(this.node1.getPrevious()).as("Node1 previous should be null").isNull(); assertThat(this.node1.getNext()).as("Node1 next should be null").isNull(); assertThat(this.node1).as("First node should be node1").isSameAs(this.list.getFirst()); assertThat(this.node1).as("Last node should be node1").isSameAs(this.list.getLast()); this.list.add( this.node2 ); assertThat(this.node2).as("node1 next should be node2").isSameAs(this.node1.getNext()); assertThat(this.node1).as("node2 previous should be node1").isSameAs(this.node2.getPrevious()); assertThat(this.node1).as("First node should be node1").isSameAs(this.list.getFirst()); assertThat(this.node2).as("Last node should be node2").isSameAs(this.list.getLast()); this.list.add( this.node3 ); assertThat(this.node3).as("node2 next should be node3").isSameAs(this.node2.getNext()); assertThat(this.node2).as("node3 previous should be node2").isSameAs(this.node3.getPrevious()); assertThat(this.list.size()).as("LinkedList should have 3 nodes").isEqualTo(3); assertThat(this.node1).as("First node should be node1").isSameAs(this.list.getFirst()); assertThat(this.node3).as("Last node should be node3").isSameAs(this.list.getLast()); }
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void testSiblingsOnResourceRequestBodyMultiple() { Reader reader = new Reader(new SwaggerConfiguration().openAPI(new OpenAPI()).openAPI31(true)); OpenAPI openAPI = reader.read(SiblingsResourceRequestBodyMultiple.class); String yaml = "openapi: 3.1.0\n" + "paths:\n" + " /test/bodyimpl:\n" + " get:\n" + " operationId: getBodyImpl\n" + " requestBody:\n" + " description: aaa\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/PetSimple'\n" + " description: resource pet\n" + " writeOnly: true\n" + " application/xml:\n" + " schema:\n" + " $ref: '#/components/schemas/PetSimple'\n" + " description: resource pet xml\n" + " writeOnly: true\n" + " responses:\n" + " default:\n" + " description: default response\n" + " content:\n" + " '*/*': {}\n" + " /test/bodyimplparam:\n" + " get:\n" + " operationId: getBodyImplParam\n" + " requestBody:\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/PetSimple'\n" + " description: resource pet\n" + " writeOnly: true\n" + " application/xml:\n" + " schema:\n" + " $ref: '#/components/schemas/PetSimple'\n" + " description: resource pet xml\n" + " writeOnly: true\n" + " responses:\n" + " default:\n" + " description: default response\n" + " content:\n" + " '*/*': {}\n" + " /test/bodyparam:\n" + " get:\n" + " operationId: getBodyParam\n" + " requestBody:\n" + " description: test\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/PetSimple'\n" + " description: resource pet\n" + " writeOnly: true\n" + " application/xml:\n" + " schema:\n" + " $ref: '#/components/schemas/PetSimple'\n" + " description: resource pet xml\n" + " writeOnly: true\n" + " responses:\n" + " default:\n" + " description: default response\n" + " content:\n" + " '*/*': {}\n" + "components:\n" + " schemas:\n" + " PetSimple:\n" + " description: Pet\n"; SerializationMatchers.assertEqualsToYaml31(openAPI, yaml); }
int run() { final Map<String, String> configProps = options.getConfigFile() .map(Ksql::loadProperties) .orElseGet(Collections::emptyMap); final Map<String, String> sessionVariables = options.getVariables(); try (KsqlRestClient restClient = buildClient(configProps)) { try (Cli cli = cliBuilder.build( options.getStreamedQueryRowLimit(), options.getStreamedQueryTimeoutMs(), options.getOutputFormat(), restClient) ) { // Add CLI variables If defined by parameters cli.addSessionVariables(sessionVariables); if (options.getExecute().isPresent()) { return cli.runCommand(options.getExecute().get()); } else if (options.getScriptFile().isPresent()) { final File scriptFile = new File(options.getScriptFile().get()); if (scriptFile.exists() && scriptFile.isFile()) { return cli.runScript(scriptFile.getPath()); } else { throw new KsqlException("No such script file: " + scriptFile.getPath()); } } else { return cli.runInteractively(); } } } }
@Test public void shouldStripSslConfigFromConfigFileWhenMakingLocalProperties() throws Exception { // Given: givenConfigFile( "ssl.truststore.location=some/path" + System.lineSeparator() + "ssl.truststore.password=letmein" + System.lineSeparator() + "some.other.setting=value" ); // When: ksql.run(); // Then: verify(clientBuilder).build(any(), eq(ImmutableMap.of("some.other.setting", "value")), any(), any(), any()); }
@Override public void onMultiTapEnded() { mParentListener.listener().onMultiTapEnded(); }
@Test public void testOnMultiTapEnded() { mUnderTest.onMultiTapEnded(); final InOrder inOrder = Mockito.inOrder(mMockParentListener, mMockKeyboardDismissAction); inOrder.verify(mMockParentListener).onMultiTapEnded(); inOrder.verifyNoMoreInteractions(); }
@Override public HttpResponse send(HttpRequest httpRequest) throws IOException { return send(httpRequest, null); }
@Test public void send_whenNoUserAgentInRequest_setsCorrectUserAgentHeader() throws IOException { mockWebServer.setDispatcher(new UserAgentTestDispatcher()); mockWebServer.start(); HttpResponse response = httpClient.send( get(mockWebServer.url(UserAgentTestDispatcher.USERAGENT_TEST_PATH).toString()) .withEmptyHeaders() .build()); assertThat(response.status()).isEqualTo(HttpStatus.OK); }
@Nullable @VisibleForTesting static List<String> computeEntrypoint( RawConfiguration rawConfiguration, ProjectProperties projectProperties, JibContainerBuilder jibContainerBuilder) throws MainClassInferenceException, InvalidAppRootException, IOException, InvalidContainerizingModeException { Optional<List<String>> rawEntrypoint = rawConfiguration.getEntrypoint(); List<String> rawExtraClasspath = rawConfiguration.getExtraClasspath(); boolean entrypointDefined = rawEntrypoint.isPresent() && !rawEntrypoint.get().isEmpty(); if (entrypointDefined && (rawConfiguration.getMainClass().isPresent() || !rawConfiguration.getJvmFlags().isEmpty() || !rawExtraClasspath.isEmpty() || rawConfiguration.getExpandClasspathDependencies())) { projectProperties.log( LogEvent.info( "mainClass, extraClasspath, jvmFlags, and expandClasspathDependencies are ignored " + "when entrypoint is specified")); } if (projectProperties.isWarProject()) { if (entrypointDefined) { return rawEntrypoint.get().size() == 1 && "INHERIT".equals(rawEntrypoint.get().get(0)) ? null : rawEntrypoint.get(); } if (rawConfiguration.getMainClass().isPresent() || !rawConfiguration.getJvmFlags().isEmpty() || !rawExtraClasspath.isEmpty() || rawConfiguration.getExpandClasspathDependencies()) { projectProperties.log( LogEvent.warn( "mainClass, extraClasspath, jvmFlags, and expandClasspathDependencies are ignored " + "for WAR projects")); } return rawConfiguration.getFromImage().isPresent() ? null // Inherit if a custom base image. : Arrays.asList("java", "-jar", "/usr/local/jetty/start.jar", "--module=ee10-deploy"); } List<String> classpath = new ArrayList<>(rawExtraClasspath); AbsoluteUnixPath appRoot = getAppRootChecked(rawConfiguration, projectProperties); ContainerizingMode mode = getContainerizingModeChecked(rawConfiguration, projectProperties); switch (mode) { case EXPLODED: classpath.add(appRoot.resolve("resources").toString()); classpath.add(appRoot.resolve("classes").toString()); break; case PACKAGED: classpath.add(appRoot.resolve("classpath/*").toString()); break; default: throw new IllegalStateException("unknown containerizing mode: " + mode); } if (projectProperties.getMajorJavaVersion() >= 9 || rawConfiguration.getExpandClasspathDependencies()) { List<Path> jars = projectProperties.getDependencies(); Map<String, Long> occurrences = jars.stream() .map(path -> path.getFileName().toString()) .collect(Collectors.groupingBy(filename -> filename, Collectors.counting())); List<String> duplicates = occurrences.entrySet().stream() .filter(entry -> entry.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toList()); for (Path jar : jars) { // Handle duplicates by appending filesize to the end of the file. This renaming logic // must be in sync with the code that does the same in the other place. See // https://github.com/GoogleContainerTools/jib/issues/3331 String jarName = jar.getFileName().toString(); if (duplicates.contains(jarName)) { jarName = jarName.replaceFirst("\\.jar$", "-" + Files.size(jar)) + ".jar"; } classpath.add(appRoot.resolve("libs").resolve(jarName).toString()); } } else { classpath.add(appRoot.resolve("libs/*").toString()); } String classpathString = String.join(":", classpath); String mainClass; try { mainClass = MainClassResolver.resolveMainClass( rawConfiguration.getMainClass().orElse(null), projectProperties); } catch (MainClassInferenceException ex) { if (entrypointDefined) { // We will use the user-given entrypoint, so don't fail. mainClass = "could-not-infer-a-main-class"; } else { throw ex; } } addJvmArgFilesLayer( rawConfiguration, projectProperties, jibContainerBuilder, classpathString, mainClass); if (projectProperties.getMajorJavaVersion() >= 9) { classpathString = "@" + appRoot.resolve(JIB_CLASSPATH_FILE); } if (entrypointDefined) { return rawEntrypoint.get().size() == 1 && "INHERIT".equals(rawEntrypoint.get().get(0)) ? null : rawEntrypoint.get(); } List<String> entrypoint = new ArrayList<>(4 + rawConfiguration.getJvmFlags().size()); entrypoint.add("java"); entrypoint.addAll(rawConfiguration.getJvmFlags()); entrypoint.add("-cp"); entrypoint.add(classpathString); entrypoint.add(mainClass); return entrypoint; }
@Test public void testComputeEntrypoint_default() throws MainClassInferenceException, InvalidAppRootException, IOException, InvalidContainerizingModeException { assertThat( PluginConfigurationProcessor.computeEntrypoint( rawConfiguration, projectProperties, jibContainerBuilder)) .containsExactly( "java", "-cp", "/app/resources:/app/classes:/app/libs/*", "java.lang.Object") .inOrder(); }
public static Set<String> getSegmentNamesForTable(String tableNameWithType, long startTimestamp, long endTimestamp, boolean excludeOverlapping, URI controllerBaseURI, @Nullable AuthProvider authProvider) throws Exception { String rawTableName = TableNameBuilder.extractRawTableName(tableNameWithType); TableType tableType = TableNameBuilder.getTableTypeFromTableName(tableNameWithType); SSLContext sslContext = MinionContext.getInstance().getSSLContext(); try (FileUploadDownloadClient fileUploadDownloadClient = new FileUploadDownloadClient(sslContext)) { Map<String, List<String>> tableTypeToSegmentNames = fileUploadDownloadClient.getSegments(controllerBaseURI, rawTableName, tableType, true, startTimestamp, endTimestamp, excludeOverlapping, authProvider); if (tableTypeToSegmentNames != null && !tableTypeToSegmentNames.isEmpty()) { List<String> allSegmentNameList = tableTypeToSegmentNames.get(tableType.toString()); if (!CollectionUtils.isEmpty(allSegmentNameList)) { return new HashSet<>(allSegmentNameList); } } return Collections.emptySet(); } }
@Test public void testNonExistentSegments() throws Exception { Assert.assertEquals( SegmentConversionUtils.getSegmentNamesForTable(TEST_TABLE_WITHOUT_TYPE + "_" + TEST_TABLE_TYPE, FileUploadDownloadClient.getURI(TEST_SCHEME, TEST_HOST, TEST_PORT), null), ImmutableSet.of(TEST_TABLE_SEGMENT_1, TEST_TABLE_SEGMENT_2)); }
@Override public Mono<DeleteUsernameLinkResponse> deleteUsernameLink(final DeleteUsernameLinkRequest request) { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); return rateLimiters.getUsernameLinkOperationLimiter().validateReactive(authenticatedDevice.accountIdentifier()) .then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))) .map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException)) .flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.setUsernameLinkDetails(null, null)))) .thenReturn(DeleteUsernameLinkResponse.newBuilder().build()); }
@Test void deleteUsernameLink() { final Account account = mock(Account.class); when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI)) .thenReturn(CompletableFuture.completedFuture(Optional.of(account))); assertDoesNotThrow( () -> authenticatedServiceStub().deleteUsernameLink(DeleteUsernameLinkRequest.newBuilder().build())); verify(account).setUsernameLinkDetails(null, null); }
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT); assert shenyuContext != null; ContextMappingRuleHandle ruleHandle = buildRuleHandle(rule); if (Objects.isNull(ruleHandle)) { LOG.error("context path rule configuration is null :{}", rule); return chain.execute(exchange); } buildRealURI(exchange, shenyuContext, ruleHandle); return chain.execute(exchange); }
@Test public void executeTest() { shenyuContext.setPath("/http/context/order/findById"); ContextMappingRuleHandle contextMappingRuleHandle = new ContextMappingRuleHandle(); contextMappingRuleHandle.setContextPath("/http/context"); when(ruleData.getId()).thenReturn("1"); CACHED_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(ruleData), contextMappingRuleHandle); when(ruleData.getHandle()).thenReturn(GsonUtils.getGson().toJson(contextMappingRuleHandle)); contextPathPlugin.doExecute(exchange, chain, selectorData, ruleData); assertEquals("/order/findById", shenyuContext.getRealUrl()); Assertions.assertDoesNotThrow(() -> contextPathPlugin.doExecute(exchange, chain, selectorData, RuleData.builder().name("RuleData").build())); contextMappingRuleHandle.setAddPrefix("/addPrefix"); Assertions.assertDoesNotThrow(() -> contextPathPlugin.doExecute(exchange, chain, selectorData, ruleData)); contextMappingRuleHandle.setContextPath("/context"); Assertions.assertDoesNotThrow(() -> contextPathPlugin.doExecute(exchange, chain, selectorData, ruleData)); shenyuContext.setPath(null); contextMappingRuleHandle.setContextPath(null); Assertions.assertDoesNotThrow(() -> contextPathPlugin.doExecute(exchange, chain, selectorData, ruleData)); }
@Override public List<MultipartUpload> find(final Path file) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("Finding multipart uploads for %s", file)); } final List<MultipartUpload> uploads = new ArrayList<>(); // This operation lists in-progress multipart uploads. An in-progress multipart upload is a // multipart upload that has been initiated, using the Initiate Multipart Upload request, but has // not yet been completed or aborted. String nextUploadIdMarker = null; String nextKeyMarker = null; boolean isTruncated; do { final Path bucket = containerService.getContainer(file); final MultipartUploadChunk chunk; try { chunk = session.getClient().multipartListUploadsChunked( bucket.isRoot() ? StringUtils.EMPTY : bucket.getName(), containerService.getKey(file), String.valueOf(Path.DELIMITER), nextKeyMarker, nextUploadIdMarker, null, false); } catch(S3ServiceException e) { final BackgroundException failure = new S3ExceptionMappingService().map("Upload {0} failed", e, file); if(failure instanceof NotfoundException) { return Collections.emptyList(); } if(failure instanceof InteroperabilityException) { return Collections.emptyList(); } throw failure; } uploads.addAll(Arrays.asList(chunk.getUploads())); if(log.isInfoEnabled()) { log.info(String.format("Found %d previous multipart uploads for %s", uploads.size(), file)); } // Sort with newest upload first in list uploads.sort(new Comparator<MultipartUpload>() { @Override public int compare(final MultipartUpload o1, final MultipartUpload o2) { return -o1.getInitiatedDate().compareTo(o2.getInitiatedDate()); } }); nextKeyMarker = chunk.getPriorLastKey(); nextUploadIdMarker = chunk.getPriorLastIdMarker(); isTruncated = !chunk.isListingComplete(); } while(isTruncated && nextUploadIdMarker != null); if(log.isInfoEnabled()) { for(MultipartUpload upload : uploads) { log.info(String.format("Found multipart upload %s for %s", upload, file)); } } return uploads; }
@Test public void testFind() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Path directory = new S3DirectoryFeature(session, new S3WriteFeature(session, acl), acl).mkdir( new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus()); final S3DefaultMultipartService service = new S3DefaultMultipartService(session); assertTrue(service.find(directory).isEmpty()); final Path file = new Path(directory, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final S3Object object = new S3WriteFeature(session, acl).getDetails(file, new TransferStatus()); final MultipartUpload first = session.getClient().multipartStartUpload(container.getName(), object); assertNotNull(first); assertFalse(service.find(directory).isEmpty()); assertTrue(service.find(new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory))).isEmpty()); assertEquals(first.getUploadId(), service.find(directory).iterator().next().getUploadId()); assertFalse(new S3FindFeature(session, acl).find(file)); final Path upload = new S3ListService(session, acl).list(directory, new DisabledListProgressListener()).find(new SimplePathPredicate(file)); assertNotNull(upload); assertTrue(new S3FindFeature(session, acl).find(upload)); assertTrue(upload.getType().contains(Path.Type.upload)); assertTrue(new S3FindFeature(session, acl).find(upload)); assertNotEquals(PathAttributes.EMPTY, new S3AttributesFinderFeature(session, acl).find(upload)); // Make sure timestamp is later. Thread.sleep(2000L); final MultipartUpload second = session.getClient().multipartStartUpload(container.getName(), object); assertNotNull(second); final MultipartUpload multipart = service.find(file).iterator().next(); assertNotNull(multipart); assertEquals(second.getUploadId(), multipart.getUploadId()); assertNotNull(multipart); service.delete(first); service.delete(second); new S3DefaultDeleteFeature(session).delete(Collections.singletonList(directory), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@Override public Optional<AuthProperty> inferAuth(String registry) throws InferredAuthException { Server server = getServerFromMavenSettings(registry); if (server == null) { return Optional.empty(); } SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(server); SettingsDecryptionResult result = decrypter.decrypt(request); // Un-encrypted passwords are passed through, so a problem indicates a real issue. // If there are any ERROR or FATAL problems reported, then decryption failed. for (SettingsProblem problem : result.getProblems()) { if (problem.getSeverity() == SettingsProblem.Severity.ERROR || problem.getSeverity() == SettingsProblem.Severity.FATAL) { throw new InferredAuthException( "Unable to decrypt server(" + registry + ") info from settings.xml: " + problem); } } Server resultServer = result.getServer(); String username = resultServer.getUsername(); String password = resultServer.getPassword(); return Optional.of( new AuthProperty() { @Override public String getUsername() { return username; } @Override public String getPassword() { return password; } @Override public String getAuthDescriptor() { return CREDENTIAL_SOURCE; } @Override public String getUsernameDescriptor() { return CREDENTIAL_SOURCE; } @Override public String getPasswordDescriptor() { return CREDENTIAL_SOURCE; } }); }
@Test public void testInferredAuth_successUnencrypted() throws InferredAuthException { Optional<AuthProperty> auth = mavenSettingsServerCredentials.inferAuth("simpleServer"); Assert.assertTrue(auth.isPresent()); Assert.assertEquals("simpleUser", auth.get().getUsername()); Assert.assertEquals("password2", auth.get().getPassword()); }
public static Type convertType(TypeInfo typeInfo) { switch (typeInfo.getOdpsType()) { case BIGINT: return Type.BIGINT; case INT: return Type.INT; case SMALLINT: return Type.SMALLINT; case TINYINT: return Type.TINYINT; case FLOAT: return Type.FLOAT; case DECIMAL: DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) typeInfo; return ScalarType.createUnifiedDecimalType(decimalTypeInfo.getPrecision(), decimalTypeInfo.getScale()); case DOUBLE: return Type.DOUBLE; case CHAR: CharTypeInfo charTypeInfo = (CharTypeInfo) typeInfo; return ScalarType.createCharType(charTypeInfo.getLength()); case VARCHAR: VarcharTypeInfo varcharTypeInfo = (VarcharTypeInfo) typeInfo; return ScalarType.createVarcharType(varcharTypeInfo.getLength()); case STRING: case JSON: return ScalarType.createDefaultCatalogString(); case BINARY: return Type.VARBINARY; case BOOLEAN: return Type.BOOLEAN; case DATE: return Type.DATE; case TIMESTAMP: case DATETIME: return Type.DATETIME; case MAP: MapTypeInfo mapTypeInfo = (MapTypeInfo) typeInfo; return new MapType(convertType(mapTypeInfo.getKeyTypeInfo()), convertType(mapTypeInfo.getValueTypeInfo())); case ARRAY: ArrayTypeInfo arrayTypeInfo = (ArrayTypeInfo) typeInfo; return new ArrayType(convertType(arrayTypeInfo.getElementTypeInfo())); case STRUCT: StructTypeInfo structTypeInfo = (StructTypeInfo) typeInfo; List<Type> fieldTypeList = structTypeInfo.getFieldTypeInfos().stream().map(EntityConvertUtils::convertType) .collect(Collectors.toList()); return new StructType(fieldTypeList); default: return Type.VARCHAR; } }
@Test public void testConvertTypeCaseStringAndJson() { TypeInfo typeInfo = TypeInfoFactory.STRING; Type result = EntityConvertUtils.convertType(typeInfo); Type expectedType = ScalarType.createDefaultCatalogString(); assertEquals(expectedType, result); }
@Override public String named() { return PluginEnum.CACHE.getName(); }
@Test public void namedTest() { final CachePlugin cachePlugin = new CachePlugin(); Assertions.assertEquals(cachePlugin.named(), PluginEnum.CACHE.getName()); }
public void setupScanRangeLocations() throws Exception { List<RemoteFileDesc> files = fileTable.getFileDescs(); for (RemoteFileDesc file : files) { addScanRangeLocations(file); } }
@Test public void testSetupScanRangeLocations() throws Exception { class ExtFileTable extends FileTable { public ExtFileTable(Map<String, String> properties) throws DdlException { super(0, "XX", new ArrayList<>(), properties); } @Override public List<RemoteFileDesc> getFileDescsFromHdfs() throws DdlException { List<RemoteFileDesc> fileDescList = new ArrayList<>(); List<RemoteFileBlockDesc> blockDescList = new ArrayList<>(); class Block extends RemoteFileBlockDesc { public Block() { super(0, 0, new long[] {10}, new long[] {20}, null); } @Override public String getDataNodeIp(long hostId) { return "XXX"; } } blockDescList.add(new Block()); RemoteFileDesc fileDesc = new RemoteFileDesc("aa", "snappy", 0, 0, ImmutableList.copyOf(blockDescList)); fileDescList.add(fileDesc); return fileDescList; } } Map<String, String> properties = new HashMap<String, String>() { { put(FileTable.JSON_KEY_FILE_PATH, "hdfs://127.0.0.1:10000/hive/"); put(FileTable.JSON_KEY_COLUMN_SEPARATOR, "XXX"); put(FileTable.JSON_KEY_ROW_DELIMITER, "YYY"); put(FileTable.JSON_KEY_COLLECTION_DELIMITER, "ZZZ"); put(FileTable.JSON_KEY_MAP_DELIMITER, "MMM"); put(FileTable.JSON_KEY_FORMAT, "text"); } }; FileTable table = new ExtFileTable(properties); TupleDescriptor desc = new TupleDescriptor(new TupleId(0)); desc.setTable(table); FileTableScanNode scanNode = new FileTableScanNode(new PlanNodeId(0), desc, "XXX"); scanNode.setupScanRangeLocations(); }
public <T> CompletableFuture<PushNotificationExperimentSample<T>> recordFinalState(final UUID accountIdentifier, final byte deviceId, final String experimentName, final T finalState) { CompletableFuture<String> finalStateJsonFuture; // Process the final state JSON on the calling thread, but inside a CompletionStage so there's just one "channel" // for reporting JSON exceptions. The alternative is to `throw JsonProcessingException`, but then callers would have // to both catch the exception when calling this method and also watch the returned future for the same exception. try { finalStateJsonFuture = CompletableFuture.completedFuture(SystemMapper.jsonMapper().writeValueAsString(finalState)); } catch (final JsonProcessingException e) { finalStateJsonFuture = CompletableFuture.failedFuture(e); } final AttributeValue aciAndDeviceIdAttributeValue = buildSortKey(accountIdentifier, deviceId); return finalStateJsonFuture.thenCompose(finalStateJson -> { return dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder() .tableName(tableName) .key(Map.of( KEY_EXPERIMENT_NAME, AttributeValue.fromS(experimentName), ATTR_ACI_AND_DEVICE_ID, aciAndDeviceIdAttributeValue)) // `UpdateItem` will, by default, create a new item if one does not already exist for the given primary key. We // want update-only-if-exists behavior, though, and so check that there's already an existing item for this ACI // and device ID. .conditionExpression("#aciAndDeviceId = :aciAndDeviceId") .updateExpression("SET #finalState = if_not_exists(#finalState, :finalState)") .expressionAttributeNames(Map.of( "#aciAndDeviceId", ATTR_ACI_AND_DEVICE_ID, "#finalState", ATTR_FINAL_STATE)) .expressionAttributeValues(Map.of( ":aciAndDeviceId", aciAndDeviceIdAttributeValue, ":finalState", AttributeValue.fromS(finalStateJson))) .returnValues(ReturnValue.ALL_NEW) .build()) .thenApply(updateItemResponse -> { try { final boolean inExperimentGroup = updateItemResponse.attributes().get(ATTR_IN_EXPERIMENT_GROUP).bool(); @SuppressWarnings("unchecked") final T parsedInitialState = (T) parseState(updateItemResponse.attributes().get(ATTR_INITIAL_STATE).s(), finalState.getClass()); @SuppressWarnings("unchecked") final T parsedFinalState = (T) parseState(updateItemResponse.attributes().get(ATTR_FINAL_STATE).s(), finalState.getClass()); return new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, parsedInitialState, parsedFinalState); } catch (final JsonProcessingException e) { throw ExceptionUtils.wrap(e); } }); }); }
@Test void recordFinalState() throws JsonProcessingException { final String experimentName = "test-experiment"; final UUID accountIdentifier = UUID.randomUUID(); final byte deviceId = (byte) ThreadLocalRandom.current().nextInt(Device.MAXIMUM_DEVICE_ID); final boolean inExperimentGroup = ThreadLocalRandom.current().nextBoolean(); final int initialBounciness = ThreadLocalRandom.current().nextInt(); final int finalBounciness = initialBounciness + 17; { pushNotificationExperimentSamples.recordInitialState(accountIdentifier, deviceId, experimentName, inExperimentGroup, new TestDeviceState(initialBounciness)) .join(); final PushNotificationExperimentSample<TestDeviceState> returnedSample = pushNotificationExperimentSamples.recordFinalState(accountIdentifier, deviceId, experimentName, new TestDeviceState(finalBounciness)) .join(); final PushNotificationExperimentSample<TestDeviceState> expectedSample = new PushNotificationExperimentSample<>(accountIdentifier, deviceId, inExperimentGroup, new TestDeviceState(initialBounciness), new TestDeviceState(finalBounciness)); assertEquals(expectedSample, returnedSample, "Attempt to update existing sample without final state should succeed"); assertEquals(expectedSample, getSample(accountIdentifier, deviceId, experimentName, TestDeviceState.class), "Attempt to update existing sample without final state should be persisted"); } assertThrows(CompletionException.class, () -> pushNotificationExperimentSamples.recordFinalState(accountIdentifier, (byte) (deviceId + 1), experimentName, new TestDeviceState(finalBounciness)) .join(), "Attempts to record a final state without an initial state should fail"); }
public ActorSystem getActorSystem() { return actorSystem; }
@Test void testRpcServiceShutDownWithRpcEndpoints() throws Exception { final PekkoRpcService pekkoRpcService = startRpcService(); try { final int numberActors = 5; final RpcServiceShutdownTestHelper rpcServiceShutdownTestHelper = startStopNCountingAsynchronousOnStopEndpoints(pekkoRpcService, numberActors); for (CompletableFuture<Void> onStopFuture : rpcServiceShutdownTestHelper.getStopFutures()) { onStopFuture.complete(null); } rpcServiceShutdownTestHelper.waitForRpcServiceTermination(); assertThat(pekkoRpcService.getActorSystem().whenTerminated().isCompleted()).isTrue(); } finally { RpcUtils.terminateRpcService(pekkoRpcService); } }
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() != 6) { onInvalidDataReceived(device, data); return; } final int featuresValue = data.getIntValue(Data.FORMAT_UINT24_LE, 0); final int typeAndSampleLocation = data.getIntValue(Data.FORMAT_UINT8, 3); final int expectedCrc = data.getIntValue(Data.FORMAT_UINT16_LE, 4); final CGMFeatures features = new CGMFeatures(featuresValue); if (features.e2eCrcSupported) { final int actualCrc = CRC16.MCRF4XX(data.getValue(), 0, 4); if (actualCrc != expectedCrc) { onContinuousGlucoseMonitorFeaturesReceivedWithCrcError(device, data); return; } } else { // If the device doesn't support E2E-safety the value of the field shall be set to 0xFFFF. if (expectedCrc != 0xFFFF) { onInvalidDataReceived(device, data); return; } } @SuppressLint("WrongConstant") final int type = typeAndSampleLocation & 0x0F; // least significant nibble final int sampleLocation = typeAndSampleLocation >> 4; // most significant nibble onContinuousGlucoseMonitorFeaturesReceived(device, features, type, sampleLocation, features.e2eCrcSupported); }
@Test public void onInvalidDataReceived_wrongDefaultCrc() { final DataReceivedCallback callback = new CGMFeatureDataCallback() { @Override public void onContinuousGlucoseMonitorFeaturesReceived(@NonNull final BluetoothDevice device, @NonNull final CGMFeatures features, final int type, final int sampleLocation, final boolean secured) { assertEquals("Wrong CRC but data reported", 1, 2); } @Override public void onContinuousGlucoseMonitorFeaturesReceivedWithCrcError(@NonNull final BluetoothDevice device, @NonNull final Data data) { assertEquals("Correct packet but invalid CRC reported", 1, 2); } @Override public void onInvalidDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { called = true; } }; final MutableData data = new MutableData(new byte[6]); assertTrue(data.setValue(0b11000111001101110, Data.FORMAT_UINT24_LE, 0)); assertTrue(data.setValue(0x16, Data.FORMAT_UINT8, 3)); assertTrue(data.setValue(0xBEAF, Data.FORMAT_UINT16_LE, 4)); called = false; //noinspection DataFlowIssue callback.onDataReceived(null, data); assertTrue(called); }
@JsonCreator public static WindowInfo of( @JsonProperty(value = "type", required = true) final WindowType type, @JsonProperty(value = "size") final Optional<Duration> size, @JsonProperty(value = "emitStrategy") final Optional<OutputRefinement> emitStrategy) { return new WindowInfo(type, size, emitStrategy); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowIfSizeZero() { WindowInfo.of(TUMBLING, Optional.of(Duration.ZERO), Optional.empty()); }
@Override public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan, final boolean restoreInProgress) { try { final ExecuteResult result = EngineExecutor .create(primaryContext, serviceContext, plan.getConfig()) .execute(plan.getPlan(), restoreInProgress); return result; } catch (final KsqlStatementException e) { throw e; } catch (final KsqlException e) { // add the statement text to the KsqlException throw new KsqlStatementException( e.getMessage(), e.getMessage(), plan.getPlan().getStatementText(), e.getCause() ); } }
@Test public void shouldFailDropStreamWhenAnInsertQueryIsReadingTheStream() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "create stream bar as select * from test1;" + "create stream foo as select * from test1;" + "insert into foo select * from bar;", ksqlConfig, Collections.emptyMap() ); // When: final KsqlStatementException e = assertThrows( KsqlStatementException.class, () -> KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "drop stream bar;", ksqlConfig, Collections.emptyMap() ) ); // Then: assertThat(e, rawMessage(is( "Cannot drop BAR.\n" + "The following queries read from this source: [INSERTQUERY_2].\n" + "The following queries write into this source: [].\n" + "You need to terminate them before dropping BAR."))); assertThat(e, statementText(is("drop stream bar;"))); }
@Override public void addPath(String word, int outputSymbol) { MutableState state = getStartState(); if (state == null) { throw new IllegalStateException("Start state cannot be null"); } List<MutableArc> arcs = state.getArcs(); boolean isFound = false; for (MutableArc arc : arcs) { if (arc.getNextState().getLabel() == word.charAt(0)) { state = arc.getNextState(); isFound = true; break; } } int foundPos = -1; if (isFound) { Pair<MutableState, Integer> pair = findPointOfDiversion(state, word); if (pair == null) { // Word already exists return; } foundPos = pair.getRight(); state = pair.getLeft(); } for (int i = foundPos + 1; i < word.length(); i++) { MutableState nextState = new MutableState(); nextState.setLabel(word.charAt(i)); int currentOutputSymbol = -1; if (i == word.length() - 1) { currentOutputSymbol = outputSymbol; } MutableArc mutableArc = new MutableArc(currentOutputSymbol, nextState); state.addArc(mutableArc); state = nextState; } state.setIsTerminal(true); }
@Test public void testRegexMatcherSuffix2() { MutableFST fst = new MutableFSTImpl(); fst.addPath("hello-world", 12); fst.addPath("hello-world123", 21); fst.addPath("still", 123); RoaringBitmapWriter<MutableRoaringBitmap> writer = RoaringBitmapWriter.bufferWriter().get(); RealTimeRegexpMatcher.regexMatch(".*123", fst, writer::add); Assert.assertEquals(writer.get().getCardinality(), 1); writer.reset(); RealTimeRegexpMatcher.regexMatch(".till", fst, writer::add); Assert.assertEquals(writer.get().getCardinality(), 1); }
public boolean equals(byte[] that) { return Arrays.equals(data, that); }
@Test public void testEquals() { ZData data = new ZData("test".getBytes(ZMQ.CHARSET)); ZData other = new ZData("test".getBytes(ZMQ.CHARSET)); assertThat(data.equals(other), is(true)); }
@Override public Set<Path> getPaths(ElementId src, ElementId dst) { checkPermission(TOPOLOGY_READ); return getPaths(src, dst, (LinkWeigher) null); }
@Test public void infraToEdge() { DeviceId src = did("src"); HostId dst = hid("12:34:56:78:90:ab/1"); fakeTopoMgr.paths.add(createPath("src", "middle", "edge")); fakeHostMgr.hosts.put(dst, host("12:34:56:78:90:ab/1", "edge")); Set<Path> paths = service.getPaths(src, dst); validatePaths(paths, 1, 3, src, dst); }
public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; }
@Test public void testIsEmpty() { assertThat(StringUtils.isEmpty(null)).isTrue(); assertThat(StringUtils.isEmpty("abc")).isFalse(); assertThat(StringUtils.isEmpty("")).isTrue(); assertThat(StringUtils.isEmpty(" ")).isFalse(); }
public synchronized void invalidateCachedControllerLeader() { long now = getCurrentTimeMs(); long millisSinceLastInvalidate = now - _lastCacheInvalidationTimeMs; if (millisSinceLastInvalidate < MIN_INVALIDATE_INTERVAL_MS) { LOGGER.info("Millis since last controller cache value invalidate {} is less than allowed frequency {}. Skipping " + "invalidate.", millisSinceLastInvalidate, MIN_INVALIDATE_INTERVAL_MS); } else { LOGGER.info("Invalidating cached controller leader value"); _cachedControllerLeaderValid = false; _lastCacheInvalidationTimeMs = now; } }
@Test public void testInvalidateCachedControllerLeader() { HelixManager helixManager = mock(HelixManager.class); HelixDataAccessor helixDataAccessor = mock(HelixDataAccessor.class); final String leaderHost = "host"; final int leaderPort = 12345; // Lead controller resource disabled. ConfigAccessor configAccessor = mock(ConfigAccessor.class); ResourceConfig resourceConfig = mock(ResourceConfig.class); when(helixManager.getConfigAccessor()).thenReturn(configAccessor); when(configAccessor.getResourceConfig(any(), anyString())).thenReturn(resourceConfig); when(resourceConfig.getSimpleConfig(anyString())).thenReturn("false"); // Mocks the helix leader when(helixManager.getHelixDataAccessor()).thenReturn(helixDataAccessor); PropertyKey.Builder keyBuilder = mock(PropertyKey.Builder.class); when(helixDataAccessor.keyBuilder()).thenReturn(keyBuilder); PropertyKey controllerLeader = mock(PropertyKey.class); when(keyBuilder.controllerLeader()).thenReturn(controllerLeader); LiveInstance liveInstance = mock(LiveInstance.class); when(helixDataAccessor.getProperty(controllerLeader)).thenReturn(liveInstance); when(liveInstance.getInstanceName()).thenReturn(leaderHost + "_" + leaderPort); // Create Controller Leader Locator FakeControllerLeaderLocator.create(helixManager); FakeControllerLeaderLocator controllerLeaderLocator = FakeControllerLeaderLocator.getInstance(); // check values at startup Assert.assertFalse(controllerLeaderLocator.isCachedControllerLeaderValid()); Assert.assertEquals(controllerLeaderLocator.getLastCacheInvalidationTimeMs(), 0); // very first invalidate long currentTimeMs = 31_000L; controllerLeaderLocator.setCurrentTimeMs(currentTimeMs); controllerLeaderLocator.invalidateCachedControllerLeader(); Assert.assertFalse(controllerLeaderLocator.isCachedControllerLeaderValid()); long lastCacheInvalidateMillis = controllerLeaderLocator.getLastCacheInvalidationTimeMs(); Assert.assertTrue(lastCacheInvalidateMillis > 0); Assert.assertEquals(lastCacheInvalidateMillis, currentTimeMs); // invalidate within {@link ControllerLeaderLocator::getMinInvalidateIntervalMs()} millis // values should remain unchanged currentTimeMs = currentTimeMs + controllerLeaderLocator.getMinInvalidateIntervalMs() / 3; controllerLeaderLocator.setCurrentTimeMs(currentTimeMs); controllerLeaderLocator.invalidateCachedControllerLeader(); Assert.assertFalse(controllerLeaderLocator.isCachedControllerLeaderValid()); Assert.assertEquals(controllerLeaderLocator.getLastCacheInvalidationTimeMs(), lastCacheInvalidateMillis); // getControllerLeader, which validates the cache controllerLeaderLocator.getControllerLeader(TEST_TABLE); Assert.assertTrue(controllerLeaderLocator.isCachedControllerLeaderValid()); Assert.assertEquals(controllerLeaderLocator.getLastCacheInvalidationTimeMs(), lastCacheInvalidateMillis); // invalidate within {@link ControllerLeaderLocator::getMinInvalidateIntervalMs()} millis // values should remain unchanged currentTimeMs = currentTimeMs + controllerLeaderLocator.getMinInvalidateIntervalMs() / 3; controllerLeaderLocator.setCurrentTimeMs(currentTimeMs); controllerLeaderLocator.invalidateCachedControllerLeader(); Assert.assertTrue(controllerLeaderLocator.isCachedControllerLeaderValid()); Assert.assertEquals(controllerLeaderLocator.getLastCacheInvalidationTimeMs(), lastCacheInvalidateMillis); // invalidate after {@link ControllerLeaderLocator::getMinInvalidateIntervalMs()} millis have elapsed, by setting // lastCacheInvalidateMillis to well before the millisBetweenInvalidate // cache should be invalidated and last cache invalidation time should get updated controllerLeaderLocator.setCurrentTimeMs( controllerLeaderLocator.getCurrentTimeMs() + 2 * controllerLeaderLocator.getMinInvalidateIntervalMs()); controllerLeaderLocator.invalidateCachedControllerLeader(); Assert.assertFalse(controllerLeaderLocator.isCachedControllerLeaderValid()); Assert.assertTrue(controllerLeaderLocator.getLastCacheInvalidationTimeMs() > lastCacheInvalidateMillis); }
public static <T> T convert(Class<T> type, Object value) throws ConvertException { return convert((Type) type, value); }
@Test public void toStrTest2() { final String result = Convert.convert(String.class, "aaaa"); assertEquals("aaaa", result); }
@Override public void upgrade() { boolean indexExists = false; for (Document document : collection.listIndexes()) { if (MongoDbGrokPatternService.INDEX_NAME.equals(document.getString("name")) && document.getBoolean("unique")) { indexExists = true; break; } } if (indexExists) { LOG.debug("Unique index for Grok patterns already exists, skipping migration."); return; } final Collection<String> grokPatterns = new HashSet<>(); final Map<ObjectId, String> duplicatePatterns = new HashMap<>(); for (Document document : collection.find()) { final ObjectId id = document.getObjectId("_id"); final String name = document.getString("name"); final String pattern = document.getString("pattern"); if (grokPatterns.contains(name)) { LOG.info("Marking duplicate Grok pattern <{}> for removal: {}\t{}", id, name, pattern); duplicatePatterns.put(id, name); } else { LOG.debug("Recording Grok pattern <{}>: {}\t{}", id, name, pattern); grokPatterns.add(name); } } for (ObjectId id : duplicatePatterns.keySet()) { LOG.info("Deleting duplicate Grok pattern with ID <{}>", id); collection.deleteOne(eq("_id", id)); } final IndexOptions indexOptions = new IndexOptions() .name(MongoDbGrokPatternService.INDEX_NAME) .unique(true); collection.createIndex(Indexes.ascending("name"), indexOptions); if (!duplicatePatterns.isEmpty()) { clusterEventBus.post(GrokPatternsDeletedEvent.create(ImmutableSet.copyOf(duplicatePatterns.values()))); } indexCreated = true; }
@Test public void insertingDuplicateGrokPatternsIsNotPossibleAfterUpgrade() { collection.insertOne(grokPattern("FOO", "[a-z]+")); migration.upgrade(); assertThatThrownBy(() -> collection.insertOne(grokPattern("FOO", "[a-z]+"))) .isInstanceOf(MongoWriteException.class) .hasMessageMatching(".*E11000 duplicate key error collection: graylog.grok_patterns index: idx_name_asc_unique dup key: \\{ (name)?: \"FOO\" \\}.*"); }
@Bean public PluginDataHandler keyAuthPluginDataHandler() { return new KeyAuthPluginDataHandler(); }
@Test public void testKeyAuthPluginDataHandler() { applicationContextRunner.run(context -> assertNotNull(context.getBean("keyAuthPluginDataHandler"))); }
public PickTableLayoutWithoutPredicate pickTableLayoutWithoutPredicate() { return new PickTableLayoutWithoutPredicate(metadata); }
@Test public void ruleAddedTableLayoutToTableScan() { tester().assertThat(pickTableLayout.pickTableLayoutWithoutPredicate()) .on(p -> p.tableScan( new TableHandle( connectorId, new TpchTableHandle("nation", 1.0), TestingTransactionHandle.create(), Optional.empty()), ImmutableList.of(p.variable("nationkey", BIGINT)), ImmutableMap.of(p.variable("nationkey", BIGINT), new TpchColumnHandle("nationkey", BIGINT)))) .matches( constrainedTableScanWithTableLayout("nation", ImmutableMap.of(), ImmutableMap.of("nationkey", "nationkey"))); }
@Override public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) { ScannerReport.LineCoverage reportCoverage = getNextLineCoverageIfMatchLine(lineBuilder.getLine()); if (reportCoverage != null) { processCoverage(lineBuilder, reportCoverage); coverage = null; } return Optional.empty(); }
@Test public void nothing_to_do_when_no_coverage_info_for_current_line() { CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList( ScannerReport.LineCoverage.newBuilder() .setLine(1) .setConditions(10) .setHits(true) .setCoveredConditions(2) .build() // No coverage info on line 2 ).iterator()); DbFileSources.Line.Builder line2Builder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(2); computeCoverageLine.read(line2Builder); assertThat(line2Builder.hasLineHits()).isFalse(); assertThat(line2Builder.hasConditions()).isFalse(); assertThat(line2Builder.hasCoveredConditions()).isFalse(); }
@Override public final void run() { long valueCount = collector.getMergingValueCount(); if (valueCount == 0) { return; } runInternal(); assert operationCount > 0 : "No merge operations have been invoked in AbstractContainerMerger"; try { long timeoutMillis = Math.max(valueCount * TIMEOUT_FACTOR, MINIMAL_TIMEOUT_MILLIS); if (!semaphore.tryAcquire(operationCount, timeoutMillis, TimeUnit.MILLISECONDS)) { logger.warning("Split-brain healing for " + getLabel() + " didn't finish within the timeout..."); } } catch (InterruptedException e) { logger.finest("Interrupted while waiting for split-brain healing of " + getLabel() + "..."); Thread.currentThread().interrupt(); } finally { collector.destroy(); } }
@Test @RequireAssertEnabled public void testMergerRun() { TestMergeOperation operation = new TestMergeOperation(); TestContainerMerger merger = new TestContainerMerger(collector, nodeEngine, operation); merger.run(); assertTrue("Expected the merge operation to be invoked", operation.hasBeenInvoked); assertTrue("Expected collected containers to be destroyed", collector.onDestroyHasBeenCalled); }
@Override public PageResult<MemberTagDO> getTagPage(MemberTagPageReqVO pageReqVO) { return memberTagMapper.selectPage(pageReqVO); }
@Test public void testGetTagPage() { // mock 数据 MemberTagDO dbTag = randomPojo(MemberTagDO.class, o -> { // 等会查询到 o.setName("test"); o.setCreateTime(buildTime(2023, 2, 18)); }); tagMapper.insert(dbTag); // 测试 name 不匹配 tagMapper.insert(cloneIgnoreId(dbTag, o -> o.setName("ne"))); // 测试 createTime 不匹配 tagMapper.insert(cloneIgnoreId(dbTag, o -> o.setCreateTime(null))); // 准备参数 MemberTagPageReqVO reqVO = new MemberTagPageReqVO(); reqVO.setName("test"); reqVO.setCreateTime(buildBetweenTime(2023, 2, 1, 2023, 2, 28)); // 调用 PageResult<MemberTagDO> pageResult = tagService.getTagPage(reqVO); // 断言 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); assertPojoEquals(dbTag, pageResult.getList().get(0)); }
@Override public List<Document> get() { try (var input = markdownResource.getInputStream()) { Node node = parser.parseReader(new InputStreamReader(input)); DocumentVisitor documentVisitor = new DocumentVisitor(config); node.accept(documentVisitor); return documentVisitor.getDocuments(); } catch (IOException e) { throw new RuntimeException(e); } }
@Test void testDocumentNotDividedViaHorizontalRulesWhenIsDisabled() { MarkdownDocumentReaderConfig config = MarkdownDocumentReaderConfig.builder() .withHorizontalRuleCreateDocument(false) .build(); MarkdownDocumentReader reader = new MarkdownDocumentReader("classpath:/horizontal-rules.md", config); List<Document> documents = reader.get(); assertThat(documents).hasSize(1); Document documentsFirst = documents.get(0); assertThat(documentsFirst.getMetadata()).isEmpty(); assertThat(documentsFirst.getContent()).startsWith("Lorem ipsum dolor sit amet, consectetur adipiscing elit") .endsWith("Phasellus eget tellus sed nibh ornare interdum eu eu mi."); }
@VisibleForTesting String validateMail(String mail) { if (StrUtil.isEmpty(mail)) { throw exception(MAIL_SEND_MAIL_NOT_EXISTS); } return mail; }
@Test public void testValidateMail_notExists() { // 准备参数 // mock 方法 // 调用,并断言异常 assertServiceException(() -> mailSendService.validateMail(null), MAIL_SEND_MAIL_NOT_EXISTS); }
public List<String> getAllOn(String fieldName) { List<String> list = get(fieldName); return (list == null) ? new ArrayList<>() : list; }
@Test public void shouldReturnEmptyListWhenNoGetAllErrorsOnExists() { assertThat(new ConfigErrors().getAllOn("field"), is(Collections.emptyList())); }
@Override public DnsCacheEntry cache(String hostname, DnsRecord[] additionals, InetAddress address, long originalTtl, EventLoop loop) { checkNotNull(hostname, "hostname"); checkNotNull(address, "address"); checkNotNull(loop, "loop"); DefaultDnsCacheEntry e = new DefaultDnsCacheEntry(hostname, address); if (maxTtl == 0 || !emptyAdditionals(additionals)) { return e; } resolveCache.cache(appendDot(hostname), e, Math.max(minTtl, (int) Math.min(maxTtl, originalTtl)), loop); return e; }
@Test public void testExpireWithToBigMinTTL() { EventLoopGroup group = new NioEventLoopGroup(1); try { EventLoop loop = group.next(); final DefaultDnsCache cache = new DefaultDnsCache(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); assertNotNull(cache.cache("netty.io", null, NetUtil.LOCALHOST, 100, loop)); } finally { group.shutdownGracefully(); } }
@Override public JmxTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName) { return getTableHandle(tableName); }
@Test public void testGetTableHandle() { JmxTableHandle handle = metadata.getTableHandle(SESSION, RUNTIME_TABLE); assertEquals(handle.getObjectNames(), ImmutableList.of(RUNTIME_OBJECT)); List<JmxColumnHandle> columns = handle.getColumnHandles(); assertTrue(columns.contains(new JmxColumnHandle("node", createUnboundedVarcharType()))); assertTrue(columns.contains(new JmxColumnHandle("Name", createUnboundedVarcharType()))); assertTrue(columns.contains(new JmxColumnHandle("StartTime", BIGINT))); }
private void executeOnKey(String[] args) { // executeOnKey <echo-string> <key> doExecute(true, false, args); }
@Test public void executeOnKey() { for (int i = 0; i < 100; i++) { consoleApp.handleCommand(String.format("executeOnKey message%d key%d", i, i)); assertTextInSystemOut("message" + i); } }
public static boolean isDirectory(Path path, Configuration conf) { try { FileSystem fileSystem = FileSystem.get(path.toUri(), conf); return fileSystem.getFileStatus(path).isDirectory(); } catch (IOException e) { LOG.error("Failed checking path {}", path, e); throw new StarRocksConnectorException("Failed checking path: " + path); } }
@Test public void testIsDirectory() { Path path = new Path("hdfs://127.0.0.1:9000/user/hive/warehouse/db"); ExceptionChecker.expectThrowsWithMsg(StarRocksConnectorException.class, "Failed checking path", () -> HiveWriteUtils.isDirectory(path, new Configuration())); new MockUp<FileSystem>() { @Mock public FileSystem get(URI uri, Configuration conf) { return new MockedRemoteFileSystem(HDFS_HIVE_TABLE); } }; Assert.assertFalse(HiveWriteUtils.isDirectory(path, new Configuration())); }
public static ParsedCommand parse( // CHECKSTYLE_RULES.ON: CyclomaticComplexity final String sql, final Map<String, String> variables) { validateSupportedStatementType(sql); final String substituted; try { substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0), variables); } catch (ParseFailedException e) { throw new MigrationException(String.format( "Failed to parse the statement. Statement: %s. Reason: %s", sql, e.getMessage())); } final SqlBaseParser.SingleStatementContext statementContext = KSQL_PARSER.parse(substituted) .get(0).getStatement(); final boolean isStatement = StatementType.get(statementContext.statement().getClass()) == StatementType.STATEMENT; return new ParsedCommand(substituted, isStatement ? Optional.empty() : Optional.of(new AstBuilder(TypeRegistry.EMPTY) .buildStatement(statementContext))); }
@Test public void shouldParseResumeStatement() { // When: List<CommandParser.ParsedCommand> commands = parse("resume some_query_id;"); // Then: assertThat(commands.size(), is(1)); assertThat(commands.get(0).getCommand(), is("resume some_query_id;")); }
@Override public void apply(IntentOperationContext<FlowRuleIntent> context) { Optional<IntentData> toUninstall = context.toUninstall(); Optional<IntentData> toInstall = context.toInstall(); if (toInstall.isPresent() && toUninstall.isPresent()) { Intent intentToInstall = toInstall.get().intent(); if (requireNonDisruptive(intentToInstall) && INSTALLED.equals(toUninstall.get().state())) { reallocate(context); return; } } if (!toInstall.isPresent() && !toUninstall.isPresent()) { // Nothing to do. intentInstallCoordinator.intentInstallSuccess(context); return; } List<FlowRuleIntent> uninstallIntents = context.intentsToUninstall(); List<FlowRuleIntent> installIntents = context.intentsToInstall(); List<FlowRule> flowRulesToUninstall; List<FlowRule> flowRulesToInstall; if (toUninstall.isPresent()) { // Remove tracked resource from both Intent and installable Intents. trackIntentResources(toUninstall.get(), uninstallIntents, REMOVE); // Retrieves all flow rules from all flow rule Intents. flowRulesToUninstall = uninstallIntents.stream() .map(FlowRuleIntent::flowRules) .flatMap(Collection::stream) .filter(flowRule -> flowRuleService.getFlowEntry(flowRule) != null) .collect(Collectors.toList()); } else { // No flow rules to be uninstalled. flowRulesToUninstall = Collections.emptyList(); } if (toInstall.isPresent()) { // Track resource from both Intent and installable Intents. trackIntentResources(toInstall.get(), installIntents, ADD); // Retrieves all flow rules from all flow rule Intents. flowRulesToInstall = installIntents.stream() .map(FlowRuleIntent::flowRules) .flatMap(Collection::stream) .collect(Collectors.toList()); } else { // No flow rules to be installed. flowRulesToInstall = Collections.emptyList(); } List<FlowRule> flowRuleToModify; List<FlowRule> dontTouch; // If both uninstall/install list contained equal (=match conditions are equal) FlowRules, // omit it from remove list, since it will/should be overwritten by install flowRuleToModify = flowRulesToInstall.stream() .filter(flowRule -> flowRulesToUninstall.stream().anyMatch(flowRule::equals)) .collect(Collectors.toList()); // If both contained exactMatch-ing FlowRules, remove from both list, // since it will result in no-op. dontTouch = flowRulesToInstall.stream() .filter(flowRule -> flowRulesToUninstall.stream().anyMatch(flowRule::exactMatch)) .collect(Collectors.toList()); flowRulesToUninstall.removeAll(flowRuleToModify); flowRulesToUninstall.removeAll(dontTouch); flowRulesToInstall.removeAll(flowRuleToModify); flowRulesToInstall.removeAll(dontTouch); flowRuleToModify.removeAll(dontTouch); if (flowRulesToInstall.isEmpty() && flowRulesToUninstall.isEmpty() && flowRuleToModify.isEmpty()) { // There is no flow rules to install/uninstall intentInstallCoordinator.intentInstallSuccess(context); return; } FlowRuleOperations.Builder builder = FlowRuleOperations.builder(); // Add flows flowRulesToInstall.forEach(builder::add); // Modify flows flowRuleToModify.forEach(builder::modify); // Remove flows flowRulesToUninstall.forEach(builder::remove); FlowRuleOperationsContext flowRuleOperationsContext = new FlowRuleOperationsContext() { @Override public void onSuccess(FlowRuleOperations ops) { intentInstallCoordinator.intentInstallSuccess(context); } @Override public void onError(FlowRuleOperations ops) { intentInstallCoordinator.intentInstallFailed(context); } }; FlowRuleOperations operations = builder.build(flowRuleOperationsContext); log.debug("applying intent {} -> {} with {} rules: {}", toUninstall.map(x -> x.key().toString()).orElse("<empty>"), toInstall.map(x -> x.key().toString()).orElse("<empty>"), operations.stages().stream().mapToLong(Set::size).sum(), operations.stages()); flowRuleService.apply(operations); }
@Test public void testUninstallOnly() { List<Intent> intentsToInstall = Lists.newArrayList(); List<Intent> intentsToUninstall = createFlowRuleIntents(); IntentData toInstall = null; IntentData toUninstall = new IntentData(createP2PIntent(), IntentState.WITHDRAWING, new WallClockTimestamp()); toUninstall = IntentData.compiled(toUninstall, intentsToUninstall); IntentOperationContext<FlowRuleIntent> operationContext; IntentInstallationContext context = new IntentInstallationContext(toUninstall, toInstall); operationContext = new IntentOperationContext(intentsToUninstall, intentsToInstall, context); flowRuleService.load(operationContext.intentsToUninstall()); installer.apply(operationContext); IntentOperationContext successContext = intentInstallCoordinator.successContext; assertEquals(successContext, operationContext); Set<FlowRule> expectedFlowRules = intentsToUninstall.stream() .map(intent -> (FlowRuleIntent) intent) .map(FlowRuleIntent::flowRules) .flatMap(Collection::stream) .collect(Collectors.toSet()); assertEquals(expectedFlowRules, flowRuleService.flowRulesRemove); }