focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public EntityExcerpt createExcerpt(NotificationDto nativeEntity) { return EntityExcerpt.builder() .id(ModelId.of(nativeEntity.id())) .type(ModelTypes.NOTIFICATION_V1) .title(nativeEntity.title()) .build(); }
@Test @MongoDBFixtures("NotificationFacadeTest.json") public void createExcerpt() { final Optional<NotificationDto> notificationDto = notificationService.get( "5d4d33753d27460ad18e0c4d"); assertThat(notificationDto).isPresent(); final EntityExcerpt excerpt = facade.create...
@Override public void checkBeforeUpdate(final CreateBroadcastTableRuleStatement sqlStatement) { ShardingSpherePreconditions.checkNotEmpty(database.getResourceMetaData().getStorageUnits(), () -> new EmptyStorageUnitException(database.getName())); if (!sqlStatement.isIfNotExists()) { check...
@Test void assertCheckSQLStatementWithEmptyStorageUnit() { BroadcastRuleConfiguration currentConfig = mock(BroadcastRuleConfiguration.class); when(currentConfig.getTables()).thenReturn(Collections.singleton("t_address")); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, R...
static void handleJvmOptions(String[] args, String lsJavaOpts) { final JvmOptionsParser parser = new JvmOptionsParser(args[0]); final String jvmOpts = args.length == 2 ? args[1] : null; try { Optional<Path> jvmOptions = parser.lookupJvmOptionsFile(jvmOpts); parser.handleJ...
@Test public void test_LS_JAVA_OPTS_isUsedWhenNoJvmOptionsIsAvailable() { JvmOptionsParser.handleJvmOptions(new String[] {temp.toString()}, "-Xblabla"); // Verify final String output = outputStreamCaptor.toString(); assertTrue("Output MUST contains the options present in LS_JAVA_OPT...
@Override public void pre(SpanAdapter span, Exchange exchange, Endpoint endpoint) { super.pre(span, exchange, endpoint); span.setTag(TagConstants.MESSAGE_BUS_DESTINATION, getDestination(exchange, endpoint)); String messageId = getMessageId(exchange); if (messageId != null) { ...
@Test public void testPreMessageBusDestination() { Endpoint endpoint = Mockito.mock(Endpoint.class); Mockito.when(endpoint.getEndpointUri()).thenReturn("jms://MyQueue?hello=world"); SpanDecorator decorator = new AbstractMessagingSpanDecorator() { @Override public St...
static TypeName buildTypeName(String typeDeclaration) throws ClassNotFoundException { return buildTypeName(typeDeclaration, false); }
@Test public void testBuildTypeName() throws Exception { assertEquals(buildTypeName("uint256"), (ClassName.get(Uint256.class))); assertEquals(buildTypeName("uint64"), (ClassName.get(Uint64.class))); assertEquals(buildTypeName("string"), (ClassName.get(Utf8String.class))); assertEqua...
public static String getSystemInformation() { String ret = System.getProperty("java.vendor"); ret += " " + System.getProperty("java.version"); ret += " on " + System.getProperty("os.name"); ret += " " + System.getProperty("os.version"); return ret; }
@Test public void testGetSystemInformation() { String result = Tools.getSystemInformation(); assertTrue(result.trim().length() > 0); }
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final Instant lower = calculateLowerBound(windowSt...
@Test @SuppressWarnings("unchecked") public void shouldCloseIterator_fetchAll() { // When: final StateQueryResult<KeyValueIterator<Windowed<GenericKey>, ValueAndTimestamp<GenericRow>>> partitionResult = new StateQueryResult<>(); final QueryResult<KeyValueIterator<Windowed<GenericKey>, ValueAndTimestamp<...
public static <T> Read<T> readMessage() { return new AutoValue_JmsIO_Read.Builder<T>() .setMaxNumRecords(Long.MAX_VALUE) .setCloseTimeout(DEFAULT_CLOSE_TIMEOUT) .setRequiresDeduping(false) .build(); }
@Test public void testReadBytesMessages() throws Exception { long count = 1L; // produce message produceTestMessages(count, JmsIOTest::createBytesMessage); // read from the queue PCollection<String> output = pipeline.apply( JmsIO.<String>readMessage() .withConne...
@Override public void collectSizeStats(StateObjectSizeStatsCollector collector) { streamSubHandles().forEach(handle -> handle.collectSizeStats(collector)); }
@Test void testCollectSizeStats() { IncrementalRemoteKeyedStateHandle handle = create(ThreadLocalRandom.current()); StateObject.StateObjectSizeStatsCollector statsCollector = StateObject.StateObjectSizeStatsCollector.create(); handle.collectSizeStats(statsCollector); ...
public static boolean regionMatches( CharSequence expected, CharSequence input, int beginIndex, int endIndex) { if (expected == null) throw new NullPointerException("expected == null"); if (input == null) throw new NullPointerException("input == null"); int regionLength = regionLength(input.length(), be...
@Test void regionMatches_badParameters() { assertThatThrownBy(() -> CharSequences.regionMatches(null, "b3", 0, 0)) .isInstanceOf(NullPointerException.class) .hasMessage("expected == null"); assertThatThrownBy(() -> CharSequences.regionMatches("b3", null, 0, 0)) .isInstanceOf(NullPointerExcepti...
public ExitStatus(Options options) { this.options = options; }
@Test void wip_with_skipped_scenarios() { createNonWipExitStatus(); bus.send(testCaseFinishedWithStatus(Status.SKIPPED)); assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x0))); }
@Override public Optional<String> canUpgradeTo(final DataSource other) { final List<String> issues = PROPERTIES.stream() .filter(prop -> !prop.isCompatible(this, other)) .map(prop -> getCompatMessage(other, prop)) .collect(Collectors.toList()); checkSchemas(getSchema(), other.getSchem...
@Test public void shouldEnforceSameTopic() { // Given: final KsqlStream<String> streamA = new KsqlStream<>( "sql", SourceName.of("A"), SOME_SCHEMA, Optional.empty(), true, topic, false ); final KsqlStream<String> streamB = new KsqlStream<>( ...
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@SuppressWarnings({"unchecked", "rawtypes"}) @Test void testMultiDimensionalArray() { // tuple array MapFunction<?, ?> function = new MapFunction<Tuple2<Integer, Double>[][], Tuple2<Integer, Double>[][]>() { private static final long serialVersionUID = 1L; ...
@Override public void execute(EventNotificationContext ctx) throws EventNotificationException { final SlackEventNotificationConfig config = (SlackEventNotificationConfig) ctx.notificationConfig(); LOG.debug("SlackEventNotification backlog size in method execute is [{}]", config.backlogSize()); ...
@Test(expected = EventNotificationException.class) public void executeWithNullEventTimerange() throws EventNotificationException { EventNotificationContext yetAnotherContext = getEventNotificationContextToSimulateNullPointerException(); assertThat(yetAnotherContext.event().timerangeStart().isPresent...
@VisibleForTesting String normalizeArchitecture(String architecture) { // Create mapping based on https://docs.docker.com/engine/install/#supported-platforms if (architecture.equals("x86_64")) { return "amd64"; } else if (architecture.equals("aarch64")) { return "arm64"; } return archi...
@Test public void testNormalizeArchitecture_arm() { assertThat(stepsRunner.normalizeArchitecture("arm")).isEqualTo("arm"); }
public GrantDTO ensure(GRN grantee, Capability capability, GRN target, String creatorUsername) { final List<GrantDTO> existingGrants = getForTargetAndGrantee(target, grantee); if (existingGrants.isEmpty()) { return create(grantee, capability, target, creatorUsername); } // Th...
@Test @MongoDBFixtures("grants.json") public void ensure() { final GRN jane = grnRegistry.parse("grn::::user:jane"); final GRN stream1 = grnRegistry.parse("grn::::stream:54e3deadbeefdeadbeef0000"); final GRN newStream = grnRegistry.parse("grn::::stream:54e3deadbeefdeadbeef0888"); ...
@Override public long getReadTimeout() { return safelyParseLongValue(READ_TIMEOUT_PROPERTY).orElse(DEFAULT_TIMEOUT); }
@Test @UseDataProvider("notALongPropertyValues") public void getReadTimeout_returns_10000_when_property_is_not_a_long(String notALong) { settings.setProperty("sonar.alm.timeout.read", notALong); assertThat(underTest.getReadTimeout()).isEqualTo(30_000L); }
@Override public boolean tryProcess() { return tryProcessInternal(null); }
@Test public void when_idleTimeout_then_idleMessageAfterTimeout() throws Exception { // We can't inject MockClock to EventTimeMapper inside the InsertWatermarkP, so we use real time. // We send no events and expect, that after 100 ms WM will be emitted. createProcessor(100); // let'...
public void setAbout(Attribute about) throws BadFieldValueException { if (XmpConstants.RDF_NAMESPACE.equals(about.getNamespace()) && XmpConstants.ABOUT_NAME.equals(about.getName())) { setAttribute(about); return; } throw new BadFieldValueExcept...
@Test void testBadRdfAbout() throws Exception { assertThrows(BadFieldValueException.class, () -> { schem.setAbout(new Attribute(null, "about", "")); }); }
@Override public KGroupedStream<K, V> groupByKey() { return groupByKey(Grouped.with(keySerde, valueSerde)); }
@Test public void shouldNotAllowNullGroupedOnGroupByKey() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.groupByKey((Grouped<String, String>) null)); assertThat(exception.getMessage(), equalTo("grouped can't be null")); ...
@Override public List<Node> getChildren() { ImmutableList.Builder<Node> result = ImmutableList.<Node>builder() .add(value) .add(pattern); escape.ifPresent(result::add); return result.build(); }
@Test public void testGetChildren() { StringLiteral value = new StringLiteral("a"); StringLiteral pattern = new StringLiteral("b"); StringLiteral escape = new StringLiteral("c"); assertEquals(new LikePredicate(value, pattern, escape).getChildren(), ImmutableList.of(value, patter...
public SearchJob executeSync(String searchId, SearchUser searchUser, ExecutionState executionState) { return searchDomain.getForUser(searchId, searchUser) .map(s -> executeSync(s, searchUser, executionState)) .orElseThrow(() -> new NotFoundException("No search found with id <" + ...
@Test public void appliesSearchExecutionState() { final Search search = makeSearch(); final SearchUser searchUser = TestSearchUser.builder() .withUser(testUser -> testUser.withUsername("frank-drebin")) .build(); when(searchDomain.getForUser(eq("search1"), eq...
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 0) { if ("getAsText".equals(methodName)) { return SelString.of(val.getAsText(Locale.US)); } else if ("withMinimumValue".equals(methodName)) { return SelJodaDateTime.of(val.withMinimumValue()); }...
@Test(expected = UnsupportedOperationException.class) public void testInvalidCallArg() { one.call("getAsText", new SelType[] {SelType.NULL}); }
@Override public String getAcknowledgmentType() { return "CE"; }
@Test public void testGetAcknowledgmentType() { instance = new MllpCommitErrorAcknowledgementException(HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, LOG_PHI_TRUE); assertEquals("CE", instance.getAcknowledgmentType()); }
public static Type convertType(TypeInfo typeInfo) { switch (typeInfo.getOdpsType()) { case BIGINT: return Type.BIGINT; case INT: return Type.INT; case SMALLINT: return Type.SMALLINT; case TINYINT: ret...
@Test public void testConvertTypeCaseTimestampAndDatetime() { TypeInfo typeInfo = TypeInfoFactory.TIMESTAMP; Type result = EntityConvertUtils.convertType(typeInfo); assertEquals(Type.DATETIME, result); }
@Override public void uploadPart(RefCountedFSOutputStream file) throws IOException { // this is to guarantee that nobody is // writing to the file we are uploading. checkState(file.isClosed()); final CompletableFuture<PartETag> future = new CompletableFuture<>(); uploadsInPr...
@Test public void multiplePartAndObjectUploadsShouldBeIncluded() throws IOException { final byte[] firstCompletePart = bytesOf("hello world"); final byte[] secondCompletePart = bytesOf("hello again"); final byte[] thirdIncompletePart = bytesOf("!!!"); uploadPart(firstCompletePart); ...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testPreferredReadReplicaOffsetError() { buildFetcher(new MetricConfig(), OffsetResetStrategy.EARLIEST, new BytesDeserializer(), new BytesDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED, Duration.ofMinutes(5).toMillis()); subscriptions.assignFromUse...
public void grant(GrantPrivilegeStmt stmt) throws DdlException { try { if (stmt.getRole() != null) { grantToRole( stmt.getObjectType(), stmt.getPrivilegeTypes(), stmt.getObjectList(), stmt...
@Test public void testSysTypeError() throws Exception { GlobalStateMgr masterGlobalStateMgr = ctx.getGlobalStateMgr(); AuthorizationMgr masterManager = masterGlobalStateMgr.getAuthorizationMgr(); UtFrameUtils.PseudoJournalReplayer.resetFollowerJournalQueue(); setCurrentUserAndRoles(...
@Description("converts the string to upper case") @ScalarFunction @LiteralParameters("x") @SqlType("varchar(x)") public static Slice upper(@SqlType("varchar(x)") Slice slice) { return toUpperCase(slice); }
@Test public void testUpper() { assertFunction("UPPER('')", createVarcharType(0), ""); assertFunction("UPPER('Hello World')", createVarcharType(11), "HELLO WORLD"); assertFunction("UPPER('what!!')", createVarcharType(6), "WHAT!!"); assertFunction("UPPER('\u00D6sterreich')", creat...
public static <T extends Throwable> void checkContainsKey(final Map<?, ?> map, final Object key, final Supplier<T> exceptionSupplierIfUnexpected) throws T { if (!map.containsKey(key)) { throw exceptionSupplierIfUnexpected.get(); } }
@Test void assertCheckContainsKeyToThrowsException() { assertThrows(SQLException.class, () -> ShardingSpherePreconditions.checkContainsKey(Collections.singletonMap("foo", "value"), "bar", SQLException::new)); }
public static CharSequence withoutSubSequence(CharSequence input, int beginIndex, int endIndex) { if (input == null) throw new NullPointerException("input == null"); int length = input.length(); // Exit early if the region is empty or the entire input int skippedRegionLength = regionLength(length, begi...
@Test void withoutSubSequence_length() { String input = "b3=1,es=2"; for (CharSequence sequence : asList( CharSequences.withoutSubSequence(input, 0, 2), CharSequences.withoutSubSequence(input, 2, 4), CharSequences.withoutSubSequence(input, 4, 6), CharSequences.withoutSubSequence(input, ...
public static <EventT> Write<EventT> write() { return new AutoValue_JmsIO_Write.Builder<EventT>().build(); }
@Test public void testWriteMessageToStaticTopicWithoutRetryPolicy() throws Exception { Instant now = Instant.now(); String messageText = now.toString(); List<String> data = Collections.singletonList(messageText); Connection connection = connectionFactory.createConnection(USERNAME, PASSWORD); conn...
public static NearCacheConfig copyWithInitializedDefaultMaxSizeForOnHeapMaps(NearCacheConfig nearCacheConfig) { if (nearCacheConfig == null) { return null; } EvictionConfig evictionConfig = nearCacheConfig.getEvictionConfig(); if (nearCacheConfig.getInMemoryFormat() == InMem...
@Test public void testCopyInitDefaultMaxSizeForOnHeapMaps_whenNull_thenDoNothing() { NearCacheConfigAccessor.copyWithInitializedDefaultMaxSizeForOnHeapMaps(null); }
public static <T> GoConfigClassLoader<T> classParser(Element e, Class<T> aClass, ConfigCache configCache, GoCipher goCipher, final ConfigElementImplementationRegistry registry, ConfigReferenceElements configReferenceElements) { return new GoConfigClassLoader<>(e, aClass, configCache, goCipher, registry, configR...
@Test public void shouldErrorOutWhenConfigClassHasAttributeAwareConfigTagAnnotationButAttributeValueIsNotMatching() { final Element element = new Element("example"); element.setAttribute("type", "foo-bar"); final GoConfigClassLoader<ConfigWithAttributeAwareConfigTagAnnotation> loader = GoCo...
public boolean contains(String headerName) { String normalName = HeaderName.normalize(Objects.requireNonNull(headerName, "headerName")); return findNormal(normalName) != ABSENT; }
@Test void contains() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("COOKie", "this=that"); headers.add("cookIE", "frizzle=frazzle"); headers.add("Soup", "salad"); assertTrue(headers.contains("CoOkIe")); assertTrue(headers.contain...
public static List<String> split(String str, String splitter) { if (str == null) { return null; } if (StringUtils.isBlank(str)) { return Collections.EMPTY_LIST; } String[] addrArray = str.split(splitter); return Arrays.asList(addrArray); }
@Test public void testSplit() { List<String> list = Arrays.asList("groupA=DENY", "groupB=PUB|SUB", "groupC=SUB"); String comma = ","; assertEquals(list, UtilAll.split("groupA=DENY,groupB=PUB|SUB,groupC=SUB", comma)); assertEquals(null, UtilAll.split(null, comma)); assertEqual...
protected void removeBadMatches(Dependency dependency) { final Set<Identifier> toRemove = new HashSet<>(); /* TODO - can we utilize the pom's groupid and artifactId to filter??? most of * these are due to low quality data. Other idea would be to say any CPE * found based on LOW confi...
@Test public void testRemoveBadMatches() throws Exception { Dependency dependency = new Dependency(); dependency.setFileName("some.jar"); dependency.setFilePath("some.jar"); Cpe cpe = builder.part(Part.APPLICATION).vendor("m-core").product("m-core").build(); CpeIdentifier id ...
public static void saveExistingErrors( final File markFile, final AtomicBuffer errorBuffer, final PrintStream logger, final String errorFilePrefix) { try { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final int observations =...
@Test void saveExistingErrorsCreatesErrorFileInTheSameDirectoryAsTheCorrespondingMarkFile() { final File markFile = tempDir.resolve("mark.dat").toFile(); final DistinctErrorLog errorLog = new DistinctErrorLog(new UnsafeBuffer(allocateDirect(10 * 1024)), SystemEpochClock.INSTANCE); ...
public static Format of(final FormatInfo formatInfo) { final Format format = fromName(formatInfo.getFormat().toUpperCase()); format.validateProperties(formatInfo.getProperties()); return format; }
@Test public void shouldCreateFromString() { assertThat(FormatFactory.of(FormatInfo.of("JsoN")), is(FormatFactory.JSON)); assertThat(FormatFactory.of(FormatInfo.of("AvRo")), is(FormatFactory.AVRO)); assertThat(FormatFactory.of(FormatInfo.of("Delimited")), is(FormatFactory.DELIMITED)); assertThat(Forma...
public static <T> TransportResponse<T> success(T response) { return new TransportResponseImpl<>(response, null, new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); }
@Test public void testSuccessResponse() { doTestSuccessResponse(TransportResponseImpl.success(RESPONSE)); doTestSuccessResponse(TransportResponseImpl.success(RESPONSE, CASE_SENSITIVE_WIRE_ATTRIBUTES)); }
public long floorFrameTs(long timestamp) { return subtractClamped(timestamp, floorMod( (timestamp >= Long.MIN_VALUE + frameOffset ? timestamp : timestamp + frameSize) - frameOffset, frameSize )); }
@Test public void when_floorOutOfRange_then_minValue() { definition = new SlidingWindowPolicy(4, 3, 10); assertEquals(Long.MIN_VALUE, definition.floorFrameTs(Long.MIN_VALUE + 2)); assertEquals(Long.MAX_VALUE, definition.floorFrameTs(Long.MAX_VALUE)); }
@SuppressWarnings("unchecked") public <T> T convert(DocString docString, Type targetType) { if (DocString.class.equals(targetType)) { return (T) docString; } List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType); if (d...
@Test void throws_when_no_converter_available_for_type() { DocString docString = DocString.create("{\"hello\":\"world\"}"); CucumberDocStringException exception = assertThrows( CucumberDocStringException.class, () -> converter.convert(docString, JsonNode.class)); asse...
@Override public Set<DiscreteResource> values() { return map.values().stream() .flatMap(x -> x.values(parent.id()).stream()) .collect(Collectors.toCollection(LinkedHashSet::new)); }
@Test public void testValues() { DiscreteResource res1 = Resources.discrete(DeviceId.deviceId("a"), PortNumber.portNumber(1)).resource(); DiscreteResource res2 = Resources.discrete(DeviceId.deviceId("a"), PortNumber.portNumber(2)).resource(); DiscreteResources sut = EncodableDiscreteResourc...
@SuppressWarnings("ConstantConditions") public boolean replaceActions(@NonNull Class<? extends Action> clazz, @NonNull Action a) { if (clazz == null) { throw new IllegalArgumentException("Action type must be non-null"); } if (a == null) { throw new IllegalArgumentExce...
@SuppressWarnings("deprecation") @Test public void replaceActions() { CauseAction a1 = new CauseAction(); ParametersAction a2 = new ParametersAction(); thing.addAction(a1); thing.addAction(a2); CauseAction a3 = new CauseAction(); assertTrue(thing.replaceActions(Ca...
@Override public ResourceAllocationResult tryFulfillRequirements( Map<JobID, Collection<ResourceRequirement>> missingResources, TaskManagerResourceInfoProvider taskManagerResourceInfoProvider, BlockedTaskManagerChecker blockedTaskManagerChecker) { final ResourceAllocation...
@Test void testUnfulfillableRequirement() { final TaskManagerInfo taskManager = new TestingTaskManagerInfo( DEFAULT_SLOT_RESOURCE.multiply(NUM_OF_SLOTS), DEFAULT_SLOT_RESOURCE.multiply(NUM_OF_SLOTS), DEFAULT_SLOT_RESOURC...
public static int getTag(byte[] raw) { try (final Asn1InputStream is = new Asn1InputStream(raw)) { return is.readTag(); } }
@Test public void getTagSingleByte() { assertEquals(0x30, Asn1Utils.getTag(new byte[] { 0x30, 0})); }
@Override public void execute(final ConnectionSession connectionSession) throws SQLException { Map<String, String> sessionVariables = extractSessionVariables(); validateSessionVariables(sessionVariables.keySet()); new CharsetSetExecutor(databaseType, connectionSession).set(sessionVariables);...
@Test void assertExecute() throws SQLException { SetStatement setStatement = prepareSetStatement(); MySQLSetVariableAdminExecutor executor = new MySQLSetVariableAdminExecutor(setStatement); ConnectionSession connectionSession = mock(ConnectionSession.class); when(connectionSession.ge...
@Override public SchemaResult getValueSchema( final Optional<String> topicName, final Optional<Integer> schemaId, final FormatInfo expectedFormat, final SerdeFeatures serdeFeatures ) { return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, false); }
@Test public void shouldPassRightSchemaToFormat() { // When: supplier.getValueSchema(Optional.of(TOPIC_NAME), Optional.empty(), expectedFormat, SerdeFeatures.of()); // Then: verify(format).getSchemaTranslator(formatProperties); verify(schemaTranslator).toColumns(parsedSchema, SerdeFeature...
@Override public void trash(final Local file) throws LocalAccessDeniedException { if(log.isDebugEnabled()) { log.debug(String.format("Move %s to Trash", file)); } final ObjCObjectByReference error = new ObjCObjectByReference(); if(!NSFileManager.defaultManager().trashItem...
@Test public void testTrash() throws Exception { Local l = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); new DefaultLocalTouchFeature().touch(l); assertTrue(l.exists()); new FileManagerTrashFeature().trash(l); assertFalse(l.exists()); }
@Override public <T> int score(List<T> left, List<T> right) { if (left.isEmpty() && right.isEmpty()) { return 0; } int distance = levenshteinDistance(left, right); return (int) (100 * (1.0 - ((double) distance) / (max(left.size(), right.size())))); }
@Test public void finding_threshold_in_line_count_to_go_below_85_score() { assertThat(underTest.score(listOf(100), listOf(115))).isEqualTo(86); assertThat(underTest.score(listOf(100), listOf(116))).isEqualTo(86); assertThat(underTest.score(listOf(100), listOf(117))).isEqualTo(85); // 85.47% - 117% ass...
@Override public boolean checkCredentials(String username, String password) { if (username == null || password == null) { return false; } Credentials credentials = new Credentials(username, password); if (validCredentialsCache.contains(credentials)) { return ...
@Test public void testPBKDF2WithHmacSHA256_lowerCaseWithoutColon() throws Exception { String algorithm = "PBKDF2WithHmacSHA256"; int iterations = 1000; int keyLength = 128; String hash = "B6:9C:5C:8A:10:3E:41:7B:BA:18:FC:E1:F2:0C:BC:D9:65:70:D3:53:AB:97:EE:2F:3F:A8:88...
public static long retainToDay4MinuteBucket(long minuteTimeBucket) { if (isMinuteBucket(minuteTimeBucket)) { return minuteTimeBucket / 10000 * 10000; } else { throw new UnexpectedException("Current time bucket is not a minute time bucket"); } }
@Test public void testRetainToDay4MinuteBucket() { Assertions.assertEquals(202407110000L, TimeBucket.retainToDay4MinuteBucket(202407112218L)); }
@Override public void runMigrations() { createMigrationsIndexIfNotExists(); super.runMigrations(); }
@Test void testValidateIndicesWithIndexPrefix() { ElasticSearchDBCreator elasticSearchDBCreator = new ElasticSearchDBCreator(elasticSearchStorageProviderMock, elasticSearchClient(), "my_index_prefix_"); assertThatThrownBy(elasticSearchDBCreator::validateIndices) .isInstanceOf(JobRunr...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { if(0L == status.getLength()) { return new NullInputStream(0L); } final Storage.Objects.Get request = sessi...
@Test public void testReadEmpty() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path directory = new GoogleStorageDirectoryFeature(session).mkdir(new Path(container, new AlphanumericRandomStringService().random(), En...
public static BsonTimestamp decodeTimestamp(BsonDocument resumeToken) { BsonValue bsonValue = Objects.requireNonNull(resumeToken, "Missing ResumeToken.").get(DATA_FIELD); final byte[] keyStringBytes; // Resume Tokens format: https://www.mongodb.com/docs/manual/changeStreams/#resu...
@Test public void testDecodeHexFormatV0() { BsonDocument resumeToken = BsonDocument.parse( " {\"_data\": \"826357B0840000000129295A1004461ECCED47A6420D9713A5135650360746645F696400646357B05F35C6AE07E1E6C7390004\"}"); BsonTimestamp expected = new BsonTimestamp(1...
public ImmutableList<PluginMatchingResult<PortScanner>> getPortScanners() { return tsunamiPlugins.entrySet().stream() .filter(entry -> entry.getKey().type().equals(PluginType.PORT_SCAN)) .map( entry -> PluginMatchingResult.<PortScanner>builder() .setPl...
@Test public void getPortScanners_whenMultiplePortScannersInstalled_returnsAllPortScanners() { PluginManager pluginManager = Guice.createInjector( new FakePortScannerBootstrapModule(), new FakePortScannerBootstrapModule2(), new FakeServiceFingerprinterBootst...
@Override public AppResponse process(Flow flow, SessionDataRequest request) throws SharedServiceClientException { return validateAmountOfApps(flow, appSession.getAccountId(), request) .orElseGet(() -> validateSms(flow, appSession.getAccountId(), request.getSmscode()) .orElseGet(...
@Test void processValidateAmountOfAppsTooManyDevices() throws SharedServiceClientException { AppAuthenticator oldApp = new AppAuthenticator(); oldApp.setDeviceName("test_device"); oldApp.setLastSignInAt(ZonedDateTime.now()); when(sharedServiceClientMock.getSSConfigInt("Maximum_aanta...
public TurnToken retrieveFromCloudflare() throws IOException { final List<String> cloudflareTurnComposedUrls; try { cloudflareTurnComposedUrls = dnsNameResolver.resolveAll(cloudflareTurnHostname).get().stream() .map(i -> switch (i) { case Inet6Address i6 -> "[" + i6.getHostAddress() ...
@Test public void testSuccess() throws IOException, CancellationException, ExecutionException, InterruptedException { wireMock.stubFor(post(urlEqualTo(GET_CREDENTIALS_PATH)) .willReturn(aResponse().withStatus(201).withHeader("Content-Type", new String[]{"application/json"}).withBody("{\"iceServers\":{\"ur...
@Override public Checksum upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final IRO...
@Test public void testInterruptStatus() 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...
static int getEncryptedPacketLength(ByteBuf buffer, int offset) { int packetLength = 0; // SSLv3 or TLS - Check ContentType boolean tls; switch (buffer.getUnsignedByte(offset)) { case SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC: case SSL_CONTENT_TYPE_ALERT: c...
@Test public void shouldGetPacketLengthOfGmsslProtocolFromByteBuffer() { int bodyLength = 65; ByteBuf buf = Unpooled.buffer() .writeByte(SslUtils.SSL_CONTENT_TYPE_HANDSHAKE) .writeShort(SslUtils.GMSSL_PROTOCOL_VERSION) ...
public static Write write() { return new AutoValue_RedisIO_Write.Builder() .setConnectionConfiguration(RedisConnectionConfiguration.create()) .setMethod(Write.Method.APPEND) .build(); }
@Test public void testWriteWithMethodLPush() { String key = "testWriteWithMethodLPush"; String value = "value"; client.lpush(key, value); String newValue = "newValue"; PCollection<KV<String, String>> write = p.apply(Create.of(KV.of(key, newValue))); write.apply(RedisIO.write().withEndpoint(RE...
@Override @ManagedOperation(description = "Remove the key from the store") public boolean remove(String key) { return setOperations.remove(repositoryName, key) != null; }
@Test public void shouldRemoveKey() { idempotentRepository.remove(KEY); verify(setOperations).remove(REPOSITORY, KEY); }
public ConfigRepoConfig getConfigRepo(MaterialConfig config) { for (ConfigRepoConfig repoConfig : this) { if (repoConfig.hasSameMaterial(config)) { return repoConfig; } } return null; }
@Test public void shouldFindReturnNullWhenConfigRepoWithSpecifiedIdIsNotPresent() { assertNull(repos.getConfigRepo("repo1")); }
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) { checkArgument( OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp); return new AutoValue_UBinary(binaryOp, lhs, rhs); }
@Test public void unsignedRightShift() { assertUnifiesAndInlines( "4 >>> 17", UBinary.create(Kind.UNSIGNED_RIGHT_SHIFT, ULiteral.intLit(4), ULiteral.intLit(17))); }
public <T> void register(MeshRuleListener subscriber) { if (ruleMapHolder != null) { List<Map<String, Object>> rule = ruleMapHolder.get(subscriber.ruleSuffix()); if (rule != null) { subscriber.onRuleChange(appName, rule); } } meshRuleDispatcher...
@Test void register() { MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener("demo-route"); StandardMeshRuleRouter standardMeshRuleRouter1 = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); StandardMeshRuleRouter standardMeshRuleRouter2 = Mockito.spy(new StandardMeshRu...
@Override public boolean consume(CodeReader code, TokenQueue output) { if (code.popTo(matcher, tmpBuilder) > 0) { // see SONAR-2499 Cursor previousCursor = code.getPreviousCursor(); if (normalizationValue != null) { output.add(new Token(normalizationValue, previousCursor.getLine(), previ...
@Test public void shouldNormalize() { TokenChannel channel = new TokenChannel("ABC", "normalized"); TokenQueue output = mock(TokenQueue.class); CodeReader codeReader = new CodeReader("ABCD"); assertThat(channel.consume(codeReader, output), is(true)); ArgumentCaptor<Token> token = ArgumentCaptor.f...
public static PDImageXObject createFromByteArray(PDDocument document, byte[] byteArray) throws IOException { // copy stream ByteArrayInputStream byteStream = new ByteArrayInputStream(byteArray); Dimensions meta = retrieveDimensions(byteStream); PDColorSpace colorSpace; ...
@Test void testPDFBox5137() throws IOException { byte[] ba = Files.readAllBytes(Paths.get("target/imgs", "PDFBOX-5196-lotus.jpg")); PDDocument document = new PDDocument(); PDImageXObject ximage = JPEGFactory.createFromByteArray(document, ba); validate(ximage, 8, 500, 500, "jpg...
@Override public ByteBuf duplicate() { ensureAccessible(); return new UnpooledDuplicatedByteBuf(this); }
@Test public void testDuplicateRelease() { ByteBuf buf = newBuffer(8); assertEquals(1, buf.refCnt()); assertTrue(buf.duplicate().release()); assertEquals(0, buf.refCnt()); }
public static void main(String[] args) { var facade = new DwarvenGoldmineFacade(); facade.startNewDay(); facade.digOutGold(); facade.endDay(); }
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public List<Pdu> getPdus() { return mPdus; }
@Test public void testCanParsePdusFromOtherBeacon() { byte[] bytes = hexStringToByteArray("0201060303aafe1516aafe00e72f234454f4911ba9ffa600000000000100000c09526164426561636f6e2047000000000000000000000000000000000000"); BleAdvertisement bleAdvert = new BleAdvertisement(bytes); assertEquals("A...
@Override public String toString(final RouteUnit routeUnit) { return identifier.getQuoteCharacter().wrap(getCursorValue(routeUnit)); }
@Test void assertToString() { CursorToken cursorToken = new CursorToken(0, 0, new IdentifierValue("t_order_cursor"), mock(CursorStatementContext.class, RETURNS_DEEP_STUBS), mock(ShardingRule.class)); RouteUnit routeUnit = mock(RouteUnit.class); when(routeUnit.getTableMappers(...
@Override public List<RecognisedObject> recognise(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { INDArray image = preProcessImage(imageLoader.asImageMatrix(stream,...
@Test public void recognise() throws Exception { assumeFalse(SystemUtils.OS_ARCH.equals("aarch64"), "doesn't yet work on aarch64"); TikaConfig config = null; try (InputStream is = getClass().getResourceAsStream("dl4j-inception3-config.xml")) { config = new TikaConfig(is); ...
public String findMsh18(byte[] hl7Message, Charset charset) { String answer = ""; if (hl7Message != null && hl7Message.length > 0) { List<Integer> fieldSeparatorIndexes = findFieldSeparatorIndicesInSegment(hl7Message, 0); if (fieldSeparatorIndexes.size() > 17) { ...
@Test public void testFindMsh18WhenExistsWithoutTrailingPipe() { final String testMessage = MSH_SEGMENT + "||||||8859/1" + '\r' + REMAINING_SEGMENTS; assertEquals("8859/1", hl7util.findMsh18(testMessage.getBytes(), charset)); }
static Timestamp toTimestamp(final JsonNode object) { if (object instanceof NumericNode) { return new Timestamp(object.asLong()); } if (object instanceof TextNode) { try { return new Timestamp(Long.parseLong(object.textValue())); } catch (final NumberFormatException e) { th...
@Test(expected = IllegalArgumentException.class) public void shouldFailWhenConvertingIncompatibleTimestamp() { JsonSerdeUtils.toTimestamp(JsonNodeFactory.instance.booleanNode(false)); }
protected static boolean isSingleQuoted(String input) { if (input == null || input.isBlank()) { return false; } return input.matches("(^" + QUOTE_CHAR + "{1}([^" + QUOTE_CHAR + "]+)" + QUOTE_CHAR + "{1})"); }
@Test public void testEmptySingleQuotedNegative2() { assertFalse(isSingleQuoted("\"")); }
@VisibleForTesting static int checkJar(Path file) throws Exception { final URI uri = file.toUri(); int numSevereIssues = 0; try (final FileSystem fileSystem = FileSystems.newFileSystem( new URI("jar:file", uri.getHost(), uri.getPath(), uri.getFragment...
@Test void testIgnoreFtlFiles(@TempDir Path tempDir) throws Exception { assertThat( JarFileChecker.checkJar( createJar( tempDir, Entry.fileEntry(VALID_NOTICE_CONTENTS, VALI...
@Override public CompletableFuture<Void> updateOrCreateSubscriptionGroup(String address, SubscriptionGroupConfig config, long timeoutMillis) { CompletableFuture<Void> future = new CompletableFuture<>(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CRE...
@Test public void assertUpdateOrCreateSubscriptionGroupWithSuccess() throws Exception { setResponseSuccess(null); SubscriptionGroupConfig config = mock(SubscriptionGroupConfig.class); CompletableFuture<Void> actual = mqClientAdminImpl.updateOrCreateSubscriptionGroup(defaultBrokerAddr, config...
public Blade disableSession() { this.sessionManager = null; return this; }
@Test public void testDisableSession() { Blade blade = Blade.create().disableSession(); Assert.assertNull(blade.sessionManager()); }
void updateOffer(ItemComposition offerItem, BufferedImage itemImage, @Nullable GrandExchangeOffer newOffer) { if (newOffer == null || newOffer.getState() == EMPTY) { return; } else { cardLayout.show(container, FACE_CARD); itemName.setText(offerItem.getMembersName()); itemIcon.setIcon(new ImageIc...
@Test public void testUpdateOffer() { when(offer.getState()).thenReturn(GrandExchangeOfferState.CANCELLED_BUY); GrandExchangeOfferSlot offerSlot = new GrandExchangeOfferSlot(mock(GrandExchangePlugin.class)); offerSlot.updateOffer(mock(ItemComposition.class), mock(AsyncBufferedImage.class), offer); }
public URI toUri() { return uri; }
@Test (timeout = 30000) public void testPathToUriConversion() throws URISyntaxException, IOException { // Path differs from URI in that it ignores the query part.. assertEquals("? mark char in to URI", new URI(null, null, "/foo?bar", null, null), new Path("/foo?bar").toUri()); asse...
@Override protected boolean notExist() { return Stream.of(DefaultPathConstants.PLUGIN_PARENT, DefaultPathConstants.APP_AUTH_PARENT, DefaultPathConstants.META_DATA).noneMatch(zkClient::isExist); }
@Test public void testNotExist() { ZookeeperDataChangedInit zookeeperDataChangedInit = new ZookeeperDataChangedInit(zkClient); when(zkClient.isExist(DefaultPathConstants.PLUGIN_PARENT)).thenReturn(true); boolean pluginExist = zookeeperDataChangedInit.notExist(); assertFalse(pluginEx...
public Span nextSpan(ConsumerRecord<?, ?> record) { // Even though the type is ConsumerRecord, this is not a (remote) consumer span. Only "poll" // events create consumer spans. Since this is a processor span, we use the normal sampler. TraceContextOrSamplingFlags extracted = extractAndClearTraceIdHea...
@Test void nextSpan_prefers_b3_header() { consumerRecord.headers().add("b3", B3SingleFormat.writeB3SingleFormatAsBytes(incoming)); Span child; try (Scope scope = tracing.currentTraceContext().newScope(parent)) { child = kafkaTracing.nextSpan(consumerRecord); } child.finish(); assertThat(...
public static IpPrefix valueOf(int address, int prefixLength) { return new IpPrefix(IpAddress.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfShortArrayIPv6() { IpPrefix ipPrefix; byte[] value; value = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; ipPrefix = IpPrefix.valueOf(IpAddress.Version.INET6, value, 120); }
public static Set<String> parseDeployOutput(File buildResult) throws IOException { try (Stream<String> linesStream = Files.lines(buildResult.toPath())) { return parseDeployOutput(linesStream); } }
@Test void testParseDeployOutputDetectsSkippedDeployments() { assertThat( DeployParser.parseDeployOutput( Stream.of( "[INFO] --- maven-deploy-plugin:2.8.2:deploy (default-deploy) @ flink-parent ---", ...
public static Object project(Schema source, Object record, Schema target) throws SchemaProjectorException { checkMaybeCompatible(source, target); if (source.isOptional() && !target.isOptional()) { if (target.defaultValue() != null) { if (record != null) { ...
@Test public void testArrayProjection() { Schema source = SchemaBuilder.array(Schema.INT32_SCHEMA).build(); Object projected = SchemaProjector.project(source, Arrays.asList(1, 2, 3), source); assertEquals(Arrays.asList(1, 2, 3), projected); Schema optionalSource = SchemaBuilder.arr...
@SuppressWarnings("unchecked") public Output run(RunContext runContext) throws Exception { Logger logger = runContext.logger(); try (HttpClient client = this.client(runContext, this.method)) { HttpRequest<String> request = this.request(runContext); HttpResponse<String> respo...
@Test void failed() throws Exception { try ( ApplicationContext applicationContext = ApplicationContext.run(); EmbeddedServer server = applicationContext.getBean(EmbeddedServer.class).start(); ) { Request task = Request.builder() .id(RequestTest.c...
public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (CollectionUtils.isNotEmpty(forbid)) { List<String> newForbid = new ArrayList<>(); for (String serviceName : forbid) { if (StringUtils.isNotContains(serviceName, ':') && StringUtils.isN...
@Test void testRevertForbid3() { String service1 = "dubbo.test.api.HelloService:1.0.0"; String service2 = "dubbo.test.api.HelloService:2.0.0"; List<String> forbid = new ArrayList<String>(); forbid.add(service1); forbid.add(service2); List<String> newForbid = UrlUtils....
public static PTransformMatcher flattenWithDuplicateInputs() { return new PTransformMatcher() { @Override public boolean matches(AppliedPTransform<?, ?, ?> application) { if (application.getTransform() instanceof Flatten.PCollections) { Set<PValue> observed = new HashSet<>(); ...
@Test public void flattenWithDuplicateInputsWithoutDuplicates() { AppliedPTransform application = AppliedPTransform.of( "Flatten", Collections.singletonMap( new TupleTag<Integer>(), PCollection.createPrimitiveOutputInternal( p, Wi...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 3) { onInvalidDataReceived(device, data); return; } final int responseCode = data.getIntValue(Data.FORMAT_UINT8, 0); final int requestCode = da...
@Test public void onInvalidDataReceived() { final MutableData data = new MutableData(new byte[] { 0x01, 0x01, 0x00, 0x00, 0x00}); response.onDataReceived(null, data); assertFalse(success); assertEquals(0, errorCode); assertFalse(response.isValid()); assertEquals(0, requestCode); assertNull(locations); }
public static Write write() { // 1000 for batch size is good enough in many cases, // ex: if document size is large, around 10KB, the request's size will be around 10MB // if document size is small, around 1KB, the request's size will be around 1MB return new AutoValue_SolrIO_Write.Builder().setMaxBatch...
@Test public void testBatchSize() { SolrIO.Write write1 = SolrIO.write() .withConnectionConfiguration(connectionConfiguration) .withMaxBatchSize(BATCH_SIZE); assertTrue(write1.getMaxBatchSize() == BATCH_SIZE); SolrIO.Write write2 = SolrIO.write().withConnectionConfiguration...
@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 (!Applicati...
@Test void testApplicationUnStarted() { RequestMeta metadata = new RequestMeta(); metadata.setClientIp("127.0.0.1"); metadata.setConnectionId(connectId); ServerCheckRequest serverCheckRequest = new ServerCheckRequest(); serverCheckRequest.setRequestId(requestId); Payl...
public boolean isCheckpointingEnabled() { if (snapshotSettings == null) { return false; } return snapshotSettings.getCheckpointCoordinatorConfiguration().isCheckpointingEnabled(); }
@Test public void checkpointingIsEnabledIfIntervalIsqAndLegal() { final JobGraph jobGraph = JobGraphBuilder.newStreamingJobGraphBuilder() .setJobCheckpointingSettings(createCheckpointSettingsWithInterval(10)) .build(); assertTrue(jobGr...
static Speed mean(Speed... speeds) { double n = speeds.length; Speed spd = Speed.ZERO; for (Speed speed : speeds) { spd = spd.plus(speed); } return spd.times(1.0 / n); }
@Test public void meanSpeedIsComputedCorrectly() { Speed negativeTenKnots = Speed.of(-10, KNOTS); Speed oneKnot = Speed.of(1, KNOTS); Speed fiveKnots = Speed.of(5, KNOTS); Speed nineKnots = Speed.of(9, KNOTS); assertThat( mean(oneKnot, nineKnots, fiveKnots).toStr...
@ConstantFunction(name = "minutes_add", argTypes = {DATETIME, INT}, returnType = DATETIME, isMonotonic = true) public static ConstantOperator minutesAdd(ConstantOperator date, ConstantOperator minute) { return ConstantOperator.createDatetimeOrNull(date.getDatetime().plusMinutes(minute.getInt())); }
@Test public void minutesAdd() { assertEquals("2015-03-23T09:33:55", ScalarOperatorFunctions.minutesAdd(O_DT_20150323_092355, O_INT_10).getDatetime().toString()); }
int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } }
@Test void getStrengthShouldReturnPreviousStrengthIfPreviousDurationCloserToGoal() { // given // when int actual = bcCryptWorkFactorService.getStrength(980, 1021, 5); // then assertThat(actual).isEqualTo(4); }
@Nullable public static ValueReference of(Object value) { if (value instanceof Boolean) { return of((Boolean) value); } else if (value instanceof Double) { return of((Double) value); } else if (value instanceof Float) { return of((Float) value); } ...
@Test public void serializeFloat() throws IOException { assertJsonEqualsNonStrict(objectMapper.writeValueAsString(ValueReference.of(1.0f)), "{\"@type\":\"float\",\"@value\":1.0}"); assertJsonEqualsNonStrict(objectMapper.writeValueAsString(ValueReference.of(42.4f)), "{\"@type\":\"float\",\"@value\":4...
@Override public Boolean isUsedInFetchArtifact(PipelineConfig pipelineConfig) { return Boolean.FALSE; }
@Test void shouldReturnFalseForIsUsedInFetchArtifact() { PackageMaterial material = new PackageMaterial(); assertThat(material.isUsedInFetchArtifact(new PipelineConfig())).isFalse(); }
static CatalogLoader createCatalogLoader( String name, Map<String, String> properties, Configuration hadoopConf) { String catalogImpl = properties.get(CatalogProperties.CATALOG_IMPL); if (catalogImpl != null) { String catalogType = properties.get(ICEBERG_CATALOG_TYPE); Preconditions.checkArgum...
@Test public void testCreateCatalogHive() { String catalogName = "hiveCatalog"; props.put( FlinkCatalogFactory.ICEBERG_CATALOG_TYPE, FlinkCatalogFactory.ICEBERG_CATALOG_TYPE_HIVE); Catalog catalog = FlinkCatalogFactory.createCatalogLoader(catalogName, props, new Configuration()) ...
@Override @Nullable public V get(@Nullable Object key) { Reference<K, V> ref = getReference(key, Restructure.WHEN_NECESSARY); Entry<K, V> entry = (ref != null ? ref.get() : null); return (entry != null ? entry.getValue() : null); }
@Test void shouldGetWithNoItems() { assertNull(this.map.get(123)); }
@Override public HttpResponseOutputStream<Chunk> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final String uploadUri; final String resourceId; if(null == status.getUrl()) { if(status.isExists()) { ...
@Test(expected = QuotaException.class) public void testMaxResourceSizeFailure() throws Exception { // If the file is already created, but not completely uploaded yet, the entry can be overwritten by setting "forceOverwrite" to true. final EueResourceIdProvider fileid = new EueResourceIdProvider(sess...