focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Map<String, String[]> getQueryMap(String query) { Map<String, String[]> map = new HashMap<>(); String[] params = query.split(PARAM_CONCATENATE); for (String param : params) { String[] paramSplit = param.split("="); if (paramSplit.length == 0) { ...
@Test void testGetQueryMapBug54055() { String query = "param2=15&param1=12&param3=bu4m1KzFvsozCnR4lra0%2Be69YzpnRcF09nDjc3VJvl8%3D"; Map<String, String[]> params = RequestViewHTTP.getQueryMap(query); Assertions.assertNotNull(params); Assertions.assertEquals(3, params.size()); ...
public static Set<String> getDependencyTree(final byte[] jarBytes) { Set<String> dependencies = new HashSet<>(); try (InputStream inputStream = new ByteArrayInputStream(jarBytes); ZipInputStream zipInputStream = new ZipInputStream(inputStream)) { ZipEntry entry; whil...
@Test public void testException() { assertThrowsExactly(ShenyuException.class, () -> JarDependencyUtils.getDependencyTree(null)); }
public static String serializeRecordToJsonExpandingValue(ObjectMapper mapper, Record<GenericObject> record, boolean flatten) throws JsonProcessingException { JsonRecord jsonRecord = new JsonRecord(); GenericObject value = record.ge...
@Test(dataProvider = "schemaType") public void testSerializeRecordToJsonExpandingValue(SchemaType schemaType) throws Exception { RecordSchemaBuilder valueSchemaBuilder = org.apache.pulsar.client.api.schema.SchemaBuilder.record("value"); valueSchemaBuilder.field("c").type(SchemaType.STRING).optional(...
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowFunctionStatusStatement) { return Optional.of(new ShowFunctionStatusExecutor((ShowFu...
@Test void assertCreateWithMySQLShowProcessListStatement() { when(sqlStatementContext.getSqlStatement()).thenReturn(new MySQLShowProcessListStatement(false)); Optional<DatabaseAdminExecutor> actual = new MySQLAdminExecutorCreator().create(sqlStatementContext, "", "", Collections.emptyList()); ...
static ApiError validateQuotaKeyValue( Map<String, ConfigDef.ConfigKey> validKeys, String key, double value ) { // Ensure we have an allowed quota key ConfigDef.ConfigKey configKey = validKeys.get(key); if (configKey == null) { return new ApiError(Errors.I...
@Test public void testValidateQuotaKeyValueForConsumerByteRateTooLarge() { assertEquals(new ApiError(Errors.INVALID_REQUEST, "Proposed value for consumer_byte_rate is too large for a LONG."), ClientQuotaControlManager.validateQuotaKeyValue( VALID_CLIENT_ID_QUO...
@Override public boolean applyFilterToCamelHeaders(String headerName, Object headerValue, Exchange exchange) { boolean answer = super.applyFilterToCamelHeaders(headerName, headerValue, exchange); // using rest producer then headers are mapping to uri and query parameters using {key} syntax /...
@Test public void shouldDecideOnApplingHeaderFilterToTemplateTokensUnencoded() { final HttpRestHeaderFilterStrategy strategy = new HttpRestHeaderFilterStrategy( "{uriToken1}{uriToken2}", "q1={queryToken1}&q2={queryToken2?}&"); assertTrue(strategy.applyFilterToCamelHe...
public String xml(String text) { if (text == null || text.isEmpty()) { return text; } return StringEscapeUtils.escapeXml11(text); }
@Test public void testXml() { EscapeTool instance = new EscapeTool(); String text = null; String expResult = null; String result = instance.xml(text); assertEquals(expResult, result); text = ""; expResult = ""; result = instance.xml(text); ass...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "Parameter examples ordering") public void testTicket3587() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(Ticket3587Resource.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + " /test/test:\n" ...
public static ReduceByKey.CombineFunctionWithIdentity<Integer> ofInts() { return SUMS_OF_INT; }
@Test public void testSumOfInts() { assertEquals(6, (int) apply(Stream.of(1, 2, 3), Sums.ofInts())); }
public static OSClient getConnectedClient(OpenstackNode osNode) { OpenstackAuth auth = osNode.keystoneConfig().authentication(); String endpoint = buildEndpoint(osNode); Perspective perspective = auth.perspective(); Config config = getSslConfig(); try { if (endpoint...
@Ignore @Test public void testGetConnectedClient() { OpenstackNode.Builder osNodeBuilderV2 = DefaultOpenstackNode.builder(); OpenstackAuth.Builder osNodeAuthBuilderV2 = DefaultOpenstackAuth.builder() .version("v2.0") .protocol(OpenstackAuth.Protocol.HTTP) ...
@VisibleForTesting static List<HivePartition> getPartitionsSample(List<HivePartition> partitions, int sampleSize) { checkArgument(sampleSize > 0, "sampleSize is expected to be greater than zero"); if (partitions.size() <= sampleSize) { return partitions; } List<Hive...
@Test public void testGetPartitionsSample() { HivePartition p1 = partition("p1=string1/p2=1234"); HivePartition p2 = partition("p1=string2/p2=2345"); HivePartition p3 = partition("p1=string3/p2=3456"); HivePartition p4 = partition("p1=string4/p2=4567"); HivePartition p5 =...
@ExecuteOn(TaskExecutors.IO) @Post(consumes = MediaType.APPLICATION_YAML) @Operation(tags = {"Flows"}, summary = "Create a flow from yaml source") public HttpResponse<FlowWithSource> create( @Parameter(description = "The flow") @Body String flow ) throws ConstraintViolationException { Fl...
@Test void updateFlowMultilineJson() { String flowId = IdUtils.create(); Flow flow = generateFlowWithFlowable(flowId, "io.kestra.unittest", "\n \n a \nb\nc"); Flow result = client.toBlocking().retrieve(POST("/api/v1/flows", flow), Flow.class); assertThat(result.getId(), is(...
void placeOrder(Order order) { sendShippingRequest(order); }
@Test void testPlaceOrderWithoutDatabaseAndExceptions() throws Exception { long paymentTime = timeLimits.paymentTime(); long queueTaskTime = timeLimits.queueTaskTime(); long messageTime = timeLimits.messageTime(); long employeeTime = timeLimits.employeeTime(); long queueTime = timeLimi...
public static String beanToString(Object o) { if (o == null) { return null; } Field[] fields = o.getClass().getDeclaredFields(); StringBuilder buffer = new StringBuilder(); buffer.append("["); for (Field field : fields) { Object val = null; ...
@Test public void testBeanToString() { BranchDO branchDO = new BranchDO("xid123123", 123L, 1, 2.2, new Date()); Assertions.assertNotNull(BeanUtils.beanToString(branchDO)); // null object Assertions.assertNull(BeanUtils.beanToString(null)); // buffer length < 2 Asserti...
Dependency newDependency(MavenProject prj) { final File pom = new File(prj.getBasedir(), "pom.xml"); if (pom.isFile()) { getLog().debug("Adding virtual dependency from pom.xml"); return new Dependency(pom, true); } else if (prj.getFile().isFile()) { getLog()....
@Test public void should_newDependency_get_default_virtual_dependency() { // Given BaseDependencyCheckMojo instance = new BaseDependencyCheckMojoImpl(); new MockUp<MavenProject>() { @Mock public File getBasedir() { return new File("src/test/resources/...
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) { final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps()); map.put( MetricCollectors.RESOURCE_LABEL_PREFIX + StreamsConfig.APPLICATION_ID_CONFIG, applicationId ); // Streams cli...
@Test public void shouldNotSetDeserializationExceptionHandlerWhenFailOnDeserializationErrorTrue() { final KsqlConfig ksqlConfig = new KsqlConfig(Collections.singletonMap(KsqlConfig.FAIL_ON_DESERIALIZATION_ERROR_CONFIG, true)); final Object result = ksqlConfig.getKsqlStreamConfigProps().get(StreamsConfig.DEFAU...
@Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Evidence)) { return false; } if (this == obj) { return true; } final Evidence o = (Evidence) obj; return new EqualsBuilder() .append(this.source =...
@Test public void testEquals() { Evidence that0 = new Evidence("file", "name", "guice-3.0", Confidence.HIGHEST); Evidence that1 = new Evidence("jar", "package name", "dependency", Confidence.HIGHEST); Evidence that2 = new Evidence("jar", "package name", "google", Confidence.HIGHEST); ...
@Override public List<Connection> getConnections(final String databaseName, final String dataSourceName, final int connectionOffset, final int connectionSize, final ConnectionMode connectionMode) throws SQLException { return getConnections0(databaseName, dataSource...
@Test void assertGetConnectionsWhenAllInCache() throws SQLException { Connection expected = databaseConnectionManager.getConnections(DefaultDatabase.LOGIC_NAME, "ds", 0, 1, ConnectionMode.MEMORY_STRICTLY).get(0); List<Connection> actual = databaseConnectionManager.getConnections(DefaultDatabase.LOGI...
@ConstantFunction(name = "bitand", argTypes = {BIGINT, BIGINT}, returnType = BIGINT) public static ConstantOperator bitandBigint(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createBigint(first.getBigint() & second.getBigint()); }
@Test public void bitandBigint() { assertEquals(100, ScalarOperatorFunctions.bitandBigint(O_BI_100, O_BI_100).getBigint()); }
public void register(Operation operation) { Map<Long, Operation> callIds = liveOperations.computeIfAbsent(operation.getCallerAddress(), (key) -> new ConcurrentHashMap<>()); if (callIds.putIfAbsent(operation.getCallId(), operation) != null) { throw new IllegalStateException("D...
@Test public void when_registerDuplicateCallId_then_exception() throws UnknownHostException { AsyncJobOperation operation = createOperation("1.2.3.4", 1234, 2222L); r.register(operation); // this should not fail r.register(createOperation("1.2.3.4", 1234, 2223L)); // adding...
@Override public Object getSmallintValue(final ResultSet resultSet, final int columnIndex) throws SQLException { return resultSet.getShort(columnIndex); }
@Test void assertGetSmallintValue() throws SQLException { when(resultSet.getShort(1)).thenReturn((short) 0); assertThat(dialectResultSetMapper.getSmallintValue(resultSet, 1), is((short) 0)); }
public static boolean isValidDnsNameOrWildcard(String name) { return name.length() <= 255 && (DNS_NAME.matcher(name).matches() || (name.startsWith("*.") && DNS_NAME.matcher(name.substring(2)).matches())); }
@Test public void testDnsNames() { assertThat(IpAndDnsValidation.isValidDnsNameOrWildcard("example"), is(true)); assertThat(IpAndDnsValidation.isValidDnsNameOrWildcard("example.com"), is(true)); assertThat(IpAndDnsValidation.isValidDnsNameOrWildcard("example:com"), is(false)); ass...
public static String extractMulti(Pattern pattern, CharSequence content, String template) { if (null == content || null == pattern || null == template) { return null; } //提取模板中的编号 final TreeSet<Integer> varNums = new TreeSet<>((o1, o2) -> ObjectUtil.compare(o2, o1)); final Matcher matcherForTemplate = Pat...
@Test public void extractMultiTest2() { // 抽取多个分组然后把它们拼接起来 final String resultExtractMulti = ReUtil.extractMulti("(\\w)(\\w)(\\w)(\\w)(\\w)(\\w)(\\w)(\\w)(\\w)(\\w)", content, "$1-$2-$3-$4-$5-$6-$7-$8-$9-$10"); assertEquals("Z-Z-Z-a-a-a-b-b-b-c", resultExtractMulti); }
public static Object get(Object object, int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index cannot be negative: " + index); } if (object instanceof Map) { Map map = (Map) object; Iterator iterator = map.entrySet().iterator(); r...
@Test void testGetEnumeration3() { Vector<Object> vector = new Vector<>(); vector.add("1"); vector.add("2"); assertEquals("1", CollectionUtils.get(vector.elements(), 0)); assertEquals("2", CollectionUtils.get(vector.elements(), 1)); }
public Object getAsJavaType( String valueName, Class<?> destinationType, InjectionTypeConverter converter ) throws KettleValueException { int idx = rowMeta.indexOfValue( valueName ); if ( idx < 0 ) { throw new KettleValueException( "Unknown column '" + valueName + "'" ); } ValueMetaInterface ...
@Test public void testBooleanConversion() throws Exception { row = new RowMetaAndData( rowsMeta, null, true, null ); assertEquals( true, row.getAsJavaType( "bool", boolean.class, converter ) ); assertEquals( true, row.getAsJavaType( "bool", Boolean.class, converter ) ); assertEquals( 1, row.getAsJava...
@JSONField(serialize = false, deserialize = false) public RetryPolicy getRetryPolicy() { if (GroupRetryPolicyType.EXPONENTIAL.equals(type)) { if (exponentialRetryPolicy == null) { return DEFAULT_RETRY_POLICY; } return exponentialRetryPolicy; } else...
@Test public void testGetRetryPolicy() { GroupRetryPolicy groupRetryPolicy = new GroupRetryPolicy(); RetryPolicy retryPolicy = groupRetryPolicy.getRetryPolicy(); assertThat(retryPolicy).isInstanceOf(CustomizedRetryPolicy.class); groupRetryPolicy.setType(GroupRetryPolicyType.EXPONENTI...
public synchronized void resetOffset(String topic, String group, Map<MessageQueue, Long> offsetTable) { DefaultMQPushConsumerImpl consumer = null; try { MQConsumerInner impl = this.consumerTable.get(group); if (impl instanceof DefaultMQPushConsumerImpl) { consumer...
@Test public void testResetOffset() throws IllegalAccessException { topicRouteTable.put(topic, createTopicRouteData()); brokerAddrTable.put(defaultBroker, createBrokerAddrMap()); consumerTable.put(group, createMQConsumerInner()); Map<MessageQueue, Long> offsetTable = new HashMap<>();...
public boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, Timer timer) { invokeCompletedOffsetCommitCallbacks(); if (offsets.isEmpty()) { // We guarantee that the callbacks for all commitAsync() will be invoked when // commitSync() completes, even if the u...
@Test public void shouldLoseAllOwnedPartitionsBeforeRejoiningAfterDroppingOutOfTheGroup() { final List<TopicPartition> partitions = singletonList(t1p); try (ConsumerCoordinator coordinator = prepareCoordinatorForCloseTest(true, false, Optional.of("group-id"), true)) { final Time realTime...
public void openFile() { openFile( false ); }
@Test public void testLoadLastUsedTransLocalNoFilenameAtStartup() throws Exception { String repositoryName = null; String fileName = null; setLoadLastUsedJobLocalWithRepository( false, repositoryName, null, fileName, true, true ); verify( spoon, never() ).openFile( anyString(), anyBoolean() ); }
@Override public List<AdminUserDO> getUserList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return Collections.emptyList(); } return userMapper.selectBatchIds(ids); }
@Test public void testGetUserList() { // mock 数据 AdminUserDO user = randomAdminUserDO(); userMapper.insert(user); // 测试 id 不匹配 userMapper.insert(randomAdminUserDO()); // 准备参数 Collection<Long> ids = singleton(user.getId()); // 调用 List<AdminUser...
protected static void configureMulticastSocket(MulticastSocket multicastSocket, Address bindAddress, HazelcastProperties hzProperties, MulticastConfig multicastConfig, ILogger logger) throws SocketException, IOException, UnknownHostException { multicastSocket.setReuseAddress(true); ...
@Test public void testSetInterfaceDefaultWhenLoopback() throws Exception { Config config = createConfig(null); MulticastConfig multicastConfig = config.getNetworkConfig().getJoin().getMulticastConfig(); multicastConfig.setLoopbackModeEnabled(true); MulticastSocket multicastSocket = m...
@Nullable public static Resource getJsBundleResource(PluginManager pluginManager, String pluginName, String bundleName) { Assert.hasText(pluginName, "The pluginName must not be blank"); Assert.hasText(bundleName, "Bundle name must not be blank"); DefaultResourceLoader resourceLoader...
@Test void getJsBundleResource() { Resource jsBundleResource = BundleResourceUtils.getJsBundleResource(pluginManager, "fake-plugin", "main.js"); assertThat(jsBundleResource).isNotNull(); assertThat(jsBundleResource.exists()).isTrue(); jsBundleResource = Bundl...
@Override public Num calculate(BarSeries series, Position position) { return position.hasLoss() ? series.one() : series.zero(); }
@Test public void calculateWithTwoShortPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(0, series), Trade.buyAt(1, series), Trade.sellAt(3, series), Trade.buyAt(5, series...
public static String toUnderlineName(String s) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean nextUpperCase = true; ...
@Test public void testToUnderlineName(){ String a = "userName"; Assert.assertEquals("user_name", StringKit.toUnderlineName(a)); }
@Override public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) { return aggregate(initializer, Materialized.with(null, null)); }
@Test public void timeWindowAggregateOverlappingWindowsTest() { final KTable<Windowed<String>, String> customers = groupedStream.cogroup(MockAggregator.TOSTRING_ADDER) .windowedBy(TimeWindows.of(ofMillis(500L)).advanceBy(ofMillis(200L))).aggregate( MockInitializer.ST...
@Override public CompletableFuture<QueryMessageResult> queryMessageAsync( String topic, String key, int maxCount, long begin, long end) { long topicId; try { TopicMetadata topicMetadata = metadataStore.getTopic(topic); if (topicMetadata == null) { log...
@Test public void testQueryMessageAsync() throws Exception { this.getMessageFromTieredStoreTest(); mq = dispatcherTest.mq; messageStore = dispatcherTest.messageStore; storeConfig = dispatcherTest.storeConfig; QueryMessageResult queryMessageResult = fetcher.queryMessageAsync(...
@EventListener void startup(StartupEvent event) { if (configuration.getBackgroundJobServer().isEnabled()) { backgroundJobServer.get().start(); } if (configuration.getDashboard().isEnabled()) { dashboardWebServer.get().start(); } }
@Test void onStartOptionalsAreNotCalledToBootstrapIfNotConfigured() { when(backgroundJobServerConfiguration.isEnabled()).thenReturn(false); when(dashboardConfiguration.isEnabled()).thenReturn(false); jobRunrStarter.startup(null); verifyNoInteractions(backgroundJobServer); v...
@Override public Component createComponent(Entry entry) { final Object existingComponent = entryAccessor.getComponent(entry); if (existingComponent != null) return (Component) existingComponent; final AFreeplaneAction action = entryAccessor.getAction(entry); final JComponent component; if(action != nul...
@Test public void testName() throws Exception { ResourceAccessor resourceAccessorMock = mock(ResourceAccessor.class); final ToolbarComponentProvider toolbarComponentProvider = new ToolbarComponentProvider(resourceAccessorMock); final Entry entry = new Entry(); final EntryAccessor entryAccessor = new EntryAcces...
public Long getHttpExpiresTime(final String pHttpExpiresHeader) { if (pHttpExpiresHeader != null && pHttpExpiresHeader.length() > 0) { try { final Date dateExpires = Configuration.getInstance().getHttpHeaderDateTimeFormat().parse(pHttpExpiresHeader); return dateExpire...
@Test public void testGetHttpExpiresTime() { final TileSourcePolicy tileSourcePolicy = new TileSourcePolicy(); for (final String string : mExpiresStringOK) { Assert.assertEquals(mExpiresValue, (long) tileSourcePolicy.getHttpExpiresTime(string)); } for (final String string...
public static Date strToDate(String dateStr) throws ParseException { return strToDate(dateStr, DATE_FORMAT_TIME); }
@Test public void strToDate() throws Exception { long d0 = 0l; long d1 = 1501127802000l; // 2017-07-27 11:56:42:975 +8 long d2 = 1501127835000l; // 2017-07-27 11:57:15:658 +8 TimeZone timeZone = TimeZone.getDefault(); Date date0 = new Date(d0 - timeZone.getOffset(d0)); ...
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 testCalculateTotalFlinkMemoryWithMissingFactors() { Configuration config = new Configuration(); config.set(TaskManagerOptions.FRAMEWORK_HEAP_MEMORY, new MemorySize(1)); config.set(TaskManagerOptions.FRAMEWORK_OFF_HEAP_MEMORY, new MemorySize(3)); config.set(TaskManagerOpti...
public ProcessingNodesState calculateProcessingState(TimeRange timeRange) { final DateTime updateThresholdTimestamp = clock.nowUTC().minus(updateThreshold.toMilliseconds()); try (DBCursor<ProcessingStatusDto> statusCursor = db.find(activeNodes(updateThresholdTimestamp))) { if (!statusCursor...
@Test @MongoDBFixtures("processing-status-idle-nodes.json") public void processingStateIdleNodesWhereLastMessageWithinTimeRange() { when(clock.nowUTC()).thenReturn(DateTime.parse("2019-01-01T04:00:00.000Z")); when(updateThreshold.toMilliseconds()).thenReturn(Duration.hours(1).toMilliseconds()); ...
public static boolean httpRequestWasMade() { return getFakeHttpLayer().hasRequestInfos(); }
@Test public void httpRequestWasMade_returnsFalseIfNoRequestMatchingGivenRuleWasMAde() throws IOException, HttpException { makeRequest("http://example.com"); assertFalse(FakeHttp.httpRequestWasMade("http://example.org")); }
public static ByteArrayOutputStream getPayload(MultipartPayload multipartPayload) throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); final String preamble = multipartPayload.getPreamble(); if (preamble != null) { os.write((preamble + "\r\n").getBytes(...
@Test public void testFileByteArrayBodyPartPayloadMultipartPayload() throws IOException { final MultipartPayload mP = new MultipartPayload("testFileByteArrayBodyPartPayloadMultipartPayload boundary"); mP.addBodyPart(new FileByteArrayBodyPartPayload("fileContent".getBytes(), "name", "filename.ext"));...
@Override public boolean shouldWait() { RingbufferContainer ringbuffer = getRingBufferContainerOrNull(); if (ringbuffer == null) { return true; } if (ringbuffer.isTooLargeSequence(sequence) || ringbuffer.isStaleSequence(sequence)) { //no need to wait, let the ...
@Test public void whenOneAfterTailAndBufferEmpty() { ReadOneOperation op = getReadOneOperation(ringbuffer.tailSequence() + 1); // since there is an item, we don't need to wait boolean shouldWait = op.shouldWait(); assertTrue(shouldWait); }
public ParseResult parse(File file) throws IOException, SchemaParseException { return parse(file, null); }
@Test void testParseURI() throws IOException { Path tempFile = Files.createTempFile("TestSchemaParser", null); Charset charset = UTF_CHARSETS[(int) Math.floor(UTF_CHARSETS.length * Math.random())]; Files.write(tempFile, singletonList(SCHEMA_JSON), charset); Schema schema = new SchemaParser().parse(te...
@Async @EventListener(ReplyCreatedEvent.class) public void onNewReply(ReplyCreatedEvent event) { Reply reply = event.getReply(); var commentName = reply.getSpec().getCommentName(); client.fetch(Comment.class, commentName) .ifPresent(comment -> newReplyReasonPublisher.publishR...
@Test void onNewReplyTest() { var reply = mock(Reply.class); var spec = mock(Reply.ReplySpec.class); when(reply.getSpec()).thenReturn(spec); when(spec.getCommentName()).thenReturn("fake-comment"); var spyReasonPublisher = spy(reasonPublisher); var comment = mock(Comm...
public StepInstanceActionResponse terminate( WorkflowInstance instance, String stepId, User user, Actions.StepInstanceAction action, boolean blocking) { validateStepId(instance, stepId, action); StepInstance stepInstance = stepInstanceDao.getStepInstance( insta...
@Test public void testInvalidTerminate() { AssertHelper.assertThrows( "Cannot manually terminate the step", MaestroBadRequestException.class, "Cannot manually STOP the step [not-existing] because the latest workflow run", () -> actionDao.terminate(instance, "not-existing", user, ST...
public void add(CSQueue queue) { String fullName = queue.getQueuePath(); String shortName = queue.getQueueShortName(); try { modificationLock.writeLock().lock(); fullNameQueues.put(fullName, queue); getMap.put(fullName, queue); //we only update short queue name ambiguity for non r...
@Test public void testAmbiguousMapping() throws IOException { CSQueueStore store = new CSQueueStore(); //root.main CSQueue main = createParentQueue("main", root); //root.main.A CSQueue mainA = createParentQueue("A", main); //root.main.A.C CSQueue mainAC = createLeafQueue("C", mainA); ...
@SuppressWarnings("unchecked") @Override public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) throws YarnException, IOException { NodeStatus remoteNodeStatus = request.getNodeStatus(); /** * Here is the node heartbeat sequence... * 1. Check if it's a valid (i.e. not excl...
@Test public void testDecommissionWithIncludeHosts() throws Exception { writeToHostsFile("localhost", "host1", "host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); ...
public Set<EntityDescriptor> resolveEntities(Collection<EntityDescriptor> unresolvedEntities) { final MutableGraph<EntityDescriptor> dependencyGraph = GraphBuilder.directed() .allowsSelfLoops(false) .nodeOrder(ElementOrder.insertion()) .build(); unresolved...
@Test public void resolveEntitiesWithNoDependencies() throws NotFoundException { final StreamMock streamMock = new StreamMock(ImmutableMap.of( "_id", "stream-1234", StreamImpl.FIELD_TITLE, "Stream Title" )); when(streamService.load("stream-1234")).thenReturn(...
@Override public TableConfig apply(PinotHelixResourceManager pinotHelixResourceManager, TableConfig tableConfig, Schema schema, Map<String, String> extraProperties) { IndexingConfig initialIndexingConfig = tableConfig.getIndexingConfig(); initialIndexingConfig.setInvertedIndexColumns(schema.getDimension...
@Test public void testTuner() { TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE) .setTableName("test").setTunerConfigList(Arrays.asList(_tunerConfig)).build(); TableConfigTunerRegistry.init(Arrays.asList(DEFAULT_TABLE_CONFIG_TUNER_PACKAGES)); TableConfigTuner tuner = TableConfig...
@Around(SYNC_UPDATE_CONFIG_ALL) public Object aroundSyncUpdateConfigAll(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response, String dataId, String group, String content, String appName, String srcUser, String tenant, String tag) throws Throwable { if (!P...
@Test void testAroundSyncUpdateConfigAllForInsertAspect() throws Throwable { //test with insert //condition: // 1. has tenant: true // 2. capacity limit check: false when(PropertyUtil.isManageCapacity()).thenReturn(false); MockHttpServletRequest mockHttpServletReque...
public static boolean canDrop(FilterPredicate pred, List<ColumnChunkMetaData> columns) { Objects.requireNonNull(pred, "pred cannot be null"); Objects.requireNonNull(columns, "columns cannot be null"); return pred.accept(new StatisticsFilter(columns)); }
@Test public void testLtEq() { assertTrue(canDrop(ltEq(intColumn, 9), columnMetas)); assertFalse(canDrop(ltEq(intColumn, 10), columnMetas)); assertFalse(canDrop(ltEq(intColumn, 100), columnMetas)); assertFalse(canDrop(ltEq(intColumn, 101), columnMetas)); assertTrue(canDrop(ltEq(intColumn, 0), nul...
public static TypeBuilder<Schema> builder() { return new TypeBuilder<>(new SchemaCompletion(), new NameContext()); }
@Test void testLong() { Schema.Type type = Schema.Type.LONG; Schema simple = SchemaBuilder.builder().longType(); Schema expected = primitive(type, simple); Schema built1 = SchemaBuilder.builder().longBuilder().prop("p", "v").endLong(); assertEquals(expected, built1); }
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testIntermediateDataSetReuse() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setBufferTimeout(-1); DataStream<Integer> source = env.fromData(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // these two vertices can reuse the same intermediate...
@Override public void setEventPublisher(EventPublisher publisher) { publisher.registerHandlerFor(Envelope.class, this::write); }
@Test void writes_index_html() throws Throwable { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); HtmlFormatter formatter = new HtmlFormatter(bytes); EventBus bus = new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID); formatter.setEventPublisher(bus); Tes...
@Override public boolean isOffsetExpired(OffsetAndMetadata offset, long currentTimestampMs, long offsetsRetentionMs) { if (offset.expireTimestampMs.isPresent()) { // Older versions with explicit expire_timestamp field => old expiration semantics is used return currentTimestampMs >= o...
@Test public void testIsOffsetExpired() { long currentTimestamp = 1500L; long commitTimestamp = 500L; OptionalLong expireTimestampMs = OptionalLong.of(1500); long offsetsRetentionMs = 500L; OffsetExpirationConditionImpl condition = new OffsetExpirationConditionImpl(__ -> com...
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertByte() { Column column = PhysicalColumn.builder().name("test").dataType(BasicType.BYTE_TYPE).build(); BasicTypeDefine typeDefine = SapHanaTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Asserti...
public NetworkClient.InFlightRequest completeLastSent(String node) { NetworkClient.InFlightRequest inFlightRequest = requestQueue(node).pollFirst(); inFlightRequestCount.decrementAndGet(); return inFlightRequest; }
@Test public void testCompleteLastSent() { int correlationId1 = addRequest(dest); int correlationId2 = addRequest(dest); assertEquals(2, inFlightRequests.count()); assertEquals(correlationId2, inFlightRequests.completeLastSent(dest).header.correlationId()); assertEquals(1, i...
@Override public AwsProxyResponse handle(Throwable ex) { if (ex instanceof ErrorResponse) { return new AwsProxyResponse(((ErrorResponse) ex).getStatusCode().value(), HEADERS, getErrorJson(ex.getMessage())); } else { return super.handle(ex); } }
@Test void noHandlerFoundExceptionResultsIn404() { AwsProxyResponse response = new SpringAwsProxyExceptionHandler(). handle(new NoHandlerFoundException(HttpMethod.GET.name(), "https://atesturl", HttpHeaders.EMPTY)); assertEquals(Response.Status.NOT_FOUND.getSt...
public static boolean isValidCidr(String cidr) { return isValidIPv4Cidr(cidr) || isValidIPv6Cidr(cidr); }
@Test public void isValidCidr() { String ipv4Cidr = "192.168.1.0/24"; String ipv6Cidr = "2001:0db8:1234:5678::/64"; String invalidCidr = "192.168.1.0"; assert IPAddressUtils.isValidCidr(ipv4Cidr); assert IPAddressUtils.isValidCidr(ipv6Cidr); assert !IPAddressUtils.is...
public static boolean isEmpty(final Object[] array) { return array == null || array.length == 0; }
@Test void isEmpty() { assertTrue(ArrayUtils.isEmpty(null)); assertTrue(ArrayUtils.isEmpty(new Object[0])); assertFalse(ArrayUtils.isEmpty(new Object[] {"abc"})); }
@Override public String toString() { return "{\"username\" : " + (_username == null ? null : "\"" + _username + "\"") + ",\"text\" : " + (_text == null ? null : "\"" + _text + "\"") + ",\"icon_emoji\" : " + (_iconEmoji == null ? null : "\"" + _iconEmoji + "\"") ...
@Test public void testSlackMessageJsonFormat() { String expectedJson = "{\"username\" : \"userA\",\"text\" : \"cc alert\",\"icon_emoji\" : \":information_source:" + "\",\"channel\" : \"#cc-alerts\"}"; assertEquals(expectedJson, new SlackMessage("userA", "cc alert", ":in...
public Timeslot getValidatedTimeslot(LocalTime other) { if (!isContainedWithin(other)) { throw new MomoException(ScheduleErrorCode.INVALID_SCHEDULE_TIMESLOT); } return Timeslot.from(other); }
@DisplayName("주어진 시간이 시간슬롯 인터벌에 포함되어 있으면 일치하는 타임슬롯을 반환한다.") @Test void successfulWhenContainingIntervalFully() { TimeslotInterval timeslotInterval = new TimeslotInterval(Timeslot.TIME_1000, Timeslot.TIME_1800); LocalTime other = Timeslot.TIME_1200.startTime(); Timeslot timeslot = timesl...
@Override public Path move(final Path file, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException { try { final BrickApiClient client = new BrickApiClient(session); if(status.isExists()) { ...
@Test(expected = NotfoundException.class) public void testMoveNotFound() throws Exception { final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new BrickMoveFeature(session).move(test, new Path(new Defa...
@Override public List<UsbSerialPort> getPorts() { return mPorts; }
@Test public void compositeRndisDevice() throws Exception { UsbDeviceConnection usbDeviceConnection = mock(UsbDeviceConnection.class); UsbDevice usbDevice = mock(UsbDevice.class); UsbInterface rndisControlInterface = mock(UsbInterface.class); UsbInterface rndisDataInterface = mock(Us...
@Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { return inject(statement, new TopicProperties.Builder()); }
@Test public void shouldUpdateStatementText() { // Given: givenStatement("CREATE STREAM x AS SELECT * FROM SOURCE;"); // When: final ConfiguredStatement<?> result = injector.inject(statement, builder); // Then: assertThat(result.getMaskedStatementText(), equalTo( "CREATE ...
@Override public TimeLimiter timeLimiter(final String name) { return timeLimiter(name, getDefaultConfig(), emptyMap()); }
@Test public void timeLimiterNewWithNullConfigSupplier() { exception.expect(NullPointerException.class); exception.expectMessage("Supplier must not be null"); TimeLimiterRegistry registry = new InMemoryTimeLimiterRegistry(config); registry.timeLimiter("name", (Supplier<TimeLimiterCo...
public Result resolve(List<PluginDescriptor> plugins) { // create graphs dependenciesGraph = new DirectedGraph<>(); dependentsGraph = new DirectedGraph<>(); // populate graphs Map<String, PluginDescriptor> pluginByIds = new HashMap<>(); for (PluginDescriptor plugin : plu...
@Test void notFoundDependencies() { PluginDescriptor pd1 = new DefaultPluginDescriptor() .setPluginId("p1") .setDependencies("p2, p3"); List<PluginDescriptor> plugins = new ArrayList<>(); plugins.add(pd1); DependencyResolver.Result result = resolver.resolve(...
int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } }
@Test void getStrengthShouldReturn4IfStrengthIs4() { // given int currentStrength = 4; // when int actual = bcCryptWorkFactorService.getStrength(0, 0, currentStrength); // then assertThat(actual).isEqualTo(4); }
@Override public void hasAllRequiredFields() { if (!actual.isInitialized()) { failWithoutActual( simpleFact("expected to have all required fields set"), fact("but was missing", actual.findInitializationErrors()), fact("proto was", actualCustomStringRepresentationForProtoPackage...
@Test public void testHasAllRequiredFields() { // Proto 3 doesn't have required fields. if (isProto3()) { return; } expectThat(parsePartial("")).hasAllRequiredFields(); expectThat(parsePartial("o_required_string_message: { required_string: \"foo\" }")) .hasAllRequiredFields(); ...
public String createNote(String notePath, AuthenticationInfo subject) throws IOException { return createNote(notePath, interpreterSettingManager.getDefaultInterpreterSetting().getName(), subject); }
@Test void testSchedulePoolUsage() throws InterruptedException, IOException { final int timeout = 30; final String everySecondCron = "* * * * * ?"; // each run starts a new JVM and the job takes about ~5 seconds final CountDownLatch jobsToExecuteCount = new CountDownLatch(5); final String noteId =...
static BsonTimestamp startAtTimestamp(Map<String, String> options) { String startAtValue = options.get(START_AT_OPTION); if (isNullOrEmpty(startAtValue)) { throw QueryException.error("startAt property is required for MongoDB stream. " + POSSIBLE_VALUES); } if ("now".equalsIgn...
@Test public void throws_at_invalid_dateTimeString() { // given long time = System.currentTimeMillis(); LocalDateTime timeDate = LocalDateTime.ofEpochSecond(time / 1000, 0, UTC); String dateAsString = timeDate.format(DateTimeFormatter.ISO_DATE_TIME) + "BLABLABLA"; // when ...
public static Map<String, String> getStringMap(String property, JsonNode node) { Preconditions.checkArgument(node.has(property), "Cannot parse missing map: %s", property); JsonNode pNode = node.get(property); Preconditions.checkArgument( pNode != null && !pNode.isNull() && pNode.isObject(), ...
@Test public void getStringMap() throws JsonProcessingException { assertThatThrownBy(() -> JsonUtil.getStringMap("items", JsonUtil.mapper().readTree("{}"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing map: items"); assertThatThrownBy( () -> Json...
public NumericIndicator dividedBy(Indicator<Num> other) { return NumericIndicator.of(BinaryOperation.quotient(this, other)); }
@Test public void dividedBy() { final NumericIndicator numericIndicator = NumericIndicator.of(cp1); final NumericIndicator staticOp = numericIndicator.dividedBy(5); assertNumEquals(1 / 5.0, staticOp.getValue(0)); assertNumEquals(9 / 5.0, staticOp.getValue(8)); final Numeric...
@Override public List<Container> allocateContainers(ResourceBlacklistRequest blackList, List<ResourceRequest> oppResourceReqs, ApplicationAttemptId applicationAttemptId, OpportunisticContainerContext opportContext, long rmIdentifier, String appSubmitter) throws YarnException { // Update b...
@Test public void testRoundRobinRackLocalAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newBuilder().all...
public static String extractFromURIPattern(String paramsRuleString, String pattern, String realURI) { Map<String, String> criteriaMap = new TreeMap<>(); pattern = sanitizeURLForRegExp(pattern); realURI = sanitizeURLForRegExp(realURI); // Build a pattern for extracting parts from pattern and a p...
@Test void testExtractFromURIPatternUnsorted() { // Check with parts not sorted in natural order. String requestPath = "/deployment/byComponent/1.2/myComp"; String operationName = "/deployment/byComponent/{version}/{component}"; String paramRule = "version && component"; // Dispatch st...
public static void removeUnavailableStepsFromMapping( Map<TargetStepAttribute, SourceStepField> targetMap, Set<SourceStepField> unavailableSourceSteps, Set<TargetStepAttribute> unavailableTargetSteps ) { Iterator<Entry<TargetStepAttribute, SourceStepField>> ta...
@Test public void removeUnavailableStepsFromMapping_unavailable_source_target_step() { TargetStepAttribute unavailableTargetStep = new TargetStepAttribute( UNAVAILABLE_STEP, TEST_ATTR_VALUE, false ); SourceStepField unavailableSourceStep = new SourceStepField( UNAVAILABLE_STEP, TEST_FIELD ); Map<TargetSte...
public ContentInfo verify(ContentInfo signedMessage, Date date) { final SignedData signedData = SignedData.getInstance(signedMessage.getContent()); final X509Certificate cert = certificate(signedData); certificateVerifier.verify(cert, date); final X500Name name = X500Name.getInstance(ce...
@Test public void verifyValidRvig2014Cms() throws Exception { final ContentInfo signedMessage = ContentInfo.getInstance(fixture("rvig2014")); final ContentInfo message = new CmsVerifier(new CertificateVerifier.None()).verify(signedMessage); assertEquals(LdsSecurityObject.OID, message.getCont...
protected File initRootProjectWorkDir(File baseDir, Map<String, String> rootProperties) { String workDir = rootProperties.get(CoreProperties.WORKING_DIRECTORY); if (StringUtils.isBlank(workDir)) { return new File(baseDir, CoreProperties.WORKING_DIRECTORY_DEFAULT_VALUE); } File customWorkDir = new...
@Test public void shouldInitRootWorkDirWithCustomAbsoluteFolder() { Map<String, String> props = singletonMap("sonar.working.directory", new File("src").getAbsolutePath()); ProjectReactorBuilder builder = new ProjectReactorBuilder(new ScannerProperties(props), mock(AnalysisWarnings.class)); File base...
public void addValueProviders(final String segmentName, final RocksDB db, final Cache cache, final Statistics statistics) { if (storeToValueProviders.isEmpty()) { logger.debug("Adding metrics record...
@Test public void shouldThrowIfCacheToAddIsSameAsOnlyOneOfMultipleCaches() { recorder.addValueProviders(SEGMENT_STORE_NAME_1, dbToAdd1, cacheToAdd1, statisticsToAdd1); recorder.addValueProviders(SEGMENT_STORE_NAME_2, dbToAdd2, cacheToAdd2, statisticsToAdd2); final Throwable exception = asse...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { if(containerService.isContainer(file)) { final PathAttributes attributes = ...
@Test public void testFind() throws Exception { final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new AzureTouchFeature(session, n...
public final void setStrictness(Strictness strictness) { Objects.requireNonNull(strictness); this.strictness = strictness; }
@Test public void testEscapeCharacterQuoteInStrictMode() { String json = "\"\\'\""; JsonReader reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextString); assertThat(expected) .hasMessageThat()...
@Override public void reset() throws IOException { createDirectory(PATH_DATA.getKey()); createDirectory(PATH_WEB.getKey()); createDirectory(PATH_LOGS.getKey()); File tempDir = createOrCleanTempDirectory(PATH_TEMP.getKey()); try (AllProcessesCommands allProcessesCommands = new AllProcessesCommands(...
@Test public void reset_cleans_the_sharedmemory_file() throws IOException { assertThat(tempDir.mkdir()).isTrue(); try (AllProcessesCommands commands = new AllProcessesCommands(tempDir)) { for (int i = 0; i < MAX_PROCESSES; i++) { commands.create(i).setUp(); } underTest.reset(); ...
@Override public int get(PageId pageId, int pageOffset, int bytesToRead, ReadTargetBuffer target, boolean isTemporary) throws IOException, PageNotFoundException { Callable<Integer> callable = () -> mPageStore.get(pageId, pageOffset, bytesToRead, target, isTemporary); try { return mTimeLimt...
@Test public void get() throws Exception { mPageStore.put(PAGE_ID, PAGE); assertEquals(PAGE.length, mTimeBoundPageStore.get(PAGE_ID, 0, PAGE.length, new ByteArrayTargetBuffer(mBuf, 0))); assertArrayEquals(PAGE, mBuf); }
public void load() { Set<CoreExtension> coreExtensions = serviceLoaderWrapper.load(getClass().getClassLoader()); ensureNoDuplicateName(coreExtensions); coreExtensionRepository.setLoadedCoreExtensions(coreExtensions); if (!coreExtensions.isEmpty()) { LOG.info("Loaded core extensions: {}", coreExte...
@Test public void load_fails_with_ISE_if_multiple_core_extensions_declare_same_names() { Set<CoreExtension> coreExtensions = ImmutableSet.of(newCoreExtension("a"), newCoreExtension("a"), newCoreExtension("b"), newCoreExtension("b")); when(serviceLoaderWrapper.load(any())).thenReturn(coreExtensions); asse...
@SuppressWarnings({"deprecation", "checkstyle:linelength"}) public void convertSiteProperties(Configuration conf, Configuration yarnSiteConfig, boolean drfUsed, boolean enableAsyncScheduler, boolean userPercentage, FSConfigToCSConfigConverterParams.PreemptionMode preemptionMode) { yarnSiteConfig...
@Test public void testSitePreemptionConversion() { yarnConfig.setBoolean(FairSchedulerConfiguration.PREEMPTION, true); yarnConfig.setInt(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 123); yarnConfig.setInt( FairSchedulerConfiguration.WAIT_TIME_BEFORE_NEXT_STARVATION_CHECK_MS, 321); ...
@Nonnull public static <T extends Throwable> T cloneExceptionWithFixedAsyncStackTrace(@Nonnull T original) { StackTraceElement[] fixedStackTrace = getFixedStackTrace(original, Thread.currentThread().getStackTrace()); Class<? extends Throwable> exceptionClass = original.getClass(); Throwabl...
@Test public void testCloneExceptionWithFixedAsyncStackTrace_whenCannotConstructSource_then_returnWithoutCloning() { IOException expectedException = new IOException(); NoPublicConstructorException result = ExceptionUtil.cloneExceptionWithFixedAsyncStackTrace( new NoPublicConstructorE...
public static String humanReadableByteCount(double bytes) { if (bytes < 1024) { return String.format("%.1f B", bytes); } int exp = (int) (Math.log(bytes) / Math.log(1024)); String pre = "KMGTPE".charAt(exp - 1) + ""; return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre); }
@Test public void testHumanReadableByteCount() { assertEquals("0.0 B", NumericUtils.humanReadableByteCount(0)); assertEquals("27.0 B", NumericUtils.humanReadableByteCount(27)); assertEquals("1023.0 B", NumericUtils.humanReadableByteCount(1023)); assertEquals("1.0 KB", NumericUtils.humanReadableByteCou...
public QueryObjectBundle rewriteQuery(@Language("SQL") String query, QueryConfiguration queryConfiguration, ClusterType clusterType) { return rewriteQuery(query, queryConfiguration, clusterType, false); }
@Test public void testRewriteFunctionCalls() { VerifierConfig verifierConfig = new VerifierConfig().setFunctionSubstitutes( "/approx_distinct(x)/count(x)/," + "/approx_percentile(x,array[0.9])/repeat(avg(x),cast(cardinality(array[0.9]) as integer))/," + ...
@Override public void execute(Exchange exchange) throws SmppException { QuerySm querySm = createQuerySm(exchange); if (log.isDebugEnabled()) { log.debug("Querying for a short message for exchange id '{}' and message id '{}'...", exchange.getExchangeId(), querySm.getM...
@Test public void execute() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "QuerySm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setHeader(SmppCo...
@Override public V getAndSet(V newValue) { return get(getAndSetAsync(newValue)); }
@Test public void testGetAndSet() { RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class)); TestType t = new TestType(); t.setName("name1"); al.set(t); NestedType nt = new NestedType(); nt.setValue(123); nt.setValues(Arr...
public static void assertThatClassIsImmutable(Class<?> clazz) { final ImmutableClassChecker checker = new ImmutableClassChecker(); if (!checker.isImmutableClass(clazz, false)) { final Description toDescription = new StringDescription(); final Description mismatchDescription = new...
@Test public void testNotFinalPrivateMember() throws Exception { boolean gotException = false; try { assertThatClassIsImmutable(NotFinalPrivateMember.class); } catch (AssertionError assertion) { assertThat(assertion.getMessage(), containsString("a ...
static int majorVersion(final String javaSpecVersion) { final String[] components = javaSpecVersion.split("\\."); final int[] version = new int[components.length]; for (int i = 0; i < components.length; i++) { version[i] = Integer.parseInt(components[i]); } if (versi...
@Test public void testMajorVersion() { assertEquals(6, PlatformDependent0.majorVersion("1.6")); assertEquals(7, PlatformDependent0.majorVersion("1.7")); assertEquals(8, PlatformDependent0.majorVersion("1.8")); assertEquals(8, PlatformDependent0.majorVersion("8")); assertEqual...
public static ExternalSorter create(Options options) { return options.getSorterType() == Options.SorterType.HADOOP ? HadoopExternalSorter.create(options) : NativeExternalSorter.create(options); }
@Test public void testAddAfterSort() throws Exception { SorterTestUtils.testAddAfterSort( ExternalSorter.create( new ExternalSorter.Options() .setTempLocation(getTmpLocation().toString()) .setSorterType(sorterType)), thrown); fail(); }
public static Map<String, FileWriteSchemaTransformFormatProvider> loadProviders() { return Providers.loadProviders(FileWriteSchemaTransformFormatProvider.class); }
@Test public void loadProviders() { Map<String, FileWriteSchemaTransformFormatProvider> formatProviderMap = FileWriteSchemaTransformFormatProviders.loadProviders(); Set<String> keys = formatProviderMap.keySet(); assertEquals(ImmutableSet.of(AVRO, CSV, JSON, PARQUET, XML), keys); }
private int refreshAdminAcls(String subClusterId) throws IOException, YarnException { // Refresh the admin acls ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RefreshAdminAclsRequest request = recordFactory.newRecordInstance(RefreshAdminAclsRequest.class); if (String...
@Test public void testRefreshAdminAcls() throws Exception { String[] args = { "-refreshAdminAcls" }; assertEquals(0, rmAdminCLI.run(args)); verify(admin).refreshAdminAcls(any(RefreshAdminAclsRequest.class)); }
public Connection getConnection() throws SQLException, SystemException, RollbackException { if (CONTAINER_DATASOURCE_NAMES.contains(dataSource.getClass().getSimpleName())) { return dataSource.getConnection(); } Transaction transaction = xaTransactionManagerProvider.getTransactionMana...
@Test void assertGetAtomikosConnection() throws SQLException, RollbackException, SystemException { DataSource dataSource = DataSourceUtils.build(AtomikosDataSourceBean.class, TypedSPILoader.getService(DatabaseType.class, "H2"), "ds1"); XATransactionDataSource transactionDataSource = new XATransactio...
public static ProducingResult createProducingResult( ResolvedSchema inputSchema, @Nullable Schema declaredSchema) { // no schema has been declared by the user, // the schema will be entirely derived from the input if (declaredSchema == null) { // go through data type to ...
@Test void testOutputToNoSchema() { final ResolvedSchema tableSchema = ResolvedSchema.of( Column.physical("id", BIGINT()), Column.metadata("rowtime", TIMESTAMP_LTZ(3), null, false), Column.physical("name", STRING())); ...