focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public AggregateAnalysisResult analyze( final ImmutableAnalysis analysis, final List<SelectExpression> finalProjection ) { if (!analysis.getGroupBy().isPresent()) { throw new IllegalArgumentException("Not an aggregate query"); } final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, ...
@Test public void shouldCaptureHavingNonAggregateFunctionArgumentsAsRequired() { // Given: when(analysis.getHavingExpression()).thenReturn(Optional.of( new FunctionCall(FunctionName.of("MAX"), ImmutableList.of(COL2)) )); // When: final AggregateAnalysisResult result = analyzer...
public static String generateKey() { return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); }
@Test public void testGenerateKey() { assertNotNull(SignUtils.generateKey()); }
@Deprecated @Override public void init(final ProcessorContext context, final StateStore root) { this.context = context instanceof InternalProcessorContext ? (InternalProcessorContext<?, ?>) context : null; taskId = context.taskId(); initStoreSerde(context); s...
@SuppressWarnings("deprecation") @Test public void shouldDelegateDeprecatedInit() { final MeteredWindowStore<String, String> outer = new MeteredWindowStore<>( innerStoreMock, WINDOW_SIZE_MS, // any size STORE_TYPE, new MockTime(), Serdes.String...
@Override public void process(Exchange exchange) throws Exception { final String msg = exchange.getIn().getBody(String.class); final String sendTo = exchange.getIn().getHeader(IrcConstants.IRC_SEND_TO, String.class); if (connection == null || !connection.isConnected()) { reconne...
@Test public void processTest() throws Exception { when(connection.isConnected()).thenReturn(true); when(exchange.getIn()).thenReturn(message); when(message.getBody(String.class)).thenReturn("PART foo"); when(message.getHeader(IrcConstants.IRC_SEND_TO, String.class)).thenReturn("bot...
void sendInternalMetadataRequest(MetadataRequest.Builder builder, String nodeConnectionId, long now) { ClientRequest clientRequest = newClientRequest(nodeConnectionId, builder, now, true); doSend(clientRequest, true, now); }
@Test public void testUnsupportedVersionDuringInternalMetadataRequest() { List<String> topics = Collections.singletonList("topic_1"); // disabling auto topic creation for versions less than 4 is not supported MetadataRequest.Builder builder = new MetadataRequest.Builder(topics, false, (shor...
@Override public PropertiesConfiguration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { final Properties properties = new Properties(); try (final InputStream configStream = source.getInputStream()) { properties.load(configStream); } catch...
@Test public void testDisableAppenderPerPipelineIsCreatedAfterLogLine() { System.setProperty(LogstashConfigurationFactory.PIPELINE_SEPARATE_LOGS, Boolean.FALSE.toString()); forceLog4JContextRefresh(); Logger logger = LogManager.getLogger(LogstashConfigurationFactoryTest.class); Thr...
@Override @NonNull public Flux<Object> decode(@NonNull Publisher<DataBuffer> input, @NonNull ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { ObjectMapper mapper = getObjectMapper(); Flux<TokenBuffer> tokens = Jackson...
@Test @SneakyThrows public void testDecodeList() { ObjectMapper mapper = new ObjectMapper(); CustomJackson2JsonDecoder decoder = new CustomJackson2JsonDecoder(new MapperEntityFactory(), mapper); ResolvableType type = ResolvableType.forClassWithGenerics(List.class, MyEntity.class); ...
BrokerResponse createQueueResponse(String queueName) throws IOException { String queryUrl = createQueueEndpoint(messageVpn); ImmutableMap<String, Object> params = ImmutableMap.<String, Object>builder() .put("accessType", "non-exclusive") .put("queueName", queueName) ....
@Test public void testCreateQueueResponseEncoding() throws IOException { MockHttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) { return new MockLowLevelHttpRequest() { @Override ...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { ByteBuf newlyByteBuf = payload.getByteBuf().readBytes(readLengthFromMeta(columnDef.getColumnMeta(), payload)); try { return MySQLJsonValueDecoder.decode(newlyByteBuf); } f...
@Test void assertReadJsonValueWithMeta1() { columnDef.setColumnMeta(1); when(byteBuf.readUnsignedByte()).thenReturn((short) 1); when(byteBuf.readBytes(1)).thenReturn(jsonValueByteBuf); assertThat(new MySQLJsonBinlogProtocolValue().read(columnDef, payload), is(EXPECTED_JSON)); }
public <T> SchemaProvider getSchemaProvider(TypeDescriptor<T> typeDescriptor) throws NoSuchSchemaException { for (SchemaProvider provider : providers) { Schema schema = provider.schemaFor(typeDescriptor); if (schema != null) { return provider; } } throw new NoSuchSchemaExcept...
@Test public void testGetSchemaProvider() throws NoSuchSchemaException { SchemaRegistry registry = SchemaRegistry.createDefault(); SchemaProvider testDefaultSchemaProvider = registry.getSchemaProvider(TestDefaultSchemaClass.class); assertEquals(DefaultSchemaProvider.class, testDefaultSchemaProvid...
@Override @Nonnull public <T extends DataConnection> T getAndRetainDataConnection(String name, Class<T> clazz) { DataConnectionEntry dataConnection = dataConnections.computeIfPresent(name, (k, v) -> { if (!clazz.isInstance(v.instance)) { throw new HazelcastException("Data con...
@Test public void should_return_true_when_config_data_connection_exists() { DataConnection dataConnection = dataConnectionService.getAndRetainDataConnection(TEST_CONFIG, DataConnection.class); assertThat(dataConnection) .describedAs("DataConnection created via config should exist") ...
@Override public long getRowCount(HoodieStorage storage, StoragePath filePath) { ParquetMetadata footer; long rowCount = 0; footer = readMetadata(storage, filePath); for (BlockMetaData b : footer.getBlocks()) { rowCount += b.getRowCount(); } return rowCount; }
@Test public void testReadCounts() throws Exception { String filePath = Paths.get(basePath, "test.parquet").toUri().toString(); List<String> rowKeys = new ArrayList<>(); for (int i = 0; i < 123; i++) { rowKeys.add(UUID.randomUUID().toString()); } writeParquetFile(BloomFilterTypeCode.SIMPLE.n...
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) { if (readerWay.hasTag("hazmat:water", "no")) { hazWaterEnc.setEnum(false, edgeId, edgeIntAccess, HazmatWater.NO); } else if (readerWay.hasTag("hazmat:water", "permiss...
@Test public void testNoNPE() { ReaderWay readerWay = new ReaderWay(1); EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1); int edgeId = 0; parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags); assertEquals(HazmatWater.YES, hazWaterEnc.getEnum(false, edgeId, ...
static List<MappingField> resolveFields(Map<String, Object> json) { Map<String, MappingField> fields = new LinkedHashMap<>(); for (Entry<String, Object> entry : json.entrySet()) { String name = entry.getKey(); QueryDataType type = resolveType(entry.getValue()); Mappi...
@Test public void test_resolveFields() { // given Map<String, Object> json = new LinkedHashMap<>() { { put("boolean", true); put("number", 1); put("string", "string"); put("object", emptyMap()); put("array", ...
@Override public Token login(LoginRequest loginRequest) { final UserEntity userEntityFromDB = userRepository .findUserEntityByEmail(loginRequest.getEmail()) .orElseThrow( () -> new UserNotFoundException("Can't find with given email: " ...
@Test void login_InvalidEmail_ThrowsAdminNotFoundException() { // Given LoginRequest loginRequest = LoginRequest.builder() .email("nonexistent@example.com") .password("password123") .build(); // When when(userRepository.findUserEntity...
@GetMapping public String getHealth() { // TODO UP DOWN WARN StringBuilder sb = new StringBuilder(); String dbStatus = dataSourceService.getHealth(); boolean addressServerHealthy = isAddressServerHealthy(); if (dbStatus.contains(HEALTH_UP) && addressServerHealthy && ServerMem...
@Test void testGetHealth() throws Exception { when(dataSourceService.getHealth()).thenReturn("UP"); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(Constants.HEALTH_CONTROLLER_PATH); String actualValue = mockmvc.perform(builder).andReturn().getResponse().getConten...
public double asMHz() { return (double) frequency / MHZ; }
@Test public void testasMHz() { Frequency frequency = Frequency.ofGHz(1); assertThat(frequency.asMHz(), is(1000.0)); }
public void setGroupId(String groupId) { this.groupId = groupId; }
@Test public void testSetGroupId() { String groupId = "aaa"; String expected = "aaa"; Model instance = new Model(); instance.setGroupId(groupId); assertEquals(expected, instance.getGroupId()); }
void move() { //moves by 1 unit in either direction this.coordinateX += RANDOM.nextInt(3) - 1; this.coordinateY += RANDOM.nextInt(3) - 1; }
@Test void moveTest() { var b = new Bubble(10, 10, 1, 2); var initialX = b.coordinateX; var initialY = b.coordinateY; b.move(); //change in x and y < |2| assertTrue(b.coordinateX - initialX < 2 && b.coordinateX - initialX > -2); assertTrue(b.coordinateY - initialY < 2 && b.coordinateY - in...
public static void validateJarOnClient(SubmitJobParameters parameterObject) throws IOException { if (parameterObject.isJarOnMember()) { throw new JetException("SubmitJobParameters is configured for jar on member"); } Path jarPath = parameterObject.getJarPath(); validateJarPa...
@Test public void failJarOnMemberConfiguration() { SubmitJobParameters parameterObject = SubmitJobParameters.withJarOnMember(); assertThatThrownBy(() -> SubmitJobParametersValidator.validateJarOnClient(parameterObject)) .isInstanceOf(JetException.class) .hasMessageCon...
public int maxAllowedPlanningFailures() { return maxAllowedPlanningFailures; }
@Test void testMaxAllowedPlanningFailures() { ScanContext context = ScanContext.builder().maxAllowedPlanningFailures(-2).build(); assertException( context, "Cannot set maxAllowedPlanningFailures to a negative number other than -1."); }
public static ObjectInputDecoder createDecoder(Type type, TypeManager typeManager) { String base = type.getTypeSignature().getBase(); switch (base) { case UnknownType.NAME: return o -> o; case BIGINT: return o -> (Long) o; case INTE...
@Test public void testPrimitiveObjectDecoders() { ObjectInputDecoder decoder; decoder = createDecoder(BIGINT, typeManager); assertTrue(decoder.decode(123456L) instanceof Long); decoder = createDecoder(INTEGER, typeManager); assertTrue(decoder.decode(12345L) instanceof I...
static String buildServiceName(AbstractInterfaceConfig config, String protocol) { if (RpcConstants.PROTOCOL_TYPE_BOLT.equals(protocol) || RpcConstants.PROTOCOL_TYPE_TR.equals(protocol)) { return ConfigUniqueNameGenerator.getServiceName(config) + ":DEFAULT"; } else { r...
@Test public void buildServiceName() { ServerConfig serverConfig = new ServerConfig() .setProtocol("bolt") .setHost("0.0.0.0") .setPort(12200); ProviderConfig<?> provider = new ProviderConfig(); provider.setInterfaceId("com.alipay.xxx.TestService") ...
@Override public void handle(SeckillWebMockRequestDTO request) { Seckill entity = new Seckill(); entity.setSeckillId(request.getSeckillId()); entity.setNumber(request.getSeckillCount()); seckillMapper.updateById(entity); // 清理已成功秒杀记录 SuccessKilled example = new Succe...
@Test public void shouldUpdateSeckillAndDeleteSuccessKilled() { SeckillWebMockRequestDTO request = new SeckillWebMockRequestDTO(); request.setSeckillId(123L); request.setSeckillCount(10); databasePreRequestHandler.handle(request); verify(seckillMapper, times(1)).updateById(...
@Override public ConnectorPageSource createPageSource( ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorSplit split, ConnectorTableLayoutHandle layout, List<ColumnHandle> columns, SplitContext splitContext, ...
@Test public void testCreatePageSource_withRowID() { HivePageSourceProvider pageSourceProvider = createPageSourceProvider(); HiveSplit hiveSplit = makeHiveSplit(ORC, Optional.of(new byte[20])); try (HivePageSource pageSource = (HivePageSource) pageSourceProvider.createPageSource( ...
public AstNode rewrite(final AstNode node, final C context) { return rewriter.process(node, context); }
@Test public void shouldRewriteCSAS() { final CreateStreamAsSelect csas = new CreateStreamAsSelect( location, sourceName, query, false, false, csasProperties ); when(mockRewriter.apply(query, context)).thenReturn(rewrittenQuery); final AstNode rewritten...
public StepExpression createExpression(StepDefinition stepDefinition) { List<ParameterInfo> parameterInfos = stepDefinition.parameterInfos(); if (parameterInfos.isEmpty()) { return createExpression( stepDefinition.getPattern(), stepDefinitionDoesNotTakeAnyPar...
@SuppressWarnings("unchecked") @Test void empty_table_cells_are_presented_as_null_to_transformer() { registry.setDefaultDataTableEntryTransformer( (map, valueType, tableCellByTypeTransformer) -> objectMapper.convertValue(map, objectMapper.constructType(valueType))); ...
public void createAcl(String addr, AclInfo aclInfo, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException { CreateAclRequestHeader requestHeader = new CreateAclRequestHeader(aclInfo.getSubject()); RemotingCommand req...
@Test public void testCreateAcl() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); mqClientAPI.createAcl(defaultBrokerAddr, new AclInfo(), defaultTimeout); }
public static String decode(String str, String encode) throws UnsupportedEncodingException { return innerDecode(null, str, encode); }
@Test void testDecode() throws UnsupportedEncodingException { // % - %25, { - %7B, } - %7D assertEquals("{k,v}", HttpUtils.decode("%7Bk,v%7D", "UTF-8")); assertEquals("{k,v}", HttpUtils.decode("%257Bk,v%257D", "UTF-8")); }
@Override public void execute(ComputationStep.Context context) { try (DbSession dbSession = dbClient.openSession(false)) { branchPersister.persist(dbSession); projectPersister.persist(dbSession); String projectUuid = treeRootHolder.getRoot().getUuid(); // safeguard, reset all rows to b-c...
@Test public void should_fail_if_project_is_not_stored_in_database_yet() { TreeRootHolder treeRootHolder = mock(TreeRootHolder.class); Component component = mock(Component.class); DbClient dbClient = mock(DbClient.class); ComponentDao componentDao = mock(ComponentDao.class); String projectKey = ra...
@Override public void removeProcessor(PacketProcessor processor) { // Remove the processor entry. for (int i = 0; i < processors.size(); i++) { if (processors.get(i).processor() == processor) { processors.remove(i); break; } } }
@Test public void removeProcessorTest() { PacketProcessor testProcessor = new TestProcessor(); packetManager1.addProcessor(testProcessor, PROCESSOR_PRIORITY); assertEquals("1 processor expected", 1, packetManager1.getProcessors().size()); assertEquals("0 process...
public int getDumpSchedulerLogsFailedRetrieved() { return numDumpSchedulerLogsFailedRetrieved.value(); }
@Test public void testDumpSchedulerLogsRetrievedFailed() { long totalBadBefore = metrics.getDumpSchedulerLogsFailedRetrieved(); badSubCluster.getDumpSchedulerLogsFailed(); Assert.assertEquals(totalBadBefore + 1, metrics.getDumpSchedulerLogsFailedRetrieved()); }
public static String[] split(String str) { return split(str, ESCAPE_CHAR, COMMA); }
@Test (timeout = 30000) public void testSimpleSplit() throws Exception { final String[] TO_TEST = { "a/b/c", "a/b/c////", "///a/b/c", "", "/", "////"}; for (String testSubject : TO_TEST) { assertArrayEquals("Testing '" + testSubject + "'", testSubj...
@Override public Long createProject(GoViewProjectCreateReqVO createReqVO) { // 插入 GoViewProjectDO goViewProject = GoViewProjectConvert.INSTANCE.convert(createReqVO) .setStatus(CommonStatusEnum.DISABLE.getStatus()); goViewProjectMapper.insert(goViewProject); // 返回 ...
@Test public void testCreateProject_success() { // 准备参数 GoViewProjectCreateReqVO reqVO = randomPojo(GoViewProjectCreateReqVO.class); // 调用 Long goViewProjectId = goViewProjectService.createProject(reqVO); // 断言 assertNotNull(goViewProjectId); // 校验记录的属性是否正确 ...
@Override public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.warn(String.f...
@Test public void testCopyNotFound() throws Exception { final DropboxCopyFeature feature = new DropboxCopyFeature(session); final Path home = new DefaultHomeFinderService(session).find(); final Path test = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); asse...
public static ThreadPoolExecutor newFixedThreadPool(int corePoolSize) { return new ThreadPoolExecutor(corePoolSize, corePoolSize, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>()); }
@Test public void newFixedThreadPool3() throws Exception { BlockingQueue<Runnable> queue = new SynchronousQueue<Runnable>(); RejectedExecutionHandler handler = new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { ...
public static ResourceId matchNewDirectory(String singleResourceSpec, String... baseNames) { ResourceId currentDir = matchNewResource(singleResourceSpec, true); for (String dir : baseNames) { currentDir = currentDir.resolve(dir, StandardResolveOptions.RESOLVE_DIRECTORY); } return currentDir; }
@Test public void testMatchNewDirectory() { List<KV<String, KV<String, String[]>>> testCases = ImmutableList.<KV<String, KV<String, String[]>>>builder() .add(KV.of("/abc/d/", KV.of("/abc", new String[] {"d"}))) .add(KV.of("/abc/d/", KV.of("/abc/", new String[] {"d"}))) ...
@Nullable public static URI uriWithTrailingSlash(@Nullable final URI uri) { if (uri == null) { return null; } final String path = firstNonNull(uri.getPath(), "/"); if (path.endsWith("/")) { return uri; } else { try { return...
@Test public void uriWithTrailingSlashReturnsNullIfURIIsNull() { assertNull(Tools.uriWithTrailingSlash(null)); }
@Bean public ShenyuPlugin tarsPlugin() { return new TarsPlugin(); }
@Test public void testTarsPlugin() { applicationContextRunner.run(context -> { ShenyuPlugin plugin = context.getBean("tarsPlugin", ShenyuPlugin.class); assertNotNull(plugin); assertThat(plugin.named()).isEqualTo(PluginEnum.TARS.getName()); } ...
@Operation(summary = "queryAllClusterList", description = "QUERY_ALL_CLUSTER_LIST_NOTES") @GetMapping(value = "/query-cluster-list") @ResponseStatus(HttpStatus.OK) @ApiException(QUERY_CLUSTER_ERROR) public Result<List<ClusterDto>> queryAllClusterList(@Parameter(hidden = true) @RequestAttribute(value = C...
@Test public void testQueryAllClusterList() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); MvcResult mvcResult = mockMvc.perform(get("/cluster/query-cluster-list") .header(SESSION_ID, sessionId) .params(paramsMap)) ...
@Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass != null) { return loadedClass; } if (isClosed) { throw new ClassNotFoun...
@Test public void shouldPerformClassLoadAndInstrumentLoadForInstrumentedClasses() throws Exception { ClassLoader classLoader = new SandboxClassLoader(configureBuilder().build()); Class<?> exampleClass = classLoader.loadClass(AnExampleClass.class.getName()); assertSame(classLoader, exampleClass.getClassLoa...
public static <T> Class<T> getClass(T t) { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>)t.getClass(); return clazz; }
@Test public void testGetClass() { //test with Integer Integer x = new Integer(42); Class<Integer> c = GenericsUtil.getClass(x); assertEquals("Correct generic type is acquired from object", Integer.class, c); //test with GenericClass<Integer> GenericClass<Integer> testSubject = n...
@Override public Object getObject(final int columnIndex) throws SQLException { return mergeResultSet.getValue(columnIndex, Object.class); }
@Test void assertGetObjectWithColumnIndex() throws SQLException { when(mergeResultSet.getValue(1, Object.class)).thenReturn("object_value"); assertThat(shardingSphereResultSet.getObject(1), is("object_value")); }
public List<RoleConfig> getRoleConfigs() { return filterRolesBy(RoleConfig.class); }
@Test public void getRoleConfigsShouldReturnOnlyNonPluginRoles() { Role admin = new RoleConfig(new CaseInsensitiveString("admin")); Role view = new RoleConfig(new CaseInsensitiveString("view")); Role blackbird = new PluginRoleConfig("blackbird", "foo"); Role spacetiger = new PluginRo...
public MapBuilder getMap(String name) { MapBuilder a = mapBuilderMap.get(name); if (a == null) { validateMap(name); a = new MapBuilder(configDefinition, name); mapBuilderMap.put(name, a); } return a; }
@Test public void require_that_maps_support_simple_values() { ConfigPayloadBuilder builder = new ConfigPayloadBuilder(); ConfigPayloadBuilder.MapBuilder map = builder.getMap("foo"); map.put("fookey", "foovalue"); map.put("barkey", "barvalue"); map.put("bazkey", "bazvalue"); ...
private synchronized RemotingCommand updateColdDataFlowCtrGroupConfig(ChannelHandlerContext ctx, RemotingCommand request) { final RemotingCommand response = RemotingCommand.createResponseCommand(null); LOGGER.info("updateColdDataFlowCtrGroupConfig called by {}", RemotingHelper.parseChannelRemote...
@Test public void testUpdateColdDataFlowCtrGroupConfig() throws RemotingCommandException { RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_COLD_DATA_FLOW_CTR_CONFIG, null); RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request); ...
public CompletableFuture<ChangeInvisibleDurationResponse> changeInvisibleDuration(ProxyContext ctx, ChangeInvisibleDurationRequest request) { CompletableFuture<ChangeInvisibleDurationResponse> future = new CompletableFuture<>(); try { validateTopicAndConsumerGroup(request.getTopic()...
@Test public void testChangeInvisibleDurationInvisibleTimeTooLarge() throws Throwable { try { this.changeInvisibleDurationActivity.changeInvisibleDuration( createContext(), ChangeInvisibleDurationRequest.newBuilder() .setInvisibleDuration(Durat...
@Override public SortedSet<String> languages() { return globalLanguagesCache; }
@Test public void should_add_languages_per_module_and_globally() { InputComponentStoreTester tester = new InputComponentStoreTester(sonarRuntime); String mod1Key = "mod1"; tester.addFile(mod1Key, "src/main/java/Foo.java", "java"); String mod2Key = "mod2"; tester.addFile(mod2Key, "src/main/groovy...
@Override public Map<QueryId, PersistentQueryMetadata> getPersistentQueries() { return Collections.unmodifiableMap(persistentQueries); }
@Test public void shouldGetPersistentQueries() { // Given: final PersistentQueryMetadata q1 = givenCreate(registry, "q1", "source", Optional.of("sink1"), CREATE_AS); final PersistentQueryMetadata q2 = givenCreate(registry, "q2", "source", Optional.of("sink2"), INSERT); final Persistent...
@Override public boolean containsMessage(String queueName, String messageId) { if (!queues.containsKey(queueName)) { queues.put(queueName, new ConcurrentLinkedDeque<>()); } return queues.get(queueName).contains(messageId); }
@Test public void testContainsMessage() { String queueName = "test-queue"; String id = "abcd-1234-defg-5678"; assertFalse(queueDao.containsMessage(queueName, id)); assertEquals(1, internalQueue.size()); assertTrue(internalQueue.get(queueName).isEmpty()); assertTrue(queueDao.pushIfNotExists(qu...
static Object parseCell(String cell, Schema.Field field) { Schema.FieldType fieldType = field.getType(); try { switch (fieldType.getTypeName()) { case STRING: return cell; case INT16: return Short.parseShort(cell); case INT32: return Integer.parseInt(c...
@Test public void givenValidIntegerCell_parses() { DefaultMapEntry cellToExpectedValue = new DefaultMapEntry("12", 12); Schema schema = Schema.builder().addInt32Field("an_integer").addInt64Field("a_long").build(); assertEquals( cellToExpectedValue.getValue(), CsvIOParseHelpers.parseCell( ...
public static Read<JmsRecord> read() { return new AutoValue_JmsIO_Read.Builder<JmsRecord>() .setMaxNumRecords(Long.MAX_VALUE) .setCoder(SerializableCoder.of(JmsRecord.class)) .setCloseTimeout(DEFAULT_CLOSE_TIMEOUT) .setRequiresDeduping(false) .setMessageMapper( ne...
@Test public void testReadMessages() throws Exception { long count = 5; produceTestMessages(count, JmsIOTest::createTextMessage); // read from the queue PCollection<JmsRecord> output = pipeline.apply( JmsIO.read() .withConnectionFactory(connectionFactory) ...
public static HiveFileInfo createHiveFileInfo(LocatedFileStatus locatedFileStatus, Optional<byte[]> extraFileContext) throws IOException { return createHiveFileInfo( locatedFileStatus, extraFileContext, ImmutableMap.of()); }
@Test public void testThriftRoundTrip() throws IOException { ThriftCodec<HiveFileInfo> hiveFileInfoThriftCodec = new ThriftCodecManager().getCodec(HiveFileInfo.class); HiveFileInfo hiveFileInfo = createHiveFileInfo(new LocatedFileStatus( 100, ...
public String parseEmbeddedExample() throws IOException, SAXException, TikaException { AutoDetectParser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); ParseContext context = new ParseContext(); context.s...
@Test public void testRecursiveParseExample() throws IOException, SAXException, TikaException { String result = parsingExample.parseEmbeddedExample(); assertContains("embed_0", result); assertContains("embed1/embed1a.txt", result); assertContains("embed3/embed3.txt", result); ...
public static <T> RetryOperator<T> of(Retry retry) { return new RetryOperator<>(retry); }
@Test public void shouldFailWithExceptionFlux() { RetryConfig config = retryConfig(); Retry retry = Retry.of("testName", config); RetryOperator<Object> retryOperator = RetryOperator.of(retry); StepVerifier.create(Flux.error(new HelloWorldException()) .transformDeferred(r...
void prioritizeCopiesAndShiftUps(List<MigrationInfo> migrations) { for (int i = 0; i < migrations.size(); i++) { prioritize(migrations, i); } if (logger.isFinestEnabled()) { StringBuilder s = new StringBuilder("Migration order after prioritization: ["); int i...
@Test public void testCopyPrioritizationAgainstShiftDownToColderIndex() throws UnknownHostException { List<MigrationInfo> migrations = new ArrayList<>(); final MigrationInfo migration1 = new MigrationInfo(0, new PartitionReplica(new Address("localhost", 5701), uuids[0]), new Partitio...
public String scope() { return scope; }
@Test public void testMethods() { BadConfigurationException ex = new BadConfigurationException("my-scope", "error"); assertThat(ex.scope()).isEqualTo("my-scope"); assertThat(ex).hasToString("BadConfigurationException{scope=my-scope, errors=[error]}"); }
@Override public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap, String serviceInterface) { if (!shouldHandle(invokers)) { return invokers; } List<Object> result = getTargetInvokersByRules(invokers, targetSe...
@Test public void testGetTargetInvokerByTagRulesWithPolicySceneFour() { // initialize the routing rule RuleInitializationUtils.initAZTagMatchTriggerThresholdMinAllInstancesPolicyRule(); // Scenario 1: The downstream provider has instances that meet the requirements List<Object> invok...
@Override public BulkWriter<T> create(FSDataOutputStream out) throws IOException { OrcFile.WriterOptions opts = getWriterOptions(); opts.physicalWriter(new PhysicalWriterImpl(out, opts)); // The path of the Writer is not used to indicate the destination file // in this case since we...
@Test void testNotOverrideInMemoryManager(@TempDir java.nio.file.Path tmpDir) throws IOException { TestMemoryManager memoryManager = new TestMemoryManager(); OrcBulkWriterFactory<Record> factory = new TestOrcBulkWriterFactory<>( new RecordVectorizer("struct<_c...
@VisibleForTesting DictTypeDO validateDictTypeExists(Long id) { if (id == null) { return null; } DictTypeDO dictType = dictTypeMapper.selectById(id); if (dictType == null) { throw exception(DICT_TYPE_NOT_EXISTS); } return dictType; }
@Test public void testValidateDictDataExists_success() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType);// @Sql: 先插入出一条存在的数据 // 调用成功 dictTypeService.validateDictTypeExists(dbDictType.getId()); }
public static WindowedValueCoderComponents getWindowedValueCoderComponents(Coder coder) { checkArgument(WINDOWED_VALUE_CODER_URN.equals(coder.getSpec().getUrn())); return new AutoValue_ModelCoders_WindowedValueCoderComponents( coder.getComponentCoderIds(0), coder.getComponentCoderIds(1)); }
@Test public void windowedValueCoderComponentsNoUrn() { thrown.expect(IllegalArgumentException.class); ModelCoders.getWindowedValueCoderComponents( Coder.newBuilder().setSpec(FunctionSpec.getDefaultInstance()).build()); }
@Override protected synchronized Class loadClass(String s, boolean b) throws ClassNotFoundException { throw new UnsupportedOperationException("I18n classloader does support only resources, but not classes"); }
@Test public void not_support_lookup_of_java_classes() throws ClassNotFoundException { assertThatThrownBy(() -> i18nClassloader.loadClass("java.lang.String")) .isInstanceOf(UnsupportedOperationException.class); }
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // has the class loaded already? Class<?> loadedClass = findLoadedClass(name); if (loadedClass == null) { try { // find the class from given jar urls as in first c...
@Test public void canLoadClassFromChildClassLoaderWhenNotPresentInParent() throws Exception { cl = new ChildFirstClassLoader(new URL[]{resourceJarUrl("deployment/sample-pojo-1.0-car.jar")}, ClassLoader.getSystemClassLoader()); String className = "com.sample.pojo.car.Car"; Class<?> clazz = c...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof TunnelEndPoint) { final TunnelEndPoint that = (TunnelEndPoint) obj; return this.getClass() == that.getClass() && Objects.equals(this.valu...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(endPoint1, sameAsEndPoint1) .addEqualityGroup(endPoint2) .addEqualityGroup(endPoint3) .testEquals(); }
public static int computeDistance(Class<?> parent, Class<?> child) { int distance = -1; if (parent.equals(child)) { distance = 0; } // Search through super classes if (distance == -1) { distance = computeSuperDistance(parent, child); } // Search through interfaces (costly) if (distance == -1) { ...
@Test public void testDistance() { assertEquals(0, TypeUtil.computeDistance(ATest.class, ATest.class)); assertEquals(100, TypeUtil.computeDistance(ATest.class, BTest.class)); assertEquals(200, TypeUtil.computeDistance(ATest.class, CTest.class)); assertEquals(300, TypeUtil.computeDistance(ATest.class, DTest.cla...
public void start() { this.nativeCacheManager.start(); }
@Test public final void startShouldStartTheNativeRemoteCacheManager() throws IOException { objectUnderTest.start(); assertTrue("Calling start() on SpringRemoteCacheManager should start the enclosed " + "Infinispan RemoteCacheManager. However, it is still not running.", ...
@Override protected List<MatchResult> match(List<String> specs) throws IOException { return match(new File(".").getAbsolutePath(), specs); }
@Test public void testMatchRelativeWildcardPath() throws Exception { File baseFolder = temporaryFolder.newFolder("A"); File expectedFile1 = new File(baseFolder, "file1"); expectedFile1.createNewFile(); List<String> expected = ImmutableList.of(expectedFile1.getAbsolutePath()); // This no longer ...
public static KTableHolder<GenericKey> build( final KGroupedStreamHolder groupedStream, final StreamAggregate aggregate, final RuntimeBuildContext buildContext, final MaterializedFactory materializedFactory) { return build( groupedStream, aggregate, buildContext, ...
@Test public void shouldBuildMaterializedWithCorrectNameForUnwindowedAggregate() { // Given: givenUnwindowedAggregate(); // When: aggregate.build(planBuilder, planInfo); // Then: verify(materializedFactory).create(any(), any(), eq("agg-regate-Materialize")); }
public NodeState getWantedState() { NodeState retiredState = new NodeState(node.getType(), State.RETIRED); // Don't let configure retired state override explicitly set Down and Maintenance. if (configuredRetired && wantedState.above(retiredState)) { return retiredState; } ...
@Test void down_wanted_state_overrides_config_retired_state() { ClusterFixture fixture = ClusterFixture.forFlatCluster(3) .markNodeAsConfigRetired(1) .proposeStorageNodeWantedState(1, State.DOWN); NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STOR...
@Override @SuppressWarnings({"rawtypes", "unchecked"}) public <T extends Gauge> T gauge(String name) { return (T) NoopGauge.INSTANCE; }
@Test @SuppressWarnings("rawtypes") public void accessingACustomGaugeRegistersAndReusesIt() { final MetricRegistry.MetricSupplier<Gauge> supplier = () -> gauge; final Gauge gauge1 = registry.gauge("thing", supplier); final Gauge gauge2 = registry.gauge("thing", supplier); assert...
@Override public List<RemoteFileInfo> getRemoteFiles(Table table, GetRemoteFilesParams params) { RemoteFileInfo remoteFileInfo = new RemoteFileInfo(); PaimonTable paimonTable = (PaimonTable) table; PaimonFilter filter = new PaimonFilter(paimonTable.getDbName(), paimonTable.getTableName(), pa...
@Test public void testGetRemoteFiles(@Mocked FileStoreTable paimonNativeTable, @Mocked ReadBuilder readBuilder) throws Catalog.TableNotExistException { new MockUp<PaimonMetadata>() { @Mock public long getTableCreateTime(String dbName, St...
@PostMapping @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "permissions", action = ActionTypes.WRITE) public Object addPermission(@RequestParam String role, @RequestParam String resource, @RequestParam String action) { nacosRoleService.addPermission(role, resource, action); re...
@Test void testAddPermission() { RestResult<String> result = (RestResult<String>) permissionController.addPermission("admin", "test", "test"); verify(nacosRoleService, times(1)).addPermission(anyString(), anyString(), anyString()); assertEquals(200, result.getCode()); }
public static <T> Values<T> of(Iterable<T> elems) { return new Values<>(elems, Optional.absent(), Optional.absent(), false); }
@Test public void testCreateDefaultOutputCoderUsingCoder() throws Exception { Coder<Record> coder = new RecordCoder(); assertThat( p.apply(Create.of(new Record(), new Record2()).withCoder(coder)).getCoder(), equalTo(coder)); }
public static long calculateTotalFlinkMemoryFromComponents(Configuration config) { Preconditions.checkArgument(config.contains(TaskManagerOptions.TASK_HEAP_MEMORY)); Preconditions.checkArgument(config.contains(TaskManagerOptions.TASK_OFF_HEAP_MEMORY)); Preconditions.checkArgument(config.contains...
@Test void testCalculateTotalFlinkMemoryWithAllFactorsBeingSet() { Configuration config = new Configuration(); config.set(TaskManagerOptions.FRAMEWORK_HEAP_MEMORY, new MemorySize(1)); config.set(TaskManagerOptions.TASK_HEAP_MEMORY, new MemorySize(2)); config.set(TaskManagerOptions.F...
static void checkValidCollectionName(String databaseName, String collectionName) { String fullCollectionName = databaseName + "." + collectionName; if (collectionName.length() < MIN_COLLECTION_NAME_LENGTH) { throw new IllegalArgumentException("Collection name cannot be empty."); } if (fullCollecti...
@Test public void testCheckValidCollectionNameThrowsErrorWhenNameContainsNull() { assertThrows( IllegalArgumentException.class, () -> checkValidCollectionName("test-database", "test\0collection")); }
@Override protected Map<String, Object> toJsonMap(ILoggingEvent event) { final MapBuilder mapBuilder = new MapBuilder(timestampFormatter, customFieldNames, additionalFields, includes.size()) .addTimestamp("timestamp", isIncluded(EventAttribute.TIMESTAMP), event.getTimeStamp()) .add("...
@Test void testReplaceFieldName() { final Map<String, String> customFieldNames = Map.of( "timestamp", "@timestamp", "message", "@message"); Map<String, Object> map = new EventJsonLayout(jsonFormatter, timestampFormatter, throwableProxyConverter, DEFAULT_EVENT_ATTRIBUT...
@SuppressWarnings("unchecked") public <IN, OUT> AvroDatumConverter<IN, OUT> create(Class<IN> inputClass) { boolean isMapOnly = ((JobConf) getConf()).getNumReduceTasks() == 0; if (AvroKey.class.isAssignableFrom(inputClass)) { Schema schema; if (isMapOnly) { schema = AvroJob.getMapOutputKeyS...
@Test void convertNullWritable() { AvroDatumConverter<NullWritable, Object> converter = mFactory.create(NullWritable.class); assertNull(converter.convert(NullWritable.get())); }
public void dropDb(String dbName, boolean force) throws MetaNotFoundException { Database database; try { database = getDb(dbName); } catch (Exception e) { LOG.error("Failed to access database {}", dbName, e); throw new MetaNotFoundException("Failed to access d...
@Test public void testDropDb() throws MetaNotFoundException { class MockedTestMetaClient extends HiveMetastoreTest.MockedHiveMetaClient { public org.apache.hadoop.hive.metastore.api.Database getDb(String dbName) throws RuntimeException { if (dbName.equals("not_exist_db")) { ...
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) { if (list == null) { return FEELFnResult.ofResult(false); } boolean result = false; for (final Object element : list) { if (element != null && !(element instanceof Boolean)) { r...
@Test void invokeListParamEmptyList() { FunctionTestUtil.assertResult(anyFunction.invoke(Collections.emptyList()), false); }
public static void main(String[] args) { var loadBalancer1 = new LoadBalancer(); var loadBalancer2 = new LoadBalancer(); loadBalancer1.serverRequest(new Request("Hello")); loadBalancer2.serverRequest(new Request("Hello World")); }
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
private String getMessage(AuthenticationException failed) { String message = "Server Error"; if (failed instanceof UsernameNotFoundException) { message = "用户不存在"; } else if (failed instanceof BadCredentialsException) { message = "密码错误"; } return message; ...
@Test public void getMessageTest() { JWTAuthenticationFilter filter = new JWTAuthenticationFilter(null); Assertions.assertEquals("用户不存在", ReflectUtil.invoke(filter, "getMessage", new UsernameNotFoundException(""))); Assertions.assertEquals("密码错误", ReflectUtil.invoke(filter, ...
@Override public ICardinality merge(ICardinality... estimators) throws LogLogMergeException { if (estimators == null) { return new LogLog(M); } byte[] mergedBytes = Arrays.copyOf(this.M, this.M.length); for (ICardinality estimator : estimators) { if (!(this.g...
@Test public void testMerge() throws CardinalityMergeException { int numToMerge = 5; int bits = 16; int cardinality = 1000000; LogLog[] loglogs = new LogLog[numToMerge]; LogLog baseline = new LogLog(bits); for (int i = 0; i < numToMerge; i++) { loglogs[i]...
public String getRepositoryName() { return repositoryName; }
@Test public void getRepositoryName() { assertEquals( "", element1.getRepositoryName() ); Element element2 = new Element( NAME, TYPE, PATH, LOCAL_PROVIDER, DUMMY_STRING ); assertEquals( DUMMY_STRING, element2.getRepositoryName() ); }
@Override public Collection<FileSourceSplit> enumerateSplits(Path[] paths, int minDesiredSplits) throws IOException { final ArrayList<FileSourceSplit> splits = new ArrayList<>(); for (Path path : paths) { final FileSystem fs = path.getFileSystem(); final FileStat...
@Test void testFilesWithNoBlockInfo() throws Exception { final Path testPath = new Path("testfs:///dir/file1"); testFs = TestingFileSystem.createForFileStatus( "testfs", TestingFileSystem.TestFileStatus.forFileWithBlocks(testPath, 12345...
@VisibleForTesting protected void copyResourcesFromJar(JarFile inputJar) throws IOException { Enumeration<JarEntry> inputJarEntries = inputJar.entries(); // The zip spec allows multiple files with the same name; the Java zip libraries do not. // Keep track of the files we've already written to filter out ...
@Test public void testCopyResourcesFromJar_copiesResources() throws IOException { List<JarEntry> entries = ImmutableList.of(new JarEntry("foo"), new JarEntry("bar"), new JarEntry("baz")); when(inputJar.entries()).thenReturn(Collections.enumeration(entries)); jarCreator.copyResourcesFromJar(inputJa...
@Override public boolean authenticateHttpRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Boolean authenticated = applyAuthProcessor( providers, provider -> { try { return provider.authenticateHttpRequest(request...
@Test public void testAuthenticateHttpRequest() throws Exception { HttpServletRequest requestAA = mock(HttpServletRequest.class); when(requestAA.getRemoteAddr()).thenReturn("127.0.0.1"); when(requestAA.getRemotePort()).thenReturn(8080); when(requestAA.getHeader("Authorization")).then...
public static void raftReadIndexFailed() { RAFT_READ_INDEX_FAILED.record(1); }
@Test void testRaftReadIndexFailed() { MetricsMonitor.raftReadIndexFailed(); MetricsMonitor.raftReadIndexFailed(); assertEquals(2D, MetricsMonitor.getRaftReadIndexFailed().totalAmount(), 0.01); }
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@Test public void testUnpartitionedOr() throws Exception { createUnpartitionedTable(spark, tableName); SparkScanBuilder builder = scanBuilder(); YearsFunction.TimestampToYearsFunction tsToYears = new YearsFunction.TimestampToYearsFunction(); UserDefinedScalarFunc udf1 = toUDF(tsToYears, expressions(...
@Override public BuiltIndex<NewAuthorizedIndex> build() { checkState(!getRelations().isEmpty(), "At least one relation mapping must be defined"); return new BuiltIndex<>(this); }
@Test public void build_fails_if_no_relation_mapping_has_been_created() { NewAuthorizedIndex underTest = new NewAuthorizedIndex(someIndex, defaultSettingsConfiguration); assertThatThrownBy(() -> underTest.build()) .isInstanceOf(IllegalStateException.class) .hasMessage("At least one relation mappi...
public boolean isAlwaysFalse() { if (conditions.isEmpty()) { return false; } for (ShardingCondition each : conditions) { if (!(each instanceof AlwaysFalseShardingCondition)) { return false; } } return true; }
@Test void assertIsAlwaysFalseTrue() { ShardingConditions shardingConditions = createSingleShardingConditions(); assertTrue(shardingConditions.isAlwaysFalse()); }
public RequestAndSize parseRequest(ByteBuffer buffer) { if (isUnsupportedApiVersionsRequest()) { // Unsupported ApiVersion requests are treated as v0 requests and are not parsed ApiVersionsRequest apiVersionsRequest = new ApiVersionsRequest(new ApiVersionsRequestData(), (short) 0, header...
@Test public void testInvalidRequestForByteArray() throws UnknownHostException { short version = (short) 1; // choose a version with fixed length encoding, for simplicity ByteBuffer corruptBuffer = serialize(version, new SaslAuthenticateRequestData().setAuthBytes(new byte[0])); // corrupt th...
public void checkUnderWritableMountPoint(AlluxioURI alluxioUri) throws InvalidPathException, AccessControlException { try (LockResource r = new LockResource(mReadLock)) { // This will re-acquire the read lock, but that is allowed. String mountPoint = getMountPoint(alluxioUri); MountInfo moun...
@Test public void writableMount() throws Exception { String mountPath = "/mnt/foo"; AlluxioURI alluxioUri = new AlluxioURI("alluxio://localhost:1234" + mountPath); addMount(alluxioUri.toString(), "hdfs://localhost:5678/foo", IdUtils.INVALID_MOUNT_ID); try { mMountTable.checkUnderWritableMountPo...
public static List<CredentialProvider> getProviders(Configuration conf ) throws IOException { List<CredentialProvider> result = new ArrayList<>(); for(String path: conf.getStringCollection(CREDENTIAL_PROVIDER_PATH)) { try { URI uri = new URI(path); ...
@Test public void testUriErrors() throws Exception { Configuration conf = new Configuration(); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, "unkn@own:/x/y"); try { List<CredentialProvider> providers = CredentialProviderFactory.getProviders(conf); assertTrue("should t...
public int doWork() { final long nowNs = nanoClock.nanoTime(); trackTime(nowNs); int workCount = 0; workCount += processTimers(nowNs); if (!asyncClientCommandInFlight) { workCount += clientCommandAdapter.receive(); } workCount += drainComm...
@Test void shouldErrorOnRemoveSubscriptionOnUnknownRegistrationId() { final long id1 = driverProxy.addSubscription(CHANNEL_4000, STREAM_ID_1); driverProxy.removeSubscription(id1 + 100); driverConductor.doWork(); driverConductor.doWork(); final InOrder inOrder = inOrder(...
public final void setStrictness(Strictness strictness) { Objects.requireNonNull(strictness); this.strictness = strictness; }
@Test public void testSetStrictness() { JsonReader reader = new JsonReader(reader("{}")); reader.setStrictness(Strictness.STRICT); assertThat(reader.getStrictness()).isEqualTo(Strictness.STRICT); }
public static Map<Integer, Map<RowExpression, VariableReferenceExpression>> collectCSEByLevel(List<? extends RowExpression> expressions) { if (expressions.isEmpty()) { return ImmutableMap.of(); } CommonSubExpressionCollector expressionCollector = new CommonSubExpressionCollector...
@Test void testCollectCSEByLevel() { List<RowExpression> expressions = ImmutableList.of(rowExpression("x * 2 + y + z"), rowExpression("(x * 2 + y + 1) * 2"), rowExpression("(x * 2) + (x * 2 + y + z)")); Map<Integer, Map<RowExpression, VariableReferenceExpression>> cseByLevel = collectCSEByLevel...
@Override public String getName() { return "Dart Package Analyzer"; }
@Test public void testDartAnalyzerGetName() { assertThat(dartAnalyzer.getName(), is("Dart Package Analyzer")); }
public static boolean isSystemGroup(String group) { if (StringUtils.isBlank(group)) { return false; } String groupInLowerCase = group.toLowerCase(); for (String prefix : SYSTEM_GROUP_PREFIX_LIST) { if (groupInLowerCase.startsWith(prefix)) { return ...
@Test public void testIsSystemGroup_EmptyGroup_ReturnsFalse() { String group = ""; boolean result = BrokerMetricsManager.isSystemGroup(group); assertThat(result).isFalse(); }
public String encode(String name, String value) { return encode(new DefaultCookie(name, value)); }
@Test public void illegalCharInCookieValueMakesStrictEncoderThrowsException() { Set<Character> illegalChars = new HashSet<Character>(); // CTLs for (int i = 0x00; i <= 0x1F; i++) { illegalChars.add((char) i); } illegalChars.add((char) 0x7F); // whitespace,...
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)); } } ...
@Test public void outOfMemoryJVM() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/out_of_memory.txt")), CrashReportAnalyzer.Rule.OUT_OF_MEMORY); }