focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static <T> AvroSchema<T> of(SchemaDefinition<T> schemaDefinition) { if (schemaDefinition.getSchemaReaderOpt().isPresent() && schemaDefinition.getSchemaWriterOpt().isPresent()) { return new AvroSchema<>(schemaDefinition.getSchemaReaderOpt().get(), schemaDefinition.getSchema...
@Test public void testAvroSchemaUserDefinedReadAndWriter() { SchemaReader<Foo> reader = new JacksonJsonReader<>(new ObjectMapper(), Foo.class); SchemaWriter<Foo> writer = new JacksonJsonWriter<>(new ObjectMapper()); SchemaDefinition<Foo> schemaDefinition = SchemaDefinition.<Foo>builder() ...
@Override public Stream<MappingField> resolveAndValidateFields( boolean isKey, List<MappingField> userFields, Map<String, String> options, InternalSerializationService serializationService ) { Map<QueryPath, MappingField> fieldsByPath = extractFields(userF...
@Test @Parameters({ "true, __key", "false, this" }) public void when_userDeclaresObjectDuplicateExternalName_then_throws(boolean key, String prefix) { Map<String, String> options = Map.of( (key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORMAT, ...
@Override public AppSettings load() { Properties p = loadPropertiesFile(homeDir); Set<String> keysOverridableFromEnv = stream(ProcessProperties.Property.values()).map(ProcessProperties.Property::getKey) .collect(Collectors.toSet()); keysOverridableFromEnv.addAll(p.stringPropertyNames()); // 1st...
@Test public void file_is_not_loaded_if_it_does_not_exist() throws Exception { File homeDir = temp.newFolder(); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serviceLoaderWrapper); AppSettings settings = underTest.load(); // no failure, file is ignored ...
void addFields( String prefix, Set<String> fieldNames, XmlObject field ) { //Salesforce SOAP Api sends IDs always in the response, even if we don't request it in SOQL query and //the id's value is null in this case. So, do not add this Id to the fields list if ( isNullIdField( field ) ) { return; ...
@Test public void testAddFields_nullIdNotAdded() throws Exception { final Set<String> fields = new LinkedHashSet<>(); XmlObject testObject = createObject( "Id", null, ObjectType.XMLOBJECT ); dialog.addFields( "", fields, testObject ); assertArrayEquals( "Null Id field not added", new String[]{}, field...
@Override public void emit(NetworkId networkId, OutboundPacket packet) { devirtualize(networkId, packet) .forEach(outboundPacket -> packetService.emit(outboundPacket)); }
@Test public void devirtualizePacket() { TrafficTreatment tr = DefaultTrafficTreatment.builder() .setOutput(VPORT_NUM1).build(); ByteBuffer data = ByteBuffer.wrap("abc".getBytes()); OutboundPacket vOutPacket = new DefaultOutboundPacket(VDID, tr, data); virtualProvid...
@Override public R apply(R record) { final Object value = operatingValue(record); final Schema schema = operatingSchema(record); if (value == null && schema == null) { return record; } requireSchema(schema, "updating schema metadata"); final boolean isArra...
@Test public void valueSchemaRequired() { final SinkRecord record = new SinkRecord("", 0, null, null, null, 42, 0); assertThrows(DataException.class, () -> xform.apply(record)); }
public static String wrapWithMarkdownClassDiv(String html) { return new StringBuilder() .append("<div class=\"markdown-body\">\n") .append(html) .append("\n</div>") .toString(); }
@Test void testStrongEmphasis() { InterpreterResult result = md.interpret("This is **strong emphasis** text", null); assertEquals( wrapWithMarkdownClassDiv("<p>This is <strong>strong emphasis</strong> text</p>\n"), result.message().get(0).getData()); }
@Override public MetadataNode child(String name) { try { Integer brokerId = Integer.valueOf(name); BrokerRegistration registration = image.brokers().get(brokerId); if (registration == null) return null; return new MetadataLeafNode(registration.toString()); ...
@Test public void testNode1Child() { MetadataNode child = NODE.child("1"); assertNotNull(child); assertEquals("BrokerRegistration(id=1, epoch=1001, " + "incarnationId=MJkaH0j0RwuC3W2GHQHtWA, " + "listeners=[], " + "supportedFeatures={metadata.version: 1-4}...
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void shadersMod() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/shaders_mod.txt")), CrashReportAnalyzer.Rule.SHADERS_MOD); }
public ServiceInfo getService(String key) { ServiceInfo serviceInfo = serviceMap.get(key); if (serviceInfo == null) { serviceInfo = new ServiceInfo(); serviceInfo.setName(key); } return serviceInfo; }
@Test void testRefreshFromEnabledToDisabled() throws InterruptedException, NoSuchFieldException, IllegalAccessException { // make sure the first no delay refresh thread finished. TimeUnit.MILLISECONDS.sleep(500); FailoverSwitch mockFailoverSwitch = new FailoverSwitch(false); when(fai...
public MessageDescription shallowParseMessage(ByteBuf packet) { final ByteBuf buffer = packet.readSlice(MessageHeader.LENGTH); LOG.debug("Shallow parse header\n{}", ByteBufUtil.prettyHexDump(buffer)); final MessageHeader header = parseMessageHeader(buffer); final MessageDescription messa...
@Test public void shallowParsePacketMultilist() throws IOException { ByteBuf packet = Utils.readPacket("ixia-multilist.ipfix"); InformationElementDefinitions definitions = new InformationElementDefinitions( Resources.getResource("ipfix-iana-elements.json"), Resources....
@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 = s...
@Test public void shouldThrowWhenNotAuthorizedToReadKeySchemaFromSR() throws Exception { // Given givenDataSourceWithSchema( TOPIC_NAME, SCHEMA, SerdeFeatures.of(SerdeFeature.UNWRAP_SINGLES), SerdeFeatures.of(), FormatInfo.of(FormatFactory.AVRO.name()), FormatIn...
public Future<CaReconciliationResult> reconcile(Clock clock) { return reconcileCas(clock) .compose(i -> verifyClusterCaFullyTrustedAndUsed()) .compose(i -> reconcileClusterOperatorSecret(clock)) .compose(i -> rollingUpdateForNewCaKey()) .compose...
@Test public void testClientsCASecretsWithoutOwnerReference(Vertx vertx, VertxTestContext context) { CertificateAuthority caConfig = new CertificateAuthority(); caConfig.setGenerateSecretOwnerReference(false); Kafka kafka = new KafkaBuilder(KAFKA) .editSpec() ...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) @Override public ClusterInfo get() { return getClusterInfo(); }
@Test public void testClusterDefault() throws JSONException, Exception { WebResource r = resource(); // test with trailing "/" to make sure acts same as without slash ClientResponse response = r.path("ws").path("v1").path("cluster") .get(ClientResponse.class); assertEquals(MediaType.APPLICATI...
@Override public Stream<HoodieBaseFile> getLatestBaseFilesInRange(List<String> commitsToReturn) { return execute(commitsToReturn, preferredView::getLatestBaseFilesInRange, (commits) -> getSecondaryView().getLatestBaseFilesInRange(commits)); }
@Test public void testGetLatestBaseFilesInRange() { Stream<HoodieBaseFile> actual; Stream<HoodieBaseFile> expected = testBaseFileStream; List<String> commitsToReturn = Collections.singletonList("/table2"); when(primary.getLatestBaseFilesInRange(commitsToReturn)).thenReturn(testBaseFileStream); ac...
public Annotator getAnnotator(AnnotationStyle style) { switch (style) { case JACKSON: case JACKSON2: return new Jackson2Annotator(generationConfig); case JSONB1: return new Jsonb1Annotator(generationConfig); case JSONB2: ...
@Test public void canCreateCorrectAnnotatorFromAnnotationStyle() { assertThat(factory.getAnnotator(JACKSON), is(instanceOf(Jackson2Annotator.class))); assertThat(factory.getAnnotator(JACKSON2), is(instanceOf(Jackson2Annotator.class))); assertThat(factory.getAnnotator(GSON), is(instanceOf(Gs...
@Override public ChannelFuture writeData(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endStream, ChannelPromise promise) { final SimpleChannelPromiseAggregator promiseAggregator = new SimpleChannelPromiseAggregator(promise, ctx.channel(), ctx.execut...
@Test public void writeEmptyDataWithPadding() { int streamId = 1; ByteBuf payloadByteBuf = Unpooled.buffer(); frameWriter.writeData(ctx, streamId, payloadByteBuf, 2, true, promise); assertEquals(0, payloadByteBuf.refCnt()); byte[] expectedFrameBytes = { (byte) ...
@SneakyThrows @Override public Integer call() throws Exception { super.call(); PicocliRunner.call(App.class, "namespace", "--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...
public void containsCell( @Nullable Object rowKey, @Nullable Object colKey, @Nullable Object value) { containsCell( Tables.<@Nullable Object, @Nullable Object, @Nullable Object>immutableCell( rowKey, colKey, value)); }
@Test public void containsCell() { ImmutableTable<String, String, String> table = ImmutableTable.of("row", "col", "val"); assertThat(table).containsCell("row", "col", "val"); assertThat(table).containsCell(cell("row", "col", "val")); }
static void parseServerIpAndPort(MysqlConnection connection, Span span) { try { URI url = URI.create(connection.getURL().substring(5)); // strip "jdbc:" String remoteServiceName = connection.getProperties().getProperty("zipkinServiceName"); if (remoteServiceName == null || "".equals(remoteServiceN...
@Test void parseServerIpAndPort_emptyZipkinServiceNameIgnored() throws SQLException { setupAndReturnPropertiesForHost("1.2.3.4").setProperty("zipkinServiceName", ""); TracingStatementInterceptor.parseServerIpAndPort(connection, span); verify(span).remoteServiceName("mysql"); verify(span).remoteIpAndPo...
@SuppressWarnings("unchecked") void sort(String[] filenames) { Arrays.sort(filenames, new Comparator<String>() { @Override public int compare(String f1, String f2) { int result = 0; for (FilenameParser p : parsers) { Comparable c2 = p.parseFilename(f2); Comparable ...
@Test public void sortsDescendingByDateAndIntegerWithMultipleDatesInPattern() { final String[] FILENAMES = new String[] { "/var/logs/my-app/2018-10/2018-10-31/9.log", "/var/logs/my-app/2019-01/2019-01-01/1.log", "/var/logs/my-app/1999-03/1999-03-17/3.log", "/var/logs/my-app/2019-01/2019-0...
public EndpointResponse streamQuery( final KsqlSecurityContext securityContext, final KsqlRequest request, final CompletableFuture<Void> connectionClosedFuture, final Optional<Boolean> isInternalRequest, final MetricsCallbackHolder metricsCallbackHolder, final Context context ) { ...
@Test public void shouldNotCreateExternalClientsForPullQuery() { // Given: when(mockKsqlEngine.getKsqlConfig()).thenReturn(new KsqlConfig(ImmutableMap.of( StreamsConfig.APPLICATION_SERVER_CONFIG, "something:1" ))); // When: testResource.streamQuery( securityContext, new Ks...
@Override public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return leftJoin(otherStream, toValueJoinerWi...
@Test public void shouldNotAllowNullValueJoinerOnTableLeftJoinWithJoined() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.leftJoin(testTable, (ValueJoiner<? super String, ? super String, ?>) null, Joined.as("name"))); asser...
@Udf public <T extends Comparable<? super T>> T arrayMax(@UdfParameter( description = "Array of values from which to find the maximum") final List<T> input) { if (input == null) { return null; } T candidate = null; for (T thisVal : input) { if (thisVal != null) { if (candida...
@Test public void shouldFindBigIntMax() { final List<Long> input = Arrays.asList(1L, 3L, -2L); assertThat(udf.arrayMax(input), is(Long.valueOf(3))); }
@Nullable @Override public BlobHttpContent getContent() { return null; }
@Test public void testGetContent() { Assert.assertNull(testAuthenticationMethodRetriever.getContent()); }
public static <K, V> String toMap(final Supplier<MultiValueMap<K, V>> supplier) { return GsonUtils.getInstance().toJson(supplier.get().toSingleValueMap()); }
@Test public void testToMap() { final MultiValueMap<String, String> args = new LinkedMultiValueMap<>(); args.add("a", "1"); args.add("a", "2"); args.add("b", "3"); String actual = HttpParamConverter.toMap(() -> args); assertEquals("{\"a\":\"1\",\"b\":\"3\"}", actual);...
public static EnvVar createEnvVarFromSecret(String name, String secret, String key) { return new EnvVarBuilder() .withName(name) .withNewValueFrom() .withNewSecretKeyRef() .withName(secret) .withKey(key) ...
@Test public void testCreateEnvVarFromSecret() { EnvVar var = ContainerUtils.createEnvVarFromSecret("VAR_1", "my-secret", "my-key"); assertThat(var.getName(), is("VAR_1")); assertThat(var.getValueFrom().getSecretKeyRef().getName(), is("my-secret")); assertThat(var.getValueFrom().g...
@Override public void set(long newValue) { COUNTER.set(this, newValue); }
@Test public void set() { counter.set(100_000); assertEquals(100_000, counter.get()); }
public static String formatExpression(final Expression expression) { return formatExpression(expression, FormatOptions.of(s -> false)); }
@Test public void shouldFormatInPredicate() { final InPredicate predicate = new InPredicate( new StringLiteral("foo"), new InListExpression(ImmutableList.of(new StringLiteral("a")))); assertThat(ExpressionFormatter.formatExpression(predicate), equalTo("('foo' IN ('a'))")); }
public PropertyPanel id(String id) { this.id = id; return this; }
@Test public void setId() { basic(); pp.id(SOME_IDENTIFICATION); assertEquals("wrong id", SOME_IDENTIFICATION, pp.id()); }
@Override @Transactional public void sendMessage(String message, String channel) { logger.info("Sending message {} to channel {}", message, channel); if (!Objects.equals(channel, Topics.APOLLO_RELEASE_TOPIC)) { logger.warn("Channel {} not supported by DatabaseMessageSender!", channel); return; ...
@Test public void testSendUnsupportedMessage() throws Exception { String someMessage = "some-message"; String someUnsupportedTopic = "some-invalid-topic"; messageSender.sendMessage(someMessage, someUnsupportedTopic); verify(releaseMessageRepository, never()).save(any(ReleaseMessage.class)); }
@Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { // 入栈 DataPermission dataPermission = this.findAnnotation(methodInvocation); if (dataPermission != null) { DataPermissionContextHolder.add(dataPermission); } try { // ...
@Test // 在 Method 上有 @DataPermission 注解 public void testInvoke_method() throws Throwable { // 参数 mockMethodInvocation(TestMethod.class); // 调用 Object result = interceptor.invoke(methodInvocation); // 断言 assertEquals("method", result); assertEquals(1, intercep...
public List<ModelNode> topologicalSort() { DependencyMap dependencyMap = new DependencyMap(modelNodes); Queue<ModelNode> unprocessed = new LinkedList<>(); unprocessed.addAll(roots); List<ModelNode> sortedList = new ArrayList<>(); while (!unprocessed.isEmpty()) { Model...
@Test void require_that_collections_can_be_empty() { ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BC()).addBuilder(new GraphMock.BA()).build(); List<ModelNode> nodes = graph.topologicalSort(); MockRoot root = new MockRoot(); GraphMock.A a = (GraphMock.A) nodes....
public abstract int getTabId();
@Test public void checkIdDuplication() { final Set<Integer> usedIds = new HashSet<>(); for (final Tab.Type type : Tab.Type.values()) { final boolean added = usedIds.add(type.getTabId()); assertTrue("Id was already used: " + type.getTabId(), added); } }
@Override public List<Object> handle(String targetName, List<Object> instances, RequestData requestData) { if (requestData == null) { return super.handle(targetName, instances, null); } if (!shouldHandle(instances)) { return instances; } List<Object> r...
@Test public void testGetMismatchInstances() { RuleInitializationUtils.initFlowMatchRule(); List<Object> instances = new ArrayList<>(); ServiceInstance instance1 = TestDefaultServiceInstance.getTestDefaultServiceInstance("1.0.0"); instances.add(instance1); ServiceInstance ins...
public static Builder custom() { return new Builder(); }
@Test(expected = IllegalArgumentException.class) public void testBuildWithIllegalMaxWaitDuration() { BulkheadConfig.custom() .maxWaitDuration(Duration.ofSeconds(-1)) .build(); }
public void recordFlush(long duration) { flushTimeSensor.record(duration); }
@Test public void shouldRecordFlushTime() { // When: producerMetrics.recordFlush(METRIC_VALUE); // Then: assertMetricValue(FLUSH_TIME_TOTAL); }
@Override public boolean equals(Object obj) { if (!(obj instanceof NormalKey)) { return false; } NormalKey rhs = (NormalKey) obj; if (algorithm != rhs.algorithm) { return false; } if (plainKey != null) { return Arrays.equals(plainKe...
@Test public void testEquals() { NormalKey key1 = NormalKey.createRandom(); NormalKey key2 = NormalKey.createRandom(); assertNotEquals(key1, new String()); assertNotEquals(key1, key2); NormalKey keyNoAlgo = new NormalKey(EncryptionAlgorithmPB.NO_ENCRYPTION, new byte[16], null...
public static String toUpperCase(@Nullable String value) { if (value == null) { throw new IllegalArgumentException("String value cannot be null"); } return value.toUpperCase(Locale.ENGLISH); }
@Test public void testToUpperCase() { //noinspection DataFlowIssue assertThatThrownBy(() -> toUpperCase(null)).isInstanceOf(IllegalArgumentException.class); assertThat(toUpperCase("")).isEqualTo(""); assertThat(toUpperCase(" ")).isEqualTo(" "); assertThat(toUpperCase("Hello")...
public String compress(String compressorName, String uncompressedString) throws IOException { Checks.notNull(uncompressedString, "uncompressedString cannot be null"); Compressor compressor = getCompressor(compressorName == null ? DEFAULT_COMPRESSOR_NAME : compressorName); return base64Encode(compres...
@Test public void testCompress() throws IOException { assertEquals("H4sIAAAAAAAA/0tMBAMAdCCLWwcAAAA=", stringCodec.compress("gzip", "aaaaaaa")); assertEquals("H4sIAAAAAAAA/0tMBAMAdCCLWwcAAAA=", stringCodec.compress(null, "aaaaaaa")); }
@Override public PageResult<NotifyMessageDO> getMyMyNotifyMessagePage(NotifyMessageMyPageReqVO pageReqVO, Long userId, Integer userType) { return notifyMessageMapper.selectPage(pageReqVO, userId, userType); }
@Test public void testGetMyNotifyMessagePage() { // mock 数据 NotifyMessageDO dbNotifyMessage = randomPojo(NotifyMessageDO.class, o -> { // 等会查询到 o.setUserId(1L); o.setUserType(UserTypeEnum.ADMIN.getValue()); o.setReadStatus(true); o.setCreateTime(buildT...
public String getEncryptedPassword() { return encryptedPassword; }
@Test public void shouldEncryptMailHostPassword() throws CryptoException { GoCipher mockGoCipher = mock(GoCipher.class); when(mockGoCipher.encrypt("password")).thenReturn("encrypted"); MailHost mailHost = new MailHost("hostname", 42, "username", "password", null, true, true, "from", "mail@a...
@VisibleForTesting static String toString(@Nullable TaskManagerLocation location) { // '(unassigned)' being the default value is added to support backward-compatibility for the // deprecated fields return location != null ? location.getEndpoint() : "(unassigned)"; }
@Test void testArchivedTaskManagerLocationHandling() { final TaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation(); assertThat(JobExceptionsHandler.toString(taskManagerLocation)) .isEqualTo( String.format( "%s...
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testJadChallengeNoPb() { ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your completion count for TzHaar-Ket-Rak's First Challenge is: <col=ff0000>3</col>.", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Chall...
public static void reset(File directory, int processNumber) { try (DefaultProcessCommands processCommands = new DefaultProcessCommands(directory, processNumber, true)) { // nothing else to do than open file and reset the space of specified process } }
@Test public void reset_fails_if_processNumber_is_higher_than_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES + 1; expectProcessNumberNoValidIAE(() -> DefaultProcessCommands.reset(temp.newFolder(), processNumber), processNumber); }
@Override public <R> HoodieData<HoodieRecord<R>> tagLocation( HoodieData<HoodieRecord<R>> records, HoodieEngineContext context, HoodieTable hoodieTable) { return HoodieJavaRDD.of(HoodieJavaRDD.getJavaRDD(records) .mapPartitionsWithIndex(locationTagFunction(hoodieTable.getMetaClient()), true));...
@Test public void testSimpleTagLocationAndUpdateWithRollback() throws Exception { // Load to memory HoodieWriteConfig config = getConfigBuilder(100, false, false) .withRollbackUsingMarkers(false).build(); SparkHoodieHBaseIndex index = new SparkHoodieHBaseIndex(config); try (SparkRDDWriteClient...
public void setAckSetByIndex(){ if (batchSize == 1){ return; } BitSetRecyclable bitSetRecyclable = BitSetRecyclable.create(); bitSetRecyclable.set(0, batchSize, true); bitSetRecyclable.clear(batchIndex); long[] ackSet = bitSetRecyclable.toLongArray(); ...
@Test(dataProvider = "batchSizeAndBatchIndexArgsArray") public void testSetAckSetByIndex(int batchSize, int batchIndex){ // test 1/64 TxnBatchedPositionImpl txnBatchedPosition = new TxnBatchedPositionImpl(1,1, batchSize, batchIndex); txnBatchedPosition.setAckSetByIndex(); long[] ls =...
public static <T> Task<T> fromListenableFuture(ListenableFuture<T> future) { /** * BaseTask's promise will be listening to this * also see {@link BaseTask#contextRun(Context, Task, Collection)} */ final SettablePromise<T> promise = Promises.settable(); // Setup cancellation propagation from...
@Test public void testFromListenableFuture() throws Exception { ListenableFutureUtil.SettableFuture<String> listenableFuture = new ListenableFutureUtil.SettableFuture<>(); Task<String> task = ListenableFutureUtil.fromListenableFuture(listenableFuture); // Test cancel propagation from Task to ListenableFu...
public static String resolveIpAddress(String hostname) throws UnknownHostException { Preconditions.checkNotNull(hostname, "hostname"); Preconditions.checkArgument(!hostname.isEmpty(), "Cannot resolve IP address for empty hostname"); return InetAddress.getByName(hostname).getHostAddress(); }
@Test(expected = IllegalArgumentException.class) public void resolveEmptyIpAddress() throws UnknownHostException { NetworkAddressUtils.resolveIpAddress(""); }
public static double conversion(String expression) { return (new Calculator()).calculate(expression); }
@Test public void conversationTest5(){ // https://github.com/dromara/hutool/issues/1984 final double conversion = Calculator.conversion("((1/1) / (1/1) -1) * 100"); assertEquals(0, conversion, 0); }
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) { if (list == null) { return FEELFnResult.ofResult(true); } boolean result = true; for (final Object element : list) { if (element != null && !(element instanceof Boolean)) { ret...
@Test void invokeArrayParamEmptyArray() { FunctionTestUtil.assertResult(nnAllFunction.invoke(new Object[]{}), true); }
public Set<String> userSelfEditPermissions(String username) { ImmutableSet.Builder<String> perms = ImmutableSet.builder(); perms.add(perInstance(RestPermissions.USERS_EDIT, username)); perms.add(perInstance(RestPermissions.USERS_PASSWORDCHANGE, username)); perms.add(perInstance(RestPermi...
@Test public void testUserSelfEditPermissions() throws Exception { assertThat(permissions.userSelfEditPermissions("john")) .containsExactly("users:edit:john", "users:passwordchange:john", "users:tokenlist:john", "users:tokencreate:john", "users:tokenremove:john"); ...
public static int scan(final UnsafeBuffer termBuffer, final int termOffset, final int limitOffset) { int offset = termOffset; while (offset < limitOffset) { final int frameLength = frameLengthVolatile(termBuffer, offset); if (frameLength <= 0) { ...
@Test void shouldFailToReadFirstMessageBecauseOfLimit() { final int offset = 0; final int messageLength = 50; final int alignedMessageLength = BitUtil.align(messageLength, FRAME_ALIGNMENT); final int limit = alignedMessageLength - 1; when(termBuffer.getIntVolatile(length...
static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) { List<String> basePath = getPathComponents(canonicalBaseFile); List<String> pathToRelativize = getPathComponents(canonicalFileToRelativize); //if the roots aren't the same (i.e. different drives on a ...
@Test public void pathUtilTest16() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some2" + File.separatorChar + "dir3"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); String path = PathUtil.getRe...
private String getEnv(String envName, InterpreterLaunchContext context) { String env = context.getProperties().getProperty(envName); if (StringUtils.isBlank(env)) { env = System.getenv(envName); } if (StringUtils.isBlank(env)) { LOGGER.warn("environment variable: {} is empty", envName); ...
@Test void testYarnClientMode_1() throws IOException { SparkInterpreterLauncher launcher = new SparkInterpreterLauncher(zConf, null); Properties properties = new Properties(); properties.setProperty("SPARK_HOME", sparkHome); properties.setProperty("property_1", "value_1"); properties.setProperty("...
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLCom...
@Test void assertNewInstanceWithComInitDbPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_INIT_DB, payload, connectionSession), instanceOf(MySQLComInitDbPacket.class)); }
@Override public Map<Errors, Integer> errorCounts() { Map<Errors, Integer> errorCounts = new HashMap<>(); updateErrorCounts(errorCounts, Errors.forCode(data.errorCode())); for (UpdatableFeatureResult result : data.results()) { updateErrorCounts(errorCounts, Errors.forCode(result....
@Test public void testErrorCounts() { UpdateFeaturesResponseData.UpdatableFeatureResultCollection results = new UpdateFeaturesResponseData.UpdatableFeatureResultCollection(); results.add(new UpdateFeaturesResponseData.UpdatableFeatureResult() .setFeature("foo") ....
public Cluster cluster() { if (clusterInstance == null) { throw new IllegalStateException("Cached Cluster instance should not be null, but was."); } else { return clusterInstance; } }
@Test public void testMissingLeaderEndpoint() { // Although the broker attempts to ensure leader information is available, the // client metadata cache may retain partition metadata across multiple responses. // For example, separate responses may contain conflicting leader epochs for ...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final List<Path> deleted = new ArrayList<Path>(); for(Path file : files.keySet()) { boolean skip = false; for(Path d : dele...
@Test public void testDeleteDirectory() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( this.getClass().getResourceAsStream("/iRODS (iPlant...
public static <T> ExtensionLoader<T> getExtensionLoader(final Class<T> clazz, final ClassLoader cl) { Objects.requireNonNull(clazz, "extension clazz is null"); if (!clazz.isInterface()) { throw new IllegalArgumentException("extension clazz (" + clazz + ") is not interface!"...
@Test public void testGetExtensionLoaderIsNull() { try { ExtensionLoader.getExtensionLoader(null); fail(); } catch (NullPointerException expected) { assertThat(expected.getMessage(), containsString("extension clazz is null")); } }
public static void readFully(InputStream stream, byte[] bytes, int offset, int length) throws IOException { int bytesRead = readRemaining(stream, bytes, offset, length); if (bytesRead < length) { throw new EOFException( "Reached the end of stream with " + (length - bytesRead) + " bytes lef...
@Test public void testReadFullyStartAndLength() throws IOException { byte[] buffer = new byte[10]; MockInputStream stream = new MockInputStream(); IOUtil.readFully(stream, buffer, 2, 5); assertThat(Arrays.copyOfRange(buffer, 2, 7)) .as("Byte array contents should match") .isEqualTo(A...
@Override public void handleDataDeleted(String dataPath) { refresh(); }
@Test public void testHandleDataDeleted() { _dynamicBrokerSelectorUnderTest.handleDataDeleted("dataPath"); verify(_mockExternalViewReader, times(2)).getTableToBrokersMap(); }
static InjectorFunction injectorFunction(InjectorFunction existing, InjectorFunction... update) { if (update == null) throw new NullPointerException("injectorFunctions == null"); LinkedHashSet<InjectorFunction> injectorFunctionSet = new LinkedHashSet<InjectorFunction>(Arrays.asList(update)); if (inj...
@Test void injectorFunction_emptyIgnored() { InjectorFunction existing = mock(InjectorFunction.class); assertThat(injectorFunction(existing)) .isSameAs(existing); }
@Override public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable { // 1. 执行请求 // 参考链接 https://api.aliyun.com/document/Dysmsapi/2017-05-25/QuerySmsTemplate TreeMap<String, Object> queryParam = new TreeMap<>(); queryParam.put("TemplateCode", apiTemplateId); ...
@Test public void testGetSmsTemplate() throws Throwable { try (MockedStatic<HttpUtils> httpUtilsMockedStatic = mockStatic(HttpUtils.class)) { // 准备参数 String apiTemplateId = randomString(); // mock 方法 httpUtilsMockedStatic.when(() -> HttpUtils.post(anyString(),...
@Override public List<String> getRegisterData(final String key) { try { List<Instance> instances = namingService.selectInstances(key, groupName, true); List<String> registerData = new ArrayList<>(); for (Instance instance : instances) { String data = build...
@Test void testGetRegisterData() throws NacosException { final String key = "test"; Instance instance1 = new Instance(); instance1.setIp("192.168.1.1"); instance1.setPort(8080); Instance instance2 = new Instance(); instance2.setIp("192.168.1.2"); instance2.se...
@Override public Object merge(T mergingValue, T existingValue) { if (mergingValue == null) { return existingValue.getRawValue(); } return mergingValue.getRawValue(); }
@Test @SuppressWarnings("ConstantConditions") public void merge_mergingNull() { MapMergeTypes existing = mergingValueWithGivenValue(EXISTING); MapMergeTypes merging = null; assertEquals(EXISTING, mergePolicy.merge(merging, existing)); }
public static int readUint16(ByteBuffer buf) throws BufferUnderflowException { return Short.toUnsignedInt(buf.order(ByteOrder.LITTLE_ENDIAN).getShort()); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void testReadUint16ThrowsException3() { ByteUtils.readUint16(new byte[]{1, 2, 3}, -1); }
public static int[] rowMax(int[][] matrix) { int[] x = new int[matrix.length]; for (int i = 0; i < x.length; i++) { x[i] = max(matrix[i]); } return x; }
@Test public void testRowMax() { System.out.println("rowMax"); double[][] A = { {0.7220180, 0.07121225, 0.6881997}, {-0.2648886, -0.89044952, 0.3700456}, {-0.6391588, 0.44947578, 0.6240573} }; double[] r = {0.7220180, 0.3700456, 0.6240573}; ...
@SuppressWarnings("checkstyle:npathcomplexity") public PartitionServiceState getPartitionServiceState() { PartitionServiceState state = getPartitionTableState(); if (state != SAFE) { return state; } if (!checkAndTriggerReplicaSync()) { return REPLICA_NOT_SYN...
@Test public void shouldBeSafe_whenInitializedOnMaster() { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(); HazelcastInstance hz = factory.newHazelcastInstance(); InternalPartitionServiceImpl partitionService = getNode(hz).partitionService; partitionService.fi...
public Table getTable(String dbName, String tableName) { try (Timer ignored = Tracers.watchScope(EXTERNAL, "HMS.getTable")) { return callRPC("getTable", String.format("Failed to get table [%s.%s]", dbName, tableName), dbName, tableName); } }
@Test public void testClientPool(@Mocked HiveMetaStoreClient metaStoreClient) throws Exception { new Expectations() { { metaStoreClient.getTable(anyString, anyString); result = new Table(); minTimes = 0; } }; final int[...
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) { final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps()); map.put( MetricCollectors.RESOURCE_LABEL_PREFIX + StreamsConfig.APPLICATION_ID_CONFIG, applicationId ); // Streams cli...
@Test public void shouldSetLogAndContinueExceptionHandlerWhenFailOnProductionErrorFalse() { final KsqlConfig ksqlConfig = new KsqlConfig(Collections.singletonMap(KsqlConfig.FAIL_ON_PRODUCTION_ERROR_CONFIG, false)); final Object result = ksqlConfig.getKsqlStreamConfigProps() .get(StreamsConfig....
@Override public int size() { return eventHandler.size(); }
@Test public void testSize() throws Exception { try (KafkaEventQueue queue = new KafkaEventQueue(Time.SYSTEM, logContext, "testEmpty")) { assertTrue(queue.isEmpty()); CompletableFuture<Void> future = new CompletableFuture<>(); queue.append(() -> future.get()); ...
public Map<Boolean, List<IssueDto>> mapIssuesByTaintStatus(List<IssueDto> issues) { Map<Boolean, List<IssueDto>> issuesMap = new HashMap<>(); issuesMap.put(true, getTaintIssuesOnly(issues)); issuesMap.put(false, getStandardIssuesOnly(issues)); return issuesMap; }
@Test public void test_mapIssuesByTaintStatus() { Map<Boolean, List<IssueDto>> issuesByTaintStatus = underTest.mapIssuesByTaintStatus(getIssues()); assertThat(issuesByTaintStatus.keySet()).hasSize(2); assertThat(issuesByTaintStatus.get(true)).hasSize(6); assertThat(issuesByTaintStatus.get(false)).has...
public static List<InetSocketAddress> getJobMasterRpcAddresses(AlluxioConfiguration conf) { // First check whether job rpc addresses are explicitly configured. if (conf.isSet(PropertyKey.JOB_MASTER_RPC_ADDRESSES)) { return parseInetSocketAddresses( conf.getList(PropertyKey.JOB_MASTER_RPC_ADDRESS...
@Test public void getJobMasterRpcAddressesDefault() { AlluxioConfiguration conf = createConf(Collections.emptyMap()); String host = NetworkAddressUtils.getLocalHostName(5 * Constants.SECOND_MS); assertEquals(Arrays.asList(InetSocketAddress.createUnresolved(host, 20001)), ConfigurationUtils.getJobM...
@Udf(description = "Returns the inverse (arc) tangent of y / x") public Double atan2( @UdfParameter( value = "y", description = "The ordinate (y) coordinate." ) final Integer y, @UdfParameter( value = "x", descriptio...
@Test public void shouldHandleNegativeYNegativeX() { assertThat(udf.atan2(-1.1, -0.24), closeTo(-1.7856117271965553, 0.000000000000001)); assertThat(udf.atan2(-6.0, -7.1), closeTo(-2.4399674339361113, 0.000000000000001)); assertThat(udf.atan2(-2, -3), closeTo(-2.5535900500422257, 0.000000000000001)); ...
@Override public SchemaTransform from(PubsubReadSchemaTransformConfiguration configuration) { if (configuration.getSubscription() == null && configuration.getTopic() == null) { throw new IllegalArgumentException( "To read from Pubsub, a subscription name or a topic name must be provided"); } ...
@Test public void testNoSchema() { PCollectionRowTuple begin = PCollectionRowTuple.empty(p); assertThrows( IllegalStateException.class, () -> begin.apply( new PubsubReadSchemaTransformProvider() .from( PubsubReadSchemaTran...
@Override public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { String datetime; if (format.isEmpty()) {// Default to milliseconds datetime = Long.toString(System.currentTimeMillis()); } else { // Resolve any alia...
@Test void testDefaultNone() throws Exception { long before = System.currentTimeMillis(); value = variable.execute(result, null); long now = Long.parseLong(value); long after = System.currentTimeMillis(); assertBetween(before, after, now); }
public void writeUnsignedLongAsHex(long value) throws IOException { int bufferIndex = 23; do { int digit = (int)(value & 15); if (digit < 10) { buffer[bufferIndex--] = (char)(digit + '0'); } else { buffer[bufferIndex--] = (char)((digit ...
@Test public void testWriteUnsignedLongAsHex() throws IOException { Assert.assertEquals("ffffffffffffffff", performWriteUnsignedLongAsHex(-1)); Assert.assertEquals("7fffffff", performWriteUnsignedLongAsHex(Integer.MAX_VALUE)); Assert.assertEquals("ffffffff80000000", performWriteUnsignedLongA...
public static VerificationMode never() { return times(0); }
@Test public void should_monitor_server_behavior_without_port() throws Exception { final MocoMonitor monitor = mock(MocoMonitor.class); final HttpServer server = httpServer(monitor); server.get(by(uri("/foo"))).response("bar"); running(server, () -> assertThat(helper.get(remoteUrl(s...
@Override public SubscriptionGroupConfig getSubscriptionGroupConfig(ProxyContext ctx, String group) { SubscriptionGroupConfig config; try { config = this.subscriptionGroupConfigCache.get(group); } catch (Exception e) { return null; } if (config == EMPT...
@Test public void testGetSubscriptionGroupConfig() { ProxyContext ctx = ProxyContext.create(); assertNotNull(this.clusterMetadataService.getSubscriptionGroupConfig(ctx, GROUP)); assertEquals(1, this.clusterMetadataService.subscriptionGroupConfigCache.asMap().size()); }
public boolean releaseInbound() { return releaseAll(inboundMessages); }
@Test public void testReleaseInbound() { ByteBuf in = Unpooled.buffer(); ByteBuf out = Unpooled.buffer(); try { EmbeddedChannel channel = new EmbeddedChannel(); assertTrue(channel.writeInbound(in)); assertEquals(1, in.refCnt()); assertTrue(cha...
public static Iterable<ServiceBusMessage> createServiceBusMessages( final Iterable<?> data, final Map<String, Object> applicationProperties, final String correlationId) { return StreamSupport.stream(data.spliterator(), false) .map(obj -> createServiceBusMessage(obj, applicationProper...
@Test void testCreateServiceBusMessages() { final List<String> inputMessages = new LinkedList<>(); inputMessages.add("test data"); inputMessages.add(String.valueOf(12345)); final Iterable<ServiceBusMessage> busMessages = ServiceBusUtils.createServiceBusMessages(inputMessages, null, ...
@Override public ConfigData get(String path) { return get(path, Files::isRegularFile); }
@Test public void testEmptyPath() { ConfigData configData = provider.get(""); assertTrue(configData.data().isEmpty()); assertNull(configData.ttl()); }
public MaterialAgent createAgent(MaterialRevision revision) { Material material = revision.getMaterial(); if (material instanceof DependencyMaterial) { return MaterialAgent.NO_OP; } else if (material instanceof PackageMaterial) { return MaterialAgent.NO_OP; } else...
@Test public void shouldGetPackageMaterialAgent() { File workingDirectory = new File("/tmp/workingDirectory"); MaterialRevision revision = new MaterialRevision(new PackageMaterial(), new Modifications()); MaterialAgentFactory factory = new MaterialAgentFactory(null, workingDirectory, null, s...
@Override public <T> Optional<T> getProperty(String key, Class<T> targetType) { var targetKey = targetPropertyName(key); var result = binder.bind(targetKey, Bindable.of(targetType)); return result.isBound() ? Optional.of(result.get()) : Optional.empty(); }
@Test void resolvesCustomConfigClassProperties() { env.setProperty("prop.0.custProps.f1", "f1val"); env.setProperty("prop.0.custProps.f2", "1234"); var resolver = new PropertyResolverImpl(env); assertThat(resolver.getProperty("prop.0.custProps", CustomPropertiesClass.class)) .hasValue(new Cus...
void regionFinished(SchedulingPipelinedRegion region) { for (ConsumerRegionGroupExecutionView executionView : executionViewByRegion.getOrDefault(region, Collections.emptySet())) { executionView.regionFinished(region); } }
@Test void testRegionFinishedMultipleTimes() throws Exception { consumerRegionGroupExecutionViewMaintainer.regionFinished(consumerRegion); consumerRegionGroupExecutionViewMaintainer.regionFinished(consumerRegion); assertThat(consumerRegionGroupExecutionView.isFinished()).isTrue(); }
public FEELFnResult<String> invoke(@ParameterName("from") Object val) { if ( val == null ) { return FEELFnResult.ofResult( null ); } else { return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) ); } }
@Test void invokeRangeClosedOpen() { FunctionTestUtil.assertResult( stringFunction.invoke(new RangeImpl(Range.RangeBoundary.CLOSED, 12, 15, Range.RangeBoundary.OPEN)), "[ 12 .. 15 )"); }
@Description("computes Hamming distance between two strings") @ScalarFunction @LiteralParameters({"x", "y"}) @SqlType(StandardTypes.BIGINT) public static long hammingDistance(@SqlType("varchar(x)") Slice left, @SqlType("varchar(y)") Slice right) { int distance = 0; int leftPosition =...
@Test public void testHammingDistance() { assertFunction("HAMMING_DISTANCE('', '')", BIGINT, 0L); assertFunction("HAMMING_DISTANCE('hello', 'hello')", BIGINT, 0L); assertFunction("HAMMING_DISTANCE('hello', 'jello')", BIGINT, 1L); assertFunction("HAMMING_DISTANCE('like', 'hate')",...
@Override public void handle(SeckillWebMockRequestDTO request) { // 状态机初始化 stateMachineService.initStateMachine(request.getSeckillId()); // 初始化库存数量 // 使用状态机控制活动状态 if (!stateMachineService.feedMachine(Events.ACTIVITY_RESET, request.getSeckillId())) { throw new Runt...
@Test public void shouldHandleRequestSuccessfully() { SeckillWebMockRequestDTO request = new SeckillWebMockRequestDTO(); request.setSeckillId(123L); when(stateMachineService.feedMachine(Events.ACTIVITY_RESET, request.getSeckillId())).thenReturn(true); when(stateMachineService.feedMac...
@ExecuteOn(TaskExecutors.IO) @Get(value = "{id}/graph") @Operation(tags = {"Blueprints"}, summary = "Get a blueprint graph") public Map<String, Object> blueprintGraph( @Parameter(description = "The blueprint id") String id, HttpRequest<?> httpRequest ) throws URISyntaxException { ...
@SuppressWarnings("unchecked") @Test void blueprintGraph(WireMockRuntimeInfo wmRuntimeInfo) { stubFor(get(urlMatching("/v1/blueprints/id_1/graph.*")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBodyFile("blueprint-graph.json"))...
@Override public UUID generateId() { long counterValue = counter.incrementAndGet(); if (counterValue == MAX_COUNTER_VALUE) { throw new CucumberException( "Out of " + IncrementingUuidGenerator.class.getSimpleName() + " capacity. Please generate usin...
@Test void generates_different_non_null_uuids() { // Given UuidGenerator generator = new IncrementingUuidGenerator(); // When List<UUID> uuids = IntStream.rangeClosed(1, 10) .mapToObj(i -> generator.generateId()) .collect(Collectors.toList()); ...
@Override public void write(T record) { recordConsumer.startMessage(); try { messageWriter.writeTopLevelMessage(record); } catch (RuntimeException e) { Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record; LOG.error("Cannot write message...
@Test public void testMapIntMessage() throws Exception { RecordConsumer readConsumerMock = Mockito.mock(RecordConsumer.class); ProtoWriteSupport<TestProtobuf.MapIntMessage> instance = createReadConsumerInstance(TestProtobuf.MapIntMessage.class, readConsumerMock); TestProtobuf.MapIntMessage.Builde...
@Override public boolean isOperational() { if (nodeOperational) { return true; } boolean flag = false; try { flag = checkOperational(); } catch (InterruptedException e) { LOG.trace("Interrupted while checking ES node is operational", e); Thread.currentThread().interrupt();...
@Test public void isOperational_should_return_false_if_ElasticsearchException_with_connection_timeout_thrown() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()) .thenThrow(new ElasticsearchException(new ExecutionException(new ConnectException("Timeout connec...
@Override public V get() throws InterruptedException, ExecutionException { try { return get(Long.MAX_VALUE, TimeUnit.SECONDS); } catch (TimeoutException e) { throw new ExecutionException(e); } }
@Test public void completeDelegate_getWithTimeout_outerAsked() throws Exception { delegateFuture.run(); assertEquals(DELEGATE_RESULT, outerFuture.get(10, TimeUnit.MILLISECONDS)); }
public long readIntLenenc() { int firstByte = readInt1(); if (firstByte < 0xfb) { return firstByte; } if (0xfb == firstByte) { return 0L; } if (0xfc == firstByte) { return readInt2(); } if (0xfd == firstByte) { ...
@Test void assertReadIntLenencWithFourBytes() { when(byteBuf.readUnsignedByte()).thenReturn((short) 0xff); when(byteBuf.readLongLE()).thenReturn(Long.MAX_VALUE); assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readIntLenenc(), is(Long.MAX_VALUE)); }
public long computeExpirationTime(final String pHttpExpiresHeader, final String pHttpCacheControlHeader, final long pNow) { final Long override = Configuration.getInstance().getExpirationOverrideDuration(); if (override != null) { return pNow + override; } final long extensi...
@Test public void testComputeExpirationTime() { final Random random = new Random(); final int oneWeek = 7 * 24 * 3600 * 1000; // 7 days in milliseconds testComputeExpirationTimeHelper(null, random.nextInt(oneWeek)); testComputeExpirationTimeHelper((long) random.nextInt(oneWeek), rand...
public List<InputSplit> getSplits(JobContext job) throws IOException { StopWatch sw = new StopWatch().start(); long minSize = Math.max(getFormatMinSplitSize(), getMinSplitSize(job)); long maxSize = getMaxSplitSize(job); // generate splits List<InputSplit> splits = new ArrayList<InputSplit>(); L...
@Test public void testNumInputFilesWithoutRecursively() throws Exception { Configuration conf = getConfiguration(); conf.setInt(FileInputFormat.LIST_STATUS_NUM_THREADS, numThreads); Job job = Job.getInstance(conf); FileInputFormat<?, ?> fileInputFormat = new TextInputFormat(); List<InputSplit> spl...
public String doLayout(ILoggingEvent event) { StringBuilder buf = new StringBuilder(); startNewTableIfLimitReached(buf); boolean odd = true; if (((counter++) & 1) == 0) { odd = false; } String level = event.getLevel().toString().toLowerCase(Locale.US); buf.append(LINE_SEPARATOR); ...
@Test @Ignore public void rawLimit() throws Exception { StringBuilder sb = new StringBuilder(); String header = layout.getFileHeader(); assertTrue(header .startsWith("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">")); sb.appe...
@Override public boolean mkdirs(String path, MkdirsOptions options) throws IOException { path = stripPath(path); File file = new File(path); if (!options.getCreateParent()) { if (file.mkdir()) { setFileSecurity(options, file); return true; } return false; } boolea...
@Test public void mkdirs() throws IOException { String parentPath = PathUtils.concatPath(mLocalUfsRoot, getUniqueFileName()); String dirpath = PathUtils.concatPath(parentPath, getUniqueFileName()); mLocalUfs.mkdirs(dirpath); assertTrue(mLocalUfs.isDirectory(dirpath)); File file = new File(dirpat...
public static String elasticSearchTimeFormatToISO8601(String time) { try { DateTime dt = DateTime.parse(time, ES_DATE_FORMAT_FORMATTER); return getISO8601String(dt); } catch (IllegalArgumentException e) { return time; } }
@Test public void testElasticSearchTimeFormatToISO8601() { assertTrue(Tools.elasticSearchTimeFormatToISO8601("2014-07-31 14:21:02.000").equals("2014-07-31T14:21:02.000Z")); }