focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public TopicName createTopic(String topicName) { checkArgument(!topicName.isEmpty(), "topicName can not be empty"); checkIsUsable(); TopicName name = getTopicName(topicName); return createTopicInternal(name); }
@Test public void testCreateTopicWithInvalidNameShouldFail() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> testManager.createTopic("")); assertThat(exception).hasMessageThat().contains("topicName can not be empty"); }
public static Date strToDate(String dateStr) throws ParseException { return strToDate(dateStr, DATE_FORMAT_TIME); }
@Test public void strToDate1() throws Exception { long d0 = 0l; long d1 = 1501127802975l; // 2017-07-27 11:56:42:975 +8 long d2 = 1501127835658l; // 2017-07-27 11:57:15:658 +8 TimeZone timeZone = TimeZone.getDefault(); Date date0 = new Date(d0 - timeZone.getOffset(d0)); Date date1 = new Date(d1 - timeZone.getOffset(d1)); Date date2 = new Date(d2 - timeZone.getOffset(d2)); String s0 = "1970-01-01 00:00:00.000"; String s1 = "2017-07-27 03:56:42.975"; String s2 = "2017-07-27 03:57:15.658"; Assert.assertEquals(DateUtils.strToDate(s0, DateUtils.DATE_FORMAT_MILLS_TIME).getTime(), date0.getTime()); Assert.assertEquals(DateUtils.strToDate(s1, DateUtils.DATE_FORMAT_MILLS_TIME).getTime(), date1.getTime()); Assert.assertEquals(DateUtils.strToDate(s2, DateUtils.DATE_FORMAT_MILLS_TIME).getTime(), date2.getTime()); }
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromString(source); FEEL_1_1Lexer lexer = new FEEL_1_1Lexer( input ); CommonTokenStream tokens = new CommonTokenStream( lexer ); FEEL_1_1Parser parser = new FEEL_1_1Parser( tokens ); ParserHelper parserHelper = new ParserHelper(eventsManager); additionalFunctions.forEach(f -> parserHelper.getSymbolTable().getBuiltInScope().define(f.getSymbol())); parser.setHelper(parserHelper); parser.setErrorHandler( new FEELErrorHandler() ); parser.removeErrorListeners(); // removes the error listener that prints to the console parser.addErrorListener( new FEELParserErrorListener( eventsManager ) ); // pre-loads the parser with symbols defineVariables( inputVariableTypes, inputVariables, parser ); if (typeRegistry != null) { parserHelper.setTypeRegistry(typeRegistry); } return parser; }
@Test void instanceOfExpression() { String inputExpression = "\"foo\" instance of string"; BaseNode instanceOfBase = parse( inputExpression ); assertThat( instanceOfBase).isInstanceOf(InstanceOfNode.class); assertThat( instanceOfBase.getText()).isEqualTo(inputExpression); assertThat( instanceOfBase.getResultType()).isEqualTo(BuiltInType.BOOLEAN); InstanceOfNode ioExpr = (InstanceOfNode) instanceOfBase; assertThat( ioExpr.getExpression()).isInstanceOf(StringNode.class); assertThat( ioExpr.getExpression().getText()).isEqualTo( "\"foo\""); assertThat( ioExpr.getType()).isInstanceOf(TypeNode.class); assertThat( ioExpr.getType().getText()).isEqualTo("string"); }
public static boolean isNameCoveredByPattern( String name, String pattern ) { if ( name == null || name.isEmpty() || pattern == null || pattern.isEmpty() ) { throw new IllegalArgumentException( "Arguments cannot be null or empty." ); } final String needle = name.toLowerCase(); final String hayStack = pattern.toLowerCase(); if ( needle.equals( hayStack )) { return true; } if ( hayStack.startsWith( "*." ) ) { return needle.endsWith( hayStack.substring( 2 ) ); } return false; }
@Test public void testNameCoveragePartialMatchButNoSubdomain() throws Exception { // setup final String name = "xmppexample.org"; final String pattern = "example.org"; // do magic final boolean result = DNSUtil.isNameCoveredByPattern( name, pattern ); // verify assertFalse( result ); }
@Override public List<MenuDO> getMenuList() { return menuMapper.selectList(); }
@Test public void testGetMenuList_ids() { // mock 数据 MenuDO menu100 = randomPojo(MenuDO.class); menuMapper.insert(menu100); MenuDO menu101 = randomPojo(MenuDO.class); menuMapper.insert(menu101); // 准备参数 Collection<Long> ids = Collections.singleton(menu100.getId()); // 调用 List<MenuDO> list = menuService.getMenuList(ids); // 断言 assertEquals(1, list.size()); assertPojoEquals(menu100, list.get(0)); }
@Override public String telnet(Channel channel, String message) { if (StringUtils.isEmpty(message)) { return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService"; } StringBuilder buf = new StringBuilder(); if ("/".equals(message) || "..".equals(message)) { String service = (String) channel.getAttribute(SERVICE_KEY); channel.removeAttribute(SERVICE_KEY); buf.append("Cancelled default service ").append(service).append('.'); } else { boolean found = false; for (Exporter<?> exporter : DubboProtocol.getDubboProtocol().getExporters()) { if (message.equals(exporter.getInvoker().getInterface().getSimpleName()) || message.equals(exporter.getInvoker().getInterface().getName()) || message.equals(exporter.getInvoker().getUrl().getPath())) { found = true; break; } } if (found) { channel.setAttribute(SERVICE_KEY, message); buf.append("Used the ") .append(message) .append(" as default.\r\nYou can cancel default service by command: cd /"); } else { buf.append("No such service ").append(message); } } return buf.toString(); }
@Test void testChangeServiceNotExport() throws RemotingException { String result = change.telnet(mockChannel, "demo"); assertEquals("No such service demo", result); }
public String convertMultipleArguments(Object... objectList) { StringBuilder buf = new StringBuilder(); Converter<Object> c = headTokenConverter; while (c != null) { if (c instanceof MonoTypedConverter) { MonoTypedConverter monoTyped = (MonoTypedConverter) c; for (Object o : objectList) { if (monoTyped.isApplicable(o)) { buf.append(c.convert(o)); } } } else { buf.append(c.convert(objectList)); } c = c.getNext(); } return buf.toString(); }
@Test public void objectListConverter() { Calendar cal = Calendar.getInstance(); cal.set(2003, 4, 20, 17, 55); FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", context); assertEquals("foo-2003.05.20-79.txt", fnp.convertMultipleArguments(cal.getTime(), 79)); }
@Override public void validateOffsetFetch( String memberId, int memberEpoch, long lastCommittedOffset ) throws UnknownMemberIdException, StaleMemberEpochException, IllegalGenerationException { // When the member id is null and the member epoch is -1, the request either comes // from the admin client or from a client which does not provide them. In this case, // the fetch request is accepted. if (memberId == null && memberEpoch < 0) return; final ConsumerGroupMember member = members.get(memberId, lastCommittedOffset); if (member == null) { throw new UnknownMemberIdException(String.format("Member %s is not a member of group %s.", memberId, groupId)); } validateMemberEpoch(memberEpoch, member.memberEpoch(), member.useClassicProtocol()); }
@Test public void testValidateOffsetFetch() { SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext()); ConsumerGroup group = new ConsumerGroup( snapshotRegistry, "group-foo", mock(GroupCoordinatorMetricsShard.class) ); // Simulate a call from the admin client without member id and member epoch. group.validateOffsetFetch(null, -1, Long.MAX_VALUE); // The member does not exist. assertThrows(UnknownMemberIdException.class, () -> group.validateOffsetFetch("member-id", 0, Long.MAX_VALUE)); // Create a member. snapshotRegistry.idempotentCreateSnapshot(0); group.updateMember(new ConsumerGroupMember.Builder("member-id").build()); // The member does not exist at last committed offset 0. assertThrows(UnknownMemberIdException.class, () -> group.validateOffsetFetch("member-id", 0, 0)); // The member exists but the epoch is stale when the last committed offset is not considered. assertThrows(StaleMemberEpochException.class, () -> group.validateOffsetFetch("member-id", 10, Long.MAX_VALUE)); // This should succeed. group.validateOffsetFetch("member-id", 0, Long.MAX_VALUE); }
@Override public ValidationTaskResult validateImpl(Map<String, String> optionMap) throws InterruptedException { String hadoopVersion; try { hadoopVersion = getHadoopVersion(); } catch (IOException e) { return new ValidationTaskResult(ValidationUtils.State.FAILED, getName(), String.format("Failed to get hadoop version:%n%s.", ExceptionUtils.asPlainText(e)), "Please check if hadoop is on your PATH."); } String version = mConf.getString(PropertyKey.UNDERFS_VERSION); for (String prefix : new String[] {CDH_PREFIX, HADOOP_PREFIX}) { if (version.startsWith(prefix)) { version = version.substring(prefix.length()); break; } } if (hadoopVersion.contains(version)) { return new ValidationTaskResult(ValidationUtils.State.OK, getName(), String.format("Hadoop version %s contains UFS version defined in alluxio %s=%s.", hadoopVersion, PropertyKey.UNDERFS_VERSION, version), ""); } return new ValidationTaskResult(ValidationUtils.State.FAILED, getName(), String.format("Hadoop version %s does not match %s=%s.", hadoopVersion, PropertyKey.UNDERFS_VERSION, version), String.format("Please configure %s to match the HDFS version.", PropertyKey.UNDERFS_VERSION)); }
@Test public void versionNotMatched() throws Exception { PowerMockito.mockStatic(ShellUtils.class); String[] cmd = new String[]{"hadoop", "version"}; BDDMockito.given(ShellUtils.execCommand(cmd)).willReturn("Hadoop 2.7"); CONF.set(PropertyKey.UNDERFS_VERSION, "2.6"); HdfsVersionValidationTask task = new HdfsVersionValidationTask(CONF); ValidationTaskResult result = task.validateImpl(ImmutableMap.of()); assertEquals(ValidationUtils.State.FAILED, result.getState()); assertThat(result.getResult(), containsString( "2.7 does not match alluxio.underfs.version=2.6")); assertThat(result.getAdvice(), containsString("configure alluxio.underfs.version")); }
@Override public void executor(final Collection<MetaDataRegisterDTO> metaDataRegisterDTOList) { for (MetaDataRegisterDTO metaDataRegisterDTO : metaDataRegisterDTOList) { shenyuClientRegisterRepository.persistInterface(metaDataRegisterDTO); } }
@Test public void testExecutorWithEmptyData() { Collection<MetaDataRegisterDTO> metaDataRegisterDTOList = new ArrayList<>(); executorSubscriber.executor(metaDataRegisterDTOList); verify(shenyuClientRegisterRepository, never()).persistInterface(any()); }
@SuppressWarnings("unchecked") // safe because we only read, not write /* * non-final because it's overridden by MultimapWithProtoValuesSubject. * * If we really, really wanted it to be final, we could investigate whether * MultimapWithProtoValuesFluentAssertion could provide its own valuesForKey method. But that * would force callers to perform any configuration _before_ the valuesForKey call, while * currently they must perform it _after_. */ public IterableSubject valuesForKey(@Nullable Object key) { return check("valuesForKey(%s)", key) .that(((Multimap<@Nullable Object, @Nullable Object>) checkNotNull(actual)).get(key)); }
@Test public void valuesForKey() { ImmutableMultimap<Integer, String> multimap = ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four"); assertThat(multimap).valuesForKey(3).hasSize(3); assertThat(multimap).valuesForKey(4).containsExactly("four", "five"); assertThat(multimap).valuesForKey(3).containsAtLeast("one", "six").inOrder(); assertThat(multimap).valuesForKey(5).isEmpty(); }
public void addShipFiles(List<Path> shipFiles) { checkArgument( !isUsrLibDirIncludedInShipFiles(shipFiles, yarnConfiguration), "User-shipped directories configured via : %s should not include %s.", YarnConfigOptions.SHIP_FILES.key(), ConfigConstants.DEFAULT_FLINK_USR_LIB_DIR); this.shipFiles.addAll(shipFiles); }
@Test void testDisableSystemClassPathIncludeUserJarAndWithIllegalShipDirectoryName() { final Configuration configuration = new Configuration(); configuration.set(CLASSPATH_INCLUDE_USER_JAR, YarnConfigOptions.UserJarInclusion.DISABLED); final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor(configuration); java.nio.file.Path p = temporaryFolder.resolve(ConfigConstants.DEFAULT_FLINK_USR_LIB_DIR); p.toFile().mkdir(); assertThatThrownBy( () -> yarnClusterDescriptor.addShipFiles( Collections.singletonList(new Path(p.toString())))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("User-shipped directories configured via :"); }
public static byte[] max(final byte[] a, final byte[] b) { return getDefaultByteArrayComparator().compare(a, b) > 0 ? a : b; }
@Test public void testMax() { byte[] array = new byte[] { 3, 4 }; Assert.assertArrayEquals(array, BytesUtil.max(array, array)); Assert.assertArrayEquals(array, BytesUtil.max(new byte[] { 1, 2 }, array)); }
@SuppressWarnings("unchecked") public V put(int key, V value) { byte[] states = this.states; int[] keys = this.keys; int mask = keys.length - 1; int i = key & mask; while (states[i] > FREE) { // states[i] == FULL if (keys[i] == key) { V oldValue = (V) values[i]; values[i] = value; return oldValue; } i = (i + 1) & mask; } byte oldState = states[i]; states[i] = FULL; keys[i] = key; values[i] = value; ++size; if (oldState == FREE && --free < 0) resize(Math.max(capacity(size), keys.length)); return null; }
@Test public void testPut() { removeOdd(); for (int i = 0; i < 45; i++) map.put(i, Integer.valueOf(i)); assertEquals(45, map.size()); for (int i = 0; i < 45; i++) assertEquals(Integer.valueOf(i), map.get(i)); }
public static <T> NavigableSet<Point<T>> fastKNearestPoints(SortedSet<Point<T>> points, Instant time, int k) { checkNotNull(points, "The input SortedSet of Points cannot be null"); checkNotNull(time, "The input time cannot be null"); checkArgument(k >= 0, "k (" + k + ") must be non-negative"); if (k >= points.size()) { return newTreeSet(points); } Point<T> stub = points.first(); Point<T> searchPoint = Point.builder(stub).time(time).latLong(0.0, 0.0).build(); //create two iterators, one goes up from the searchPoint, one goes down from the searchPoint NavigableSet<Point<T>> headSet = ((NavigableSet<Point<T>>) points).headSet(searchPoint, true); NavigableSet<Point<T>> tailSet = ((NavigableSet<Point<T>>) points).tailSet(searchPoint, false); Iterator<Point<T>> headIter = headSet.descendingIterator(); Iterator<Point<T>> tailIter = tailSet.iterator(); TreeSet<Point<T>> results = newTreeSet(); Point<T> up = (headIter.hasNext()) ? headIter.next() : null; Point<T> down = (tailIter.hasNext()) ? tailIter.next() : null; while (results.size() < k) { //add an element from the "down set" when we are out of elements in the "up set" if (up == null) { results.add(down); down = tailIter.next(); continue; } //add an element from the "up set" when we are out of elements in the "down set" if (down == null) { results.add(up); up = headIter.next(); continue; } //add the nearest point when we can choose between the "up set" and the "down set" Duration upDistance = Duration.between(up.time(), time); Duration downDistance = Duration.between(time, down.time()); if (theDuration(upDistance).isLessThanOrEqualTo(downDistance)) { results.add(up); up = (headIter.hasNext()) ? headIter.next() : null; } else { results.add(down); down = (tailIter.hasNext()) ? tailIter.next() : null; } } return results; }
@Test public void testFastKNearestPoints_7() { NavigableSet<Point<String>> knn = fastKNearestPoints(points, EPOCH.plusSeconds(5), 0); assertEquals(0, knn.size()); assertEquals(12, points.size()); }
@Override public void syncHoodieTable() { switch (bqSyncClient.getTableType()) { case COPY_ON_WRITE: case MERGE_ON_READ: syncTable(bqSyncClient); break; default: throw new UnsupportedOperationException(bqSyncClient.getTableType() + " table type is not supported yet."); } }
@Test void useBQManifestFile_existingNonPartitionedTable() { properties.setProperty(BigQuerySyncConfig.BIGQUERY_SYNC_USE_BQ_MANIFEST_FILE.key(), "true"); when(mockBqSyncClient.getTableType()).thenReturn(HoodieTableType.COPY_ON_WRITE); when(mockBqSyncClient.getBasePath()).thenReturn(TEST_TABLE_BASE_PATH); when(mockBqSyncClient.datasetExists()).thenReturn(true); when(mockBqSyncClient.tableNotExistsOrDoesNotMatchSpecification(TEST_TABLE)).thenReturn(false); Path manifestPath = new Path("file:///local/path"); when(mockManifestFileWriter.getManifestSourceUri(true)).thenReturn(manifestPath.toUri().getPath()); when(mockBqSchemaResolver.getTableSchema(any(), eq(Collections.emptyList()))).thenReturn(schema); BigQuerySyncTool tool = new BigQuerySyncTool(properties, mockManifestFileWriter, mockBqSyncClient, mockMetaClient, mockBqSchemaResolver); tool.syncHoodieTable(); verify(mockBqSyncClient).updateTableSchema(TEST_TABLE, schema, Collections.emptyList()); verify(mockManifestFileWriter).writeManifestFile(true); }
@Override public boolean supports(Ref ref) { Assert.notNull(ref, "Subject ref must not be null."); GroupVersionKind groupVersionKind = new GroupVersionKind(ref.getGroup(), ref.getVersion(), ref.getKind()); return GroupVersionKind.fromExtension(SinglePage.class).equals(groupVersionKind); }
@Test void supports() { SinglePage singlePage = new SinglePage(); singlePage.setMetadata(new Metadata()); singlePage.getMetadata().setName("test"); boolean supports = singlePageCommentSubject.supports(Ref.of(singlePage)); assertThat(supports).isTrue(); FakeExtension fakeExtension = new FakeExtension(); fakeExtension.setMetadata(new Metadata()); fakeExtension.getMetadata().setName("test"); supports = singlePageCommentSubject.supports(Ref.of(fakeExtension)); assertThat(supports).isFalse(); }
public static Builder newBuilder() { return new Builder(); }
@Test public void testConstructor() { try { ConcurrentLongPairSet.newBuilder() .expectedItems(0) .build(); fail("should have thrown exception"); } catch (IllegalArgumentException e) { // ok } try { ConcurrentLongPairSet.newBuilder() .expectedItems(16) .concurrencyLevel(0) .build(); fail("should have thrown exception"); } catch (IllegalArgumentException e) { // ok } try { ConcurrentLongPairSet.newBuilder() .expectedItems(4) .concurrencyLevel(8) .build(); fail("should have thrown exception"); } catch (IllegalArgumentException e) { // ok } }
public static Collection<ExecutionUnit> build(final ShardingSphereDatabase database, final SQLRewriteResult sqlRewriteResult, final SQLStatementContext sqlStatementContext) { return sqlRewriteResult instanceof GenericSQLRewriteResult ? build(database, (GenericSQLRewriteResult) sqlRewriteResult, sqlStatementContext) : build((RouteSQLRewriteResult) sqlRewriteResult); }
@Test void assertBuildRouteSQLRewriteResult() { RouteUnit routeUnit1 = new RouteUnit(new RouteMapper("logicName1", "actualName1"), Collections.singletonList(new RouteMapper("logicName1", "actualName1"))); SQLRewriteUnit sqlRewriteUnit1 = new SQLRewriteUnit("sql1", Collections.singletonList("parameter1")); RouteUnit routeUnit2 = new RouteUnit(new RouteMapper("logicName2", "actualName2"), Collections.singletonList(new RouteMapper("logicName1", "actualName1"))); SQLRewriteUnit sqlRewriteUnit2 = new SQLRewriteUnit("sql2", Collections.singletonList("parameter2")); Map<RouteUnit, SQLRewriteUnit> sqlRewriteUnits = new HashMap<>(2, 1F); sqlRewriteUnits.put(routeUnit1, sqlRewriteUnit1); sqlRewriteUnits.put(routeUnit2, sqlRewriteUnit2); ResourceMetaData resourceMetaData = new ResourceMetaData(Collections.emptyMap()); RuleMetaData ruleMetaData = new RuleMetaData(Collections.emptyList()); ShardingSphereDatabase database = new ShardingSphereDatabase(DefaultDatabase.LOGIC_NAME, mock(DatabaseType.class), resourceMetaData, ruleMetaData, buildDatabase()); Collection<ExecutionUnit> actual = ExecutionContextBuilder.build(database, new RouteSQLRewriteResult(sqlRewriteUnits), mock(SQLStatementContext.class)); ExecutionUnit expectedUnit1 = new ExecutionUnit("actualName1", new SQLUnit("sql1", Collections.singletonList("parameter1"))); ExecutionUnit expectedUnit2 = new ExecutionUnit("actualName2", new SQLUnit("sql2", Collections.singletonList("parameter2"))); Collection<ExecutionUnit> expected = new LinkedHashSet<>(2, 1F); expected.add(expectedUnit1); expected.add(expectedUnit2); assertThat(actual, is(expected)); }
void onAddSendDestination(final long registrationId, final String destinationChannel, final long correlationId) { final ChannelUri channelUri = ChannelUri.parse(destinationChannel); validateDestinationUri(channelUri, destinationChannel); validateSendDestinationUri(channelUri, destinationChannel); SendChannelEndpoint sendChannelEndpoint = null; for (int i = 0, size = networkPublications.size(); i < size; i++) { final NetworkPublication publication = networkPublications.get(i); if (registrationId == publication.registrationId()) { sendChannelEndpoint = publication.channelEndpoint(); break; } } if (null == sendChannelEndpoint) { throw new ControlProtocolException(UNKNOWN_PUBLICATION, "unknown publication: " + registrationId); } sendChannelEndpoint.validateAllowsManualControl(); final InetSocketAddress dstAddress = UdpChannel.destinationAddress(channelUri, nameResolver); senderProxy.addDestination(sendChannelEndpoint, channelUri, dstAddress); clientProxy.operationSucceeded(correlationId); }
@Test void shouldThrowExceptionWhenSendDestinationHasResponseCorrelationIdSet() { final Exception exception = assertThrowsExactly(InvalidChannelException.class, () -> driverConductor.onAddSendDestination(4, "aeron:udp?response-correlation-id=1234", 8) ); assertThat(exception.getMessage(), containsString(RESPONSE_CORRELATION_ID_PARAM_NAME)); }
@Override public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) { traceIfNecessary(grpcRequest, true); String type = grpcRequest.getMetadata().getType(); long startTime = System.nanoTime(); //server is on starting. if (!ApplicationUtils.isStarted()) { Payload payloadResponse = GrpcUtils.convert( ErrorResponse.build(NacosException.INVALID_SERVER_STATUS, "Server is starting,please try later.")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.INVALID_SERVER_STATUS, null, null, System.nanoTime() - startTime); return; } // server check. if (ServerCheckRequest.class.getSimpleName().equals(type)) { Payload serverCheckResponseP = GrpcUtils.convert(new ServerCheckResponse(GrpcServerConstants.CONTEXT_KEY_CONN_ID.get(), true)); traceIfNecessary(serverCheckResponseP, false); responseObserver.onNext(serverCheckResponseP); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, true, 0, null, null, System.nanoTime() - startTime); return; } RequestHandler requestHandler = requestHandlerRegistry.getByRequestType(type); //no handler found. if (requestHandler == null) { Loggers.REMOTE_DIGEST.warn(String.format("[%s] No handler for request type : %s :", "grpc", type)); Payload payloadResponse = GrpcUtils .convert(ErrorResponse.build(NacosException.NO_HANDLER, "RequestHandler Not Found")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.NO_HANDLER, null, null, System.nanoTime() - startTime); return; } //check connection status. String connectionId = GrpcServerConstants.CONTEXT_KEY_CONN_ID.get(); boolean requestValid = connectionManager.checkValid(connectionId); if (!requestValid) { Loggers.REMOTE_DIGEST .warn("[{}] Invalid connection Id ,connection [{}] is un registered ,", "grpc", connectionId); Payload payloadResponse = GrpcUtils .convert(ErrorResponse.build(NacosException.UN_REGISTER, "Connection is unregistered.")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.UN_REGISTER, null, null, System.nanoTime() - startTime); return; } Object parseObj = null; try { parseObj = GrpcUtils.parse(grpcRequest); } catch (Exception e) { Loggers.REMOTE_DIGEST .warn("[{}] Invalid request receive from connection [{}] ,error={}", "grpc", connectionId, e); Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(NacosException.BAD_GATEWAY, e.getMessage())); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.BAD_GATEWAY, e.getClass().getSimpleName(), null, System.nanoTime() - startTime); return; } if (parseObj == null) { Loggers.REMOTE_DIGEST.warn("[{}] Invalid request receive ,parse request is null", connectionId); Payload payloadResponse = GrpcUtils .convert(ErrorResponse.build(NacosException.BAD_GATEWAY, "Invalid request")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.BAD_GATEWAY, null, null, System.nanoTime() - startTime); return; } if (!(parseObj instanceof Request)) { Loggers.REMOTE_DIGEST .warn("[{}] Invalid request receive ,parsed payload is not a request,parseObj={}", connectionId, parseObj); Payload payloadResponse = GrpcUtils .convert(ErrorResponse.build(NacosException.BAD_GATEWAY, "Invalid request")); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, NacosException.BAD_GATEWAY, null, null, System.nanoTime() - startTime); return; } Request request = (Request) parseObj; try { Connection connection = connectionManager.getConnection(GrpcServerConstants.CONTEXT_KEY_CONN_ID.get()); RequestMeta requestMeta = new RequestMeta(); requestMeta.setClientIp(connection.getMetaInfo().getClientIp()); requestMeta.setConnectionId(GrpcServerConstants.CONTEXT_KEY_CONN_ID.get()); requestMeta.setClientVersion(connection.getMetaInfo().getVersion()); requestMeta.setLabels(connection.getMetaInfo().getLabels()); requestMeta.setAbilityTable(connection.getAbilityTable()); connectionManager.refreshActiveTime(requestMeta.getConnectionId()); prepareRequestContext(request, requestMeta, connection); Response response = requestHandler.handleRequest(request, requestMeta); Payload payloadResponse = GrpcUtils.convert(response); traceIfNecessary(payloadResponse, false); if (response.getErrorCode() == NacosException.OVER_THRESHOLD) { RpcScheduledExecutor.CONTROL_SCHEDULER.schedule(() -> { traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); }, 1000L, TimeUnit.MILLISECONDS); } else { traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); } MetricsMonitor.recordGrpcRequestEvent(type, response.isSuccess(), response.getErrorCode(), null, request.getModule(), System.nanoTime() - startTime); } catch (Throwable e) { Loggers.REMOTE_DIGEST .error("[{}] Fail to handle request from connection [{}] ,error message :{}", "grpc", connectionId, e); Payload payloadResponse = GrpcUtils.convert(ErrorResponse.build(e)); traceIfNecessary(payloadResponse, false); responseObserver.onNext(payloadResponse); responseObserver.onCompleted(); MetricsMonitor.recordGrpcRequestEvent(type, false, ResponseCode.FAIL.getCode(), e.getClass().getSimpleName(), request.getModule(), System.nanoTime() - startTime); } finally { RequestContextHolder.removeContext(); } }
@Test void testHandleRequestError() { ApplicationUtils.setStarted(true); Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler); Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(true); RequestMeta metadata = new RequestMeta(); metadata.setClientIp("127.0.0.1"); metadata.setConnectionId(connectId); InstanceRequest instanceRequest = new InstanceRequest(); Payload payload = GrpcUtils.convert(instanceRequest, metadata); StreamObserver<Payload> streamObserver = new StreamObserver<Payload>() { @Override public void onNext(Payload payload) { System.out.println("Receive data from server: " + payload); Object res = GrpcUtils.parse(payload); assertTrue(res instanceof ErrorResponse); ErrorResponse errorResponse = (ErrorResponse) res; assertEquals(NacosException.SERVER_ERROR, errorResponse.getErrorCode()); } @Override public void onError(Throwable throwable) { fail(throwable.getMessage()); } @Override public void onCompleted() { System.out.println("complete"); } }; streamStub.request(payload, streamObserver); ApplicationUtils.setStarted(false); }
public static long calculateTotalProcessMemoryFromComponents(Configuration config) { Preconditions.checkArgument(config.contains(TaskManagerOptions.JVM_METASPACE)); Preconditions.checkArgument(config.contains(TaskManagerOptions.JVM_OVERHEAD_MAX)); Preconditions.checkArgument(config.contains(TaskManagerOptions.JVM_OVERHEAD_MIN)); Preconditions.checkArgument( config.get(TaskManagerOptions.JVM_OVERHEAD_MAX) .equals(config.get(TaskManagerOptions.JVM_OVERHEAD_MIN))); return calculateTotalFlinkMemoryFromComponents(config) + config.get(TaskManagerOptions.JVM_METASPACE) .add(config.get(TaskManagerOptions.JVM_OVERHEAD_MAX)) .getBytes(); }
@Test void testCalculateTotalProcessMemoryWithMissingFactors() { Configuration config = new Configuration(); config.set(TaskManagerOptions.FRAMEWORK_HEAP_MEMORY, new MemorySize(1)); config.set(TaskManagerOptions.FRAMEWORK_OFF_HEAP_MEMORY, new MemorySize(3)); config.set(TaskManagerOptions.TASK_OFF_HEAP_MEMORY, new MemorySize(4)); config.set(TaskManagerOptions.NETWORK_MEMORY_MAX, new MemorySize(6)); config.set(TaskManagerOptions.MANAGED_MEMORY_SIZE, new MemorySize(7)); config.set(TaskManagerOptions.JVM_METASPACE, new MemorySize(8)); assertThatThrownBy( () -> TaskExecutorResourceUtils.calculateTotalProcessMemoryFromComponents( config)) .isInstanceOf(IllegalArgumentException.class); }
public static void verifyIncrementPubContent(String content) { if (content == null || content.length() == 0) { throw new IllegalArgumentException("publish/delete content can not be null"); } for (int i = 0; i < content.length(); i++) { char c = content.charAt(i); if (c == '\r' || c == '\n') { throw new IllegalArgumentException("publish/delete content can not contain return and linefeed"); } if (c == Constants.WORD_SEPARATOR.charAt(0)) { throw new IllegalArgumentException("publish/delete content can not contain(char)2"); } } }
@Test void testVerifyIncrementPubContentFail3() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> { String content = ""; ContentUtils.verifyIncrementPubContent(content); }); assertTrue(exception.getMessage().contains("publish/delete content can not be null")); }
@Override public AppToken createAppToken(long appId, String privateKey) { Algorithm algorithm = readApplicationPrivateKey(appId, privateKey); LocalDateTime now = LocalDateTime.now(clock); // Expiration period is configurable and could be greater if needed. // See https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app LocalDateTime expiresAt = now.plus(AppToken.EXPIRATION_PERIOD_IN_MINUTES, ChronoUnit.MINUTES); ZoneOffset offset = clock.getZone().getRules().getOffset(now); Date nowDate = Date.from(now.toInstant(offset)); Date expiresAtDate = Date.from(expiresAt.toInstant(offset)); JWTCreator.Builder builder = JWT.create() .withIssuer(String.valueOf(appId)) .withIssuedAt(nowDate) .withExpiresAt(expiresAtDate); return new AppToken(builder.sign(algorithm)); }
@Test public void createAppToken_fails_with_IAE_if_privateKey_content_is_garbage() { String garbage = randomAlphanumeric(555); GithubAppConfiguration githubAppConfiguration = createAppConfigurationForPrivateKey(garbage); assertThatThrownBy(() -> underTest.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())) .isInstanceOf(IllegalArgumentException.class) .hasRootCauseMessage("Failed to decode Github Application private key"); }
@Override public Serde<GenericRow> create( final FormatInfo format, final PersistenceSchema schema, final KsqlConfig ksqlConfig, final Supplier<SchemaRegistryClient> srClientFactory, final String loggerNamePrefix, final ProcessingLogContext processingLogContext, final Optional<TrackedCallback> tracker ) { final Serde<List<?>> formatSerde = innerFactory.createFormatSerde("Value", format, schema, ksqlConfig, srClientFactory, false); final Serde<GenericRow> genericRowSerde = toGenericRowSerde(formatSerde, schema); final Serde<GenericRow> loggingSerde = innerFactory.wrapInLoggingSerde( genericRowSerde, loggerNamePrefix, processingLogContext, queryId); final Serde<GenericRow> serde = tracker .map(callback -> innerFactory.wrapInTrackingSerde(loggingSerde, callback)) .orElse(loggingSerde); serde.configure(Collections.emptyMap(), false); return serde; }
@Test public void shouldWrapInLoggingSerde() { // When: factory.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt, Optional.empty()); // Then: verify(innerFactory).wrapInLoggingSerde(any(), eq(LOGGER_PREFIX), eq(processingLogCxt), eq(Optional.of(queryId))); }
@Override @MethodNotAvailable public <T> Map<K, EntryProcessorResult<T>> invokeAll(Set<? extends K> keys, EntryProcessor<K, V, T> entryProcessor, Object... arguments) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testInvokeAll() { Set<Integer> keys = new HashSet<>(asList(23, 65, 88)); adapter.invokeAll(keys, new ICacheReplaceEntryProcessor(), "value", "newValue"); }
public static PropertyKey fromString(String input) { // First try to parse it as default key PropertyKey key = DEFAULT_KEYS_MAP.get(input); if (key != null) { return key; } // Try to match input with alias key = DEFAULT_ALIAS_MAP.get(input); if (key != null) { return key; } // Try different templates and see if any template matches for (Template template : Template.values()) { key = template.getPropertyKey(input); if (key != null) { return key; } } if (isRemoved(input)) { String errorMsg = format("%s is no longer a valid property. %s", input, PropertyKey.getRemovalMessage(input)); LOG.error(errorMsg); throw new IllegalArgumentException(errorMsg); } else { throw new IllegalArgumentException( ExceptionMessage.INVALID_CONFIGURATION_KEY.getMessage(input)); } }
@Test public void fromString() throws Exception { assertEquals(PropertyKey.VERSION, PropertyKey.fromString(PropertyKey.VERSION.toString())); PropertyKey.fromString(PropertyKey.VERSION.toString()); assertEquals(mTestProperty, PropertyKey.fromString("alluxio.test.property.alias1")); assertEquals(mTestProperty, PropertyKey.fromString("alluxio.test.property.alias2")); assertEquals(mTestProperty, PropertyKey.fromString(mTestProperty.toString())); }
@VisibleForTesting AdminUserDO validateUserExists(Long id) { if (id == null) { return null; } AdminUserDO user = userMapper.selectById(id); if (user == null) { throw exception(USER_NOT_EXISTS); } return user; }
@Test public void testValidateUserExists_notExists() { assertServiceException(() -> userService.validateUserExists(randomLongId()), USER_NOT_EXISTS); }
public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "Rotate"; case INTVAR_EVENT: return "Intvar"; case LOAD_EVENT: return "Load"; case NEW_LOAD_EVENT: return "New_load"; case SLAVE_EVENT: return "Slave"; case CREATE_FILE_EVENT: return "Create_file"; case APPEND_BLOCK_EVENT: return "Append_block"; case DELETE_FILE_EVENT: return "Delete_file"; case EXEC_LOAD_EVENT: return "Exec_load"; case RAND_EVENT: return "RAND"; case XID_EVENT: return "Xid"; case USER_VAR_EVENT: return "User var"; case FORMAT_DESCRIPTION_EVENT: return "Format_desc"; case TABLE_MAP_EVENT: return "Table_map"; case PRE_GA_WRITE_ROWS_EVENT: return "Write_rows_event_old"; case PRE_GA_UPDATE_ROWS_EVENT: return "Update_rows_event_old"; case PRE_GA_DELETE_ROWS_EVENT: return "Delete_rows_event_old"; case WRITE_ROWS_EVENT_V1: return "Write_rows_v1"; case UPDATE_ROWS_EVENT_V1: return "Update_rows_v1"; case DELETE_ROWS_EVENT_V1: return "Delete_rows_v1"; case BEGIN_LOAD_QUERY_EVENT: return "Begin_load_query"; case EXECUTE_LOAD_QUERY_EVENT: return "Execute_load_query"; case INCIDENT_EVENT: return "Incident"; case HEARTBEAT_LOG_EVENT: case HEARTBEAT_LOG_EVENT_V2: return "Heartbeat"; case IGNORABLE_LOG_EVENT: return "Ignorable"; case ROWS_QUERY_LOG_EVENT: return "Rows_query"; case WRITE_ROWS_EVENT: return "Write_rows"; case UPDATE_ROWS_EVENT: return "Update_rows"; case DELETE_ROWS_EVENT: return "Delete_rows"; case GTID_LOG_EVENT: return "Gtid"; case ANONYMOUS_GTID_LOG_EVENT: return "Anonymous_Gtid"; case PREVIOUS_GTIDS_LOG_EVENT: return "Previous_gtids"; case PARTIAL_UPDATE_ROWS_EVENT: return "Update_rows_partial"; case TRANSACTION_CONTEXT_EVENT : return "Transaction_context"; case VIEW_CHANGE_EVENT : return "view_change"; case XA_PREPARE_LOG_EVENT : return "Xa_prepare"; case TRANSACTION_PAYLOAD_EVENT : return "transaction_payload"; default: return "Unknown type:" + type; } }
@Test public void getTypeNameInputPositiveOutputNotNull37() { // Arrange final int type = 1; // Act final String actual = LogEvent.getTypeName(type); // Assert result Assert.assertEquals("Start_v3", actual); }
@Override public boolean canPass(Node node, int acquireCount) { return canPass(node, acquireCount, false); }
@Test public void testThrottlingControllerNormal() throws InterruptedException { ThrottlingController paceController = new ThrottlingController(500, 10d); Node node = mock(Node.class); long start = TimeUtil.currentTimeMillis(); for (int i = 0; i < 6; i++) { assertTrue(paceController.canPass(node, 1)); } long end = TimeUtil.currentTimeMillis(); assertTrue((end - start) > 400); }
public static Result label(long durationInMillis) { double nbSeconds = durationInMillis / 1000.0; double nbMinutes = nbSeconds / 60; double nbHours = nbMinutes / 60; double nbDays = nbHours / 24; double nbYears = nbDays / 365; return getMessage(nbSeconds, nbMinutes, nbHours, nbDays, nbYears); }
@Test public void age_in_hour() { DurationLabel.Result result = DurationLabel.label(now() - ago(HOUR)); assertThat(result.key()).isEqualTo("duration.hour"); assertThat(result.value()).isNull(); }
public AdminStatisticsJobRequestHandler(RepositoryService repositories, AdminStatisticsService service) { this.repositories = repositories; this.service = service; }
@Test public void testAdminStatisticsJobRequestHandler() throws Exception { var expectedStatistics = mockAdminStatistics(); var request = new AdminStatisticsJobRequest(2023, 11); handler.run(request); Mockito.verify(service).saveAdminStatistics(expectedStatistics); }
@Override protected Result check() throws IOException { final boolean isHealthy = tcpCheck(host, port); if (isHealthy) { LOGGER.debug("Health check against url={}:{} successful", host, port); return Result.healthy(); } LOGGER.debug("Health check against url={}:{} failed", host, port); return Result.unhealthy("TCP health check against host=%s port=%s failed", host, port); }
@Test void tcpHealthCheckShouldReturnUnhealthyIfCannotConnect() throws IOException { serverSocket.close(); assertThatThrownBy(() -> tcpHealthCheck.check()).isInstanceOfAny(ConnectException.class, SocketTimeoutException.class); }
public boolean unreference() { int newVal = status.decrementAndGet(); Preconditions.checkState(newVal != 0xffffffff, "called unreference when the reference count was already at 0."); return newVal == STATUS_CLOSED_MASK; }
@Test public void testUnreference() throws ClosedChannelException { CloseableReferenceCount clr = new CloseableReferenceCount(); clr.reference(); clr.reference(); assertFalse("New reference count should not equal STATUS_CLOSED_MASK", clr.unreference()); assertEquals("Incorrect reference count", 1, clr.getReferenceCount()); }
public boolean matches(Evidence evidence) { return sourceMatches(evidence) && confidenceMatches(evidence) && name.equalsIgnoreCase(evidence.getName()) && valueMatches(evidence); }
@Test public void testRegExWildcardSourceMatching() throws Exception { final EvidenceMatcher regexMediumWildcardSourceMatcher = new EvidenceMatcher(null, "name", "^.*v[al]{2,2}ue[a-z ]+$", true, Confidence.MEDIUM); assertFalse("regex medium wildcard source matcher should not match REGEX_EVIDENCE_HIGHEST", regexMediumWildcardSourceMatcher.matches(REGEX_EVIDENCE_HIGHEST)); assertFalse("regex medium wildcard source matcher should not match REGEX_EVIDENCE_HIGH", regexMediumWildcardSourceMatcher.matches(REGEX_EVIDENCE_HIGH)); assertFalse("regex medium wildcard source matcher should not match REGEX_EVIDENCE_MEDIUM", regexMediumWildcardSourceMatcher.matches(REGEX_EVIDENCE_MEDIUM)); assertTrue("regex medium wildcard source matcher should match REGEX_EVIDENCE_MEDIUM_SECOND_SOURCE", regexMediumWildcardSourceMatcher.matches(REGEX_EVIDENCE_MEDIUM_SECOND_SOURCE)); assertTrue("regex medium wildcard source matcher should match REGEX_EVIDENCE_MEDIUM_THIRD_SOURCE", regexMediumWildcardSourceMatcher.matches(REGEX_EVIDENCE_MEDIUM_THIRD_SOURCE)); assertFalse("regex medium wildcard source matcher should not match REGEX_EVIDENCE_LOW", regexMediumWildcardSourceMatcher.matches(REGEX_EVIDENCE_LOW)); }
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter, MetricsRecorder metricsRecorder, BufferSupplier bufferSupplier) { if (sourceCompressionType == CompressionType.NONE && targetCompression.type() == CompressionType.NONE) { // check the magic value if (!records.hasMatchingMagic(toMagic)) return convertAndAssignOffsetsNonCompressed(offsetCounter, metricsRecorder); else // Do in-place validation, offset assignment and maybe set timestamp return assignOffsetsNonCompressed(offsetCounter, metricsRecorder); } else return validateMessagesAndAssignOffsetsCompressed(offsetCounter, metricsRecorder, bufferSupplier); }
@Test public void testOffsetAssignmentAfterUpConversionV0ToV1NonCompressed() { MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V0, RecordBatch.NO_TIMESTAMP, Compression.NONE); checkOffsets(records, 0); long offset = 1234567; LogValidator.ValidationResult validatedResults = new LogValidator( records, new TopicPartition("topic", 0), time, CompressionType.NONE, Compression.NONE, false, RecordBatch.MAGIC_VALUE_V1, TimestampType.LOG_APPEND_TIME, 1000L, 1000L, RecordBatch.NO_PARTITION_LEADER_EPOCH, AppendOrigin.CLIENT, MetadataVersion.latestTesting() ).validateMessagesAndAssignOffsets( PrimitiveRef.ofLong(offset), metricsRecorder, RequestLocal.withThreadConfinedCaching().bufferSupplier() ); checkOffsets(validatedResults.validatedRecords, offset); verifyRecordValidationStats( validatedResults.recordValidationStats, 3, // numConvertedRecords records, false // compressed ); }
Set<SourceName> analyzeExpression( final Expression expression, final String clauseType ) { final Validator extractor = new Validator(clauseType); extractor.process(expression, null); return extractor.referencedSources; }
@Test public void shouldThrowOnPossibleSyntheticKeyColumnIfNotPossible() { // Given: analyzer = new ColumnReferenceValidator(sourceSchemas, false); // When: final Exception e = assertThrows( UnknownColumnException.class, () -> analyzer.analyzeExpression(POSSIBLE_SYNTHETIC_KEY, "SELECT") ); // Then: assertThat(e.getMessage(), containsString( "SELECT column 'ROWKEY' cannot be resolved.")); }
@PutMapping @Secured(resource = AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, action = ActionTypes.WRITE) public Object updateUser(@RequestParam String username, @RequestParam String newPassword, HttpServletResponse response, HttpServletRequest request) throws IOException { // admin or same user try { if (!hasPermission(username, request)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "authorization failed!"); return null; } } catch (HttpSessionRequiredException e) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "session expired!"); return null; } catch (AccessException exception) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "authorization failed!"); return null; } User user = userDetailsService.getUserFromDatabase(username); if (user == null) { throw new IllegalArgumentException("user " + username + " not exist!"); } userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword)); return RestResultUtils.success("update user ok!"); }
@Test void testUpdateUser2() { when(authConfigs.isAuthEnabled()).thenReturn(false); when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(null); MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); assertThrows(IllegalArgumentException.class, () -> { userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest); }); }
@Override public void execute(Map<String, List<String>> parameters, PrintWriter output) throws Exception { final List<String> loggerNames = getLoggerNames(parameters); final Level loggerLevel = getLoggerLevel(parameters); final Duration duration = getDuration(parameters); for (String loggerName : loggerNames) { Logger logger = ((LoggerContext) loggerContext).getLogger(loggerName); String message = String.format("Configured logging level for %s to %s", loggerName, loggerLevel); if (loggerLevel != null && duration != null) { final long millis = duration.toMillis(); getTimer().schedule(new TimerTask() { @Override public void run() { logger.setLevel(null); } }, millis); message += String.format(" for %s milliseconds", millis); } logger.setLevel(loggerLevel); output.println(message); output.flush(); } }
@Test void configuresSpecificLevelForALogger() throws Exception { // given Level twoEffectiveBefore = logger2.getEffectiveLevel(); Map<String, List<String>> parameters = Map.of( "logger", List.of("logger.one"), "level", List.of("debug")); // when task.execute(parameters, output); // then assertThat(logger1.getEffectiveLevel()).isEqualTo(Level.DEBUG); assertThat(logger2.getEffectiveLevel()).isEqualTo(twoEffectiveBefore); assertThat(stringWriter).hasToString(String.format("Configured logging level for logger.one to DEBUG%n")); }
public static <T> T loadObject(String content, Class<T> type) { return new Yaml(new YamlParserConstructor(), new CustomRepresenter()).loadAs(content, type); }
@Test void testLoadObject() { ConfigMetadata configMetadata = YamlParserUtil.loadObject(CONFIG_METADATA_STRING, ConfigMetadata.class); assertNotNull(configMetadata); List<ConfigMetadata.ConfigExportItem> metadataList = configMetadata.getMetadata(); assertNotNull(metadataList); assertEquals(2, metadataList.size()); ConfigMetadata.ConfigExportItem configExportItem1 = metadataList.get(0); ConfigMetadata.ConfigExportItem configExportItem2 = metadataList.get(1); assertEquals(configExportItem1, item1); assertEquals(configExportItem2, item2); }
@Override public void apply(IntentOperationContext<DomainIntent> context) { Optional<IntentData> toUninstall = context.toUninstall(); Optional<IntentData> toInstall = context.toInstall(); List<DomainIntent> uninstallIntents = context.intentsToUninstall(); List<DomainIntent> installIntents = context.intentsToInstall(); if (!toInstall.isPresent() && !toUninstall.isPresent()) { intentInstallCoordinator.intentInstallSuccess(context); return; } if (toUninstall.isPresent()) { IntentData intentData = toUninstall.get(); trackerService.removeTrackedResources(intentData.key(), intentData.intent().resources()); uninstallIntents.forEach(installable -> trackerService.removeTrackedResources(intentData.intent().key(), installable.resources())); } if (toInstall.isPresent()) { IntentData intentData = toInstall.get(); trackerService.addTrackedResources(intentData.key(), intentData.intent().resources()); installIntents.forEach(installable -> trackerService.addTrackedResources(intentData.key(), installable.resources())); } // Generate domain Intent operations DomainIntentOperations.Builder builder = DomainIntentOperations.builder(); DomainIntentOperationsContext domainOperationsContext; uninstallIntents.forEach(builder::remove); installIntents.forEach(builder::add); domainOperationsContext = new DomainIntentOperationsContext() { @Override public void onSuccess(DomainIntentOperations idops) { intentInstallCoordinator.intentInstallSuccess(context); } @Override public void onError(DomainIntentOperations idos) { intentInstallCoordinator.intentInstallFailed(context); } }; log.debug("submitting domain intent {} -> {}", toUninstall.map(x -> x.key().toString()).orElse("<empty>"), toInstall.map(x -> x.key().toString()).orElse("<empty>")); // Submit domain Inten operations with domain context domainIntentService.sumbit(builder.build(domainOperationsContext)); }
@Test public void testInstall() { List<Intent> intentsToUninstall = Lists.newArrayList(); List<Intent> intentsToInstall = createDomainIntents(); IntentData toUninstall = null; IntentData toInstall = new IntentData(createP2PIntent(), IntentState.INSTALLING, new WallClockTimestamp()); toInstall = IntentData.compiled(toInstall, intentsToInstall); IntentOperationContext<DomainIntent> operationContext; IntentInstallationContext context = new IntentInstallationContext(toUninstall, toInstall); operationContext = new IntentOperationContext(intentsToUninstall, intentsToInstall, context); installer.apply(operationContext); assertEquals(intentInstallCoordinator.successContext, operationContext); }
public static boolean check(@NonNull Fragment fragment, int requestCode) { final String[] permissions = getPermissionsStrings(requestCode); if (EasyPermissions.hasPermissions(fragment.requireContext(), permissions)) { return true; } else { // Do not have permissions, request them now EasyPermissions.requestPermissions( new PermissionRequest.Builder(fragment, requestCode, permissions) .setRationale(getRationale(requestCode)) .setPositiveButtonText(R.string.allow_permission) .setTheme(R.style.Theme_AppCompat_Dialog_Alert) .build()); return false; } }
@Test @Config(sdk = Build.VERSION_CODES.KITKAT) public void testCheckAlreadyHasPermissionsBeforeM() { try (var scenario = ActivityScenario.launch(TestFragmentActivity.class)) { scenario.onActivity( activity -> { Assert.assertTrue( PermissionRequestHelper.check( activity, PermissionRequestHelper.CONTACTS_PERMISSION_REQUEST_CODE)); Assert.assertTrue( PermissionRequestHelper.check( activity, PermissionRequestHelper.NOTIFICATION_PERMISSION_REQUEST_CODE)); }); } }
public void isIn(@Nullable Iterable<?> iterable) { checkNotNull(iterable); if (!contains(iterable, actual)) { failWithActual("expected any of", iterable); } }
@Test public void isInNullInListWithNull() { assertThat((String) null).isIn(oneShotIterable("a", "b", (String) null)); }
@Override public Object deserialize(Writable writable) { return ((Container<?>) writable).get(); }
@Test public void testDeserialize() { HiveIcebergSerDe serDe = new HiveIcebergSerDe(); Record record = RandomGenericData.generate(schema, 1, 0).get(0); Container<Record> container = new Container<>(); container.set(record); Assert.assertEquals(record, serDe.deserialize(container)); }
@SneakyThrows @Override public Integer call() throws Exception { super.call(); PicocliRunner.call(App.class, "namespace", "files", "--help"); return 0; }
@Test void runWithNoParam() { ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); try (ApplicationContext ctx = ApplicationContext.builder().deduceEnvironment(false).start()) { String[] args = {}; Integer call = PicocliRunner.call(NamespaceFilesCommand.class, ctx, args); assertThat(call, is(0)); assertThat(out.toString(), containsString("Usage: kestra namespace files")); } }
public static boolean isNodeAttributesEquals( Set<NodeAttribute> leftNodeAttributes, Set<NodeAttribute> rightNodeAttributes) { if (leftNodeAttributes == null && rightNodeAttributes == null) { return true; } else if (leftNodeAttributes == null || rightNodeAttributes == null || leftNodeAttributes.size() != rightNodeAttributes.size()) { return false; } return leftNodeAttributes.stream() .allMatch(e -> isNodeAttributeIncludes(rightNodeAttributes, e)); }
@Test void testIsNodeAttributesEquals() { NodeAttribute nodeAttributeCK1V1 = NodeAttribute .newInstance(NodeAttribute.PREFIX_CENTRALIZED, "K1", NodeAttributeType.STRING, "V1"); NodeAttribute nodeAttributeCK1V1Copy = NodeAttribute .newInstance(NodeAttribute.PREFIX_CENTRALIZED, "K1", NodeAttributeType.STRING, "V1"); NodeAttribute nodeAttributeDK1V1 = NodeAttribute .newInstance(NodeAttribute.PREFIX_DISTRIBUTED, "K1", NodeAttributeType.STRING, "V1"); NodeAttribute nodeAttributeDK1V1Copy = NodeAttribute .newInstance(NodeAttribute.PREFIX_DISTRIBUTED, "K1", NodeAttributeType.STRING, "V1"); NodeAttribute nodeAttributeDK2V1 = NodeAttribute .newInstance(NodeAttribute.PREFIX_DISTRIBUTED, "K2", NodeAttributeType.STRING, "V1"); NodeAttribute nodeAttributeDK2V2 = NodeAttribute .newInstance(NodeAttribute.PREFIX_DISTRIBUTED, "K2", NodeAttributeType.STRING, "V2"); /* * equals if set size equals and items are all the same */ assertTrue(NodeLabelUtil.isNodeAttributesEquals(null, null)); assertTrue(NodeLabelUtil .isNodeAttributesEquals(ImmutableSet.of(), ImmutableSet.of())); assertTrue(NodeLabelUtil .isNodeAttributesEquals(ImmutableSet.of(nodeAttributeCK1V1), ImmutableSet.of(nodeAttributeCK1V1Copy))); assertTrue(NodeLabelUtil .isNodeAttributesEquals(ImmutableSet.of(nodeAttributeDK1V1), ImmutableSet.of(nodeAttributeDK1V1Copy))); assertTrue(NodeLabelUtil.isNodeAttributesEquals( ImmutableSet.of(nodeAttributeCK1V1, nodeAttributeDK1V1), ImmutableSet.of(nodeAttributeCK1V1Copy, nodeAttributeDK1V1Copy))); /* * not equals if set size not equals or items are different */ assertFalse( NodeLabelUtil.isNodeAttributesEquals(null, ImmutableSet.of())); assertFalse( NodeLabelUtil.isNodeAttributesEquals(ImmutableSet.of(), null)); // different attribute prefix assertFalse(NodeLabelUtil .isNodeAttributesEquals(ImmutableSet.of(nodeAttributeCK1V1), ImmutableSet.of(nodeAttributeDK1V1))); // different attribute name assertFalse(NodeLabelUtil .isNodeAttributesEquals(ImmutableSet.of(nodeAttributeDK1V1), ImmutableSet.of(nodeAttributeDK2V1))); // different attribute value assertFalse(NodeLabelUtil .isNodeAttributesEquals(ImmutableSet.of(nodeAttributeDK2V1), ImmutableSet.of(nodeAttributeDK2V2))); // different set assertFalse(NodeLabelUtil .isNodeAttributesEquals(ImmutableSet.of(nodeAttributeCK1V1), ImmutableSet.of())); assertFalse(NodeLabelUtil .isNodeAttributesEquals(ImmutableSet.of(nodeAttributeCK1V1), ImmutableSet.of(nodeAttributeCK1V1, nodeAttributeDK1V1))); assertFalse(NodeLabelUtil.isNodeAttributesEquals( ImmutableSet.of(nodeAttributeCK1V1, nodeAttributeDK1V1), ImmutableSet.of(nodeAttributeDK1V1))); }
public void isNotNull() { standardIsNotEqualTo(null); }
@Test public void isNotNullWhenSubjectForbidsIsEqualToFail() { expectFailure.whenTesting().about(objectsForbiddingEqualityCheck()).that(null).isNotNull(); }
@SqlNullable @Description("Returns TRUE if and only if the line is closed and simple") @ScalarFunction("ST_IsRing") @SqlType(BOOLEAN) public static Boolean stIsRing(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { OGCGeometry geometry = EsriGeometrySerde.deserialize(input); validateType("ST_IsRing", geometry, EnumSet.of(LINE_STRING)); OGCLineString line = (OGCLineString) geometry; return line.isClosed() && line.isSimple(); }
@Test public void testSTIsRing() { assertFunction("ST_IsRing(ST_GeometryFromText('LINESTRING (8 4, 4 8)'))", BOOLEAN, false); assertFunction("ST_IsRing(ST_GeometryFromText('LINESTRING (0 0, 1 1, 0 2, 0 0)'))", BOOLEAN, true); assertInvalidFunction("ST_IsRing(ST_GeometryFromText('POLYGON ((2 0, 2 1, 3 1, 2 0))'))", "ST_IsRing only applies to LINE_STRING. Input type is: POLYGON"); }
@Override public CiConfiguration loadConfiguration() { String revision = system.envVariable("SEMAPHORE_GIT_SHA"); return new CiConfigurationImpl(revision, getName()); }
@Test public void loadConfiguration() { setEnvVariable("SEMAPHORE", "true"); setEnvVariable("SEMAPHORE_PROJECT_ID", "d782a107-aaf9-494d-8153-206b1a6bc8e9"); setEnvVariable("SEMAPHORE_GIT_SHA", "abd12fc"); assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc"); }
public static void checkNullOrNonNullNonEmptyEntries( @Nullable Collection<String> values, String propertyName) { if (values == null) { // pass return; } for (String value : values) { Preconditions.checkNotNull( value, "Property '" + propertyName + "' cannot contain null entries"); Preconditions.checkArgument( !value.trim().isEmpty(), "Property '" + propertyName + "' cannot contain empty strings"); } }
@Test public void testCheckNullOrNonNullNonEmptyEntries_mapEmptyKeyFail() { try { Validator.checkNullOrNonNullNonEmptyEntries(Collections.singletonMap(" ", "val1"), "test"); Assert.fail(); } catch (IllegalArgumentException iae) { Assert.assertEquals("Property 'test' cannot contain empty string keys", iae.getMessage()); } }
@Override public Map<String, String[]> getParameterMap() { return stringMap; }
@Test void testGetParameterMap() { Map<String, String[]> parameterMap = reuseHttpServletRequest.getParameterMap(); assertNotNull(parameterMap); assertEquals(2, parameterMap.size()); assertEquals("test", parameterMap.get("name")[0]); assertEquals("123", parameterMap.get("value")[0]); }
public int read() { int b = -1; if (position < length) { b = buffer.getByte(offset + position) & 0xFF; ++position; } return b; }
@Test void shouldReturnMinusOneOnEndOfStream() { final byte[] data = { 1, 2 }; final DirectBuffer buffer = new UnsafeBuffer(data); final DirectBufferInputStream inputStream = new DirectBufferInputStream(buffer); assertEquals(inputStream.read(), 1); assertEquals(inputStream.read(), 2); assertEquals(inputStream.read(), END_OF_STREAM_MARKER); }
public static InternalLogger getInstance(Class<?> clazz) { return getInstance(clazz.getName()); }
@Test public void testWarn() { final InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.warn("a"); verify(mockLogger).warn("a"); }
@Override public void run() { JobRunrMetadata metadata = storageProvider.getMetadata("database_version", "cluster"); if (metadata != null && "6.0.0".equals(metadata.getValue())) return; migrateScheduledJobsIfNecessary(); storageProvider.saveMetadata(new JobRunrMetadata("database_version", "cluster", "6.0.0")); }
@Test void doesMigrationsOfAllScheduledJobsIfStorageProviderIsAnSqlStorageProvider() { doReturn(PostgresStorageProvider.class).when(storageProviderInfo).getImplementationClass(); when(storageProvider.getScheduledJobs(any(), any())) .thenAnswer(i -> aLotOfScheduledJobs(i.getArgument(1, OffsetBasedPageRequest.class), 5500)); task.run(); verify(storageProvider, times(2)).getScheduledJobs(any(), any()); verify(storageProvider, times(6)).save(anyList()); }
public void writePDF( OutputStream output ) throws IOException { output.write(String.valueOf(value).getBytes(StandardCharsets.ISO_8859_1)); }
@Test void testWritePDF() { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); int index = 0; try { for (int i = -1000; i < 3000; i += 200) { index = i; COSInteger cosInt = COSInteger.get(i); cosInt.writePDF(outStream); testByteArrays(String.valueOf(i).getBytes(StandardCharsets.ISO_8859_1), outStream.toByteArray()); outStream.reset(); } } catch (Exception e) { fail("Failed to write " + index + " exception: " + e.getMessage()); } }
@Override public void judgeContinueToExecute(final SQLStatement statement) throws SQLException { ShardingSpherePreconditions.checkState(statement instanceof CommitStatement || statement instanceof RollbackStatement, () -> new SQLFeatureNotSupportedException("Current transaction is aborted, commands ignored until end of transaction block.")); }
@Test void assertJudgeContinueToExecuteWithRollbackStatement() { assertDoesNotThrow(() -> allowedSQLStatementHandler.judgeContinueToExecute(mock(RollbackStatement.class))); }
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { if(log.isWarnEnabled()) { log.warn(String.format("Disable checksum verification for %s", file)); // Do not set checksum when metadata key X-Static-Large-Object is present. Disable checksum verification in download filter. status.setChecksum(Checksum.NONE); } final Response response; if(status.isAppend()) { final HttpRange range = HttpRange.withStatus(status); if(TransferStatus.UNKNOWN_LENGTH == range.getEnd()) { response = session.getClient().getObject(regionService.lookup(file), containerService.getContainer(file).getName(), containerService.getKey(file), range.getStart()); } else { response = session.getClient().getObject(regionService.lookup(file), containerService.getContainer(file).getName(), containerService.getKey(file), range.getStart(), range.getLength()); } } else { response = session.getClient().getObject(regionService.lookup(file), containerService.getContainer(file).getName(), containerService.getKey(file)); } return new HttpMethodReleaseInputStream(response.getResponse(), status); } catch(GenericException e) { throw new SwiftExceptionMappingService().map("Download {0} failed", e, file); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map(e, file); } }
@Test(expected = NotfoundException.class) public void testReadNotFound() throws Exception { final TransferStatus status = new TransferStatus(); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final SwiftRegionService regionService = new SwiftRegionService(session); new SwiftReadFeature(session, regionService).read(new Path(container, "nosuchname", EnumSet.of(Path.Type.file)), status, new DisabledConnectionCallback()); }
private ByteBuf buffer(int i) { ByteBuf b = buffers[i]; return b instanceof Component ? ((Component) b).buf : b; }
@Test public void testGatheringWritesHeap() throws Exception { testGatheringWrites(buffer(), buffer()); }
@Override public DictDataDO getDictData(Long id) { return dictDataMapper.selectById(id); }
@Test public void testGetDictData() { // mock 数据 DictDataDO dbDictData = randomDictDataDO(); dictDataMapper.insert(dbDictData); // 准备参数 Long id = dbDictData.getId(); // 调用 DictDataDO dictData = dictDataService.getDictData(id); // 断言 assertPojoEquals(dbDictData, dictData); }
AwsCredentials credentials() { if (!StringUtil.isNullOrEmptyAfterTrim(awsConfig.getAccessKey())) { return AwsCredentials.builder() .setAccessKey(awsConfig.getAccessKey()) .setSecretKey(awsConfig.getSecretKey()) .build(); } if (!StringUtil.isNullOrEmptyAfterTrim(ec2IamRole)) { return fetchCredentialsFromEc2(); } if (environment.isRunningOnEcs()) { return fetchCredentialsFromEcs(); } throw new NoCredentialsException(); }
@Test(expected = InvalidConfigurationException.class) public void credentialsEc2Exception() { // given String iamRole = "sample-iam-role"; AwsConfig awsConfig = AwsConfig.builder() .setIamRole(iamRole) .build(); given(awsMetadataApi.credentialsEc2(iamRole)).willThrow(new RuntimeException("Error fetching credentials")); given(environment.isRunningOnEcs()).willReturn(false); AwsCredentialsProvider credentialsProvider = new AwsCredentialsProvider(awsConfig, awsMetadataApi, environment); // when credentialsProvider.credentials(); // then // throws exception }
@Udf public String lpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (padding == null || padding.isEmpty() || targetLen == null || targetLen < 0) { return null; } final StringBuilder sb = new StringBuilder(targetLen + padding.length()); final int padUpTo = Math.max(targetLen - input.length(), 0); for (int i = 0; i < padUpTo; i += padding.length()) { sb.append(padding); } sb.setLength(padUpTo); sb.append(input); sb.setLength(targetLen); return sb.toString(); }
@Test public void shouldReturnNullForNullInputBytes() { final ByteBuffer result = udf.lpad(null, 4, BYTES_45); assertThat(result, is(nullValue())); }
public static String decodeReferenceToken(final String s) { String decoded = s; List<String> reverseOrderedKeys = new ArrayList<String>(SUBSTITUTIONS.keySet()); Collections.reverse(reverseOrderedKeys); for (String key : reverseOrderedKeys) { decoded = decoded.replace(SUBSTITUTIONS.get(key), key); } return decoded; }
@Test public void testDecodeReferenceToken() { assertThat(JsonPointerUtils.decodeReferenceToken("com~1vsv~2~3~3~3~4"), is("com/vsv#...?")); assertThat(JsonPointerUtils.decodeReferenceToken("~01~02~001~03~04"), is("~1~2~01~3~4")); }
static List<byte[]> readCertificates(Path path) throws CertificateException { final byte[] bytes; try { bytes = Files.readAllBytes(path); } catch (IOException e) { throw new CertificateException("Couldn't read certificates from file: " + path, e); } final String content = new String(bytes, StandardCharsets.US_ASCII); final Matcher m = CERT_PATTERN.matcher(content); final List<byte[]> certs = new ArrayList<>(); int start = 0; while (m.find(start)) { final String s = m.group(1); byte[] der = Base64.getDecoder().decode(CharMatcher.breakingWhitespace().removeFrom(s)); certs.add(der); start = m.end(); } if (certs.isEmpty()) { throw new CertificateException("No certificates found in file: " + path); } return certs; }
@Test public void readCertificatesHandlesSingleCertificate() throws Exception { final URL url = Resources.getResource("org/graylog2/shared/security/tls/single.crt"); final List<byte[]> certificates = PemReader.readCertificates(Paths.get(url.toURI())); assertThat(certificates).hasSize(1); }
@Override protected Set<StepField> getUsedFields( RestMeta stepMeta ) { Set<StepField> usedFields = new HashSet<>(); // add url field if ( stepMeta.isUrlInField() && StringUtils.isNotEmpty( stepMeta.getUrlField() ) ) { usedFields.addAll( createStepFields( stepMeta.getUrlField(), getInputs() ) ); } // add method field if ( stepMeta.isDynamicMethod() && StringUtils.isNotEmpty( stepMeta.getMethodFieldName() ) ) { usedFields.addAll( createStepFields( stepMeta.getMethodFieldName(), getInputs() ) ); } // add body field if ( StringUtils.isNotEmpty( stepMeta.getBodyField() ) ) { usedFields.addAll( createStepFields( stepMeta.getBodyField(), getInputs() ) ); } // add parameters as used fields String[] parameterFields = stepMeta.getParameterField(); if ( ArrayUtils.isNotEmpty( parameterFields ) ) { for ( String paramField : parameterFields ) { usedFields.addAll( createStepFields( paramField, getInputs() ) ); } } // add headers as used fields String[] headerFields = stepMeta.getHeaderField(); if ( ArrayUtils.isNotEmpty( headerFields ) ) { for ( String headerField : headerFields ) { usedFields.addAll( createStepFields( headerField, getInputs() ) ); } } return usedFields; }
@Test public void testGetUsedFields_methodInFieldNoFieldSet() throws Exception { Set<StepField> fields = new HashSet<>(); when( meta.isDynamicMethod() ).thenReturn( true ); when( meta.getMethodFieldName() ).thenReturn( null ); Set<StepField> usedFields = analyzer.getUsedFields( meta ); verify( analyzer, never() ).createStepFields( anyString(), any( StepNodes.class ) ); }
@SuppressWarnings("MethodMayBeStatic") // Non-static to support DI. public long parse(final String text) { final String date; final String time; final String timezone; if (text.contains("T")) { date = text.substring(0, text.indexOf('T')); final String withTimezone = text.substring(text.indexOf('T') + 1); timezone = getTimezone(withTimezone); time = completeTime(withTimezone.substring(0, withTimezone.length() - timezone.length()) .replaceAll("Z$","")); } else { date = completeDate(text); time = completeTime(""); timezone = ""; } try { final ZoneId zoneId = parseTimezone(timezone); return PARSER.parse(date + "T" + time, zoneId); } catch (final RuntimeException e) { throw new KsqlException("Failed to parse timestamp '" + text + "': " + e.getMessage() + HELP_MESSAGE, e ); } }
@Test public void shouldParseFullDateTime() { // When: assertThat(parser.parse("2020-12-02T13:59:58.123"), is(fullParse("2020-12-02T13:59:58.123+0000"))); assertThat(parser.parse("2020-12-02T13:59:58.123Z"), is(fullParse("2020-12-02T13:59:58.123+0000"))); }
@Override public boolean getTcpNoDelay() { return clientConfig.getPropertyAsBoolean(TCP_NO_DELAY, false); }
@Test void testGetTcpNoDelay() { assertFalse(connectionPoolConfig.getTcpNoDelay()); }
@GetMapping("/enum") public ShenyuAdminResult queryEnums() { return ShenyuAdminResult.success(enumService.list()); }
@Test public void testQueryEnums() throws Exception { final String queryEnumsUri = "/platform/enum"; this.mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, queryEnumsUri)) .andExpect(status().isOk()) .andExpect(jsonPath("$.code", is(CommonErrorCode.SUCCESSFUL))) .andExpect(jsonPath("$.data", is(this.enumService.list()))) .andReturn(); }
synchronized void unlock(final TaskId taskId) { final Thread lockOwner = lockedTasksToOwner.get(taskId); if (lockOwner != null && lockOwner.equals(Thread.currentThread())) { lockedTasksToOwner.remove(taskId); log.debug("{} Released state dir lock for task {}", logPrefix(), taskId); } }
@Test public void shouldBeAbleToUnlockEvenWithoutLocking() { final TaskId taskId = new TaskId(0, 0); directory.unlock(taskId); }
public boolean add(final Integer value) { return add(value.intValue()); }
@Test void forEachShouldInvokeConsumerWithTheMissingValueAtTheIfOneWasAddedToTheSet() { @SuppressWarnings("unchecked") final Consumer<Integer> consumer = mock(Consumer.class); testSet.add(MISSING_VALUE); testSet.add(15); testSet.add(MISSING_VALUE); testSet.forEach(consumer); final InOrder inOrder = inOrder(consumer); inOrder.verify(consumer).accept(15); inOrder.verify(consumer).accept(MISSING_VALUE); verifyNoMoreInteractions(consumer); }
@Override public void encode(final ChannelHandlerContext context, final DatabasePacket message, final ByteBuf out) { boolean isIdentifierPacket = message instanceof PostgreSQLIdentifierPacket; if (isIdentifierPacket) { prepareMessageHeader(out, ((PostgreSQLIdentifierPacket) message).getIdentifier().getValue()); } PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(out, context.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get()); try { message.write(payload); // CHECKSTYLE:OFF } catch (final RuntimeException ex) { // CHECKSTYLE:ON payload.getByteBuf().resetWriterIndex(); // TODO consider what severity to use PostgreSQLErrorResponsePacket errorResponsePacket = PostgreSQLErrorResponsePacket.newBuilder( PostgreSQLMessageSeverityLevel.ERROR, PostgreSQLVendorError.SYSTEM_ERROR, ex.getMessage()).build(); isIdentifierPacket = true; prepareMessageHeader(out, errorResponsePacket.getIdentifier().getValue()); errorResponsePacket.write(payload); } finally { if (isIdentifierPacket) { updateMessageLength(out); } } }
@Test void assertEncodePostgreSQLPacket() { PostgreSQLPacket packet = mock(PostgreSQLPacket.class); new PostgreSQLPacketCodecEngine().encode(context, packet, byteBuf); verify(packet).write(any(PostgreSQLPacketPayload.class)); }
@Override public void setOriginalFile(Component file, OriginalFile originalFile) { storeOriginalFileInCache(originalFiles, file, originalFile); }
@Test public void setOriginalFile_does_not_fail_if_same_original_file_is_added_multiple_times_for_the_same_component() { underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE); for (int i = 0; i < 1 + Math.abs(new Random().nextInt(10)); i++) { underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE); } }
public String getString(String path) { return ObjectConverter.convertObjectTo(get(path), String.class); }
@Test public void can_parse_multiple_values() { // Given final JsonPath jsonPath = new JsonPath(JSON); // When final String category1 = jsonPath.getString("store.book.category[0]"); final String category2 = jsonPath.getString("store.book.category[1]"); // Then assertThat(category1, equalTo("reference")); assertThat(category2, equalTo("fiction")); }
public Histogram histogram(String name) { return histogram(MetricName.build(name)); }
@Test public void accessingAHistogramRegistersAndReusesIt() throws Exception { final Histogram histogram1 = registry.histogram(THING); final Histogram histogram2 = registry.histogram(THING); assertThat(histogram1) .isSameAs(histogram2); verify(listener).onHistogramAdded(THING, histogram1); }
@Override public DataSourceProvenance getProvenance() { return new DemoLabelDataSourceProvenance(this); }
@Test public void testNoisyInterlockingCrescents() { // Check zero samples throws assertThrows(PropertyException.class, () -> new NoisyInterlockingCrescentsDataSource(0, 1, 0.1)); // Check invalid variance throws assertThrows(PropertyException.class, () -> new NoisyInterlockingCrescentsDataSource(200, 1, -0.1)); assertThrows(PropertyException.class, () -> new NoisyInterlockingCrescentsDataSource(200, 1, 0.0)); // Check valid parameters work NoisyInterlockingCrescentsDataSource source = new NoisyInterlockingCrescentsDataSource(200, 1, 0.1); assertEquals(200, source.examples.size()); Dataset<Label> dataset = new MutableDataset<>(source); Map<String, Long> map = new HashMap<>(); dataset.getOutputInfo().outputCountsIterable().forEach((p) -> map.put(p.getA(), p.getB())); assertEquals(100, map.get("X")); assertEquals(100, map.get("O")); Helpers.testProvenanceMarshalling(source.getProvenance()); }
public static String toIpAddress(SocketAddress address) { InetSocketAddress inetSocketAddress = (InetSocketAddress) address; return inetSocketAddress.getAddress().getHostAddress(); }
@Test public void testToIpAddress() throws UnknownHostException { assertThat(NetUtil.toIpAddress(ipv4)).isEqualTo(ipv4.getAddress().getHostAddress()); assertThat(NetUtil.toIpAddress(ipv6)).isEqualTo(ipv6.getAddress().getHostAddress()); }
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = statement.getStatement(); final MetaStore metaStore = executionContext.getMetaStore(); final KsqlConfig config = statement.getSessionConfig().getConfig(true); final DataSource dataSource = getDataSource(config, metaStore, insertValues); validateInsert(insertValues.getColumns(), dataSource); final ProducerRecord<byte[], byte[]> record = buildRecord(statement, metaStore, dataSource, serviceContext); try { producer.sendRecord(record, serviceContext, config.getProducerClientConfigProps()); } catch (final TopicAuthorizationException e) { // TopicAuthorizationException does not give much detailed information about why it failed, // except which topics are denied. Here we just add the ACL to make the error message // consistent with other authorization error messages. final Exception rootCause = new KsqlTopicAuthorizationException( AclOperation.WRITE, e.unauthorizedTopics() ); throw new KsqlException(createInsertFailedExceptionMessage(insertValues), rootCause); } catch (final ClusterAuthorizationException e) { // ClusterAuthorizationException is thrown when using idempotent producers // and either a topic write permission or a cluster-level idempotent write // permission (only applicable for broker versions no later than 2.8) is // missing. In this case, we include additional context to help the user // distinguish this type of failure from other permissions exceptions // such as the ones thrown above when TopicAuthorizationException is caught. throw new KsqlException( createInsertFailedExceptionMessage(insertValues), createClusterAuthorizationExceptionRootCause(dataSource) ); } catch (final KafkaException e) { if (e.getCause() != null && e.getCause() instanceof ClusterAuthorizationException) { // The error message thrown when an idempotent producer is missing permissions // is (nondeterministically) inconsistent: it is either a raw ClusterAuthorizationException, // as checked for above, or a ClusterAuthorizationException wrapped inside a KafkaException. // ksqlDB handles these two the same way, accordingly. // See https://issues.apache.org/jira/browse/KAFKA-14138 for more. throw new KsqlException( createInsertFailedExceptionMessage(insertValues), createClusterAuthorizationExceptionRootCause(dataSource) ); } else { throw new KsqlException(createInsertFailedExceptionMessage(insertValues), e); } } catch (final Exception e) { throw new KsqlException(createInsertFailedExceptionMessage(insertValues), e); } }
@Test public void shouldNotAllowInsertOnMultipleKeySchemaDefinitionsWithDifferentOrder() throws Exception { final String protoMultiSchema = "syntax = \"proto3\";\n" + "package io.proto;\n" + "\n" + "message SingleKey {\n" + " string k0 = 1;\n" + "}\n" + "message MultiKeys {\n" + " string k1 = 1;\n" + " string k0 = 2;\n" + "}\n"; // Given: when(srClient.getLatestSchemaMetadata(Mockito.any())) .thenReturn(new SchemaMetadata(1, 1, protoMultiSchema)); when(srClient.getSchemaById(1)) .thenReturn(new ProtobufSchema(protoMultiSchema)); givenDataSourceWithSchema( TOPIC_NAME, SCHEMA_WITH_MUTI_KEYS, SerdeFeatures.of(SerdeFeature.SCHEMA_INFERENCE), SerdeFeatures.of(), FormatInfo.of(FormatFactory.PROTOBUF.name(), ImmutableMap.of( AvroProperties.FULL_SCHEMA_NAME,"io.proto.MultiKeys", AvroProperties.SCHEMA_ID, "1" )), FormatInfo.of(FormatFactory.JSON.name()), false, false); final ConfiguredStatement<InsertValues> statement = givenInsertValues( ImmutableList.of(K1, K0, COL0, COL1), ImmutableList.of( new StringLiteral("K1"), new StringLiteral("K0"), new StringLiteral("V0"), new LongLiteral(21)) ); // When: final Exception e = assertThrows( KsqlException.class, () -> executor.execute(statement, mock(SessionProperties.class), engine, serviceContext) ); // Then: assertThat(e.getMessage(), containsString("ksqlDB generated schema would overwrite existing key schema")); assertThat(e.getMessage(), containsString("Existing Schema: [`K1` STRING, `K0` STRING]")); assertThat(e.getMessage(), containsString("ksqlDB Generated: [`k0` STRING KEY, `k1` STRING KEY]")); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { super.doFilter(request, response, chain); return; } final HttpServletRequest httpRequest = (HttpServletRequest) request; registerSessionIfNeeded(httpRequest); super.doFilter(request, response, chain); // si logout on prend en compte de suite la destruction de la session unregisterSessionIfNeeded(httpRequest); }
@Test public void testWithSessionCreated() throws IOException, ServletException { final int sessionCount = SessionListener.getSessionCount(); final HttpServletRequest request = createNiceMock(HttpServletRequest.class); final HttpServletResponse response = createNiceMock(HttpServletResponse.class); final FilterChain chain = createNiceMock(FilterChain.class); expect(request.getRequestURI()).andReturn(CONTEXT_PATH + TEST_REQUEST).anyTimes(); expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes(); final HttpSession session = createNiceMock(HttpSession.class); expect(request.isRequestedSessionIdValid()).andReturn(true).anyTimes(); expect(request.getSession(false)).andReturn(session).anyTimes(); expect(request.getLocale()).andReturn(Locale.FRANCE).anyTimes(); expect(session.getId()).andReturn("1234567890").anyTimes(); replay(request); replay(response); replay(chain); replay(session); pluginMonitoringFilter.doFilter(request, response, chain); assertEquals("sessionCount", sessionCount + 1, SessionListener.getSessionCount()); pluginMonitoringFilter.doFilter(request, response, chain); assertEquals("sessionCount", sessionCount + 1, SessionListener.getSessionCount()); verify(request); verify(response); verify(chain); verify(session); }
public Labels withAdditionalLabels(Map<String, String> additionalLabels) { if (additionalLabels == null || additionalLabels.isEmpty()) { return this; } else { Map<String, String> newLabels = new HashMap<>(labels.size()); newLabels.putAll(labels); newLabels.putAll(Labels.additionalLabels(additionalLabels).toMap()); return new Labels(newLabels); } }
@Test public void testWithInvalidUserSuppliedLabels() { Map<String, String> userLabelsWithStrimzi = new HashMap<>(3); userLabelsWithStrimzi.put("key1", "value1"); userLabelsWithStrimzi.put("key2", "value2"); userLabelsWithStrimzi.put(Labels.STRIMZI_DOMAIN + "something", "value3"); assertThrows(IllegalArgumentException.class, () -> Labels.EMPTY.withAdditionalLabels(userLabelsWithStrimzi)); }
public LionBundle stitch(String id) { String source = base + SLASH + CONFIG_DIR + SLASH + id + SUFFIX; // the following may throw IllegalArgumentException... LionConfig cfg = new LionConfig().load(source); LionBundle.Builder builder = new LionBundle.Builder(id); int total = 0; int added = 0; for (LionConfig.CmdFrom from : cfg.entries()) { total += 1; log.debug(" processing: {}", from.orig()); if (addItemsToBuilder(builder, from)) { added += 1; } } log.debug(" added items for {}/{} FROM entries", added, total); return builder.build(); }
@Test public void cardGame1English() { title("cardGame1English"); // use default locale (en_US) lion = testStitcher().stitch("CardGame1"); print(lion); assertEquals("wrong key", "CardGame1", lion.id()); assertEquals("bad key count", 12, lion.size()); verifyItems(lion, CARD_GAME_1_ENGLISH); }
public FEELFnResult<Boolean> invoke(@ParameterName("string") String string, @ParameterName("match") String match) { if ( string == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null")); } if ( match == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "match", "cannot be null")); } return FEELFnResult.ofResult( string.startsWith( match ) ); }
@Test void invokeEmptyString() { FunctionTestUtil.assertResult(startsWithFunction.invoke("", ""), true); FunctionTestUtil.assertResult(startsWithFunction.invoke("", "test"), false); FunctionTestUtil.assertResult(startsWithFunction.invoke("test", ""), true); }
public static boolean isSupportPrometheus() { return isClassPresent("io.micrometer.prometheus.PrometheusConfig") && isClassPresent("io.prometheus.client.exporter.BasicAuthHttpConnectionFactory") && isClassPresent("io.prometheus.client.exporter.HttpConnectionFactory") && isClassPresent("io.prometheus.client.exporter.PushGateway"); }
@Test void isSupportPrometheus() { boolean supportPrometheus = new DefaultApplicationDeployer(ApplicationModel.defaultModel()).isSupportPrometheus(); Assert.assertTrue(supportPrometheus, "DefaultApplicationDeployer.isSupportPrometheus() should return true"); }
@Override public double rand() { return inverseTransformSampling(); }
@Test public void testSd() { System.out.println("sd"); FDistribution instance = new FDistribution(10, 20); instance.rand(); assertEquals(0.6573422, instance.sd(), 1E-7); }
@Override public ShardingSphereSchema swapToObject(final YamlShardingSphereSchema yamlConfig) { return Optional.ofNullable(yamlConfig).map(this::swapSchema).orElseGet(() -> new ShardingSphereSchema(yamlConfig.getName())); }
@Test void assertSwapToShardingSphereSchema() { YamlShardingSphereSchema yamlSchema = YamlEngine.unmarshal(readYAML(YAML), YamlShardingSphereSchema.class); ShardingSphereSchema actualSchema = new YamlSchemaSwapper().swapToObject(yamlSchema); assertThat(actualSchema.getAllTableNames(), is(Collections.singleton("t_order"))); ShardingSphereTable actualTable = actualSchema.getTable("t_order"); assertColumn(actualTable); assertThat(actualTable.getIndexValues().size(), is(1)); assertThat(actualTable.getIndexValues().iterator().next().getName(), is("PRIMARY")); assertThat(actualSchema.getAllColumnNames("t_order").size(), is(2)); assertTrue(actualSchema.containsColumn("t_order", "id")); assertTrue(actualSchema.containsColumn("t_order", "name")); }
@Override public boolean createTopic( final String topic, final int numPartitions, final short replicationFactor, final Map<String, ?> configs, final CreateTopicsOptions createOptions ) { final Optional<Long> retentionMs = KafkaTopicClient.getRetentionMs(configs); if (isTopicExists(topic)) { validateTopicProperties(topic, numPartitions, replicationFactor, retentionMs); return false; } final short resolvedReplicationFactor = replicationFactor == TopicProperties.DEFAULT_REPLICAS ? getDefaultClusterReplication() : replicationFactor; final NewTopic newTopic = new NewTopic(topic, numPartitions, resolvedReplicationFactor); newTopic.configs(toStringConfigs(configs)); try { LOG.info("Creating topic '{}' {}", topic, (createOptions.shouldValidateOnly()) ? "(ONLY VALIDATE)" : "" ); ExecutorUtil.executeWithRetries( () -> adminClient.get().createTopics( Collections.singleton(newTopic), createOptions ).all().get(), ExecutorUtil.RetryBehaviour.ON_RETRYABLE); return true; } catch (final InterruptedException e) { Thread.currentThread().interrupt(); throw new KafkaResponseGetFailedException( "Failed to guarantee existence of topic " + topic, e); } catch (final TopicExistsException e) { // if the topic already exists, it is most likely because another node just created it. // ensure that it matches the partition count, replication factor, and retention // before returning success validateTopicProperties(topic, numPartitions, replicationFactor, retentionMs); return false; } catch (final TopicAuthorizationException e) { throw new KsqlTopicAuthorizationException( AclOperation.CREATE, Collections.singleton(topic)); } catch (final Exception e) { throw new KafkaResponseGetFailedException( "Failed to guarantee existence of topic " + topic, e); } }
@Test public void shouldCreateTopic() { // When: kafkaTopicClient.createTopic("someTopic", 1, (short) 2, configs); // Then: verify(adminClient).createTopics( eq(ImmutableSet.of(newTopic("someTopic", 1, 2, configs))), argThat(createOptions -> !createOptions.shouldValidateOnly()) ); }
public static String toString(String unicode) { if (StrUtil.isBlank(unicode)) { return unicode; } final int len = unicode.length(); StringBuilder sb = new StringBuilder(len); int i; int pos = 0; while ((i = StrUtil.indexOfIgnoreCase(unicode, "\\u", pos)) != -1) { sb.append(unicode, pos, i);//写入Unicode符之前的部分 pos = i; if (i + 5 < len) { char c; try { c = (char) Integer.parseInt(unicode.substring(i + 2, i + 6), 16); sb.append(c); pos = i + 6;//跳过整个Unicode符 } catch (NumberFormatException e) { //非法Unicode符,跳过 sb.append(unicode, pos, i + 2);//写入"\\u" pos = i + 2; } } else { //非Unicode符,结束 break; } } if (pos < len) { sb.append(unicode, pos, len); } return sb.toString(); }
@Test public void convertTest2() { String str = "aaaa\\u0026bbbb\\u0026cccc"; String unicode = UnicodeUtil.toString(str); assertEquals("aaaa&bbbb&cccc", unicode); }
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception { return fromXmlPartial(toInputStream(partial, UTF_8), o); }
@Test void shouldBeAbleToExplicitlyLockAPipeline() throws Exception { String pipelineXmlPartial = (""" <pipeline name="pipeline" lockBehavior="%s"> <materials> <hg url="/hgrepo"/> </materials> <stage name="mingle"> <jobs> <job name="functional"> <artifacts> <log src="artifact1.xml" dest="cruise-output" /> </artifacts> </job> </jobs> </stage> </pipeline> """).formatted(LOCK_VALUE_LOCK_ON_FAILURE); PipelineConfig pipeline = xmlLoader.fromXmlPartial(pipelineXmlPartial, PipelineConfig.class); assertThat(pipeline.hasExplicitLock()).isTrue(); assertThat(pipeline.explicitLock()).isTrue(); }
public void store(String sourceAci, UUID messageGuid) { try { Objects.requireNonNull(sourceAci); reportMessageDynamoDb.store(hash(messageGuid, sourceAci)); } catch (final Exception e) { logger.warn("Failed to store hash", e); } }
@Test void testStore() { assertDoesNotThrow(() -> reportMessageManager.store(null, messageGuid)); verifyNoInteractions(reportMessageDynamoDb); reportMessageManager.store(sourceAci.toString(), messageGuid); verify(reportMessageDynamoDb).store(any()); doThrow(RuntimeException.class) .when(reportMessageDynamoDb).store(any()); assertDoesNotThrow(() -> reportMessageManager.store(sourceAci.toString(), messageGuid)); }
public static FieldScope allowingFields(int firstFieldNumber, int... rest) { return FieldScopeImpl.createAllowingFields(asList(firstFieldNumber, rest)); }
@Test public void testIgnoringTopLevelAnyField_fieldScopes_allowingFields() { String typeUrl = isProto3() ? "type.googleapis.com/com.google.common.truth.extensions.proto.SubTestMessage3" : "type.googleapis.com/com.google.common.truth.extensions.proto.SubTestMessage2"; Message message = parse("o_int: 1 o_any_message { [" + typeUrl + "]: { o_int: 2 r_string: \"foo\" } }"); Message diffMessage = parse("o_int: 1"); int goodFieldNumber = getFieldNumber("o_int"); expectThat(message) .withPartialScope(FieldScopes.allowingFields(goodFieldNumber)) .isEqualTo(diffMessage); }
public static int createEdgeKey(int edgeId, boolean reverse) { // edge state in storage direction -> edge key is even // edge state against storage direction -> edge key is odd return (edgeId << 1) + (reverse ? 1 : 0); }
@Test public void testEdgeStuff() { assertEquals(2, GHUtility.createEdgeKey(1, false)); assertEquals(3, GHUtility.createEdgeKey(1, true)); }
static void populateGeneratedResources(GeneratedResources toPopulate, EfestoCompilationOutput compilationOutput) { toPopulate.add(getGeneratedResource(compilationOutput)); if (compilationOutput instanceof EfestoClassesContainer) { toPopulate.addAll(getGeneratedResources((EfestoClassesContainer) compilationOutput)); } }
@Test void populateGeneratedResources() { GeneratedResources toPopulate = new GeneratedResources(); assertThat(toPopulate).isEmpty(); CompilationManagerUtils.populateGeneratedResources(toPopulate, finalOutput); int expectedResources = 4; // 1 final resource + 3 intermediate resources assertThat(toPopulate).hasSize(expectedResources); GeneratedResource finalResource = toPopulate.stream().filter(generatedResource -> generatedResource instanceof GeneratedExecutableResource).findFirst().orElse(null); commonEvaluateGeneratedExecutableResource(finalResource); List<GeneratedResource> classResources = toPopulate.stream().filter(generatedResource -> generatedResource instanceof GeneratedClassResource).map(GeneratedClassResource.class::cast).collect(Collectors.toList()); commonEvaluateGeneratedIntermediateResources(classResources); }
@Override protected Map<String, ConfigValue> validateSourceConnectorConfig(SourceConnector connector, ConfigDef configDef, Map<String, String> config) { Map<String, ConfigValue> result = super.validateSourceConnectorConfig(connector, configDef, config); validateSourceConnectorExactlyOnceSupport(config, result, connector); validateSourceConnectorTransactionBoundary(config, result, connector); return result; }
@Test public void testExactlyOnceSourceSupportValidationOnUnknownConnector() { herder = exactlyOnceHerder(); Map<String, String> config = new HashMap<>(); config.put(SourceConnectorConfig.EXACTLY_ONCE_SUPPORT_CONFIG, REQUIRED.toString()); SourceConnector connectorMock = mock(SourceConnector.class); when(connectorMock.exactlyOnceSupport(eq(config))).thenReturn(null); Map<String, ConfigValue> validatedConfigs = herder.validateSourceConnectorConfig( connectorMock, SourceConnectorConfig.configDef(), config); List<String> errors = validatedConfigs.get(SourceConnectorConfig.EXACTLY_ONCE_SUPPORT_CONFIG).errorMessages(); assertFalse(errors.isEmpty()); assertTrue( errors.get(0).contains("The connector does not implement the API required for preflight validation of exactly-once source support."), "Error message did not contain expected text: " + errors.get(0)); assertEquals(1, errors.size()); }
public static Map<AbilityKey, Boolean> getStaticAbilities() { return INSTANCE.getSupportedAbilities(); }
@Test void testGetStaticAbilities() { // TODO add the cluster client abilities. assertTrue(ClusterClientAbilities.getStaticAbilities().isEmpty()); }
public Command create( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext context) { return create(statement, context.getServiceContext(), context); }
@Test public void shouldValidateTerminateCluster() { // Given: configuredStatement = configuredStatement( TerminateCluster.TERMINATE_CLUSTER_STATEMENT_TEXT, terminateQuery ); // When: final Command command = commandFactory.create(configuredStatement, executionContext); // Then: assertThat(command, is(Command.of(configuredStatement))); }
public Set<GsonUser> getDirectGroupMembers(String gitlabUrl, String token, String groupId) { return getMembers(gitlabUrl, token, format(GITLAB_GROUPS_MEMBERS_ENDPOINT, groupId)); }
@Test public void getDirectGroupMembers_whenCallIsSuccessful_deserializesAndReturnsCorrectlyGroupMembers() throws IOException { ArgumentCaptor<Function<String, List<GsonUser>>> deserializerCaptor = ArgumentCaptor.forClass(Function.class); String token = "token-toto"; GitlabToken gitlabToken = new GitlabToken(token); List<GsonUser> expectedGroupMembers = expectedGroupMembers(); when(gitlabPaginatedHttpClient.get(eq(gitlabUrl), eq(gitlabToken), eq("/groups/42/members"), deserializerCaptor.capture())).thenReturn(expectedGroupMembers); Set<GsonUser> actualGroupMembers = underTest.getDirectGroupMembers(gitlabUrl, token, "42"); assertThat(actualGroupMembers).containsExactlyInAnyOrderElementsOf(expectedGroupMembers); String responseContent = getResponseContent("group-members-full-response.json"); List<GsonUser> deserializedUsers = deserializerCaptor.getValue().apply(responseContent); assertThat(deserializedUsers).usingRecursiveComparison().isEqualTo(expectedGroupMembers); }
private ExitStatus run() { try { init(); return new Processor().processNamespace().getExitStatus(); } catch (IllegalArgumentException e) { System.out.println(e + ". Exiting ..."); return ExitStatus.ILLEGAL_ARGUMENTS; } catch (IOException e) { System.out.println(e + ". Exiting ..."); LOG.error(e + ". Exiting ..."); return ExitStatus.IO_EXCEPTION; } finally { dispatcher.shutdownNow(); } }
@Test(timeout=100000) public void testBalancerMaxIterationTimeNotAffectMover() throws Exception { long blockSize = 10*1024*1024; final Configuration conf = new HdfsConfiguration(); initConf(conf); conf.setInt(DFSConfigKeys.DFS_MOVER_MOVERTHREADS_KEY, 1); conf.setInt( DFSConfigKeys.DFS_DATANODE_BALANCE_MAX_NUM_CONCURRENT_MOVES_KEY, 1); // set a fairly large block size to run into the limitation conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize); conf.setLong(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, blockSize); // set a somewhat grater than zero max iteration time to have the move time // to surely exceed it conf.setLong(DFSConfigKeys.DFS_BALANCER_MAX_ITERATION_TIME_KEY, 200L); conf.setInt(DFSConfigKeys.DFS_MOVER_RETRY_MAX_ATTEMPTS_KEY, 1); // set client socket timeout to have an IN_PROGRESS notification back from // the DataNode about the copy in every second. conf.setLong(DFSConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY, 1000L); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(2) .storageTypes( new StorageType[][] {{StorageType.DISK, StorageType.DISK}, {StorageType.ARCHIVE, StorageType.ARCHIVE}}) .build(); try { cluster.waitActive(); final DistributedFileSystem fs = cluster.getFileSystem(); final String file = "/testMaxIterationTime.dat"; final Path path = new Path(file); short rep_factor = 1; int seed = 0xFAFAFA; // write to DISK DFSTestUtil.createFile(fs, path, 4L * blockSize, rep_factor, seed); // move to ARCHIVE fs.setStoragePolicy(new Path(file), "COLD"); int rc = ToolRunner.run(conf, new Mover.Cli(), new String[] {"-p", file}); Assert.assertEquals("Retcode expected to be ExitStatus.SUCCESS (0).", ExitStatus.SUCCESS.getExitCode(), rc); } finally { cluster.shutdown(); } }
@ExecuteOn(TaskExecutors.IO) @Delete(uri = "{namespace}/files") @Operation(tags = {"Files"}, summary = "Delete a file or directory") public void delete( @Parameter(description = "The namespace id") @PathVariable String namespace, @Parameter(description = "The internal storage uri of the file / directory to delete") @QueryValue URI path ) throws IOException, URISyntaxException { ensureWritableNamespaceFile(path); String pathWithoutScheme = path.getPath(); List<String> allNamespaceFilesPaths = storageInterface.allByPrefix(tenantService.resolveTenant(), NamespaceFile.of(namespace).storagePath().toUri(), true) .stream() .map(uri -> NamespaceFile.of(namespace, uri).path(true).toString()) .collect(Collectors.toCollection(ArrayList::new)); if (allNamespaceFilesPaths.contains(pathWithoutScheme + "/")) { // the given path to delete is a directory pathWithoutScheme = pathWithoutScheme + "/"; } while (!pathWithoutScheme.equals("/")) { String parentFolder = pathWithoutScheme.substring(0, pathWithoutScheme.lastIndexOf('/') + 1); if (parentFolder.equals("/")) { break; } List<String> filesInParentFolder = allNamespaceFilesPaths.stream().filter(p -> p.length() > parentFolder.length() && p.startsWith(parentFolder)).toList(); // there is more than one file in this folder so we stop the cascade deletion there if (filesInParentFolder.size() > 1) { break; } allNamespaceFilesPaths.removeIf(filesInParentFolder::contains); pathWithoutScheme = parentFolder.endsWith("/") ? parentFolder.substring(0, parentFolder.length() - 1) : parentFolder; } storageInterface.delete(tenantService.resolveTenant(), NamespaceFile.of(namespace, Path.of(pathWithoutScheme)).uri()); }
@Test void delete() throws IOException { storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folder/file.txt")), new ByteArrayInputStream("Hello".getBytes())); client.toBlocking().exchange(HttpRequest.DELETE("/api/v1/namespaces/" + NAMESPACE + "/files?path=/folder/file.txt", null)); assertThat(storageInterface.exists(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folder/file.txt"))), is(false)); // Zombie folders are deleted, but not the root folder assertThat(storageInterface.exists(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folder"))), is(false)); assertThat(storageInterface.exists(null, toNamespacedStorageUri(NAMESPACE, null)), is(true)); storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folderWithMultipleFiles/file1.txt")), new ByteArrayInputStream("Hello".getBytes())); storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folderWithMultipleFiles/file2.txt")), new ByteArrayInputStream("Hello".getBytes())); client.toBlocking().exchange(HttpRequest.DELETE("/api/v1/namespaces/" + NAMESPACE + "/files?path=/folderWithMultipleFiles/file1.txt", null)); assertThat(storageInterface.exists(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folderWithMultipleFiles/file1.txt"))), is(false)); assertThat(storageInterface.exists(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folderWithMultipleFiles/file2.txt"))), is(true)); // Since there is still one file in the folder, it should not be deleted assertThat(storageInterface.exists(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folderWithMultipleFiles"))), is(true)); assertThat(storageInterface.exists(null, toNamespacedStorageUri(NAMESPACE, null)), is(true)); client.toBlocking().exchange(HttpRequest.DELETE("/api/v1/namespaces/" + NAMESPACE + "/files?path=/folderWithMultipleFiles", null)); assertThat(storageInterface.exists(null, toNamespacedStorageUri(NAMESPACE, URI.create("/folderWithMultipleFiles/"))), is(false)); assertThat(storageInterface.exists(null, toNamespacedStorageUri(NAMESPACE, null)), is(true)); }
@Override public String getName() { return this.name; }
@Test public void shouldReturnTheCorrectName() { assertThat(bulkhead.getName()).isEqualTo("test"); }
@Override public boolean offset(final Path file) { return false; }
@Test public void testOffsetSupport() { assertFalse(new SpectraReadFeature(session).offset(null)); }
@Udf public String concatWS( @UdfParameter(description = "Separator string and values to join") final String... inputs) { if (inputs == null || inputs.length < 2) { throw new KsqlFunctionException("Function Concat_WS expects at least two input arguments."); } final String separator = inputs[0]; if (separator == null) { return null; } return Arrays.stream(inputs, 1, inputs.length) .filter(Objects::nonNull) .collect(Collectors.joining(separator)); }
@Test public void shouldSkipAnyNullInputs() { assertThat(udf.concatWS("SEP", "foo", null, "bar"), is("fooSEPbar")); assertThat(udf.concatWS(ByteBuffer.wrap(new byte[] {1}), ByteBuffer.wrap(new byte[] {2}), null, ByteBuffer.wrap(new byte[] {3})), is(ByteBuffer.wrap(new byte[] {2, 1, 3}))); }
public boolean test(final IndexRange indexRange, final Set<Stream> validStreams) { // If index range is incomplete, check the prefix against the valid index sets. if (indexRange.streamIds() == null) { return validStreams.stream() .map(Stream::getIndexSet) .anyMatch(indexSet -> indexSet.isManagedIndex(indexRange.indexName())); } final Set<String> validStreamIds = validStreams.stream() .map(Stream::getId) .collect(Collectors.toSet()); // Otherwise check if the index range contains any of the valid stream ids. return !Collections.disjoint(indexRange.streamIds(), validStreamIds); }
@Test public void closedIndexRangeShouldNotMatchIfNotContainingAnyStreamId() { when(indexRange.streamIds()).thenReturn(Collections.emptyList()); when(stream1.getId()).thenReturn("stream1"); when(stream2.getId()).thenReturn("stream2"); assertThat(toTest.test(indexRange, Set.of(stream1, stream2))).isFalse(); verify(stream1.getIndexSet(), never()).isManagedIndex(any()); verify(stream2.getIndexSet(), never()).isManagedIndex(any()); verify(indexRange, never()).indexName(); }