focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public int runScript(final String scriptFile) { int errorCode = NO_ERROR; RemoteServerSpecificCommand.validateClient(terminal.writer(), restClient); try { // RUN SCRIPT calls the `makeKsqlRequest` directly, which does not support PRINT/SELECT. // // To avoid interfere with the RUN SCRIPT behavior, this code loads the content of the // script and execute it with the 'handleLine', which supports PRINT/SELECT statements. // // RUN SCRIPT should be fixed to support PRINT/SELECT, but also should prevent override // variables and properties from the CLI session. final String content = Files.readAllLines(Paths.get(scriptFile), StandardCharsets.UTF_8) .stream().collect(Collectors.joining(System.lineSeparator())); handleLine(content); } catch (final Exception exception) { errorCode = ERROR; LOGGER.error("An error occurred while running a script file. Error = " + exception.getMessage(), exception); terminal.printError(ErrorMessageUtil.buildErrorMessage(exception), exception.toString()); } terminal.flush(); return errorCode; }
@Test public void shouldRunScriptOnRunScript() throws Exception { // Given: final File scriptFile = TMP.newFile("script.sql"); Files.write(scriptFile.toPath(), ("" + "CREATE STREAM shouldRunScript AS SELECT * FROM " + ORDER_DATA_PROVIDER.sourceName() + ";" + "").getBytes(StandardCharsets.UTF_8)); // When: localCli.runScript(scriptFile.getPath()); // Then: assertThat(terminal.getOutputString(), containsString("Created query with ID CSAS_SHOULDRUNSCRIPT")); }
@Override public Mono<Void> apply(final ServerWebExchange exchange, final ShenyuPluginChain shenyuPluginChain, final ParamMappingRuleHandle paramMappingRuleHandle) { return exchange.getFormData() .switchIfEmpty(Mono.defer(() -> Mono.just(new LinkedMultiValueMap<>()))) .flatMap(multiValueMap -> { if (Objects.isNull(multiValueMap) || multiValueMap.isEmpty()) { return shenyuPluginChain.execute(exchange); } String original = GsonUtils.getInstance().toJson(multiValueMap); LOG.info("get from data success data:{}", original); String modify = operation(original, paramMappingRuleHandle); if (!StringUtils.hasLength(modify)) { return shenyuPluginChain.execute(exchange); } HttpHeaders headers = exchange.getRequest().getHeaders(); HttpHeaders httpHeaders = new HttpHeaders(); Charset charset = Objects.requireNonNull(headers.getContentType()).getCharset(); charset = charset == null ? StandardCharsets.UTF_8 : charset; LinkedMultiValueMap<String, String> modifyMap = toLinkedMultiValueMap(modify); List<String> list = prepareParams(modifyMap, charset.name()); String content = String.join("&", list); byte[] bodyBytes = content.getBytes(charset); int contentLength = bodyBytes.length; final BodyInserter<LinkedMultiValueMap<String, String>, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromValue(modifyMap); httpHeaders.putAll(headers); httpHeaders.remove(HttpHeaders.CONTENT_LENGTH); httpHeaders.setContentLength(contentLength); CachedBodyOutputMessage cachedBodyOutputMessage = new CachedBodyOutputMessage(exchange, httpHeaders); return bodyInserter.insert(cachedBodyOutputMessage, new BodyInserterContext()) .then(Mono.defer(() -> shenyuPluginChain.execute(exchange.mutate() .request(new ModifyServerHttpRequestDecorator(httpHeaders, exchange.getRequest(), cachedBodyOutputMessage)) .build()) )).onErrorResume((Function<Throwable, Mono<Void>>) throwable -> release(cachedBodyOutputMessage, throwable)); }); }
@Test public void testApply() { when(this.chain.execute(any())).thenReturn(Mono.empty()); StepVerifier.create(formDataOperator.apply(this.exchange, this.chain, paramMappingRuleHandle)).expectSubscription().verifyComplete(); }
@SuppressWarnings({"CastCanBeRemovedNarrowingVariableType", "unchecked"}) public E relaxedPeek() { final E[] buffer = consumerBuffer; final long index = consumerIndex; final long mask = consumerMask; final long offset = modifiedCalcElementOffset(index, mask); Object e = lvElement(buffer, offset);// LoadLoad if (e == JUMP) { return newBufferPeek(getNextBuffer(buffer, mask), index); } return (E) e; }
@Test(dataProvider = "populated") public void relaxedPeek_whenPopulated(MpscGrowableArrayQueue<Integer> queue) { assertThat(queue.relaxedPeek()).isNotNull(); assertThat(queue).hasSize(POPULATED_SIZE); }
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } return results; }
@Test public void tooOldJava1() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/crash-report/too_old_java.txt")), CrashReportAnalyzer.Rule.TOO_OLD_JAVA); assertEquals("52", result.getMatcher().group("expected")); }
public static Config configFromYaml(File yamlFile) throws Exception { return parseYaml(yamlFile, RunAirborneOnKafkaNop.Config.class); }
@Test public void canBuildConfigFromYaml() throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); File yamlFile = new File(classLoader.getResource("fullAirborneConfig.yaml").getFile()); RunAirborneOnKafkaNop.Config config = configFromYaml(yamlFile); config.airFactory(); //fails if the AirborneFactory can't be made verifyKafkaProps(config.inputKafkaProps()); verifyOptions(config.options()); config.partitionMap(); //fails if the mapping can't be made assertThat(config.loggingPeriod(), is(Duration.ofSeconds(15243))); }
@Override public Object cloneAggregatedValue(Object value) { return deserializeAggregatedValue(serializeAggregatedValue(value)); }
@Test public void shouldRetainSketchOrdering() { UpdateSketch input = Sketches.updateSketchBuilder().build(); IntStream.range(0, 10).forEach(input::update); Sketch unordered = input.compact(false, null); Sketch ordered = input.compact(true, null); DistinctCountThetaSketchValueAggregator agg = new DistinctCountThetaSketchValueAggregator(); assertTrue(toSketch(agg.cloneAggregatedValue(ordered)).isOrdered()); assertFalse(toSketch(agg.cloneAggregatedValue(unordered)).isOrdered()); }
@PostMapping("/insertOrUpdate") public ShenyuAdminResult createOrUpdate(@Valid @RequestBody final MockRequestRecordDTO mockRequestRecordDTO) { return ShenyuAdminResult.success(ShenyuResultMessage.SUCCESS, mockRequestRecordService.createOrUpdate(mockRequestRecordDTO)); }
@Test public void testCreateOrUpdate() throws Exception { given(mockRequestRecordService.createOrUpdate(any())).willReturn(1); this.mockMvc.perform(MockMvcRequestBuilders.post("/mock/insertOrUpdate") .contentType(MediaType.APPLICATION_JSON) .content(GsonUtils.getInstance().toJson(new MockRequestRecordDTO()))) .andExpect(status().isOk()) .andExpect(jsonPath("$.message", is(ShenyuResultMessage.SUCCESS))) .andReturn(); }
@Override public void upgrade() { MongoCollection<Document> roles = mongoDatabase.getCollection("roles"); Document viewsUserRole = roles.findOneAndDelete(eq("name", "Views User")); if (viewsUserRole != null) { removeRoleFromUsers(viewsUserRole); } }
@Test public void removesRoleFromRolesCollection() { insertRole("Views User"); Document otherRole = insertRole("Some Other Role"); migration.upgrade(); assertThat(rolesCollection.find()).containsOnly(otherRole); }
@Override public List<PrivilegedOperation> bootstrap(Configuration conf) throws ResourceHandlerException { super.bootstrap(conf); swappiness = conf .getInt(YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS, YarnConfiguration.DEFAULT_NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS); if (swappiness < 0 || swappiness > 100) { throw new ResourceHandlerException( "Illegal value '" + swappiness + "' for " + YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS + ". Value must be between 0 and 100."); } return null; }
@Test public void testBootstrap() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false); conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false); List<PrivilegedOperation> ret = cGroupsMemoryResourceHandler.bootstrap(conf); verify(mockCGroupsHandler, times(1)) .initializeCGroupController(CGroupsHandler.CGroupController.MEMORY); Assert.assertNull(ret); Assert.assertEquals("Default swappiness value incorrect", 0, cGroupsMemoryResourceHandler.getSwappiness()); conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, true); try { cGroupsMemoryResourceHandler.bootstrap(conf); } catch(ResourceHandlerException re) { Assert.fail("Pmem check should be allowed to run with cgroups"); } conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false); conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, true); try { cGroupsMemoryResourceHandler.bootstrap(conf); } catch(ResourceHandlerException re) { Assert.fail("Vmem check should be allowed to run with cgroups"); } }
public String getQuery() throws Exception { return getQuery(weatherConfiguration.getLocation()); }
@Test public void testSingleIdDailyForecastQuery() throws Exception { WeatherConfiguration weatherConfiguration = new WeatherConfiguration(); weatherConfiguration.setIds("524901"); weatherConfiguration.setMode(WeatherMode.XML); weatherConfiguration.setLanguage(WeatherLanguage.nl); weatherConfiguration.setAppid(APPID); weatherConfiguration.setPeriod("20"); WeatherQuery weatherQuery = new WeatherQuery(weatherConfiguration); weatherConfiguration.setGeoLocationProvider(geoLocationProvider); String query = weatherQuery.getQuery(); assertThat(query, is( "http://api.openweathermap.org/data/2.5/forecast/daily?id=524901&lang=nl&cnt=20&mode=xml&APPID=9162755b2efa555823cfe0451d7fff38")); }
@Override // mappedStatementId 参数,暂时没有用。以后,可以基于 mappedStatementId + DataPermission 进行缓存 public List<DataPermissionRule> getDataPermissionRule(String mappedStatementId) { // 1. 无数据权限 if (CollUtil.isEmpty(rules)) { return Collections.emptyList(); } // 2. 未配置,则默认开启 DataPermission dataPermission = DataPermissionContextHolder.get(); if (dataPermission == null) { return rules; } // 3. 已配置,但禁用 if (!dataPermission.enable()) { return Collections.emptyList(); } // 4. 已配置,只选择部分规则 if (ArrayUtil.isNotEmpty(dataPermission.includeRules())) { return rules.stream().filter(rule -> ArrayUtil.contains(dataPermission.includeRules(), rule.getClass())) .collect(Collectors.toList()); // 一般规则不会太多,所以不采用 HashSet 查询 } // 5. 已配置,只排除部分规则 if (ArrayUtil.isNotEmpty(dataPermission.excludeRules())) { return rules.stream().filter(rule -> !ArrayUtil.contains(dataPermission.excludeRules(), rule.getClass())) .collect(Collectors.toList()); // 一般规则不会太多,所以不采用 HashSet 查询 } // 6. 已配置,全部规则 return rules; }
@Test public void testGetDataPermissionRule_02() { // 准备参数 String mappedStatementId = randomString(); // 调用 List<DataPermissionRule> result = dataPermissionRuleFactory.getDataPermissionRule(mappedStatementId); // 断言 assertSame(rules, result); }
public static String maskJson(String input, String key) { if(input == null) return null; DocumentContext ctx = JsonPath.parse(input); return maskJson(ctx, key); }
@Test public void testMaskIssue942() { String input = "{\"name\":\"Steve\", \"list\":[{\"name\":\"Josh\", \"creditCardNumber\":\"4586996854721123\"}],\"password\":\"secret\"}"; String output = Mask.maskJson(input, "testIssue942"); System.out.println(output); Assert.assertEquals(output, "{\"name\":\"Steve\",\"list\":[{\"name\":\"Josh\",\"creditCardNumber\":\"****************\"}],\"password\":\"secret\"}"); }
public static String buildErrorMessage(final Throwable throwable) { if (throwable == null) { return ""; } final List<String> messages = dedup(getErrorMessages(throwable)); final String msg = messages.remove(0); final String causeMsg = messages.stream() .filter(s -> !s.isEmpty()) .map(cause -> WordUtils.wrap(PREFIX + cause, 80, "\n\t", true)) .collect(Collectors.joining(System.lineSeparator())); return causeMsg.isEmpty() ? msg : msg + System.lineSeparator() + causeMsg; }
@Test public void shouldBuildErrorMessageFromExceptionChain() { final Throwable cause = new TestException("Something went wrong"); final Throwable subLevel2 = new TestException("Intermediate message 2", cause); final Throwable subLevel1 = new TestException("Intermediate message 1", subLevel2); final Throwable e = new TestException("Top level", subLevel1); assertThat( buildErrorMessage(e), is("Top level" + System.lineSeparator() + "Caused by: Intermediate message 1" + System.lineSeparator() + "Caused by: Intermediate message 2" + System.lineSeparator() + "Caused by: Something went wrong") ); }
protected AccessControlList toAcl(final Acl acl) { if(Acl.EMPTY.equals(acl)) { return null; } if(Acl.CANNED_PRIVATE.equals(acl)) { return AccessControlList.REST_CANNED_PRIVATE; } if(Acl.CANNED_BUCKET_OWNER_FULLCONTROL.equals(acl)) { return AccessControlList.REST_CANNED_BUCKET_OWNER_FULLCONTROL; } if(Acl.CANNED_BUCKET_OWNER_READ.equals(acl)) { return AccessControlList.REST_CANNED_BUCKET_OWNER_READ; } if(Acl.CANNED_AUTHENTICATED_READ.equals(acl)) { return AccessControlList.REST_CANNED_AUTHENTICATED_READ; } if(Acl.CANNED_PUBLIC_READ.equals(acl)) { return AccessControlList.REST_CANNED_PUBLIC_READ; } if(Acl.CANNED_PUBLIC_READ_WRITE.equals(acl)) { return AccessControlList.REST_CANNED_PUBLIC_READ_WRITE; } final AccessControlList list = new AccessControlList(); for(Acl.UserAndRole userAndRole : acl.asList()) { if(!userAndRole.isValid()) { continue; } if(userAndRole.getUser() instanceof Acl.Owner) { list.setOwner(new StorageOwner(userAndRole.getUser().getIdentifier(), userAndRole.getUser().getDisplayName())); } else if(userAndRole.getUser() instanceof Acl.EmailUser) { list.grantPermission(new EmailAddressGrantee(userAndRole.getUser().getIdentifier()), Permission.parsePermission(userAndRole.getRole().getName())); } else if(userAndRole.getUser() instanceof Acl.GroupUser) { // Handle special cases if(userAndRole.getUser().getIdentifier().equals(Acl.GroupUser.EVERYONE)) { list.grantPermission(GroupGrantee.ALL_USERS, Permission.parsePermission(userAndRole.getRole().getName())); } else if(userAndRole.getUser().getIdentifier().equals(Acl.GroupUser.AUTHENTICATED)) { list.grantPermission(GroupGrantee.AUTHENTICATED_USERS, Permission.parsePermission(userAndRole.getRole().getName())); } else { // Generic mappings list.grantPermission(new GroupGrantee(userAndRole.getUser().getIdentifier()), Permission.parsePermission(userAndRole.getRole().getName())); } } else if(userAndRole.getUser() instanceof Acl.CanonicalUser) { list.grantPermission(new CanonicalGrantee(userAndRole.getUser().getIdentifier()), Permission.parsePermission(userAndRole.getRole().getName())); } else { log.warn(String.format("Unsupported user %s", userAndRole.getUser())); } } if(null == list.getOwner()) { log.warn(String.format("Missing owner in %s", acl)); return null; } return list; }
@Test public void testInvalidOwner() { final S3AccessControlListFeature f = new S3AccessControlListFeature(session); assertNull(f.toAcl(Acl.EMPTY)); assertNull(f.toAcl(new Acl(new Acl.UserAndRole(new Acl.Owner(""), new Acl.Role(Acl.Role.FULL))))); }
public Optional<Node> node(String listenerName) { Endpoint endpoint = listeners().get(listenerName); if (endpoint == null) { return Optional.empty(); } return Optional.of(new Node(id, endpoint.host(), endpoint.port(), null)); }
@Test public void testToNode() { assertEquals(Optional.empty(), REGISTRATIONS.get(0).node("NONEXISTENT")); assertEquals(Optional.of(new Node(0, "localhost", 9107, null)), REGISTRATIONS.get(0).node("PLAINTEXT")); assertEquals(Optional.of(new Node(0, "localhost", 9207, null)), REGISTRATIONS.get(0).node("SSL")); }
@Override public boolean match(Message msg, StreamRule rule) { Object rawField = msg.getField(rule.getField()); if (rawField == null) { return rule.getInverted(); } if (rawField instanceof String) { String field = (String) rawField; Boolean result = rule.getInverted() ^ !(field.trim().isEmpty()); return result; } return !rule.getInverted(); }
@Test public void testInvertedEmptyStringFieldMatch() throws Exception { String fieldName = "sampleField"; StreamRule rule = getSampleRule(); rule.setField(fieldName); rule.setType(StreamRuleType.PRESENCE); rule.setInverted(true); Message message = getSampleMessage(); message.addField(fieldName, ""); StreamRuleMatcher matcher = getMatcher(rule); Boolean result = matcher.match(message, rule); assertTrue(result); }
@Override public List<TimelineEntity> getContainerEntities( ApplicationId appId, String fields, Map<String, String> filters, long limit, String fromId) throws IOException { String path = PATH_JOINER.join("clusters", clusterId, "apps", appId, "entities", YARN_CONTAINER); if (fields == null || fields.isEmpty()) { fields = "INFO"; } MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("fields", fields); if (limit > 0) { params.add("limit", Long.toString(limit)); } if (fromId != null && !fromId.isEmpty()) { params.add("fromid", fromId); } mergeFilters(params, filters); ClientResponse response = doGetUri(baseUri, path, params); TimelineEntity[] entity = response.getEntity(TimelineEntity[].class); return Arrays.asList(entity); }
@Test void testGetContainersForAppAttempt() throws Exception { ApplicationId appId = ApplicationId.fromString("application_1234_0001"); List<TimelineEntity> entities = client.getContainerEntities(appId, null, ImmutableMap.of("infofilters", appAttemptInfoFilter), 0, null); assertEquals(2, entities.size()); assertEquals("mockContainer4", entities.get(1).getId()); }
@Override public void execute(Exchange exchange) throws SmppException { SubmitSm[] submitSms = createSubmitSm(exchange); List<String> messageIDs = new ArrayList<>(submitSms.length); String messageID = null; for (int i = 0; i < submitSms.length; i++) { SubmitSm submitSm = submitSms[i]; messageID = null; if (log.isDebugEnabled()) { log.debug("Sending short message {} for exchange id '{}'...", i, exchange.getExchangeId()); } try { SubmitSmResult result = session.submitShortMessage( submitSm.getServiceType(), TypeOfNumber.valueOf(submitSm.getSourceAddrTon()), NumberingPlanIndicator.valueOf(submitSm.getSourceAddrNpi()), submitSm.getSourceAddr(), TypeOfNumber.valueOf(submitSm.getDestAddrTon()), NumberingPlanIndicator.valueOf(submitSm.getDestAddrNpi()), submitSm.getDestAddress(), new ESMClass(submitSm.getEsmClass()), submitSm.getProtocolId(), submitSm.getPriorityFlag(), submitSm.getScheduleDeliveryTime(), submitSm.getValidityPeriod(), new RegisteredDelivery(submitSm.getRegisteredDelivery()), submitSm.getReplaceIfPresent(), DataCodings.newInstance(submitSm.getDataCoding()), (byte) 0, submitSm.getShortMessage(), submitSm.getOptionalParameters()); if (result != null) { messageID = result.getMessageId(); } } catch (Exception e) { throw new SmppException(e); } if (messageID != null) { messageIDs.add(messageID); } } if (log.isDebugEnabled()) { log.debug("Sent short message for exchange id '{}' and received message ids '{}'", exchange.getExchangeId(), messageIDs); } Message message = ExchangeHelper.getResultMessage(exchange); message.setHeader(SmppConstants.ID, messageIDs); message.setHeader(SmppConstants.SENT_MESSAGE_COUNT, messageIDs.size()); }
@Test public void bodyWithLatin1DataCodingNarrowedToCharset() throws Exception { final byte dataCoding = (byte) 0x03; /* ISO-8859-1 (Latin1) */ byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; byte[] bodyNarrowed = { '?', 'A', 'B', '\0', '?', (byte) 0x7F, 'C', '?' }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.DATA_CODING, dataCoding); exchange.getIn().setBody(body); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance(dataCoding)), eq((byte) 0), eq(bodyNarrowed))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); }
public static CharSequence escapeCsv(CharSequence value) { return escapeCsv(value, false); }
@Test public void escapeCsvWithCarriageReturnAtEnd() { CharSequence value = "testing\r"; CharSequence expected = "\"testing\r\""; escapeCsv(value, expected); }
@Override public <OUT> NonKeyedPartitionStream<OUT> fromSource(Source<OUT> source, String sourceName) { if (source instanceof WrappedSource) { org.apache.flink.api.connector.source.Source<OUT, ?, ?> innerSource = ((WrappedSource<OUT>) source).getWrappedSource(); final TypeInformation<OUT> resolvedTypeInfo = getSourceTypeInfo(innerSource, sourceName); SourceTransformation<OUT, ?, ?> sourceTransformation = new SourceTransformation<>( sourceName, innerSource, WatermarkStrategy.noWatermarks(), resolvedTypeInfo, getParallelism(), false); return new NonKeyedPartitionStreamImpl<>(this, sourceTransformation); } else if (source instanceof FromDataSource) { Collection<OUT> data = ((FromDataSource<OUT>) source).getData(); TypeInformation<OUT> outType = extractTypeInfoFromCollection(data); FromElementsGeneratorFunction<OUT> generatorFunction = new FromElementsGeneratorFunction<>(outType, executionConfig, data); DataGeneratorSource<OUT> generatorSource = new DataGeneratorSource<>(generatorFunction, data.size(), outType); return fromSource(new WrappedSource<>(generatorSource), "Collection Source"); } else { throw new UnsupportedOperationException( "Unsupported type of sink, you could use DataStreamV2SourceUtils to wrap a FLIP-27 based source."); } }
@Test void testFromSource() { ExecutionEnvironmentImpl env = new ExecutionEnvironmentImpl( new DefaultExecutorServiceLoader(), new Configuration(), null); NonKeyedPartitionStream<Integer> source = env.fromSource( DataStreamV2SourceUtils.fromData(Arrays.asList(1, 2, 3)), "test-source"); source.process(new StreamTestUtils.NoOpOneInputStreamProcessFunction()); StreamGraph streamGraph = StreamTestUtils.getStreamGraph(env); Collection<StreamNode> nodes = streamGraph.getStreamNodes(); assertThat(nodes).hasSize(2); Collection<Integer> sourceIDs = streamGraph.getSourceIDs(); for (StreamNode node : nodes) { if (node.getOperatorName().contains("source")) { assertThat(sourceIDs).containsExactly(node.getId()); } } }
@Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (isEnabled()) return super.onInterceptTouchEvent(ev); else return false; }
@Test public void onInterceptTouchEventDisabled() throws Exception { mUnderTest.setEnabled(false); Assert.assertFalse( mUnderTest.onInterceptTouchEvent( MotionEvent.obtain(10, 10, MotionEvent.ACTION_DOWN, 1f, 1f, 0))); }
@Override public synchronized Set<InternalNode> getResourceManagers() { return resourceManagers; }
@Test public void testGetResourceManagers() { DiscoveryNodeManager manager = new DiscoveryNodeManager(selector, workerNodeInfo, new NoOpFailureDetector(), Optional.of(host -> false), expectedVersion, testHttpClient, new TestingDriftClient<>(), internalCommunicationConfig); try { assertEquals(manager.getResourceManagers(), ImmutableSet.of(resourceManager)); } finally { manager.stop(); } }
@Override public int addListener(StatusListener listener) { RFuture<Integer> future = addListenerAsync(listener); return commandExecutor.get(future.toCompletableFuture()); }
@Test public void testReattachPatternTopicListenersOnClusterFailover() { withNewCluster((nodes2, redisson) -> { RedisCluster nodes = redisson.getRedisNodes(RedisNodes.CLUSTER); for (RedisClusterMaster master : nodes.getMasters()) { master.setConfig("notify-keyspace-events", "K$"); } for (RedisClusterSlave slave : nodes.getSlaves()) { slave.setConfig("notify-keyspace-events", "K$"); } AtomicInteger subscriptions = new AtomicInteger(); AtomicInteger messagesReceived = new AtomicInteger(); RPatternTopic topic = redisson.getPatternTopic("__keyspace*__:i*", StringCodec.INSTANCE); topic.addListener(new PatternStatusListener() { @Override public void onPUnsubscribe(String pattern) {} @Override public void onPSubscribe(String pattern) { subscriptions.incrementAndGet(); } }); topic.addListener(String.class, (pattern, channel, msg) -> messagesReceived.incrementAndGet()); assertThat(subscriptions.get()).isEqualTo(1); try { sendCommands(redisson, "dummy").join(); } catch (InterruptedException e) { throw new RuntimeException(e); } await().atMost(30, TimeUnit.SECONDS).until(() -> { return messagesReceived.get() == 100; }); List<ContainerState> masters = getMasterNodes(nodes2); for (ContainerState master : masters) { String r = execute(master, "redis-cli", "exists", "i99"); if (r.contains("1")) { stop(master); break; } } await().atMost(30, TimeUnit.SECONDS).until(() -> { return subscriptions.get() == 2; }); for (RedisClusterMaster master : nodes.getMasters()) { master.setConfig("notify-keyspace-events", "K$"); } redisson.getBucket("i99").set(""); await().atMost(1, TimeUnit.SECONDS).until(() -> { System.out.println("messagesReceived.get() " + messagesReceived.get()); return messagesReceived.get() == 101; }); }); }
@ApiOperation(value = "Delete entity view (deleteEntityView)", notes = "Delete the EntityView object based on the provided entity view id. " + TENANT_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAuthority('TENANT_ADMIN')") @RequestMapping(value = "/entityView/{entityViewId}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) public void deleteEntityView( @Parameter(description = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { checkParameter(ENTITY_VIEW_ID, strEntityViewId); EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); EntityView entityView = checkEntityViewId(entityViewId, Operation.DELETE); tbEntityViewService.delete(entityView, getCurrentUser()); }
@Test public void testDeleteEntityView() throws Exception { EntityView view = getNewSavedEntityView("Test entity view"); Customer customer = doPost("/api/customer", getNewCustomer("My customer"), Customer.class); view.setCustomerId(customer.getId()); EntityView savedView = doPost("/api/entityView", view, EntityView.class); Mockito.reset(tbClusterService, auditLogService); String entityIdStr = savedView.getId().getId().toString(); doDelete("/api/entityView/" + entityIdStr) .andExpect(status().isOk()); testNotifyEntityBroadcastEntityStateChangeEventOneTime(savedView, savedView.getId(), savedView.getId(), tenantId, view.getCustomerId(), tenantAdminUserId, TENANT_ADMIN_EMAIL, ActionType.DELETED, entityIdStr); doGet("/api/entityView/" + entityIdStr) .andExpect(status().isNotFound()) .andExpect(statusReason(containsString(msgErrorNoFound(EntityType.ENTITY_VIEW.getNormalName(), entityIdStr)))); }
static public String map2String(final Map<String, String> tags) { if(tags != null && !tags.isEmpty()) { StringJoiner joined = new StringJoiner(","); for (Object o : tags.entrySet()) { Map.Entry pair = (Map.Entry) o; joined.add(pair.getKey() + "=" + pair.getValue()); } return joined.toString(); } else { return ""; } }
@Test public void testMap2String() { Map<String, String> map = new LinkedHashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); Assert.assertEquals("key1=value1,key2=value2,key3=value3", InfluxDbPoint.map2String(map)); }
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testNugetconfAnalysis() throws Exception { try (Engine engine = new Engine(getSettings())) { File file = BaseTest.getResourceAsFile(this, "nugetconf/packages.config"); Dependency toScan = new Dependency(file); NugetconfAnalyzer analyzer = new NugetconfAnalyzer(); analyzer.setFilesMatched(true); analyzer.initialize(getSettings()); analyzer.prepare(engine); analyzer.setEnabled(true); analyzer.analyze(toScan, engine); int foundCount = 0; for (Dependency result : engine.getDependencies()) { assertEquals(DEPENDENCY_ECOSYSTEM, result.getEcosystem()); assertTrue(result.isVirtual()); switch(result.getName()) { case "Autofac": foundCount++; assertTrue(result.getEvidence(EvidenceType.PRODUCT).toString().contains("Autofac")); assertTrue(result.getEvidence(EvidenceType.VERSION).toString().contains("4.6.2")); break; case "Microsoft.AspNet.WebApi.Core": foundCount++; assertTrue(result.getEvidence(EvidenceType.PRODUCT).toString().contains("Microsoft.AspNet.WebApi.Core")); assertTrue(result.getEvidence(EvidenceType.VERSION).toString().contains("5.2.4")); break; case "Microsoft.Owin": foundCount++; assertTrue(result.getEvidence(EvidenceType.PRODUCT).toString().contains("Microsoft.Owin")); assertTrue(result.getEvidence(EvidenceType.VERSION).toString().contains("3.1.0")); break; case "Newtonsoft.Json": foundCount++; assertTrue(result.getEvidence(EvidenceType.PRODUCT).toString().contains("Newtonsoft.Json")); assertTrue(result.getEvidence(EvidenceType.VERSION).toString().contains("10.0.3")); break; default : break; } } assertEquals("4 dependencies should be found", 4, foundCount); } }
@Override public String resourceNamePrefix() { return appId(); }
@Test void testResourceNamePrefix() { // Resource prefix shall be deterministic per SparkApp per attempt SparkConf sparkConf = new SparkConf(); sparkConf.set("foo", "bar"); sparkConf.set("spark.executor.instances", "1"); String appId = UUID.randomUUID().toString(); SparkAppDriverConf sparkAppDriverConf = SparkAppDriverConf.create( sparkConf, appId, mock(JavaMainAppResource.class), "foo", null, Option.empty()); String resourcePrefix = sparkAppDriverConf.resourceNamePrefix(); assertEquals( resourcePrefix, appId, "Secondary resource prfix should be the same as app id, " + "but different values are detected"); assertTrue( sparkAppDriverConf.configMapNameDriver().contains(resourcePrefix), "ConfigMap name" + " should include secondary resource prefix"); assertTrue( sparkAppDriverConf.driverServiceName().contains(resourcePrefix), "Driver service " + "name should include secondary resource prefix"); }
public boolean delete(PageId pageId, boolean isTemporary) { if (mState.get() != READ_WRITE) { Metrics.DELETE_NOT_READY_ERRORS.inc(); Metrics.DELETE_ERRORS.inc(); return false; } ReadWriteLock pageLock = getPageLock(pageId); try (LockResource r = new LockResource(pageLock.writeLock())) { PageInfo pageInfo; try (LockResource r1 = new LockResource(mPageMetaStore.getLock().writeLock())) { try { pageInfo = mPageMetaStore.removePage(pageId, isTemporary); } catch (PageNotFoundException e) { LOG.debug("Failed to delete page {} from metaStore ", pageId, e); Metrics.DELETE_NON_EXISTING_PAGE_ERRORS.inc(); Metrics.DELETE_ERRORS.inc(); return false; } } boolean ok = deletePage(pageInfo, isTemporary); LOG.debug("delete({}) exits, success: {}", pageId, ok); if (!ok) { Metrics.DELETE_STORE_DELETE_ERRORS.inc(); Metrics.DELETE_ERRORS.inc(); } return ok; } }
@Test public void deleteNotExist() throws Exception { assertFalse(mCacheManager.delete(PAGE_ID1)); }
public MetricsBuilder prometheus(PrometheusConfig prometheus) { this.prometheus = prometheus; return getThis(); }
@Test void prometheus() { PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter(); exporter.setEnabled(true); exporter.setEnableHttpServiceDiscovery(true); exporter.setHttpServiceDiscoveryUrl("localhost:8080"); PrometheusConfig.Pushgateway pushGateway = new PrometheusConfig.Pushgateway(); pushGateway.setEnabled(true); pushGateway.setBaseUrl("localhost:9091"); pushGateway.setUsername("username"); pushGateway.setPassword("password"); pushGateway.setJob("job"); pushGateway.setPushInterval(30); PrometheusConfig prometheus = new PrometheusConfig(); prometheus.setExporter(exporter); prometheus.setPushgateway(pushGateway); MetricsBuilder builder = MetricsBuilder.newBuilder(); builder.prometheus(prometheus); Assertions.assertSame(prometheus, builder.build().getPrometheus()); Assertions.assertSame(exporter, builder.build().getPrometheus().getExporter()); Assertions.assertSame(pushGateway, builder.build().getPrometheus().getPushgateway()); Assertions.assertTrue(builder.build().getPrometheus().getExporter().getEnabled()); Assertions.assertTrue(builder.build().getPrometheus().getExporter().getEnableHttpServiceDiscovery()); Assertions.assertEquals( "localhost:8080", builder.build().getPrometheus().getExporter().getHttpServiceDiscoveryUrl()); Assertions.assertTrue(builder.build().getPrometheus().getPushgateway().getEnabled()); Assertions.assertEquals( "localhost:9091", builder.build().getPrometheus().getPushgateway().getBaseUrl()); Assertions.assertEquals( "username", builder.build().getPrometheus().getPushgateway().getUsername()); Assertions.assertEquals( "password", builder.build().getPrometheus().getPushgateway().getPassword()); Assertions.assertEquals( "job", builder.build().getPrometheus().getPushgateway().getJob()); Assertions.assertEquals( 30, builder.build().getPrometheus().getPushgateway().getPushInterval()); }
protected boolean isPassed() { return !agentHealthHolder.hasLostContact(); }
@Test void shouldReturnFalseIfAgentHasLostContact() { AgentHealthHolder mock = mock(AgentHealthHolder.class); when(mock.hasLostContact()).thenReturn(true); IsConnectedToServerV1 handler = new IsConnectedToServerV1(mock); assertThat(handler.isPassed()).isFalse(); }
static Point map(MeasurementInfo info, Instant timestamp, Gauge<?> gauge) { Point.Builder builder = builder(info, timestamp); Object value = gauge.getValue(); if (value instanceof Number) { builder.addField("value", (Number) value); } else { builder.addField("value", String.valueOf(value)); } return builder.build(); }
@Test void testMapMeter() { Meter meter = new TestMeter(); verifyPoint(MetricMapper.map(INFO, TIMESTAMP, meter), "count=100", "rate=5.0"); }
public void unlockAndDestroy() { if (this.destroyed) { return; } this.destroyed = true; unlock(); }
@Test public void testUnlockAndDestroy() throws Exception { AtomicInteger lockSuccess = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(10); this.id.lock(); for (int i = 0; i < 10; i++) { new Thread() { @Override public void run() { if (ThreadIdTest.this.id.lock() != null) { lockSuccess.incrementAndGet(); } latch.countDown(); } }.start(); } this.id.unlockAndDestroy(); latch.await(); assertEquals(0, lockSuccess.get()); assertNull(this.id.lock()); }
@Override public TopologyCluster getCluster(Topology topology, ClusterId clusterId) { checkNotNull(clusterId, CLUSTER_ID_NULL); return defaultTopology(topology).getCluster(clusterId); }
@Test public void testGetCluster() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); Set<TopologyCluster> clusters = topologyService.getClusters(topology); assertNotNull("The clusters should not be null.", clusters); assertEquals("The clusters size did not match.", 2, clusters.size()); // test the getCluster() method. TopologyCluster cluster = clusters.stream().findFirst().get(); assertNotNull("The cluster should not be null.", cluster); TopologyCluster cluster1 = topologyService.getCluster(topology, cluster.id()); assertNotNull("The cluster should not be null.", cluster1); assertEquals("The cluster ID did not match.", cluster.id(), cluster1.id()); }
static boolean isModern(Class<? extends LoadStatistics> clazz) { // cannot use Util.isOverridden as these are protected methods. boolean hasGetNodes = false; boolean hasMatches = false; while (clazz != LoadStatistics.class && clazz != null && !(hasGetNodes && hasMatches)) { if (!hasGetNodes) { try { final Method getNodes = clazz.getDeclaredMethod("getNodes"); hasGetNodes = !Modifier.isAbstract(getNodes.getModifiers()); } catch (NoSuchMethodException e) { // ignore } } if (!hasMatches) { try { final Method getNodes = clazz.getDeclaredMethod("matches", Queue.Item.class, SubTask.class); hasMatches = !Modifier.isAbstract(getNodes.getModifiers()); } catch (NoSuchMethodException e) { // ignore } } if (!(hasGetNodes && hasMatches) && LoadStatistics.class.isAssignableFrom(clazz.getSuperclass())) { clazz = (Class<? extends LoadStatistics>) clazz.getSuperclass(); } } return hasGetNodes && hasMatches; }
@Test public void isModernWorks() { assertThat(LoadStatistics.isModern(Modern.class), is(true)); assertThat(LoadStatistics.isModern(LoadStatistics.class), is(false)); }
public String getJobName() { if (isBuilding()) { try { return buildLocator.split("/")[4]; } catch (ArrayIndexOutOfBoundsException e) { return null; } } return null; }
@Test public void shouldReturnTheJobName() { AgentBuildingInfo agentBuildingInfo = new AgentBuildingInfo("buildInfo", "foo/1/bar/3/job"); assertThat(agentBuildingInfo.getJobName(), is("job")); }
@Override public void write(ApiMessageAndVersion record) { if (closed) throw new ImageWriterClosedException(); records.add(record); }
@Test public void testWrite() { RecordListWriter writer = new RecordListWriter(); writer.write(testRecord(0)); writer.write(testRecord(1)); writer.close(true); assertEquals(Arrays.asList(testRecord(0), testRecord(1)), writer.records()); }
@Override public SchemaResult getKeySchema( final Optional<String> topicName, final Optional<Integer> schemaId, final FormatInfo expectedFormat, final SerdeFeatures serdeFeatures ) { return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, true); }
@Test public void shouldReturnErrorFromGetKeyIfUnauthorized() throws Exception { // Given: when(srClient.getSchemaBySubjectAndId(any(), anyInt())) .thenThrow(unauthorizedException()); // When: final SchemaResult result = supplier.getKeySchema(Optional.of(TOPIC_NAME), Optional.of(42), expectedFormat, SerdeFeatures.of(SerdeFeature.UNWRAP_SINGLES)); // Then: assertThat(result.schemaAndId, is(Optional.empty())); assertThat(result.failureReason, is(not(Optional.empty()))); verifyFailureMessageForKey(result, Optional.of(42)); }
public void convert(FSConfigToCSConfigConverterParams params) throws Exception { validateParams(params); this.clusterResource = getClusterResource(params); this.convertPlacementRules = params.isConvertPlacementRules(); this.outputDirectory = params.getOutputDirectory(); this.rulesToFile = params.isPlacementRulesToFile(); this.usePercentages = params.isUsePercentages(); this.preemptionMode = params.getPreemptionMode(); prepareOutputFiles(params.isConsole()); loadConversionRules(params.getConversionRulesConfig()); Configuration inputYarnSiteConfig = getInputYarnSiteConfig(params); handleFairSchedulerConfig(params, inputYarnSiteConfig); convert(inputYarnSiteConfig); }
@Test public void testFairSchedulerXmlIsNotDefinedNeitherDirectlyNorInYarnSiteXml() throws Exception { FSConfigToCSConfigConverterParams params = createParamsBuilder(YARN_SITE_XML_NO_REF_TO_FS_XML) .withClusterResource(CLUSTER_RESOURCE_STRING) .build(); expectedException.expect(PreconditionException.class); expectedException.expectMessage("fair-scheduler.xml is not defined"); converter.convert(params); }
public T result() { return result; }
@Test public void testResult() { ResultOrError<Integer> resultOrError = new ResultOrError<>(123); assertFalse(resultOrError.isError()); assertTrue(resultOrError.isResult()); assertEquals(123, resultOrError.result()); assertNull(resultOrError.error()); }
static String cleanUpPath(String path) { return PATH_DIRTY_SLASHES.matcher(path).replaceAll("/").trim(); }
@Test void testEndpointLoggerPathCleaning() { String dirtyPath = " /this//is///a/dirty//path/ "; String anotherDirtyPath = "a/l//p/h/ /a/b ///// e/t"; assertThat(DropwizardResourceConfig.cleanUpPath(dirtyPath)).isEqualTo("/this/is/a/dirty/path/"); assertThat(DropwizardResourceConfig.cleanUpPath(anotherDirtyPath)).isEqualTo("a/l/p/h/a/b/e/t"); }
@Override public Connection connect(String url, Properties info) throws SQLException { // calciteConnection is initialized with an empty Beam schema, // we need to populate it with pipeline options, load table providers, etc return JdbcConnection.initialize((CalciteConnection) super.connect(url, info)); }
@Test public void testInternalConnect_resetAll() throws Exception { CalciteConnection connection = JdbcDriver.connect(BOUNDED_TABLE, PipelineOptionsFactory.create()); Statement statement = connection.createStatement(); assertEquals(0, statement.executeUpdate("SET runner = bogus")); assertEquals(0, statement.executeUpdate("RESET ALL")); assertTrue(statement.execute("SELECT * FROM test")); }
@SuppressWarnings("unchecked") public static void validateResponse(HttpURLConnection conn, int expectedStatus) throws IOException { if (conn.getResponseCode() != expectedStatus) { Exception toThrow; InputStream es = null; try { es = conn.getErrorStream(); Map json = JsonSerialization.mapReader().readValue(es); json = (Map) json.get(ERROR_JSON); String exClass = (String) json.get(ERROR_CLASSNAME_JSON); String exMsg = (String) json.get(ERROR_MESSAGE_JSON); if (exClass != null) { try { ClassLoader cl = HttpExceptionUtils.class.getClassLoader(); Class klass = cl.loadClass(exClass); Preconditions.checkState(Exception.class.isAssignableFrom(klass), "Class [%s] is not a subclass of Exception", klass); MethodHandle methodHandle = PUBLIC_LOOKUP.findConstructor( klass, EXCEPTION_CONSTRUCTOR_TYPE); toThrow = (Exception) methodHandle.invoke(exMsg); } catch (Throwable t) { toThrow = new IOException(String.format( "HTTP status [%d], exception [%s], message [%s], URL [%s]", conn.getResponseCode(), exClass, exMsg, conn.getURL())); } } else { String msg = (exMsg != null) ? exMsg : conn.getResponseMessage(); toThrow = new IOException(String.format( "HTTP status [%d], message [%s], URL [%s]", conn.getResponseCode(), msg, conn.getURL())); } } catch (Exception ex) { toThrow = new IOException(String.format( "HTTP status [%d], message [%s], URL [%s], exception [%s]", conn.getResponseCode(), conn.getResponseMessage(), conn.getURL(), ex.toString()), ex); } finally { if (es != null) { try { es.close(); } catch (IOException ex) { //ignore } } } throwEx(toThrow); } }
@Test public void testValidateResponseOK() throws IOException { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_CREATED); HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED); }
public PartitionMetadata read() { synchronized (lock) { try { try (BufferedReader reader = Files.newBufferedReader(path(), StandardCharsets.UTF_8)) { PartitionMetadataReadBuffer partitionBuffer = new PartitionMetadataReadBuffer(file.getAbsolutePath(), reader); return partitionBuffer.read(); } } catch (IOException e) { String msg = "Error while reading partition metadata file " + file.getAbsolutePath(); logDirFailureChannel.maybeAddOfflineLogDir(logDir(), msg, e); throw new KafkaStorageException(msg, e); } } }
@Test public void testRead() { LogDirFailureChannel channel = Mockito.mock(LogDirFailureChannel.class); PartitionMetadataFile partitionMetadataFile = new PartitionMetadataFile(file, channel); Uuid topicId = Uuid.randomUuid(); partitionMetadataFile.record(topicId); partitionMetadataFile.maybeFlush(); PartitionMetadata metadata = partitionMetadataFile.read(); assertEquals(0, metadata.version()); assertEquals(topicId, metadata.topicId()); }
@Override public boolean checkExists(String path) { try { if (client.checkExists().forPath(path) != null) { return true; } } catch (Exception ignored) { } return false; }
@Test void testCreateContent4Persistent() { String path = "/curatorTest4CrContent/content.data"; String content = "createContentTest"; curatorClient.delete(path); assertThat(curatorClient.checkExists(path), is(false)); assertNull(curatorClient.getContent(path)); curatorClient.createOrUpdate(path, content, false); assertThat(curatorClient.checkExists(path), is(true)); assertEquals(curatorClient.getContent(path), content); }
@Override public TimeSlot apply(TimeSlot timeSlot, SegmentInMinutes segmentInMinutes) { int segmentInMinutesDuration = segmentInMinutes.value(); Instant segmentStart = normalizeStart(timeSlot.from(), segmentInMinutesDuration); Instant segmentEnd = normalizeEnd(timeSlot.to(), segmentInMinutesDuration); TimeSlot normalized = new TimeSlot(segmentStart, segmentEnd); TimeSlot minimalSegment = new TimeSlot(segmentStart, segmentStart.plus(segmentInMinutes.value(), ChronoUnit.MINUTES)); if (normalized.within(minimalSegment)) { return minimalSegment; } return normalized; }
@Test void normalizedToTheHour() { //given Instant start = Instant.parse("2023-09-09T00:10:00Z"); Instant end = Instant.parse("2023-09-09T00:59:00Z"); TimeSlot timeSlot = new TimeSlot(start, end); SegmentInMinutes oneHour = SegmentInMinutes.of(60, FIFTEEN_MINUTES_SEGMENT_DURATION); //when TimeSlot normalized = SLOT_TO_NORMALIZED_SLOT.apply(timeSlot, oneHour); //then assertEquals(Instant.parse("2023-09-09T00:00:00Z"), normalized.from()); assertEquals(Instant.parse("2023-09-09T01:00:00Z"), normalized.to()); }
public static RemoteCall<TransactionReceipt> sendFunds( Web3j web3j, Credentials credentials, String toAddress, BigDecimal value, Convert.Unit unit) throws InterruptedException, IOException, TransactionException { TransactionManager transactionManager = new RawTransactionManager(web3j, credentials); return new RemoteCall<>( () -> new Transfer(web3j, transactionManager).send(toAddress, value, unit)); }
@Test public void testSendFunds() throws Exception { assertEquals( sendFunds(SampleKeys.CREDENTIALS, ADDRESS, BigDecimal.TEN, Convert.Unit.ETHER), (transactionReceipt)); }
public List<String> getAllowsToSignUpEnabledIdentityProviders() { if (managedInstanceService.isInstanceExternallyManaged()) { return emptyList(); } return identityProviderRepository.getAllEnabledAndSorted() .stream() .filter(IdentityProvider::isEnabled) .filter(IdentityProvider::allowsUsersToSignUp) .map(IdentityProvider::getName) .toList(); }
@Test public void getAllowsToSignUpEnabledIdentityProviders_whenDefined_shouldReturnOnlyEnabled() { mockIdentityProviders(List.of( new TestIdentityProvider().setKey("saml").setName("Okta").setEnabled(true).setAllowsUsersToSignUp(true), new TestIdentityProvider().setKey("github").setName("GitHub").setEnabled(true).setAllowsUsersToSignUp(false), new TestIdentityProvider().setKey("bitbucket").setName("BitBucket").setEnabled(false).setAllowsUsersToSignUp(false) )); assertThat(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()) .containsExactly("Okta"); }
@Override public void upgrade() { if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed!"); return; } final List<ViewWidgetLimitMigration> widgetLimitMigrations = StreamSupport.stream(this.views.find().spliterator(), false) .flatMap(document -> { final String viewId = document.get("_id", ObjectId.class).toHexString(); final Map<String, Document> state = document.get("state", Collections.emptyMap()); return state.entrySet().stream() .flatMap(entry -> { final String queryId = entry.getKey(); final List<Document> widgets = entry.getValue().get("widgets", Collections.emptyList()); return EntryStream.of(widgets) .filter(widget -> "aggregation".equals(widget.getValue().getString("type"))) .flatMap(widgetEntry -> { final Document widget = widgetEntry.getValue(); final Integer widgetIndex = widgetEntry.getKey(); final Document config = widget.get("config", new Document()); final boolean hasRowLimit = config.containsKey("row_limit"); final boolean hasColumnLimit = config.containsKey("column_limit"); final Optional<Integer> rowLimit = Optional.ofNullable(config.getInteger("row_limit")); final Optional<Integer> columnLimit = Optional.ofNullable(config.getInteger("column_limit")); if (widgetIndex != null && (hasRowLimit || hasColumnLimit)) { return Stream.of(new ViewWidgetLimitMigration(viewId, queryId, widgetIndex, rowLimit, columnLimit)); } return Stream.empty(); }); }); }) .collect(Collectors.toList()); final List<WriteModel<Document>> operations = widgetLimitMigrations.stream() .flatMap(widgetMigration -> { final ImmutableList.Builder<WriteModel<Document>> builder = ImmutableList.builder(); builder.add( updateView( widgetMigration.viewId, doc("$unset", doc(widgetConfigPath(widgetMigration) + ".row_limit", 1)) ) ); builder.add( updateView( widgetMigration.viewId, doc("$set", doc(widgetConfigPath(widgetMigration) + ".row_pivots.$[config].config.limit", widgetMigration.rowLimit.orElse(DEFAULT_LIMIT))), matchValuePivots ) ); builder.add( updateView( widgetMigration.viewId, doc("$unset", doc(widgetConfigPath(widgetMigration) + ".column_limit", 1)) ) ); builder.add( updateView( widgetMigration.viewId, doc("$set", doc(widgetConfigPath(widgetMigration) + ".column_pivots.$[config].config.limit", widgetMigration.columnLimit.orElse(DEFAULT_LIMIT))), matchValuePivots ) ); return builder.build().stream(); }) .collect(Collectors.toList()); if (!operations.isEmpty()) { LOG.debug("Updating {} widgets ...", widgetLimitMigrations.size()); this.views.bulkWrite(operations); } clusterConfigService.write(new MigrationCompleted(widgetLimitMigrations.size())); }
@Test @MongoDBFixtures("V20230113095300_MigrateGlobalPivotLimitsToGroupingsInViewsTest_null_limits.json") void migratingPivotsWithNullLimits() { this.migration.upgrade(); assertThat(migrationCompleted().migratedViews()).isEqualTo(1); final Document document = this.collection.find().first(); final List<Document> widgets = getWidgets(document); for (Document widget : widgets) { assertThatFieldsAreUnset(widget); } }
@Override public MutableTreeRootHolder setRoots(Component root, Component reportRoot) { checkState(this.root == null, "root can not be set twice in holder"); this.root = requireNonNull(root, "root can not be null"); this.extendedTreeRoot = requireNonNull(reportRoot, "extended tree root can not be null"); return this; }
@Test public void setRoots_throws_NPE_if_root_is_null() { assertThatThrownBy(() -> underTest.setRoots(null, DUMB_PROJECT)) .isInstanceOf(NullPointerException.class) .hasMessage("root can not be null"); }
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public HistoryInfo get() { return getHistoryInfo(); }
@Test public void testHS() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("history") .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, response.getType().toString()); JSONObject json = response.getEntity(JSONObject.class); assertEquals("incorrect number of elements", 1, json.length()); verifyHSInfo(json.getJSONObject("historyInfo"), appContext); }
public RandomForest prune(DataFrame test) { Model[] forest = Arrays.stream(models).parallel() .map(model -> new Model(model.tree.prune(test, formula, classes), model.metrics)) .toArray(Model[]::new); // The tree weight and OOB metrics are still the old one // as we don't access to the training data here. return new RandomForest(formula, k, forest, metrics, importance(forest), classes); }
@Test public void testPrune() { System.out.println("prune"); // Overfitting with very large maxNodes and small nodeSize RandomForest model = RandomForest.fit(USPS.formula, USPS.train, 200, 16, SplitRule.GINI, 20, 2000, 1, 1.0, null, Arrays.stream(seeds)); double[] importance = model.importance(); for (int i = 0; i < importance.length; i++) { System.out.format("%-15s %.4f%n", model.schema().name(i), importance[i]); } int[] prediction = model.predict(USPS.test); int error = Error.of(USPS.testy, prediction); System.out.println("Error = " + error); assertEquals(115, error); RandomForest lean = model.prune(USPS.test); importance = lean.importance(); for (int i = 0; i < importance.length; i++) { System.out.format("%-15s %.4f%n", lean.schema().name(i), importance[i]); } // The old model should not be modified. prediction = model.predict(USPS.test); error = Error.of(USPS.testy, prediction); System.out.println("Error of old model after pruning = " + error); assertEquals(115, error); prediction = lean.predict(USPS.test); error = Error.of(USPS.testy, prediction); System.out.println("Error of pruned model after pruning = " + error); assertEquals(87, error); }
@Override public void updatePost(PostSaveReqVO updateReqVO) { // 校验正确性 validatePostForCreateOrUpdate(updateReqVO.getId(), updateReqVO.getName(), updateReqVO.getCode()); // 更新岗位 PostDO updateObj = BeanUtils.toBean(updateReqVO, PostDO.class); postMapper.updateById(updateObj); }
@Test public void testValidatePost_codeDuplicateForUpdate() { // mock 数据 PostDO postDO = randomPostDO(); postMapper.insert(postDO); // mock 数据:稍后模拟重复它的 code PostDO codePostDO = randomPostDO(); postMapper.insert(codePostDO); // 准备参数 PostSaveReqVO reqVO = randomPojo(PostSaveReqVO.class, o -> { // 设置更新的 ID o.setId(postDO.getId()); // 模拟 code 重复 o.setCode(codePostDO.getCode()); }); // 调用, 并断言异常 assertServiceException(() -> postService.updatePost(reqVO), POST_CODE_DUPLICATE); }
public Flux<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, List<CopyParameters> toCopy) { checkBackupLevel(backupUser, BackupLevel.MEDIA); return Mono // Figure out how many objects we're allowed to copy, updating the quota usage for the amount we are allowed .fromFuture(enforceQuota(backupUser, toCopy)) // Copy the ones we have enough quota to hold .flatMapMany(quotaResult -> Flux.concat( // These fit in our remaining quota, so perform the copy. If the copy fails, our estimated quota usage may not // be exact since we already updated our usage. We make a best-effort attempt to undo the usage update if we // know that the copied failed for sure though. Flux.fromIterable(quotaResult.requestsToCopy()).flatMapSequential( copyParams -> copyToBackup(backupUser, copyParams) .flatMap(copyResult -> switch (copyResult.outcome()) { case SUCCESS -> Mono.just(copyResult); case SOURCE_WRONG_LENGTH, SOURCE_NOT_FOUND, OUT_OF_QUOTA -> Mono .fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize())) .thenReturn(copyResult); }), COPY_CONCURRENCY), // There wasn't enough quota remaining to perform these copies Flux.fromIterable(quotaResult.requestsToReject()) .map(arg -> new CopyResult(CopyResult.Outcome.OUT_OF_QUOTA, arg.destinationMediaId(), null)))); }
@Test public void copyPartialSuccess() { final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupLevel.MEDIA); final List<CopyParameters> toCopy = List.of( new CopyParameters(3, "success", 100, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15)), new CopyParameters(3, "missing", 200, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15)), new CopyParameters(3, "badlength", 300, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15))); when(tusCredentialGenerator.generateUpload(any())) .thenReturn(new BackupUploadDescriptor(3, "", Collections.emptyMap(), "")); when(remoteStorageManager.copy(eq(3), eq("success"), eq(100), any(), any())) .thenReturn(CompletableFuture.completedFuture(null)); when(remoteStorageManager.copy(eq(3), eq("missing"), eq(200), any(), any())) .thenReturn(CompletableFuture.failedFuture(new SourceObjectNotFoundException())); when(remoteStorageManager.copy(eq(3), eq("badlength"), eq(300), any(), any())) .thenReturn(CompletableFuture.failedFuture(new InvalidLengthException(""))); final List<CopyResult> results = backupManager.copyToBackup(backupUser, toCopy) .collectList().block(); assertThat(results.get(0).outcome()).isEqualTo(CopyResult.Outcome.SUCCESS); assertThat(results.get(1).outcome()).isEqualTo(CopyResult.Outcome.SOURCE_NOT_FOUND); assertThat(results.get(2).outcome()).isEqualTo(CopyResult.Outcome.SOURCE_WRONG_LENGTH); // usage should be rolled back after a known copy failure final Map<String, AttributeValue> backup = getBackupItem(backupUser); assertThat(AttributeValues.getLong(backup, BackupsDb.ATTR_MEDIA_BYTES_USED, -1L)) .isEqualTo(toCopy.get(0).destinationObjectSize()); assertThat(AttributeValues.getLong(backup, BackupsDb.ATTR_MEDIA_COUNT, -1L)).isEqualTo(1L); }
public static Builder newBuilder() { return new Builder(); }
@Test public void fail_if_malformed_URL() { assertThatThrownBy(() -> newBuilder().url("wrong URL").build()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Malformed URL: 'wrong URL'"); }
public void delete(boolean drainQueue) { addTask(TbQueueConsumerManagerTask.delete(drainQueue)); }
@Test public void testDelete_singleConsumer() { queue.setConsumerPerPartition(false); consumerManager.init(queue); Set<TopicPartitionInfo> partitions = createTpis(1, 2); consumerManager.update(partitions); TestConsumer consumer = getConsumer(); verifySubscribedAndLaunched(consumer, partitions); verifyMsgProcessed(consumer.testMsg); consumerManager.delete(true); await().atMost(2, TimeUnit.SECONDS) .untilAsserted(() -> { verify(ruleEngineMsgProducer).send(any(), any(), any()); }); clearInvocations(actorContext); verify(consumer, never()).unsubscribe(); int msgCount = totalConsumedMsgs.get(); await().atLeast(2, TimeUnit.SECONDS) // based on topicDeletionDelayInSec(5) = 5 - ( 3 seconds the code may execute starting consumerManager.delete() call) .atMost(20, TimeUnit.SECONDS) .untilAsserted(() -> { partitions.stream() .map(TopicPartitionInfo::getFullTopicName) .forEach(topic -> { verify(queueAdmin).deleteTopic(eq(topic)); }); }); verify(consumer).unsubscribe(); int movedMsgs = totalConsumedMsgs.get() - msgCount; assertThat(movedMsgs).isNotZero(); verify(ruleEngineMsgProducer, atLeast(movedMsgs)).send(any(), any(), any()); verify(actorContext, never()).tell(any()); generateQueueMsgs = false; }
@Override public Server build(Environment environment) { printBanner(environment.getName()); final ThreadPool threadPool = createThreadPool(environment.metrics()); final Server server = buildServer(environment.lifecycle(), threadPool); final Handler applicationHandler = createAppServlet(server, environment.jersey(), environment.getObjectMapper(), environment.getValidator(), environment.getApplicationContext(), environment.getJerseyServletContainer(), environment.metrics()); final Handler adminHandler = createAdminServlet(server, environment.getAdminContext(), environment.metrics(), environment.healthChecks(), environment.admin()); final RoutingHandler routingHandler = buildRoutingHandler(environment.metrics(), server, applicationHandler, adminHandler); final Handler gzipHandler = buildGzipHandler(routingHandler); server.setHandler(addStatsHandler(addRequestLog(server, gzipHandler, environment.getName()))); return server; }
@Test void configuresDumpAfterStart() { http.setDumpAfterStart(true); assertThat(http.build(environment).isDumpAfterStart()).isTrue(); }
public final void contains(@Nullable Object element) { if (!Iterables.contains(checkNotNull(actual), element)) { List<@Nullable Object> elementList = newArrayList(element); if (hasMatchingToStringPair(actual, elementList)) { failWithoutActual( fact("expected to contain", element), fact("an instance of", objectToTypeName(element)), simpleFact("but did not"), fact( "though it did contain", countDuplicatesAndAddTypeInfo( retainMatchingToString(actual, /* itemsToCheck= */ elementList))), fullContents()); } else { failWithActual("expected to contain", element); } } }
@Test public void iterableContainsWithNull() { assertThat(asList(1, null, 3)).contains(null); }
public static String toChecksumAddress(String address) { String lowercaseAddress = Numeric.cleanHexPrefix(address).toLowerCase(); String addressHash = Numeric.cleanHexPrefix(Hash.sha3String(lowercaseAddress)); StringBuilder result = new StringBuilder(lowercaseAddress.length() + 2); result.append("0x"); for (int i = 0; i < lowercaseAddress.length(); i++) { if (Integer.parseInt(String.valueOf(addressHash.charAt(i)), 16) >= 8) { result.append(String.valueOf(lowercaseAddress.charAt(i)).toUpperCase()); } else { result.append(lowercaseAddress.charAt(i)); } } return result.toString(); }
@Test public void testToChecksumAddress() { // Test cases as per https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md#test-cases assertEquals( Keys.toChecksumAddress("0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359"), ("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359")); // All uppercase assertEquals( Keys.toChecksumAddress("0x52908400098527886E0F7030069857D2E4169EE7"), ("0x52908400098527886E0F7030069857D2E4169EE7")); assertEquals( Keys.toChecksumAddress("0x8617E340B3D01FA5F11F306F4090FD50E238070D"), ("0x8617E340B3D01FA5F11F306F4090FD50E238070D")); // All lowercase assertEquals( Keys.toChecksumAddress("0xde709f2102306220921060314715629080e2fb77"), ("0xde709f2102306220921060314715629080e2fb77")); assertEquals( Keys.toChecksumAddress("0x27b1fdb04752bbc536007a920d24acb045561c26"), ("0x27b1fdb04752bbc536007a920d24acb045561c26")); // Normal assertEquals( Keys.toChecksumAddress("0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"), ("0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed")); assertEquals( Keys.toChecksumAddress("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359"), ("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359")); assertEquals( Keys.toChecksumAddress("0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB"), ("0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB")); assertEquals( Keys.toChecksumAddress("0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb"), ("0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb")); }
public static boolean equals(ByteBuf a, int aStartIndex, ByteBuf b, int bStartIndex, int length) { checkNotNull(a, "a"); checkNotNull(b, "b"); // All indexes and lengths must be non-negative checkPositiveOrZero(aStartIndex, "aStartIndex"); checkPositiveOrZero(bStartIndex, "bStartIndex"); checkPositiveOrZero(length, "length"); if (a.writerIndex() - length < aStartIndex || b.writerIndex() - length < bStartIndex) { return false; } final int longCount = length >>> 3; final int byteCount = length & 7; if (a.order() == b.order()) { for (int i = longCount; i > 0; i --) { if (a.getLong(aStartIndex) != b.getLong(bStartIndex)) { return false; } aStartIndex += 8; bStartIndex += 8; } } else { for (int i = longCount; i > 0; i --) { if (a.getLong(aStartIndex) != swapLong(b.getLong(bStartIndex))) { return false; } aStartIndex += 8; bStartIndex += 8; } } for (int i = byteCount; i > 0; i --) { if (a.getByte(aStartIndex) != b.getByte(bStartIndex)) { return false; } aStartIndex ++; bStartIndex ++; } return true; }
@Test public void notEqualsBufferUnderflow() { final byte[] b1 = new byte[8]; final byte[] b2 = new byte[16]; Random rand = new Random(); rand.nextBytes(b1); rand.nextBytes(b2); final int iB1 = b1.length / 2; final int iB2 = iB1 + b1.length; final int length = b1.length - iB1; System.arraycopy(b1, iB1, b2, iB2, length - 1); assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() { ByteBufUtil.equals(Unpooled.wrappedBuffer(b1), iB1, Unpooled.wrappedBuffer(b2), iB2, -1); } }); }
@Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { if (!TbJsonPathNodeConfiguration.DEFAULT_JSON_PATH.equals(this.jsonPathValue)) { try { Object jsonPathData = jsonPath.read(msg.getData(), this.configurationJsonPath); ctx.tellSuccess(TbMsg.transformMsgData(msg, JacksonUtil.toString(jsonPathData))); } catch (PathNotFoundException e) { ctx.tellFailure(msg, e); } } else { ctx.tellSuccess(msg); } }
@Test void givenNoResultsForPath_whenOnMsg_thenTellFailure() throws Exception { String data = "{\"Attribute_1\":22.5,\"Attribute_5\":10.3}"; JsonNode dataNode = JacksonUtil.toJsonNode(data); TbMsg msg = getTbMsg(deviceId, dataNode.toString()); node.onMsg(ctx, msg); ArgumentCaptor<TbMsg> newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class); ArgumentCaptor<Exception> exceptionCaptor = ArgumentCaptor.forClass(Exception.class); verify(ctx, never()).tellSuccess(any()); verify(ctx, times(1)).tellFailure(newMsgCaptor.capture(), exceptionCaptor.capture()); assertThat(newMsgCaptor.getValue()).isSameAs(msg); assertThat(exceptionCaptor.getValue()).isInstanceOf(PathNotFoundException.class); }
@Override public LifecycleConfiguration getConfiguration(final Path file) throws BackgroundException { final Path bucket = containerService.getContainer(file); if(file.getType().contains(Path.Type.upload)) { return LifecycleConfiguration.empty(); } try { final LifecycleConfig status = session.getClient().getLifecycleConfig(bucket.isRoot() ? StringUtils.EMPTY : bucket.getName()); if(null == status) { log.warn(String.format("Failure parsing lifecycle config for %s", bucket)); return LifecycleConfiguration.empty(); } Integer transition = null; Integer expiration = null; String storageClass = null; for(LifecycleConfig.Rule rule : status.getRules()) { if(StringUtils.isBlank(rule.getPrefix())) { if(rule.getTransition() != null) { transition = rule.getTransition().getDays(); } if(rule.getExpiration() != null) { expiration = rule.getExpiration().getDays(); } } } return new LifecycleConfiguration(transition, expiration); } catch(ServiceException e) { try { throw new S3ExceptionMappingService().map("Failure to read attributes of {0}", e, bucket); } catch(AccessDeniedException | InteroperabilityException l) { log.warn(String.format("Missing permission to read lifecycle configuration for %s %s", bucket, e.getMessage())); return LifecycleConfiguration.empty(); } } }
@Test public void testGetConfiguration() throws Exception { final LifecycleConfiguration configuration = new S3LifecycleConfiguration(session).getConfiguration( new Path("test-lifecycle-us-east-1-cyberduck", EnumSet.of(Path.Type.directory)) ); assertEquals(30, configuration.getExpiration(), 0L); assertEquals(1, configuration.getTransition(), 0L); }
public List<? extends Coder<?>> getElementCoders() { return elementCoders; }
@Test public void testGetElementCoders() { UnionCoder unionCoder = UnionCoder.of(ImmutableList.of(StringUtf8Coder.of(), DoubleCoder.of())); assertThat(unionCoder.getElementCoders().get(0), Matchers.equalTo(StringUtf8Coder.of())); assertThat(unionCoder.getElementCoders().get(1), Matchers.equalTo(DoubleCoder.of())); }
public static Map<String, Object> decryptMap(Map<String, Object> map) { decryptNode(map); return map; }
@Test public void testDecryptMap() { Map<String, Object> secretMap = Config.getInstance().getJsonMapConfig("secret"); DecryptUtil.decryptMap(secretMap); Assert.assertEquals("password", secretMap.get("serverKeystorePass")); }
public void submit(Zombie zombie) { Task<?> reapTask = zombie.reap().onFailure(e -> { if (ZKUtil.isRecoverable(e)) { submit(zombie); } else { LOG.error("failed to delete zombie node: {}", zombie); } }); _engine.run(reapTask); }
@Test public void testReaperRetry() throws InterruptedException { final int MAX_RETRY = 3; final CountDownLatch failure = new CountDownLatch(MAX_RETRY); final CountDownLatch success = new CountDownLatch(1); Reaper.Zombie zombie = new Reaper.Zombie() { private int count = 0; @Override public Task<Void> reap() { if (count++ < MAX_RETRY) { return Task.action(() -> failure.countDown()) .andThen(Task.failure(KeeperException.create(KeeperException.Code.CONNECTIONLOSS))); } else { return Task.action(() -> success.countDown()); } } }; _reaper.submit(zombie); Assert.assertTrue(failure.await(10, TimeUnit.SECONDS)); Assert.assertTrue(success.await(10, TimeUnit.SECONDS)); }
@Override @Transactional public Product createProduct(String title, String details) { return this.productRepository.save(new Product(null, title, details)); }
@Test void createProduct_ReturnsCreatedProduct() { // given var title = "Новый товар"; var details = "Описание нового товара"; doReturn(new Product(1, "Новый товар", "Описание нового товара")) .when(this.productRepository).save(new Product(null, "Новый товар", "Описание нового товара")); // when var result = this.service.createProduct(title, details); // then assertEquals(new Product(1, "Новый товар", "Описание нового товара"), result); verify(this.productRepository).save(new Product(null, "Новый товар", "Описание нового товара")); verifyNoMoreInteractions(this.productRepository); }
@Override public List<TransferItem> normalize(final List<TransferItem> roots) { final List<TransferItem> normalized = new ArrayList<>(); for(TransferItem upload : roots) { boolean duplicate = false; for(Iterator<TransferItem> iter = normalized.iterator(); iter.hasNext(); ) { TransferItem n = iter.next(); if(upload.local.isChild(n.local)) { // The selected file is a child of a directory already included duplicate = true; break; } if(n.local.isChild(upload.local)) { iter.remove(); } if(upload.remote.equals(n.remote)) { // The selected file has the same name; if uploaded as a root element // it would overwrite the earlier final Path parent = upload.remote.getParent(); final String filename = upload.remote.getName(); String proposal; int no = 0; int index = filename.lastIndexOf('.'); Path remote; do { if(index != -1 && index != 0) { proposal = String.format("%s-%d%s", filename.substring(0, index), ++no, filename.substring(index)); } else { proposal = String.format("%s-%d", filename, ++no); } remote = new Path(parent, proposal, upload.remote.getType()); } while(false);//(upload.exists()); if(log.isInfoEnabled()) { log.info(String.format("Changed name from %s to %s", filename, remote.getName())); } upload.remote = remote; } } // Prunes the list of selected files. Files which are a child of an already included directory // are removed from the returned list. if(!duplicate) { normalized.add(new TransferItem(upload.remote, upload.local)); } } return normalized; }
@Test public void testNormalizeLargeSet() { UploadRootPathsNormalizer n = new UploadRootPathsNormalizer(); final List<TransferItem> list = new ArrayList<>(); for(int i = 0; i < 1000; i++) { final String name = String.format("f-%d", i); list.add(new TransferItem(new Path(name, EnumSet.of(Path.Type.file)), new NullLocal(name))); } final List<TransferItem> normalized = n.normalize(list); assertEquals(1000, normalized.size()); }
@Override public Authenticator create(KeycloakSession session) { logger.info("Trying to create {} via factory.", this.getClass().getSimpleName()); return SINGLETON; }
@Test public void testCreate() { //GIVEN CorporateEdsLoginAuthenticatorFactory factory = new CorporateEdsLoginAuthenticatorFactory(); // Mock the KeycloakSession KeycloakSession session = Mockito.mock(KeycloakSession.class); //WHEN var authenticator = factory.create(session); //THEN assertNotNull("Created Authenticator should not be null", authenticator); assertEquals("Class of the created authenticator should be CorporateEdsLoginAuthenticator", CorporateEdsLoginAuthenticator.class, authenticator.getClass()); }
@Override public int compareTo(VirtualPointer other) { return Long.compare(logicalOffset, other.logicalOffset); }
@Test public void testCompare() { final VirtualPointer lower = new VirtualPointer(100L); final VirtualPointer higher = new VirtualPointer(200L); assertEquals(1, higher.compareTo(lower), higher.logicalOffset + " must be greater than " + lower.logicalOffset); assertEquals(-1, lower.compareTo(higher), lower.logicalOffset + " must be lower than " + higher.logicalOffset); assertEquals(0, lower.compareTo(lower), "identity must be equal"); }
@Override public List<SelectMappedBufferResult> getBulkCommitLogData(final long offset, final int size) { if (this.shutdown) { LOGGER.warn("message store has shutdown, so getBulkCommitLogData is forbidden"); return null; } return this.commitLog.getBulkData(offset, size); }
@Test public void testGetBulkCommitLogData() { DefaultMessageStore defaultMessageStore = (DefaultMessageStore) messageStore; messageBody = new byte[2 * 1024 * 1024]; for (int i = 0; i < 10; i++) { MessageExtBrokerInner msg1 = buildMessage(); messageStore.putMessage(msg1); } System.out.printf("%d%n", defaultMessageStore.getMaxPhyOffset()); List<SelectMappedBufferResult> bufferResultList = defaultMessageStore.getBulkCommitLogData(0, (int) defaultMessageStore.getMaxPhyOffset()); List<MessageExt> msgList = new ArrayList<>(); for (SelectMappedBufferResult bufferResult : bufferResultList) { msgList.addAll(MessageDecoder.decodesBatch(bufferResult.getByteBuffer(), true, false, false)); bufferResult.release(); } assertThat(msgList.size()).isEqualTo(10); }
@Override public String getHttpMethod() { return HttpMethods.GET; }
@Test public void testGetHttpMethod() { Assert.assertEquals("GET", testBlobPuller.getHttpMethod()); }
@Override public Long clusterCountKeysInSlot(int slot) { MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(slot); RFuture<Long> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLUSTER_COUNTKEYSINSLOT, slot); return syncFuture(f); }
@Test public void testClusterCountKeysInSlot() { Long t = connection.clusterCountKeysInSlot(1); assertThat(t).isZero(); }
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType); return BINARY_PROTOCOL_VALUES.get(binaryColumnType); }
@Test void assertGetBinaryProtocolValueWithMySQLTypeYear() { assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.YEAR), instanceOf(MySQLInt2BinaryProtocolValue.class)); }
public Object normalizeValue( ValueMetaInterface valueMeta, Object value ) throws KettleValueException { if ( valueMeta.isDate() ) { // Pass date field converted to UTC, see PDI-10836 Calendar cal = Calendar.getInstance( valueMeta.getDateFormatTimeZone() ); cal.setTime( valueMeta.getDate( value ) ); Calendar utc = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); // Reset time-related fields utc.clear(); utc.set( cal.get( Calendar.YEAR ), cal.get( Calendar.MONTH ), cal.get( Calendar.DATE ), cal.get( Calendar.HOUR_OF_DAY ), cal.get( Calendar.MINUTE ), cal.get( Calendar.SECOND ) ); value = utc; } else if ( valueMeta.isStorageBinaryString() ) { value = valueMeta.convertToNormalStorageType( value ); } if ( ValueMetaInterface.TYPE_INTEGER == valueMeta.getType() ) { // Salesforce integer values can be only http://www.w3.org/2001/XMLSchema:int // see org.pentaho.di.ui.trans.steps.salesforceinput.SalesforceInputDialog#addFieldToTable // So we need convert Hitachi Vantara integer (real java Long value) to real int. // It will be sent correct as http://www.w3.org/2001/XMLSchema:int // use checked cast for prevent losing data value = Ints.checkedCast( (Long) value ); } return value; }
@Test public void createDateObjectTest() throws KettleValueException, ParseException { SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) ); ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class ); DateFormat dateFormat = new SimpleDateFormat( "dd-MM-yyyy hh:mm:ss" ); Date date = dateFormat.parse( "12-10-2017 15:10:25" ); Mockito.when( valueMeta.isDate() ).thenReturn( true ); Mockito.when( valueMeta.getDateFormatTimeZone() ).thenReturn( TimeZone.getTimeZone( "UTC" ) ); Mockito.when( valueMeta.getDate( Mockito.eq( date ) ) ).thenReturn( date ); Object value = step.normalizeValue( valueMeta, date ); Assert.assertTrue( value instanceof Calendar ); DateFormat minutesDateFormat = new SimpleDateFormat( "mm:ss" ); //check not missing minutes and seconds Assert.assertEquals( minutesDateFormat.format( date ), minutesDateFormat.format( ( (Calendar) value ).getTime() ) ); }
public static String getHttpMethod(Exchange exchange, Endpoint endpoint) { // 1. Use method provided in header. Object method = exchange.getIn().getHeader(Exchange.HTTP_METHOD); if (method instanceof String) { return (String) method; } else if (method instanceof Enum) { return ((Enum<?>) method).name(); } else if (method != null) { return exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange, method); } // 2. GET if query string is provided in header. if (exchange.getIn().getHeader(Exchange.HTTP_QUERY) != null) { return GET_METHOD; } // 3. GET if endpoint is configured with a query string. if (endpoint.getEndpointUri().indexOf('?') != -1) { return GET_METHOD; } // 4. POST if there is data to send (body is not null). if (exchange.getIn().getBody() != null) { return POST_METHOD; } // 5. GET otherwise. return GET_METHOD; }
@Test public void testGetMethodQueryStringHeader() { Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(exchange.getIn()).thenReturn(message); Mockito.when(message.getHeader(Exchange.HTTP_QUERY)).thenReturn("MyQuery"); assertEquals(AbstractHttpSpanDecorator.GET_METHOD, AbstractHttpSpanDecorator.getHttpMethod(exchange, null)); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("brick.listing.chunksize")); }
@Test public void testListEmptyDirectory() throws Exception { final Path directory = new BrickDirectoryFeature(session).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(AbstractPath.Type.directory)), new TransferStatus()); final AttributedList<Path> list = new BrickListService(session).list(directory, new DisabledListProgressListener()); assertNotSame(AttributedList.emptyList(), list); assertTrue(list.isEmpty()); new BrickDeleteFeature(session).delete(Collections.singletonList(directory), new DisabledPasswordCallback(), new Delete.DisabledCallback()); }
@Nonnull @Override public ProgressState call() { progTracker.reset(); stateMachineStep(); return progTracker.toProgressState(); }
@Test public void when_notAbleToOffer_then_offeredLater() { // When init(singletonList(entry("k", "v"))); mockSsWriter.ableToOffer = false; assertEquals(MADE_PROGRESS, sst.call()); assertEquals(0, input.remainingItems().size()); assertEquals(NO_PROGRESS, sst.call()); assertNull(mockSsWriter.poll()); // Then mockSsWriter.ableToOffer = true; assertEquals(MADE_PROGRESS, sst.call()); assertEquals(entry(serialize("k"), serialize("v")), mockSsWriter.poll()); assertNull(mockSsWriter.poll()); }
@Override public T remove(int index) { return data.remove(index); }
@Test public void remove() { l.remove("nosuchthing"); assertEquals(3, l.size()); l.remove("B"); assertEquals(2, l.size()); assertEquals("D", l.get(0)); assertEquals("F", l.get(1)); }
@Override public String getExpression() { return null == owner ? "*" : owner.getValue() + ".*"; }
@Test void assertGetExpression() { assertThat(new ShorthandProjection(new IdentifierValue("owner"), Collections.emptyList()).getExpression(), is("owner.*")); }
public static String formatHex(byte[] bytes) { return hexFormat.formatHex(bytes); }
@Test @Parameters(method = "bytesToHexStringVectors") public void formatHexValid(byte[] bytes, String expectedHexString) { String actual = ByteUtils.formatHex(bytes); assertEquals("incorrect hex formatted string", expectedHexString, actual); }
@VisibleForTesting void addPluginsFoldersToShipFiles(Collection<Path> effectiveShipFiles) { final Optional<File> pluginsDir = PluginConfig.getPluginsDir(); pluginsDir.ifPresent(dir -> effectiveShipFiles.add(getPathFromLocalFile(dir))); }
@Test void testEnvironmentEmptyPluginsShipping() { try (YarnClusterDescriptor descriptor = createYarnClusterDescriptor()) { File pluginsFolder = Paths.get( temporaryFolder.toFile().getAbsolutePath(), "s0m3_p4th_th4t_sh0uld_n0t_3x1sts") .toFile(); Set<Path> effectiveShipFiles = new HashSet<>(); final Map<String, String> oldEnv = System.getenv(); try { Map<String, String> env = new HashMap<>(1); env.put(ConfigConstants.ENV_FLINK_PLUGINS_DIR, pluginsFolder.getAbsolutePath()); CommonTestUtils.setEnv(env); // only execute part of the deployment to test for shipped files descriptor.addPluginsFoldersToShipFiles(effectiveShipFiles); } finally { CommonTestUtils.setEnv(oldEnv); } assertThat(effectiveShipFiles).isEmpty(); } }
public SchemaMapping fromParquet(MessageType parquetSchema) { List<Type> fields = parquetSchema.getFields(); List<TypeMapping> mappings = fromParquet(fields); List<Field> arrowFields = fields(mappings); return new SchemaMapping(new Schema(arrowFields), parquetSchema, mappings); }
@Test public void testParquetInt96ToArrowTimestamp() { final SchemaConverter converterInt96ToTimestamp = new SchemaConverter(true); MessageType parquet = Types.buildMessage().addField(Types.optional(INT96).named("a")).named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Timestamp(TimeUnit.NANOSECOND, null)))); Assert.assertEquals( expected, converterInt96ToTimestamp.fromParquet(parquet).getArrowSchema()); }
static void clearCache() { CONSTRUCTOR_CACHE.clear(); }
@Test public void testCache() throws Exception { assertEquals(0, cacheSize()); doTestCache(); assertEquals(toConstruct.length, cacheSize()); ReflectionUtils.clearCache(); assertEquals(0, cacheSize()); }
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster.getNodeInfos()) { final NodeState nodeState = computeEffectiveNodeState(nodeInfo, params, nodeStateReasons); workingState.setNodeState(nodeInfo.getNode(), nodeState); } takeDownGroupsWithTooLowAvailability(workingState, nodeStateReasons, params); final Optional<ClusterStateReason> reasonToBeDown = clusterDownReason(workingState, params); if (reasonToBeDown.isPresent()) { workingState.setClusterState(State.DOWN); } workingState.setDistributionBits(inferDistributionBitCount(cluster, workingState, params)); return new AnnotatedClusterState(workingState, reasonToBeDown, nodeStateReasons); }
@Test void reported_down_retired_node_within_transition_time_transitions_to_maintenance() { final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp(); final ClusterStateGenerator.Params params = fixture.generatorParams() .currentTimeInMillis(10_000) .transitionTimes(2000); fixture.proposeStorageNodeWantedState(2, State.RETIRED); fixture.reportStorageNodeState(2, State.DOWN); final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 2)); nodeInfo.setTransitionTime(9000); final AnnotatedClusterState state = ClusterStateGenerator.generatedStateFrom(params); assertThat(state.toString(), equalTo("distributor:5 storage:5 .2.s:m")); }
@SuppressWarnings("unchecked") public <T extends Expression> T rewrite(final T expression, final C context) { return (T) rewriter.process(expression, context); }
@Test public void shouldRewriteInPredicate() { // Given: final InPredicate parsed = parseExpression("1 IN (1, 2, 3)"); when(processor.apply(parsed.getValue(), context)).thenReturn(expr1); when(processor.apply(parsed.getValueList(), context)).thenReturn(inList); // When: final Expression rewritten = expressionRewriter.rewrite(parsed, context); // Then: assertThat(rewritten, equalTo(new InPredicate(parsed.getLocation(), expr1, inList))); }
public int nextInt() { return twister.nextInt(); }
@Test public void testRandomInt_int() { System.out.println("nextInt"); smile.math.Random instance = new Random(System.currentTimeMillis()); for (int i = 0; i < 1000000; i++) { int n = instance.nextInt(1000000) + 1; int result = instance.nextInt(n); assertTrue(result >= 0); assertTrue(result < n); } }
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from(outputNode.getKsqlTopic()), outputNode.getKsqlTopic().getKeyFormat().getWindowInfo(), Optional.of(outputNode.getOrReplace()), Optional.of(false) ); }
@Test public void shouldNotThrowOnKeyColumnThatIsNotCalledRowKey() { // Given: final CreateStream statement = new CreateStream( SOME_NAME, TableElements.of(tableElement("someKey", new Type(SqlTypes.STRING), KEY_CONSTRAINT)), false, true, withProperties, false ); // When: final CreateStreamCommand result = createSourceFactory .createStreamCommand(statement, ksqlConfig); // Then: assertThat(result.getSchema().key(), contains( keyColumn(ColumnName.of("someKey"), SqlTypes.STRING) )); }
public void consume(Inbox inbox) { ensureNotDone(); if (limit <= 0) { done.compareAndSet(null, new ResultLimitReachedException()); ensureNotDone(); } while (offset > 0 && inbox.poll() != null) { offset--; } for (JetSqlRow row; (row = (JetSqlRow) inbox.peek()) != null && rows.offer(row); ) { inbox.remove(); if (limit != Long.MAX_VALUE) { limit -= 1; if (limit < 1) { done.compareAndSet(null, new ResultLimitReachedException()); ensureNotDone(); } } } }
@Test public void when_queueCapacityExceeded_then_inboxNotConsumed() { initProducer(false); int numExcessItems = 2; for (int i = 0; i < QueryResultProducerImpl.QUEUE_CAPACITY + numExcessItems; i++) { inbox.queue().add(jetRow()); } producer.consume(inbox); assertThat(inbox).hasSize(2); }
@Override public void register(long ref, String uuid, boolean file) { requireNonNull(uuid, "uuid can not be null"); Long existingRef = refsByUuid.get(uuid); if (existingRef != null) { checkArgument(ref == existingRef, "Uuid '%s' already registered under ref '%s' in repository", uuid, existingRef); boolean existingIsFile = fileUuids.contains(uuid); checkArgument(file == existingIsFile, "Uuid '%s' already registered but %sas a File", uuid, existingIsFile ? "" : "not "); } else { refsByUuid.put(uuid, ref); if (file) { fileUuids.add(uuid); } } }
@Test public void register_throws_NPE_if_uuid_is_null() { assertThatThrownBy(() -> underTest.register(SOME_REF, null, true)) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can not be null"); }
@Override public void verify(X509Certificate certificate, Date date) { logger.debug("Verifying {} issued by {}", certificate.getSubjectX500Principal(), certificate.getIssuerX500Principal()); // Create trustAnchors final Set<TrustAnchor> trustAnchors = getTrusted().stream().map( c -> new TrustAnchor(c, null) ).collect(Collectors.toSet()); if (trustAnchors.isEmpty()) { throw new VerificationException("No trust anchors available"); } // Create the selector that specifies the starting certificate final X509CertSelector selector = new X509CertSelector(); selector.setCertificate(certificate); // Configure the PKIX certificate builder algorithm parameters try { final PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector); // Set assume date if (date != null) { pkixParams.setDate(date); } // Add cert store with certificate to check pkixParams.addCertStore(CertStore.getInstance( "Collection", new CollectionCertStoreParameters(ImmutableList.of(certificate)), "BC")); // Add cert store with intermediates pkixParams.addCertStore(CertStore.getInstance( "Collection", new CollectionCertStoreParameters(getIntermediates()), "BC")); // Add cert store with CRLs pkixParams.addCertStore(CertStore.getInstance( "Collection", new CollectionCertStoreParameters(getCRLs()), "BC")); // Toggle to check revocation list pkixParams.setRevocationEnabled(checkRevocation()); // Build and verify the certification chain final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); builder.build(pkixParams); } catch (CertPathBuilderException e) { throw new VerificationException( String.format("Invalid certificate %s issued by %s", certificate.getSubjectX500Principal(), certificate.getIssuerX500Principal() ), e ); } catch (GeneralSecurityException e) { throw new CryptoException( String.format("Could not verify certificate %s issued by %s", certificate.getSubjectX500Principal(), certificate.getIssuerX500Principal() ), e ); } }
@Test public void shouldVerifyExpiredCertificateIfTestedAgainstCorrectDate() { createCertificateService( new String[] { "root.crt" }, new String[] { "intermediate.crt"}, new String[0], false ).verify(readCert("expired.crt"), new Date(1521638101000L)); }
@Override protected void processOptions(LinkedList<String> args) { CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, OPTION_QUOTA, OPTION_HUMAN, OPTION_HEADER, OPTION_QUOTA_AND_USAGE, OPTION_EXCLUDE_SNAPSHOT, OPTION_ECPOLICY, OPTION_SNAPSHOT_COUNT); cf.addOptionWithValue(OPTION_TYPE); cf.parse(args); if (args.isEmpty()) { // default path is the current working directory args.add("."); } showQuotas = cf.getOpt(OPTION_QUOTA); humanReadable = cf.getOpt(OPTION_HUMAN); showQuotasAndUsageOnly = cf.getOpt(OPTION_QUOTA_AND_USAGE); excludeSnapshots = cf.getOpt(OPTION_EXCLUDE_SNAPSHOT); displayECPolicy = cf.getOpt(OPTION_ECPOLICY); showSnapshot = cf.getOpt(OPTION_SNAPSHOT_COUNT); if (showQuotas || showQuotasAndUsageOnly) { String types = cf.getOptValue(OPTION_TYPE); if (null != types) { showQuotabyType = true; storageTypes = getAndCheckStorageTypes(types); } else { showQuotabyType = false; } if (excludeSnapshots) { out.println(OPTION_QUOTA + " or " + OPTION_QUOTA_AND_USAGE + " option " + "is given, the -x option is ignored."); excludeSnapshots = false; } } if (cf.getOpt(OPTION_HEADER)) { StringBuilder headString = new StringBuilder(); if (showQuotabyType) { headString.append(QuotaUsage.getStorageTypeHeader(storageTypes)); } else { if (showQuotasAndUsageOnly) { headString.append(QuotaUsage.getHeader()); } else { headString.append(ContentSummary.getHeader(showQuotas)); } } if (displayECPolicy) { headString.append(ContentSummary.getErasureCodingPolicyHeader()); } if (showSnapshot) { headString.append(ContentSummary.getSnapshotHeader()); } headString.append("PATHNAME"); out.println(headString.toString()); } }
@Test public void processPathWithSnapshotHeader() throws Exception { Path path = new Path("mockfs:/test"); when(mockFs.getFileStatus(eq(path))).thenReturn(fileStat); PrintStream out = mock(PrintStream.class); Count count = new Count(); count.out = out; LinkedList<String> options = new LinkedList<String>(); options.add("-s"); options.add("-v"); options.add("dummy"); count.processOptions(options); String withSnapshotHeader = " DIR_COUNT FILE_COUNT CONTENT_SIZE " + " SNAPSHOT_LENGTH SNAPSHOT_FILE_COUNT " + " SNAPSHOT_DIR_COUNT SNAPSHOT_SPACE_CONSUMED PATHNAME"; verify(out).println(withSnapshotHeader); verifyNoMoreInteractions(out); }
public Optional<Projection> createProjection(final ProjectionSegment projectionSegment) { if (projectionSegment instanceof ShorthandProjectionSegment) { return Optional.of(createProjection((ShorthandProjectionSegment) projectionSegment)); } if (projectionSegment instanceof ColumnProjectionSegment) { return Optional.of(createProjection((ColumnProjectionSegment) projectionSegment)); } if (projectionSegment instanceof ExpressionProjectionSegment) { return Optional.of(createProjection((ExpressionProjectionSegment) projectionSegment)); } if (projectionSegment instanceof AggregationDistinctProjectionSegment) { return Optional.of(createProjection((AggregationDistinctProjectionSegment) projectionSegment)); } if (projectionSegment instanceof AggregationProjectionSegment) { return Optional.of(createProjection((AggregationProjectionSegment) projectionSegment)); } if (projectionSegment instanceof SubqueryProjectionSegment) { return Optional.of(createProjection((SubqueryProjectionSegment) projectionSegment)); } if (projectionSegment instanceof ParameterMarkerExpressionSegment) { return Optional.of(createProjection((ParameterMarkerExpressionSegment) projectionSegment)); } return Optional.empty(); }
@Test void assertCreateProjectionWhenProjectionSegmentInstanceOfExpressionProjectionSegment() { ExpressionProjectionSegment expressionProjectionSegment = new ExpressionProjectionSegment(0, 10, "text"); Optional<Projection> actual = new ProjectionEngine(databaseType).createProjection(expressionProjectionSegment); assertTrue(actual.isPresent()); assertThat(actual.get(), instanceOf(ExpressionProjection.class)); }
public Properties translate(Properties source) { Properties hikariProperties = new Properties(); // Iterate over source Properties and translate from HZ to Hikari source.forEach((key, value) -> { String keyString = (String) key; if (PROPERTY_MAP.containsKey(keyString)) { hikariProperties.put(keyString, value); } else if (keyString.startsWith(HIKARI_PREFIX)) { String keyNoPrefix = keyString.substring(HIKARI_PREFIX.length()); hikariProperties.put(keyNoPrefix, source.get(keyString)); } else { hikariProperties.put("dataSource." + keyString, value); } }); int cnt = poolCounter.getAndIncrement(); hikariProperties.put("poolName", "HikariPool-" + cnt + "-" + name); return hikariProperties; }
@Test public void testPoolNameProperty() { Properties hzProperties = new Properties(); Properties hikariProperties = hikariTranslator.translate(hzProperties); HikariConfig hikariConfig = new HikariConfig(hikariProperties); String poolName = hikariConfig.getPoolName(); assertThat(poolName).isEqualTo("HikariPool-0-foo"); }
@Override @SuppressWarnings("nls") public void setConf(Configuration conf) { isInitialized = false; this.conf = conf; this.areTxnStatsSupported = MetastoreConf.getBoolVar(conf, ConfVars.HIVE_TXN_STATS_ENABLED); configureSSL(conf); PersistenceManagerProvider.updatePmfProperties(conf); assert (!isActiveTransaction()); shutdown(); // Always want to re-create pm as we don't know if it were created by the // most recent instance of the pmf pm = null; directSql = null; expressionProxy = null; openTrasactionCalls = 0; currentTransaction = null; transactionStatus = TXN_STATUS.NO_STATE; initialize(); String partitionValidationRegex = MetastoreConf.getVar(this.conf, ConfVars.PARTITION_NAME_WHITELIST_PATTERN); if (partitionValidationRegex != null && !partitionValidationRegex.isEmpty()) { partitionValidationPattern = Pattern.compile(partitionValidationRegex); } else { partitionValidationPattern = null; } // Note, if metrics have not been initialized this will return null, which means we aren't // using metrics. Thus we should always check whether this is non-null before using. MetricRegistry registry = Metrics.getRegistry(); if (registry != null) { directSqlErrors = Metrics.getOrCreateCounter(MetricsConstants.DIRECTSQL_ERRORS); } this.batchSize = MetastoreConf.getIntVar(conf, ConfVars.RAWSTORE_PARTITION_BATCH_SIZE); if (!isInitialized) { throw new RuntimeException("Unable to create persistence manager. Check log for details"); } else { LOG.debug("Initialized ObjectStore"); } if (tablelocks == null) { synchronized (ObjectStore.class) { if (tablelocks == null) { int numTableLocks = MetastoreConf.getIntVar(conf, ConfVars.METASTORE_NUM_STRIPED_TABLE_LOCKS); tablelocks = Striped.lazyWeakLock(numTableLocks); } } } }
@Ignore // See comment in ObjectStore.getDataSourceProps @Test public void testNonConfDatanucleusValueSet() { String key = "datanucleus.no.such.key"; String value = "test_value"; String key1 = "blabla.no.such.key"; String value1 = "another_value"; Assume.assumeTrue(System.getProperty(key) == null); Configuration localConf = MetastoreConf.newMetastoreConf(); MetaStoreTestUtils.setConfForStandloneMode(localConf); localConf.set(key, value); localConf.set(key1, value1); objectStore = new ObjectStore(); objectStore.setConf(localConf); Assert.assertEquals(value, PersistenceManagerProvider.getProperty(key)); Assert.assertNull(PersistenceManagerProvider.getProperty(key1)); }
public static String cleanKey(final String key) { return INVALID_KEY_CHARS.matcher(key).replaceAll(String.valueOf(KEY_REPLACEMENT_CHAR)); }
@Test public void testCleanKey() throws Exception { // Valid keys assertEquals("foo123", Message.cleanKey("foo123")); assertEquals("foo-bar123", Message.cleanKey("foo-bar123")); assertEquals("foo_bar123", Message.cleanKey("foo_bar123")); assertEquals("foo.bar123", Message.cleanKey("foo.bar123")); assertEquals("foo@bar", Message.cleanKey("foo@bar")); assertEquals("123", Message.cleanKey("123")); assertEquals("", Message.cleanKey("")); assertEquals("foo_bar", Message.cleanKey("foo bar")); assertEquals("foo_bar", Message.cleanKey("foo+bar")); assertEquals("foo_bar", Message.cleanKey("foo$bar")); assertEquals("foo_bar", Message.cleanKey("foo{bar")); assertEquals("foo_bar", Message.cleanKey("foo,bar")); assertEquals("foo_bar", Message.cleanKey("foo?bar")); assertEquals("_", Message.cleanKey(" ")); }
public FloatArrayAsIterable usingTolerance(double tolerance) { return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_contains_failure() { expectFailureWhenTestingThat(array(1.1f, INTOLERABLE_2POINT2, 3.3f)) .usingTolerance(DEFAULT_TOLERANCE) .contains(2.0f); assertFailureKeys("value of", "expected to contain", "testing whether", "but was"); assertFailureValue("expected to contain", Float.toString(2.0f)); assertFailureValue( "testing whether", "actual element is a finite number within " + (double) DEFAULT_TOLERANCE + " of expected element"); assertFailureValue("but was", "[" + 1.1f + ", " + INTOLERABLE_2POINT2 + ", " + 3.3f + "]"); }
static int interpretOrdinal(int ordinal, int numTiers) { if (ordinal >= 0) { return Math.min(ordinal, numTiers - 1); } return Math.max(numTiers + ordinal, 0); }
@Test public void interpretTier() throws Exception { Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(0, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(1, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(2, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(-1, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(-2, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(-3, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(Constants.FIRST_TIER, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(Constants.SECOND_TIER, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(Constants.LAST_TIER, 1)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(0, 10)); Assert.assertEquals(8, DefaultStorageTierAssoc.interpretOrdinal(8, 10)); Assert.assertEquals(9, DefaultStorageTierAssoc.interpretOrdinal(9, 10)); Assert.assertEquals(9, DefaultStorageTierAssoc.interpretOrdinal(10, 10)); Assert.assertEquals(9, DefaultStorageTierAssoc.interpretOrdinal(-1, 10)); Assert.assertEquals(1, DefaultStorageTierAssoc.interpretOrdinal(-9, 10)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(-10, 10)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(-11, 10)); Assert.assertEquals(0, DefaultStorageTierAssoc.interpretOrdinal(Constants.FIRST_TIER, 10)); Assert.assertEquals(1, DefaultStorageTierAssoc.interpretOrdinal(Constants.SECOND_TIER, 10)); Assert.assertEquals(9, DefaultStorageTierAssoc.interpretOrdinal(Constants.LAST_TIER, 10)); }
@SuppressWarnings("unchecked") public static Class<? extends UuidGenerator> parseUuidGenerator(String cucumberUuidGenerator) { Class<?> uuidGeneratorClass; try { uuidGeneratorClass = Class.forName(cucumberUuidGenerator); } catch (ClassNotFoundException e) { throw new IllegalArgumentException( String.format("Could not load UUID generator class for '%s'", cucumberUuidGenerator), e); } if (!UuidGenerator.class.isAssignableFrom(uuidGeneratorClass)) { throw new IllegalArgumentException(String.format("UUID generator class '%s' was not a subclass of '%s'", uuidGeneratorClass, UuidGenerator.class)); } return (Class<? extends UuidGenerator>) uuidGeneratorClass; }
@Test void parseUuidGenerator_not_a_generator() { // When IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> UuidGeneratorParser.parseUuidGenerator(String.class.getName())); // Then assertThat(exception.getMessage(), Matchers.containsString("not a subclass")); }
@Override public void start() { MasterServletFilter masterServletFilter = MasterServletFilter.getInstance(); if (masterServletFilter != null) { // Probably a database upgrade. MasterSlaveFilter was instantiated by the servlet container // while spring was not completely up. // See https://jira.sonarsource.com/browse/SONAR-3612 masterServletFilter.initHttpFilters(Arrays.asList(httpFilters)); masterServletFilter.initServletFilters(Arrays.asList(servletFilters)); } }
@Test public void should_not_fail_if_master_filter_is_not_up() { MasterServletFilter.setInstance(null); new RegisterServletFilters(new ServletFilter[2], new HttpFilter[2]).start(); }
public synchronized long calculateObjectSize(Object obj) { // Breadth-first traversal instead of naive depth-first with recursive // implementation, so we don't blow the stack traversing long linked lists. boolean init = true; try { for (;;) { visit(obj, init); init = false; if (mPending.isEmpty()) { return mSize; } obj = mPending.removeFirst(); } } finally { mVisited.clear(); mPending.clear(); mSize = 0; } }
@Test public void testConstantMap() { Map<Long, CompositeObject> test = new ConcurrentHashMap<>(); for (long i = 0; i < 4; i++) { test.put(i, new CompositeObject()); } long size = mObjectSizeCalculator.calculateObjectSize(test); Set<Class<?>> testSet = new HashSet<>(); testSet.add(CompositeObject.class); testSet.add(Long.class); ObjectSizeCalculator constantCalc = new ObjectSizeCalculator( MEMORY_LAYOUT_SPECIFICATION, testSet); assertEquals(size, constantCalc.calculateObjectSize(test)); }
public int getBytes(int index, byte[] dst, int off, int len) { int count = Math.min(len, size - index); if (buf.hasArray()) { System.arraycopy(buf.array(), buf.arrayOffset() + index, dst, off, count); } else { ByteBuffer dup = buf.duplicate(); dup.position(index); dup.get(dst, off, count); } return count; }
@Test public void testGetBytesOffset() { final Msg msg = initMsg(); final byte[] dst = new byte[6]; msg.getBytes(3, dst, 1, 2); assertThat(dst, is(new byte[] { 0, 3, 4, 0, 0, 0 })); }