focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public JobStatus getJobStatus(JobID oldJobID) throws IOException { org.apache.hadoop.mapreduce.v2.api.records.JobId jobId = TypeConverter.toYarn(oldJobID); GetJobReportRequest request = recordFactory.newRecordInstance(GetJobReportRequest.class); request.setJobId(jobId); JobReport report = ((GetJobReportResponse) invoke("getJobReport", GetJobReportRequest.class, request)).getJobReport(); JobStatus jobStatus = null; if (report != null) { if (StringUtils.isEmpty(report.getJobFile())) { String jobFile = MRApps.getJobFile(conf, report.getUser(), oldJobID); report.setJobFile(jobFile); } String historyTrackingUrl = report.getTrackingUrl(); String url = StringUtils.isNotEmpty(historyTrackingUrl) ? historyTrackingUrl : trackingUrl; jobStatus = TypeConverter.fromYarn(report, url); } return jobStatus; }
@Test public void testHistoryServerNotConfigured() throws Exception { //RM doesn't have app report and job History Server is not configured ClientServiceDelegate clientServiceDelegate = getClientServiceDelegate( null, getRMDelegate()); JobStatus jobStatus = clientServiceDelegate.getJobStatus(oldJobId); Assert.assertEquals("N/A", jobStatus.getUsername()); Assert.assertEquals(JobStatus.State.PREP, jobStatus.getState()); //RM has app report and job History Server is not configured ResourceMgrDelegate rm = mock(ResourceMgrDelegate.class); ApplicationReport applicationReport = getFinishedApplicationReport(); when(rm.getApplicationReport(jobId.getAppId())).thenReturn( applicationReport); clientServiceDelegate = getClientServiceDelegate(null, rm); jobStatus = clientServiceDelegate.getJobStatus(oldJobId); Assert.assertEquals(applicationReport.getUser(), jobStatus.getUsername()); Assert.assertEquals(JobStatus.State.SUCCEEDED, jobStatus.getState()); }
@ScalarOperator(SUBTRACT) @SqlType(StandardTypes.BIGINT) public static long subtract(@SqlType(StandardTypes.BIGINT) long left, @SqlType(StandardTypes.BIGINT) long right) { try { return Math.subtractExact(left, right); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, format("bigint subtraction overflow: %s - %s", left, right), e); } }
@Test public void testSubtract() { assertFunction("100000000037 - 37", BIGINT, 100000000037L - 37L); assertFunction("37 - 100000000017", BIGINT, 37 - 100000000017L); assertFunction("100000000017 - 37", BIGINT, 100000000017L - 37L); assertFunction("100000000017 - 100000000017", BIGINT, 100000000017L - 100000000017L); }
public Connection connection(Connection connection) { // It is common to implement both interfaces if (connection instanceof XAConnection) { return xaConnection((XAConnection) connection); } return TracingConnection.create(connection, this); }
@Test void connection_wrapsInput() { assertThat(jmsTracing.connection(mock(Connection.class))) .isInstanceOf(TracingConnection.class); }
public static Checksum crc32() { return Crc32.INSTANCE; }
@Test void crc32() { assertSame(Crc32.INSTANCE, Checksums.crc32()); }
public ApplicationBuilder appendParameters(Map<String, String> appendParameters) { this.parameters = appendParameters(parameters, appendParameters); return getThis(); }
@Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); ApplicationBuilder builder = new ApplicationBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); }
@Override public Map<String, Boolean> getGroupUuidToManaged(DbSession dbSession, Set<String> groupUuids) { return findManagedInstanceService() .map(managedInstanceService -> managedInstanceService.getGroupUuidToManaged(dbSession, groupUuids)) .orElse(returnNonManagedForAll(groupUuids)); }
@Test public void getGroupUuidToManaged_ifMoreThanOneDelegatesActivated_throws() { Set<ManagedInstanceService> managedInstanceServices = Set.of(new AlwaysManagedInstanceService(), new AlwaysManagedInstanceService()); DelegatingManagedServices delegatingManagedServices = new DelegatingManagedServices(managedInstanceServices); assertThatIllegalStateException() .isThrownBy(() -> delegatingManagedServices.getGroupUuidToManaged(dbSession, Set.of("a"))) .withMessage("The instance can't be managed by more than one identity provider and 2 were found."); }
@SuppressWarnings("deprecation") public static void setClasspath(Map<String, String> environment, Configuration conf) throws IOException { boolean userClassesTakesPrecedence = conf.getBoolean(MRJobConfig.MAPREDUCE_JOB_USER_CLASSPATH_FIRST, false); String classpathEnvVar = conf.getBoolean(MRJobConfig.MAPREDUCE_JOB_CLASSLOADER, false) ? Environment.APP_CLASSPATH.name() : Environment.CLASSPATH.name(); MRApps.addToEnvironment(environment, classpathEnvVar, crossPlatformifyMREnv(conf, Environment.PWD), conf); if (!userClassesTakesPrecedence) { MRApps.setMRFrameworkClasspath(environment, conf); } /* * We use "*" for the name of the JOB_JAR instead of MRJobConfig.JOB_JAR for * the case where the job jar is not necessarily named "job.jar". This can * happen, for example, when the job is leveraging a resource from the YARN * shared cache. */ MRApps.addToEnvironment( environment, classpathEnvVar, MRJobConfig.JOB_JAR + Path.SEPARATOR + "*", conf); MRApps.addToEnvironment( environment, classpathEnvVar, MRJobConfig.JOB_JAR + Path.SEPARATOR + "classes" + Path.SEPARATOR, conf); MRApps.addToEnvironment( environment, classpathEnvVar, MRJobConfig.JOB_JAR + Path.SEPARATOR + "lib" + Path.SEPARATOR + "*", conf); MRApps.addToEnvironment( environment, classpathEnvVar, crossPlatformifyMREnv(conf, Environment.PWD) + Path.SEPARATOR + "*", conf); // a * in the classpath will only find a .jar, so we need to filter out // all .jars and add everything else addToClasspathIfNotJar(JobContextImpl.getFileClassPaths(conf), JobContextImpl.getCacheFiles(conf), conf, environment, classpathEnvVar); addToClasspathIfNotJar(JobContextImpl.getArchiveClassPaths(conf), JobContextImpl.getCacheArchives(conf), conf, environment, classpathEnvVar); if (userClassesTakesPrecedence) { MRApps.setMRFrameworkClasspath(environment, conf); } }
@Test @Timeout(120000) public void testSetClasspath() throws IOException { Configuration conf = new Configuration(); conf.setBoolean(MRConfig.MAPREDUCE_APP_SUBMISSION_CROSS_PLATFORM, true); Job job = Job.getInstance(conf); Map<String, String> environment = new HashMap<String, String>(); MRApps.setClasspath(environment, job.getConfiguration()); assertTrue(environment.get("CLASSPATH").startsWith( ApplicationConstants.Environment.PWD.$$() + ApplicationConstants.CLASS_PATH_SEPARATOR)); String yarnAppClasspath = job.getConfiguration().get( YarnConfiguration.YARN_APPLICATION_CLASSPATH, StringUtils.join(",", YarnConfiguration.DEFAULT_YARN_CROSS_PLATFORM_APPLICATION_CLASSPATH)); if (yarnAppClasspath != null) { yarnAppClasspath = yarnAppClasspath.replaceAll(",\\s*", ApplicationConstants.CLASS_PATH_SEPARATOR).trim(); } assertTrue(environment.get("CLASSPATH").contains(yarnAppClasspath)); String mrAppClasspath = job.getConfiguration().get( MRJobConfig.MAPREDUCE_APPLICATION_CLASSPATH, MRJobConfig.DEFAULT_MAPREDUCE_CROSS_PLATFORM_APPLICATION_CLASSPATH); if (mrAppClasspath != null) { mrAppClasspath = mrAppClasspath.replaceAll(",\\s*", ApplicationConstants.CLASS_PATH_SEPARATOR).trim(); } assertTrue(environment.get("CLASSPATH").contains(mrAppClasspath)); }
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) { String trackTypeTag = readerWay.getTag("tracktype"); TrackType trackType = TrackType.find(trackTypeTag); if (trackType != MISSING) trackTypeEnc.setEnum(false, edgeId, edgeIntAccess, trackType); }
@Test public void testNoNPE() { ReaderWay readerWay = new ReaderWay(1); EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1); int edgeId = 0; parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags); assertEquals(TrackType.MISSING, ttEnc.getEnum(false, edgeId, edgeIntAccess)); }
@GET @Produces(MediaType.APPLICATION_JSON) @Path("{networkId}/hosts") public Response getVirtualHosts(@PathParam("networkId") long networkId) { NetworkId nid = NetworkId.networkId(networkId); Set<VirtualHost> vhosts = vnetService.getVirtualHosts(nid); return ok(encodeArray(VirtualHost.class, "hosts", vhosts)).build(); }
@Test public void testGetVirtualHostsEmptyArray() { NetworkId networkId = networkId4; expect(mockVnetService.getVirtualHosts(networkId)).andReturn(ImmutableSet.of()).anyTimes(); replay(mockVnetService); WebTarget wt = target(); String location = "vnets/" + networkId.toString() + "/hosts"; String response = wt.path(location).request().get(String.class); assertThat(response, is("{\"hosts\":[]}")); verify(mockVnetService); }
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLComQuitPacket(); case COM_INIT_DB: return new MySQLComInitDbPacket(payload); case COM_FIELD_LIST: return new MySQLComFieldListPacket(payload); case COM_QUERY: return new MySQLComQueryPacket(payload); case COM_STMT_PREPARE: return new MySQLComStmtPreparePacket(payload); case COM_STMT_EXECUTE: MySQLServerPreparedStatement serverPreparedStatement = connectionSession.getServerPreparedStatementRegistry().getPreparedStatement(payload.getByteBuf().getIntLE(payload.getByteBuf().readerIndex())); return new MySQLComStmtExecutePacket(payload, serverPreparedStatement.getSqlStatementContext().getSqlStatement().getParameterCount()); case COM_STMT_SEND_LONG_DATA: return new MySQLComStmtSendLongDataPacket(payload); case COM_STMT_RESET: return new MySQLComStmtResetPacket(payload); case COM_STMT_CLOSE: return new MySQLComStmtClosePacket(payload); case COM_SET_OPTION: return new MySQLComSetOptionPacket(payload); case COM_PING: return new MySQLComPingPacket(); case COM_RESET_CONNECTION: return new MySQLComResetConnectionPacket(); default: return new MySQLUnsupportedCommandPacket(commandPacketType); } }
@Test void assertNewInstanceWithComStmtSendLongDataPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_STMT_SEND_LONG_DATA, payload, connectionSession), instanceOf(MySQLComStmtSendLongDataPacket.class)); }
@VisibleForTesting public Optional<ProcessContinuation> run( PartitionMetadata partition, ChildPartitionsRecord record, RestrictionTracker<TimestampRange, Timestamp> tracker, ManualWatermarkEstimator<Instant> watermarkEstimator) { final String token = partition.getPartitionToken(); LOG.debug("[{}] Processing child partition record {}", token, record); final Timestamp startTimestamp = record.getStartTimestamp(); final Instant startInstant = new Instant(startTimestamp.toSqlTimestamp().getTime()); if (!tracker.tryClaim(startTimestamp)) { LOG.debug("[{}] Could not claim queryChangeStream({}), stopping", token, startTimestamp); return Optional.of(ProcessContinuation.stop()); } watermarkEstimator.setWatermark(startInstant); for (ChildPartition childPartition : record.getChildPartitions()) { processChildPartition(partition, record, childPartition); } LOG.debug("[{}] Child partitions action completed successfully", token); return Optional.empty(); }
@Test public void testRestrictionNotClaimed() { final String partitionToken = "partitionToken"; final Timestamp startTimestamp = Timestamp.ofTimeMicroseconds(10L); final PartitionMetadata partition = mock(PartitionMetadata.class); final ChildPartitionsRecord record = new ChildPartitionsRecord( startTimestamp, "recordSequence", Arrays.asList( new ChildPartition("childPartition1", partitionToken), new ChildPartition("childPartition2", partitionToken)), null); when(partition.getPartitionToken()).thenReturn(partitionToken); when(tracker.tryClaim(startTimestamp)).thenReturn(false); final Optional<ProcessContinuation> maybeContinuation = action.run(partition, record, tracker, watermarkEstimator); assertEquals(Optional.of(ProcessContinuation.stop()), maybeContinuation); verify(watermarkEstimator, never()).setWatermark(any()); verify(dao, never()).insert(any()); }
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call(configForEdit); config = preprocessAndValidate(configForEdit); return new GoConfigHolder(config, configForEdit); }
@Test void shouldThrowXsdValidationException_WhenNoRepository() { assertThatThrownBy(() -> xmlLoader.loadConfigHolder(configWithConfigRepos( """ <config-repos> <config-repo pluginId="myplugin"> </config-repo > </config-repos> """ ))).isInstanceOf(XsdValidationException.class); }
Map<Class, Object> getSerializers() { return serializers; }
@Test public void testLoad_withParametrizedConstructorAndCompatibilitySwitchOn() { String propName = "hazelcast.compat.serializers.use.default.constructor.only"; String origProperty = System.getProperty(propName); try { System.setProperty(propName, "true"); SerializerConfig serializerConfig = new SerializerConfig(); serializerConfig.setClassName("com.hazelcast.internal.serialization.impl.TestSerializerHook$TestSerializerWithTypeConstructor"); serializerConfig.setTypeClassName("com.hazelcast.internal.serialization.impl.SampleIdentifiedDataSerializable"); SerializationConfig serializationConfig = getConfig().getSerializationConfig(); serializationConfig.addSerializerConfig(serializerConfig); SerializerHookLoader hook = new SerializerHookLoader(serializationConfig, classLoader); Map<Class, Object> serializers = hook.getSerializers(); TestSerializerHook.TestSerializerWithTypeConstructor serializer = (TestSerializerHook.TestSerializerWithTypeConstructor) serializers.get(SampleIdentifiedDataSerializable.class); assertNull(serializer.getClazz()); } finally { if (origProperty != null) { System.setProperty(propName, origProperty); } else { System.clearProperty(propName); } } }
protected final void ensureCapacity(final int index, final int length) { if (index < 0 || length < 0) { throw new IndexOutOfBoundsException("negative value: index=" + index + " length=" + length); } final long resultingPosition = index + (long)length; if (resultingPosition > capacity) { if (resultingPosition > MAX_ARRAY_LENGTH) { throw new IndexOutOfBoundsException( "index=" + index + " length=" + length + " maxCapacity=" + MAX_ARRAY_LENGTH); } final int newCapacity = calculateExpansion(capacity, resultingPosition); byteArray = Arrays.copyOf(byteArray, newCapacity); capacity = newCapacity; } }
@Test void ensureCapacityThrowsIndexOutOfBoundsExceptionIfLengthIsNegative() { final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(1); final IndexOutOfBoundsException exception = assertThrowsExactly(IndexOutOfBoundsException.class, () -> buffer.ensureCapacity(8, -100)); assertEquals("negative value: index=8 length=-100", exception.getMessage()); }
public void pickSuggestionManually(int index, CharSequence suggestion) { pickSuggestionManually(index, suggestion, mAutoSpace); }
@Test public void testNextWordHappyPath() { mAnySoftKeyboardUnderTest.simulateTextTyping("hello face hello face hello face hello face "); mAnySoftKeyboardUnderTest.simulateTextTyping("hello "); verifySuggestions(true, "face"); mAnySoftKeyboardUnderTest.pickSuggestionManually(0, "face"); TestRxSchedulers.drainAllTasks(); Assert.assertEquals( "hello face hello face hello face hello face hello face ", getCurrentTestInputConnection().getCurrentTextInInputConnection()); verifySuggestions(true, "hello"); }
public static String encode(final String input) { try { final StringBuilder b = new StringBuilder(); final StringTokenizer t = new StringTokenizer(input, "/"); if(!t.hasMoreTokens()) { return input; } if(StringUtils.startsWith(input, String.valueOf(Path.DELIMITER))) { b.append(Path.DELIMITER); } while(t.hasMoreTokens()) { b.append(URLEncoder.encode(t.nextToken(), StandardCharsets.UTF_8.name())); if(t.hasMoreTokens()) { b.append(Path.DELIMITER); } } if(StringUtils.endsWith(input, String.valueOf(Path.DELIMITER))) { b.append(Path.DELIMITER); } // Because URLEncoder uses <code>application/x-www-form-urlencoded</code> we have to replace these // for proper URI percented encoding. return StringUtils.replaceEach(b.toString(), new String[]{"+", "*", "%7E", "%40"}, new String[]{"%20", "%2A", "~", "@"}); } catch(UnsupportedEncodingException e) { log.warn(String.format("Failure %s encoding input %s", e, input)); return input; } }
@Test public void testEncodeRelativeUri() { assertEquals("a/p", URIEncoder.encode("a/p")); assertEquals("a/p/", URIEncoder.encode("a/p/")); }
public MllpConfiguration getConfiguration() { return configuration; }
@Test public void testCreateEndpointWithDefaultConfigurations() { MllpEndpoint mllpEndpoint = new MllpEndpoint("mllp://dummy", new MllpComponent(), new MllpConfiguration()); assertEquals(5, mllpEndpoint.getConfiguration().getMaxConcurrentConsumers()); }
@Override public void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt) throws BackgroundException { try { for(Path file : files) { if(containerService.isContainer(file)) { session.getClient().purgeCDNContainer(regionService.lookup(containerService.getContainer(file)), container.getName(), null); } else { session.getClient().purgeCDNObject(regionService.lookup(containerService.getContainer(file)), container.getName(), containerService.getKey(file), null); } } } catch(GenericException e) { throw new SwiftExceptionMappingService().map("Cannot write CDN configuration", e); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Cannot write CDN configuration", e); } }
@Test(expected = InteroperabilityException.class) public void testInvalidateContainer() throws Exception { final SwiftDistributionPurgeFeature feature = new SwiftDistributionPurgeFeature(session); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.volume, Path.Type.directory)); container.attributes().setRegion("IAD"); feature.invalidate(container, Distribution.DOWNLOAD, Collections.singletonList(container), new DisabledLoginCallback()); }
void addGetModelForKieBaseMethod(StringBuilder sb) { sb.append( " public java.util.List<Model> getModelsForKieBase(String kieBaseName) {\n"); if (!modelMethod.getKieBaseNames().isEmpty()) { sb.append( " switch (kieBaseName) {\n"); for (String kBase : modelMethod.getKieBaseNames()) { sb.append(" case \"" + kBase + "\": "); List<String> models = modelsByKBase.get(kBase); String collected = null; if (models != null) { collected = models.stream() .map(element -> "new " + element + "()") .collect(Collectors.joining(",")); } sb.append(collected != null && !collected.isEmpty() ? "return java.util.Arrays.asList( " + collected + " );\n" : "return getModels();\n"); } sb.append(" }\n"); } sb.append( " throw new IllegalArgumentException(\"Unknown KieBase: \" + kieBaseName);\n" + " }\n" + "\n" ); }
@Test public void addGetModelForKieBaseMethodEmptyModelsByKBaseTest() { KieBaseModel kieBaseModel = getKieBaseModel("ModelTest"); Map<String, KieBaseModel> kBaseModels = new HashMap<>(); kBaseModels.put("default-kie", kieBaseModel); ModelSourceClass modelSourceClass = new ModelSourceClass(RELEASE_ID, kBaseModels, new HashMap<>()); StringBuilder sb = new StringBuilder(); modelSourceClass.addGetModelForKieBaseMethod(sb); String retrieved = sb.toString(); String expected = "switch (kieBaseName) {"; assertThat(retrieved.contains(expected)).isTrue(); expected = "case \"default-kie\": return getModels();"; assertThat(retrieved.contains(expected)).isTrue(); }
public FEELFnResult<TemporalAccessor> invoke(@ParameterName( "from" ) String val) { if ( val == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } if (!BEGIN_YEAR.matcher(val).find()) { // please notice the regex strictly requires the beginning, so we can use find. return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "year not compliant with XML Schema Part 2 Datatypes")); } try { return FEELFnResult.ofResult(LocalDate.from(FEEL_DATE.parse(val))); } catch (DateTimeException e) { return manageDateTimeException(e, val); } }
@Test void invokeParamYearMonthDayInvalidDate() { FunctionTestUtil.assertResultError(dateFunction.invoke(2017, 6, 59), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(2017, 59, 12), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(Integer.MAX_VALUE, 6, 12), InvalidParametersEvent.class); }
public static <T> Iterator<T> prepend(T prepend, @Nonnull Iterator<? extends T> iterator) { checkNotNull(iterator, "iterator cannot be null."); return new PrependIterator<>(prepend, iterator); }
@Test public void prependNullIterator() { assertThatThrownBy(() -> IterableUtil.prepend(null, null)) .isInstanceOf(NullPointerException.class) .hasMessage("iterator cannot be null."); }
public void initializeSession(AuthenticationRequest authenticationRequest, SAMLBindingContext bindingContext) throws SamlSessionException, SharedServiceClientException { final String httpSessionId = authenticationRequest.getRequest().getSession().getId(); if (authenticationRequest.getFederationName() != null) { findOrInitializeFederationSession(authenticationRequest, httpSessionId); } findOrInitializeSamlSession(authenticationRequest, httpSessionId, bindingContext); }
@Test public void forceLoginWhenMinimumAuthenticationLevelIsSubstantieelTest() throws SamlSessionException, SharedServiceClientException { FederationSession federationSession = new FederationSession(600); federationSession.setAuthLevel(25); authenticationRequest.setMinimumRequestedAuthLevel(25); authenticationRequest.setFederationName("federationName"); Optional<FederationSession> optionalFederationSession = Optional.of(federationSession); when(federationSessionRepositoryMock.findByHttpSessionIdAndFederationName(anyString(), anyString())).thenReturn(optionalFederationSession); when(sharedServiceClientMock.getSSConfigLong(anyString())).thenReturn(10L); samlSessionService.initializeSession(authenticationRequest, bindingContext); assertTrue(authenticationRequest.getAuthnRequest().isForceAuthn()); }
public static Optional<Object> getAdjacentValue(Type type, Object value, boolean isPrevious) { if (!type.isOrderable()) { throw new IllegalStateException("Type is not orderable: " + type); } requireNonNull(value, "value is null"); if (type.equals(BIGINT) || type instanceof TimestampType) { return getBigintAdjacentValue(value, isPrevious); } if (type.equals(INTEGER) || type.equals(DATE)) { return getIntegerAdjacentValue(value, isPrevious); } if (type.equals(SMALLINT)) { return getSmallIntAdjacentValue(value, isPrevious); } if (type.equals(TINYINT)) { return getTinyIntAdjacentValue(value, isPrevious); } if (type.equals(DOUBLE)) { return getDoubleAdjacentValue(value, isPrevious); } if (type.equals(REAL)) { return getRealAdjacentValue(value, isPrevious); } return Optional.empty(); }
@Test public void testNextValueForTinyInt() { long minValue = Byte.MIN_VALUE; long maxValue = Byte.MAX_VALUE; assertThat(getAdjacentValue(TINYINT, minValue, false)) .isEqualTo(Optional.of(minValue + 1)); assertThat(getAdjacentValue(TINYINT, minValue + 1, false)) .isEqualTo(Optional.of(minValue + 2)); assertThat(getAdjacentValue(TINYINT, 123L, false)) .isEqualTo(Optional.of(124L)); assertThat(getAdjacentValue(TINYINT, maxValue - 1, false)) .isEqualTo(Optional.of(maxValue)); assertThat(getAdjacentValue(TINYINT, maxValue, false)) .isEqualTo(Optional.empty()); }
protected String getHttpURL(Exchange exchange, Endpoint endpoint) { Object url = exchange.getIn().getHeader(Exchange.HTTP_URL); if (url instanceof String) { return (String) url; } else { Object uri = exchange.getIn().getHeader(Exchange.HTTP_URI); if (uri instanceof String) { return (String) uri; } else { // Try to obtain from endpoint int index = endpoint.getEndpointUri().lastIndexOf("http:"); if (index != -1) { return endpoint.getEndpointUri().substring(index); } } } return null; }
@Test public void testGetHttpURLFromEndpointUri() { Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpointUri()).thenReturn(TEST_URI); Mockito.when(exchange.getIn()).thenReturn(message); AbstractHttpSpanDecorator decorator = new AbstractHttpSpanDecorator() { @Override public String getComponent() { return null; } @Override public String getComponentClassName() { return null; } }; assertEquals(TEST_URI, decorator.getHttpURL(exchange, endpoint)); }
public void deleteBoardById(final Long boardId, final Long memberId) { Board board = findBoard(boardId); board.validateWriter(memberId); boardRepository.deleteByBoardId(boardId); imageUploader.delete(board.getImages()); Events.raise(new BoardDeletedEvent(boardId)); }
@Test void ๊ฒŒ์‹œ๊ธ€_์ฃผ์ธ์ด_๋‹ค๋ฅด๋‹ค๋ฉด_์‚ญ์ œํ•˜์ง€_๋ชปํ•œ๋‹ค() { // given Board savedBoard = boardRepository.save(๊ฒŒ์‹œ๊ธ€_์ƒ์„ฑ_์‚ฌ์ง„์—†์Œ()); // when & then assertThatThrownBy(() -> boardService.deleteBoardById(savedBoard.getId(), savedBoard.getWriterId() + 1)) .isInstanceOf(WriterNotEqualsException.class); }
@Override public String toString() { return "Counter{value=" + value + '}'; }
@Test public void test_toString() { String s = counter.toString(); assertEquals("Counter{value=0}", s); }
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentImportExecutor, TokensAndUrlAuthData authData, MusicContainerResource data) throws Exception { if (data == null) { // Nothing to do return new ImportResult(new AppleContentException("Null MusicContainerResource received on AppleMusicImporter::importItem")); } int playlistsCount = 0; int playlistItemsCount = 0; AppleMusicInterface musicInterface = factory .getOrCreateMusicInterface(jobId, authData, appCredentials, exportingService, monitor); if (!data.getPlaylists().isEmpty()) { playlistsCount = musicInterface.importPlaylists(jobId, idempotentImportExecutor, data.getPlaylists()); } if (!data.getPlaylistItems().isEmpty()) { playlistItemsCount = musicInterface.importMusicPlaylistItems(jobId, idempotentImportExecutor, data.getPlaylistItems()); } final Map<String, Integer> counts = new ImmutableMap.Builder<String, Integer>() .put(AppleMusicConstants.PLAYLISTS_COUNT_DATA_NAME, playlistsCount) .put(AppleMusicConstants.PLAYLIST_ITEMS_COUNT_DATA_NAME, playlistItemsCount) .build(); return ImportResult.OK .copyWithCounts(counts); }
@Test public void importTwoPlaylistItemsInDifferentPlaylists() throws Exception { MusicPlaylistItem item1 = createTestPlaylistItem(randomString(), 1); MusicPlaylistItem item2 = createTestPlaylistItem(randomString(), 1); List<MusicPlaylistItem> musicPlaylistItems = List.of(item1, item2); setUpImportPlaylistTracksBatchResponse(musicPlaylistItems.stream().collect( Collectors.toMap(item -> item.getTrack().getIsrcCode(), item -> SC_OK))); MusicContainerResource itemsResource = new MusicContainerResource(null, musicPlaylistItems, null, null); final ImportResult importResult = appleMusicImporter.importItem(uuid, executor, authData, itemsResource); verify(appleMusicInterface) .importMusicPlaylistItemsBatch(uuid.toString(), musicPlaylistItems); assertThat(executor.getErrors()).isEmpty(); assertThat(importResult.getCounts().isPresent()); assertThat(importResult.getCounts().get().get(AppleMusicConstants.PLAYLIST_ITEMS_COUNT_DATA_NAME) == itemsResource.getPlaylistItems().size()); assertThat(importResult.getCounts().get().get(AppleMusicConstants.PLAYLISTS_COUNT_DATA_NAME) == 0); }
public Map<String, Parameter> getAllParams( Step stepDefinition, WorkflowSummary workflowSummary, StepRuntimeSummary runtimeSummary) { return paramsManager.generateMergedStepParams( workflowSummary, stepDefinition, getStepRuntime(stepDefinition.getType()), runtimeSummary); }
@Test public void testMergeNestedStringMap() { when(this.defaultParamManager.getDefaultStepParams()) .thenReturn( ImmutableMap.of( "nested-default-new", StringMapParamDefinition.builder() .name("nested-default-new") .value(singletonMap("default-new", "from-default")) .build(), "nested-common", StringMapParamDefinition.builder() .name("nested-common") .value( twoItemMap( "default-param", "from-default", "common-param", "from-default")) .build(), "foo", ParamDefinition.buildParamDefinition("foo", "some-default"), "test-param", ParamDefinition.buildParamDefinition("test-param", "some-other-default"))); TypedStep testStep = new TypedStep(); testStep.setParams( ImmutableMap.of( "nested-step-new", StringMapParamDefinition.builder() .name("nested-step-new") .value(singletonMap("step-new", "from-step")) .build(), "nested-common", StringMapParamDefinition.builder() .name("nested-common") .value( twoItemMap( "step-param", "from-step", "common-param", "from-step")) .build(), "foo", ParamDefinition.buildParamDefinition("foo", "bar"), "test-param", ParamDefinition.buildParamDefinition("test-param", "hello"))); testStep.setType(StepType.NOOP); testStep.setId("step1"); Map<String, Parameter> params = runtimeManager.getAllParams(testStep, workflowSummary, runtimeSummary); assertEquals("bar", params.get("foo").getValue()); assertEquals("hello", params.get("test-param").getValue()); assertEquals( "from-step", params.get("nested-step-new").asStringMapParam().getValue().get("step-new")); assertEquals( "from-default", params.get("nested-default-new").asStringMapParam().getValue().get("default-new")); assertEquals( "from-default", params.get("nested-common").asStringMapParam().getValue().get("default-param")); assertEquals( "from-step", params.get("nested-common").asStringMapParam().getValue().get("step-param")); assertEquals( "from-step", params.get("nested-common").asStringMapParam().getValue().get("common-param")); }
@Override public YamlProcess swapToYamlConfiguration(final Process data) { YamlProcess result = new YamlProcess(); result.setId(data.getId()); result.setStartMillis(data.getStartMillis()); result.setSql(data.getSql()); result.setDatabaseName(data.getDatabaseName()); result.setUsername(data.getUsername()); result.setHostname(data.getHostname()); result.setTotalUnitCount(data.getTotalUnitCount().get()); result.setCompletedUnitCount(data.getCompletedUnitCount().get()); result.setIdle(data.isIdle()); result.setInterrupted(data.isInterrupted()); return result; }
@Test void assertSwapToYamlConfiguration() { String processId = new UUID(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()).toString().replace("-", ""); ExecutionGroupReportContext reportContext = new ExecutionGroupReportContext(processId, "foo_db", new Grantee("root", "localhost")); ExecutionGroupContext<? extends SQLExecutionUnit> executionGroupContext = new ExecutionGroupContext<>(Collections.emptyList(), reportContext); Process process = new Process("SELECT 1", executionGroupContext); YamlProcess actual = new YamlProcessSwapper().swapToYamlConfiguration(process); assertNotNull(actual.getId()); assertThat(actual.getStartMillis(), lessThanOrEqualTo(System.currentTimeMillis())); assertThat(actual.getSql(), is("SELECT 1")); assertThat(actual.getDatabaseName(), is("foo_db")); assertThat(actual.getUsername(), is("root")); assertThat(actual.getHostname(), is("localhost")); assertThat(actual.getCompletedUnitCount(), is(0)); assertThat(actual.getTotalUnitCount(), is(0)); assertFalse(actual.isIdle()); }
public static boolean isStorage(ServiceCluster cluster) { return ServiceType.STORAGE.equals(cluster.serviceType()); }
@Test public void verifyNonStorageClusterIsNotRecognized() { ServiceCluster cluster = createServiceCluster(new ServiceType("foo")); assertFalse(VespaModelUtil.isStorage(cluster)); }
public DateTimeStamp add(double offsetInDecimalSeconds) { if (Double.isNaN(offsetInDecimalSeconds)) throw new IllegalArgumentException("Cannot add " + Double.NaN); double adjustedTimeStamp = Double.NaN; ZonedDateTime adjustedDateStamp = null; if ( hasTimeStamp()) { adjustedTimeStamp = getTimeStamp() + offsetInDecimalSeconds; } if (hasDateStamp()) { double offset = (Double.isNaN(offsetInDecimalSeconds)) ? 0.000d : offsetInDecimalSeconds; int seconds = (int) offset; long nanos = ((long) ((offset % 1) * 1_000L)) * 1_000_000L; adjustedDateStamp = dateTime.plusSeconds(seconds).plusNanos(nanos); } return new DateTimeStamp(adjustedDateStamp, adjustedTimeStamp); }
@Test void add() { DateTimeStamp a = new DateTimeStamp(.586); double a_ts = a.getTimeStamp(); ZonedDateTime a_dt = a.getDateTime(); DateTimeStamp b = new DateTimeStamp(.586 + .587); assertEquals(b.getTimeStamp(), a.add(.587).getTimeStamp(), .001); assertEquals(a_ts, a.getTimeStamp(), .001); // test that a is unmodified assertEquals(a_dt, a.getDateTime()); // test that a is unmodified a = new DateTimeStamp("2018-04-04T09:10:00.586-0100"); a_ts = a.getTimeStamp(); a_dt = a.getDateTime(); b = new DateTimeStamp("2018-04-04T09:10:01.173-0100"); assertEquals(b.getDateTime(), a.add(.587).getDateTime()); assertEquals(a_ts, a.getTimeStamp(), .001); // test that a is unmodified assertEquals(a_dt, a.getDateTime()); // test that a is unmodified a = new DateTimeStamp("2018-04-04T09:10:00.586-0100", 0.18); a_ts = a.getTimeStamp(); a_dt = a.getDateTime(); b = new DateTimeStamp("2018-04-04T09:10:01.173-0100", 0.18 + .587); DateTimeStamp c = a.add(.587); assertEquals(b.getDateTime(), c.getDateTime()); assertEquals(b.getTimeStamp(), c.getTimeStamp(), 0.001); assertEquals(a_ts, a.getTimeStamp(), .001); // test that a is unmodified assertEquals(a_dt, a.getDateTime()); // test that a is unmodified }
@Override public Object evaluateLiteralExpression(String rawExpression, String className, List<String> genericClasses) { Object expressionResult = compileAndExecute(rawExpression, new HashMap<>()); Class<Object> requiredClass = loadClass(className, classLoader); if (expressionResult != null && !requiredClass.isAssignableFrom(expressionResult.getClass())) { throw new IllegalArgumentException("Cannot assign a '" + expressionResult.getClass().getCanonicalName() + "' to '" + requiredClass.getCanonicalName() + "'"); } return expressionResult; }
@Test public void evaluateLiteralExpression_many() { assertThat(evaluateLiteralExpression("1", Integer.class)).isEqualTo(1); assertThat(evaluateLiteralExpression("\"Value\"", String.class)).isEqualTo("Value"); assertThat(evaluateLiteralExpression("2 * 3", Integer.class)).isEqualTo(6); assertThat(evaluateLiteralExpression("-1 + (3 * 5)", Integer.class)).isEqualTo(14); assertThat(evaluateLiteralExpression("[\"Jim\"]", ArrayList.class)).isEqualTo(List.of("Jim")); assertThat(evaluateLiteralExpression("[]", ArrayList.class)).isEqualTo(List.of()); assertThat(evaluateLiteralExpression("\"abc..\"[2]", Character.class)).isEqualTo('c'); assertThat(evaluateLiteralExpression("1.234B", BigDecimal.class)).isEqualTo(new BigDecimal("1.234")); assertThat(evaluateLiteralExpression("1.234d", Double.class)).isEqualTo(Double.valueOf("1.234")); assertThat(evaluateLiteralExpression("\"Value\"", String.class)).isEqualTo("Value"); assertThat(evaluateLiteralExpression("a = 1; b = 2; a+b;", Integer.class)).isEqualTo(3); assertThat(evaluateLiteralExpression("a = \"Te\"; b = \"st\"; a+b;", String.class)).isEqualTo("Test"); assertThatThrownBy(() -> evaluateLiteralExpression("a = 1 b = 2 a+b;", Integer.class)) .isInstanceOf(CompileException.class); assertThatThrownBy(() -> evaluateLiteralExpression("a = 1; a+b;", Integer.class)) .isInstanceOf(CompileException.class); assertThat(evaluateLiteralExpression("a = \"Bob\";\n" + "test = new java.util.ArrayList();\n" + "test.add(a);\n" + "test.add(\"Michael\");\n" + "test;", ArrayList.class)).isEqualTo(List.of("Bob", "Michael")); Map<String, String> expectedMap = Map.of("Jim", "Person"); assertThat(evaluateLiteralExpression("[\"Jim\" : \"Person\"]", HashMap.class)).isEqualTo(expectedMap); assertThat(evaluateLiteralExpression("a = \"Person\";\n" + "test = new java.util.HashMap();\n" + "test.put(\"Jim\", a);\n" + "test;", HashMap.class)).isEqualTo(expectedMap); assertThat(evaluateLiteralExpression("a = \"Person\";test = new java.util.HashMap();test.put(\"Jim\", a);test;", HashMap.class)).isEqualTo(expectedMap); assertThat(evaluateLiteralExpression("a = \"Person\";\n" + "test = new java.util.HashMap();\n" + "test.put(\"Jim\", a);\n" + "test;\n" + "test.clear();\n" + "test;", HashMap.class)).isEqualTo(Map.of()); assertThatThrownBy(() -> evaluateLiteralExpression("1+", String.class)).isInstanceOf(RuntimeException.class); assertThatThrownBy(() -> evaluateLiteralExpression("1", String.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Cannot assign a 'java.lang.Integer"); }
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat( String groupId, String memberId, int memberEpoch, String instanceId, String rackId, int rebalanceTimeoutMs, String clientId, String clientHost, List<String> subscribedTopicNames, String assignorName, List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions ) throws ApiException { final long currentTimeMs = time.milliseconds(); final List<CoordinatorRecord> records = new ArrayList<>(); // Get or create the consumer group. boolean createIfNotExists = memberEpoch == 0; final ConsumerGroup group = getOrMaybeCreateConsumerGroup(groupId, createIfNotExists, records); throwIfConsumerGroupIsFull(group, memberId); // Get or create the member. if (memberId.isEmpty()) memberId = Uuid.randomUuid().toString(); final ConsumerGroupMember member; if (instanceId == null) { member = getOrMaybeSubscribeDynamicConsumerGroupMember( group, memberId, memberEpoch, ownedTopicPartitions, createIfNotExists, false ); } else { member = getOrMaybeSubscribeStaticConsumerGroupMember( group, memberId, memberEpoch, instanceId, ownedTopicPartitions, createIfNotExists, false, records ); } // 1. Create or update the member. If the member is new or has changed, a ConsumerGroupMemberMetadataValue // record is written to the __consumer_offsets partition to persist the change. If the subscriptions have // changed, the subscription metadata is updated and persisted by writing a ConsumerGroupPartitionMetadataValue // record to the __consumer_offsets partition. Finally, the group epoch is bumped if the subscriptions have // changed, and persisted by writing a ConsumerGroupMetadataValue record to the partition. ConsumerGroupMember updatedMember = new ConsumerGroupMember.Builder(member) .maybeUpdateInstanceId(Optional.ofNullable(instanceId)) .maybeUpdateRackId(Optional.ofNullable(rackId)) .maybeUpdateRebalanceTimeoutMs(ofSentinel(rebalanceTimeoutMs)) .maybeUpdateServerAssignorName(Optional.ofNullable(assignorName)) .maybeUpdateSubscribedTopicNames(Optional.ofNullable(subscribedTopicNames)) .setClientId(clientId) .setClientHost(clientHost) .setClassicMemberMetadata(null) .build(); boolean bumpGroupEpoch = hasMemberSubscriptionChanged( groupId, member, updatedMember, records ); int groupEpoch = group.groupEpoch(); Map<String, TopicMetadata> subscriptionMetadata = group.subscriptionMetadata(); Map<String, Integer> subscribedTopicNamesMap = group.subscribedTopicNames(); SubscriptionType subscriptionType = group.subscriptionType(); if (bumpGroupEpoch || group.hasMetadataExpired(currentTimeMs)) { // The subscription metadata is updated in two cases: // 1) The member has updated its subscriptions; // 2) The refresh deadline has been reached. subscribedTopicNamesMap = group.computeSubscribedTopicNames(member, updatedMember); subscriptionMetadata = group.computeSubscriptionMetadata( subscribedTopicNamesMap, metadataImage.topics(), metadataImage.cluster() ); int numMembers = group.numMembers(); if (!group.hasMember(updatedMember.memberId()) && !group.hasStaticMember(updatedMember.instanceId())) { numMembers++; } subscriptionType = ModernGroup.subscriptionType( subscribedTopicNamesMap, numMembers ); if (!subscriptionMetadata.equals(group.subscriptionMetadata())) { log.info("[GroupId {}] Computed new subscription metadata: {}.", groupId, subscriptionMetadata); bumpGroupEpoch = true; records.add(newConsumerGroupSubscriptionMetadataRecord(groupId, subscriptionMetadata)); } if (bumpGroupEpoch) { groupEpoch += 1; records.add(newConsumerGroupEpochRecord(groupId, groupEpoch)); log.info("[GroupId {}] Bumped group epoch to {}.", groupId, groupEpoch); metrics.record(CONSUMER_GROUP_REBALANCES_SENSOR_NAME); } group.setMetadataRefreshDeadline(currentTimeMs + consumerGroupMetadataRefreshIntervalMs, groupEpoch); } // 2. Update the target assignment if the group epoch is larger than the target assignment epoch. The delta between // the existing and the new target assignment is persisted to the partition. final int targetAssignmentEpoch; final Assignment targetAssignment; if (groupEpoch > group.assignmentEpoch()) { targetAssignment = updateTargetAssignment( group, groupEpoch, member, updatedMember, subscriptionMetadata, subscriptionType, records ); targetAssignmentEpoch = groupEpoch; } else { targetAssignmentEpoch = group.assignmentEpoch(); targetAssignment = group.targetAssignment(updatedMember.memberId(), updatedMember.instanceId()); } // 3. Reconcile the member's assignment with the target assignment if the member is not // fully reconciled yet. updatedMember = maybeReconcile( groupId, updatedMember, group::currentPartitionEpoch, targetAssignmentEpoch, targetAssignment, ownedTopicPartitions, records ); scheduleConsumerGroupSessionTimeout(groupId, memberId); // Prepare the response. ConsumerGroupHeartbeatResponseData response = new ConsumerGroupHeartbeatResponseData() .setMemberId(updatedMember.memberId()) .setMemberEpoch(updatedMember.memberEpoch()) .setHeartbeatIntervalMs(consumerGroupHeartbeatIntervalMs(groupId)); // The assignment is only provided in the following cases: // 1. The member sent a full request. It does so when joining or rejoining the group with zero // as the member epoch; or on any errors (e.g. timeout). We use all the non-optional fields // (rebalanceTimeoutMs, subscribedTopicNames and ownedTopicPartitions) to detect a full request // as those must be set in a full request. // 2. The member's assignment has been updated. boolean isFullRequest = memberEpoch == 0 || (rebalanceTimeoutMs != -1 && subscribedTopicNames != null && ownedTopicPartitions != null); if (isFullRequest || hasAssignedPartitionsChanged(member, updatedMember)) { response.setAssignment(createConsumerGroupResponseAssignment(updatedMember)); } return new CoordinatorResult<>(records, response); }
@Test public void testConsumerHeartbeatRequestValidation() { MockPartitionAssignor assignor = new MockPartitionAssignor("range"); GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .withConsumerGroupAssignors(Collections.singletonList(assignor)) .build(); Exception ex; // GroupId must be present in all requests. ex = assertThrows(InvalidRequestException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData())); assertEquals("GroupId can't be empty.", ex.getMessage()); // GroupId can't be all whitespaces. ex = assertThrows(InvalidRequestException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId(" "))); assertEquals("GroupId can't be empty.", ex.getMessage()); // RebalanceTimeoutMs must be present in the first request (epoch == 0). ex = assertThrows(InvalidRequestException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId("foo") .setMemberEpoch(0))); assertEquals("RebalanceTimeoutMs must be provided in first request.", ex.getMessage()); // TopicPartitions must be present and empty in the first request (epoch == 0). ex = assertThrows(InvalidRequestException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId("foo") .setMemberEpoch(0) .setRebalanceTimeoutMs(5000))); assertEquals("TopicPartitions must be empty when (re-)joining.", ex.getMessage()); // SubscribedTopicNames must be present and empty in the first request (epoch == 0). ex = assertThrows(InvalidRequestException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId("foo") .setMemberEpoch(0) .setRebalanceTimeoutMs(5000) .setTopicPartitions(Collections.emptyList()))); assertEquals("SubscribedTopicNames must be set in first request.", ex.getMessage()); // MemberId must be non-empty in all requests except for the first one where it // could be empty (epoch != 0). ex = assertThrows(InvalidRequestException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId("foo") .setMemberEpoch(1))); assertEquals("MemberId can't be empty.", ex.getMessage()); // InstanceId must be non-empty if provided in all requests. ex = assertThrows(InvalidRequestException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId("foo") .setMemberId(Uuid.randomUuid().toString()) .setMemberEpoch(1) .setInstanceId(""))); assertEquals("InstanceId can't be empty.", ex.getMessage()); // RackId must be non-empty if provided in all requests. ex = assertThrows(InvalidRequestException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId("foo") .setMemberId(Uuid.randomUuid().toString()) .setMemberEpoch(1) .setRackId(""))); assertEquals("RackId can't be empty.", ex.getMessage()); // ServerAssignor must exist if provided in all requests. ex = assertThrows(UnsupportedAssignorException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId("foo") .setMemberId(Uuid.randomUuid().toString()) .setMemberEpoch(1) .setServerAssignor("bar"))); assertEquals("ServerAssignor bar is not supported. Supported assignors: range.", ex.getMessage()); ex = assertThrows(InvalidRequestException.class, () -> context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId("foo") .setMemberId(Uuid.randomUuid().toString()) .setMemberEpoch(LEAVE_GROUP_STATIC_MEMBER_EPOCH) .setRebalanceTimeoutMs(5000) .setSubscribedTopicNames(Arrays.asList("foo", "bar")) .setTopicPartitions(Collections.emptyList()))); assertEquals("InstanceId can't be null.", ex.getMessage()); }
@Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { if (tokenQueue.isNextTokenValue(tokenToMatch)) { matchedTokenList.add(tokenQueue.poll()); return true; } return false; }
@Test public void shouldMatch() { Token t1 = new Token("a", 1, 1); Token t2 = new Token("b", 2, 1); TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2))); List<Token> output = mock(List.class); ExactTokenMatcher matcher = new ExactTokenMatcher("a"); assertThat(matcher.matchToken(tokenQueue, output), is(true)); verify(tokenQueue).isNextTokenValue("a"); verify(tokenQueue).poll(); verifyNoMoreInteractions(tokenQueue); verify(output).add(t1); verifyNoMoreInteractions(output); }
public CompiledPipeline.CompiledExecution buildExecution() { return buildExecution(false); }
@SuppressWarnings({"unchecked"}) @Test public void buildsForkedPipeline() throws Exception { final ConfigVariableExpander cve = ConfigVariableExpander.withoutSecret(EnvironmentVariableProvider.defaultProvider()); final PipelineIR pipelineIR = ConfigCompiler.configToPipelineIR(IRHelpers.toSourceWithMetadata( "input {mockinput{}} filter { " + "if [foo] != \"bar\" { " + "mockfilter {} " + "mockaddfilter {} " + "if [foo] != \"bar\" { " + "mockfilter {} " + "}} " + "} output {mockoutput{} }"), false, cve); final JrubyEventExtLibrary.RubyEvent testEvent = JrubyEventExtLibrary.RubyEvent.newRubyEvent(RubyUtil.RUBY, new Event()); final Map<String, Supplier<IRubyObject>> filters = new HashMap<>(); filters.put("mockfilter", () -> IDENTITY_FILTER); filters.put("mockaddfilter", () -> ADD_FIELD_FILTER); new CompiledPipeline( pipelineIR, new CompiledPipelineTest.MockPluginFactory( Collections.singletonMap("mockinput", () -> null), filters, Collections.singletonMap("mockoutput", mockOutputSupplier()) ) ).buildExecution().compute(RubyUtil.RUBY.newArray(testEvent), false, false); final Collection<JrubyEventExtLibrary.RubyEvent> outputEvents = EVENT_SINKS.get(runId); MatcherAssert.assertThat(outputEvents.size(), CoreMatchers.is(1)); MatcherAssert.assertThat(outputEvents.contains(testEvent), CoreMatchers.is(true)); }
public void init(ScannerReportWriter writer) { File analysisLog = writer.getFileStructure().analysisLog(); try (BufferedWriter fileWriter = Files.newBufferedWriter(analysisLog.toPath(), StandardCharsets.UTF_8)) { writePlugins(fileWriter); writeBundledAnalyzers(fileWriter); writeGlobalSettings(fileWriter); writeProjectSettings(fileWriter); writeModulesSettings(fileWriter); } catch (IOException e) { throw new IllegalStateException("Unable to write analysis log", e); } }
@Test public void shouldOnlyDumpPluginsByDefault() throws Exception { when(pluginRepo.getExternalPluginsInfos()).thenReturn(singletonList(new PluginInfo("xoo").setName("Xoo").setVersion(Version.create("1.0")))); DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinition.create() .setBaseDir(temp.newFolder()) .setWorkDir(temp.newFolder())); when(store.allModules()).thenReturn(singletonList(rootModule)); when(hierarchy.root()).thenReturn(rootModule); publisher.init(writer); assertThat(writer.getFileStructure().analysisLog()).exists(); assertThat(FileUtils.readFileToString(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8)).contains("Xoo 1.0 (xoo)"); verifyNoInteractions(system2); }
@Override public List<ProductSpuDO> getSpuList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return Collections.emptyList(); } return productSpuMapper.selectBatchIds(ids); }
@Test void getSpuList() { // ๅ‡†ๅค‡ๅ‚ๆ•ฐ ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{ o.setCategoryId(generateId()); o.setBrandId(generateId()); o.setDeliveryTemplateId(generateId()); o.setSort(RandomUtil.randomInt(1,100)); // ้™ๅˆถๆŽ’ๅบ่Œƒๅ›ด o.setGiveIntegral(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setVirtualSalesCount(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setPrice(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setMarketPrice(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setCostPrice(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setStock(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setGiveIntegral(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setSalesCount(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setBrowseCount(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ }), randomPojo(ProductSpuDO.class,o->{ o.setCategoryId(generateId()); o.setBrandId(generateId()); o.setDeliveryTemplateId(generateId()); o.setSort(RandomUtil.randomInt(1,100)); // ้™ๅˆถๆŽ’ๅบ่Œƒๅ›ด o.setGiveIntegral(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setVirtualSalesCount(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setPrice(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setMarketPrice(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setCostPrice(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setStock(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setGiveIntegral(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setSalesCount(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ o.setBrowseCount(generaInt()); // ้™ๅˆถ่Œƒๅ›ดไธบๆญฃๆ•ดๆ•ฐ })); productSpuMapper.insertBatch(createReqVOs); // ่ฐƒ็”จ List<ProductSpuDO> spuList = productSpuService.getSpuList(createReqVOs.stream().map(ProductSpuDO::getId).collect(Collectors.toList())); Assertions.assertIterableEquals(createReqVOs, spuList); }
@Override public AuthorityRuleConfiguration swapToObject(final YamlAuthorityRuleConfiguration yamlConfig) { Collection<ShardingSphereUser> users = yamlConfig.getUsers().stream().map(userSwapper::swapToObject).collect(Collectors.toList()); AlgorithmConfiguration provider = algorithmSwapper.swapToObject(yamlConfig.getPrivilege()); if (null == provider) { provider = new DefaultAuthorityRuleConfigurationBuilder().build().getPrivilegeProvider(); } Map<String, AlgorithmConfiguration> authenticators = yamlConfig.getAuthenticators().entrySet().stream() .collect(Collectors.toMap(Entry::getKey, entry -> algorithmSwapper.swapToObject(entry.getValue()))); return new AuthorityRuleConfiguration(users, provider, authenticators, yamlConfig.getDefaultAuthenticator()); }
@Test void assertSwapToObjectWithDefaultProvider() { YamlAuthorityRuleConfiguration authorityRuleConfig = new YamlAuthorityRuleConfiguration(); authorityRuleConfig.setUsers(Collections.singletonList(getYamlUser())); AuthorityRuleConfiguration actual = swapper.swapToObject(authorityRuleConfig); assertThat(actual.getUsers().size(), is(1)); assertThat(actual.getPrivilegeProvider().getType(), is("ALL_PERMITTED")); assertThat(actual.getUsers().size(), is(1)); assertNull(actual.getDefaultAuthenticator()); assertTrue(actual.getAuthenticators().isEmpty()); }
@Override public ExecuteContext after(ExecuteContext context) { RocketMqPullConsumerController.removePullConsumer((DefaultLitePullConsumer) context.getObject()); if (handler != null) { handler.doAfter(context); } return context; }
@Test public void testAfter() { interceptor.after(context); Assert.assertEquals(RocketMqPullConsumerController.getPullConsumerCache().size(), 0); }
@Override public NullsOrderType getDefaultNullsOrderType() { return NullsOrderType.FIRST; }
@Test void assertGetDefaultNullsOrderType() { assertThat(dialectDatabaseMetaData.getDefaultNullsOrderType(), is(NullsOrderType.FIRST)); }
public static String getBaseName(String versionName) throws IOException { Objects.requireNonNull(versionName, "VersionName cannot be null"); int div = versionName.lastIndexOf('@'); if (div == -1) { throw new IOException("No version in key path " + versionName); } return versionName.substring(0, div); }
@Test public void testParseVersionName() throws Exception { assertEquals("/a/b", KeyProvider.getBaseName("/a/b@3")); assertEquals("/aaa", KeyProvider.getBaseName("/aaa@112")); try { KeyProvider.getBaseName("no-slashes"); assertTrue("should have thrown", false); } catch (IOException e) { assertTrue(true); } intercept(NullPointerException.class, () -> KeyProvider.getBaseName(null)); }
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { final Stacker contextStacker = buildContext.buildNodeContext(getId().toString()); return schemaKStreamFactory.create( buildContext, dataSource, contextStacker.push(SOURCE_OP_NAME) ); }
@Test public void shouldBeOfTypeSchemaKStreamWhenDataSourceIsKsqlStream() { // When: realStream = buildStream(node); // Then: assertThat(realStream.getClass(), equalTo(SchemaKStream.class)); }
public static boolean isCompositeURI(URI uri) { String ssp = stripPrefix(uri.getRawSchemeSpecificPart().trim(), "//").trim(); if (ssp.indexOf('(') == 0 && checkParenthesis(ssp)) { return true; } return false; }
@Test public void testIsCompositeURINoQueryNoSlashes() throws URISyntaxException { URI[] compositeURIs = new URI[] { new URI("test:(part1://host,part2://(sub1://part,sube2:part))"), new URI("test:(path)/path") }; for (URI uri : compositeURIs) { assertTrue(uri + " must be detected as composite URI", URISupport.isCompositeURI(uri)); } }
@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 ReadOnlyWindowStore<GenericKey, ValueAndTimestamp<GenericRow>> store = stateStore .store(QueryableStoreTypes.timestampedWindowStore(), partition); final Instant lower = calculateLowerBound(windowStartBounds, windowEndBounds); final Instant upper = calculateUpperBound(windowStartBounds, windowEndBounds); try (WindowStoreIterator<ValueAndTimestamp<GenericRow>> it = cacheBypassFetcher.fetch(store, key, lower, upper)) { final Builder<WindowedRow> builder = ImmutableList.builder(); while (it.hasNext()) { final KeyValue<Long, ValueAndTimestamp<GenericRow>> next = it.next(); final Instant windowStart = Instant.ofEpochMilli(next.key); if (!windowStartBounds.contains(windowStart)) { continue; } final Instant windowEnd = windowStart.plus(windowSize); if (!windowEndBounds.contains(windowEnd)) { continue; } final TimeWindow window = new TimeWindow(windowStart.toEpochMilli(), windowEnd.toEpochMilli()); final WindowedRow row = WindowedRow.of( stateStore.schema(), new Windowed<>(key, window), next.value.value(), next.value.timestamp() ); builder.add(row); } return KsMaterializedQueryResult.rowIterator(builder.build().iterator()); } } catch (final Exception e) { throw new MaterializationException("Failed to get value from materialized table", e); } }
@Test public void shouldThrowIfStoreFetchFails() { // Given: when(cacheBypassFetcher.fetch(any(), any(), any(), any())) .thenThrow(new MaterializationTimeOutException("Boom")); // When: final Exception e = assertThrows( MaterializationException.class, () -> table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS) ); // Then: assertThat(e.getMessage(), containsString( "Failed to get value from materialized table")); assertThat(e.getCause(), (instanceOf(MaterializationTimeOutException.class))); }
public static ExecutionEnvironment createBatchExecutionEnvironment(FlinkPipelineOptions options) { return createBatchExecutionEnvironment( options, MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()), options.getFlinkConfDir()); }
@Test public void shouldDetectMalformedPortBatch() { FlinkPipelineOptions options = getDefaultPipelineOptions(); options.setRunner(FlinkRunner.class); options.setFlinkMaster("host:p0rt"); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Unparseable port number"); FlinkExecutionEnvironments.createBatchExecutionEnvironment(options); }
@Override public void write(DataOutput out) throws IOException { String json = GsonUtils.GSON.toJson(this, OptimizeJobV2.class); Text.writeString(out, json); }
@Test public void testSerializeOfOptimizeJob() throws IOException { // prepare file File file = new File(TEST_FILE_NAME); file.createNewFile(); file.deleteOnExit(); DataOutputStream out = new DataOutputStream(new FileOutputStream(file)); OptimizeJobV2 optimizeJobV2 = new OptimizeJobV2(1, 1, 1, "test", 600000); Deencapsulation.setField(optimizeJobV2, "jobState", AlterJobV2.JobState.FINISHED); // write schema change job optimizeJobV2.write(out); out.flush(); out.close(); DataInputStream in = new DataInputStream(new FileInputStream(file)); OptimizeJobV2 result = (OptimizeJobV2) AlterJobV2.read(in); Assert.assertEquals(1, result.getJobId()); Assert.assertEquals(AlterJobV2.JobState.FINISHED, result.getJobState()); }
@Nullable public PasswordAlgorithm forPassword(String hashedPassword) { for (PasswordAlgorithm passwordAlgorithm : passwordAlgorithms.values()) { if (passwordAlgorithm.supports(hashedPassword)) return passwordAlgorithm; } return null; }
@Test public void testForPasswordShouldReturnNull() throws Exception { when(passwordAlgorithm1.supports(anyString())).thenReturn(false); when(passwordAlgorithm2.supports(anyString())).thenReturn(false); final PasswordAlgorithmFactory passwordAlgorithmFactory = new PasswordAlgorithmFactory(passwordAlgorithms, passwordAlgorithm2); assertThat(passwordAlgorithmFactory.forPassword("foobar")).isNull(); }
public Uuid directory(int replica) { for (int i = 0; i < replicas.length; i++) { if (replicas[i] == replica) { return directories[i]; } } throw new IllegalArgumentException("Replica " + replica + " is not assigned to this partition."); }
@Test public void testDirectories() { PartitionRegistration partitionRegistration = new PartitionRegistration.Builder(). setReplicas(new int[] {3, 2, 1}). setDirectories(new Uuid[]{ Uuid.fromString("FbRuu7CeQtq5YFreEzg16g"), Uuid.fromString("4rtHTelWSSStAFMODOg3cQ"), Uuid.fromString("Id1WXzHURROilVxZWJNZlw") }). setIsr(new int[] {1, 2, 3}).setLeader(1).setLeaderRecoveryState(LeaderRecoveryState.RECOVERED). setLeaderEpoch(100).setPartitionEpoch(200).build(); assertEquals(Uuid.fromString("Id1WXzHURROilVxZWJNZlw"), partitionRegistration.directory(1)); assertEquals(Uuid.fromString("4rtHTelWSSStAFMODOg3cQ"), partitionRegistration.directory(2)); assertEquals(Uuid.fromString("FbRuu7CeQtq5YFreEzg16g"), partitionRegistration.directory(3)); assertThrows(IllegalArgumentException.class, () -> partitionRegistration.directory(4)); }
public static <T> RestResponse<T> toRestResponse( final ResponseWithBody resp, final String path, final Function<ResponseWithBody, T> mapper ) { final int statusCode = resp.getResponse().statusCode(); return statusCode == OK.code() ? RestResponse.successful(statusCode, mapper.apply(resp)) : createErrorResponse(path, resp); }
@Test public void shouldCreateRestResponseFromUnknownResponse() { // Given: when(httpClientResponse.statusCode()).thenReturn(INTERNAL_SERVER_ERROR.code()); when(httpClientResponse.statusMessage()).thenReturn(ERROR_REASON); // When: final RestResponse<KsqlEntityList> restResponse = KsqlClientUtil.toRestResponse(response, PATH, mapper); // Then: assertThat("is erroneous", restResponse.isErroneous()); assertThat(restResponse.getStatusCode(), is(INTERNAL_SERVER_ERROR.code())); assertThat(restResponse.getErrorMessage().getMessage(), containsString("The server returned an unexpected error")); assertThat(restResponse.getErrorMessage().getMessage(), containsString(ERROR_REASON)); }
static void setTableInputInformation( TableInput.Builder tableInputBuilder, TableMetadata metadata) { setTableInputInformation(tableInputBuilder, metadata, null); }
@Test public void testSetTableDescription() { String tableDescription = "hello world!"; Map<String, String> tableProperties = ImmutableMap.<String, String>builder() .putAll((tableLocationProperties)) .put(IcebergToGlueConverter.GLUE_DESCRIPTION_KEY, tableDescription) .build(); TableInput.Builder actualTableInputBuilder = TableInput.builder(); Schema schema = new Schema(Types.NestedField.required(1, "x", Types.StringType.get(), "comment1")); TableMetadata tableMetadata = TableMetadata.newTableMetadata( schema, PartitionSpec.unpartitioned(), "s3://test", tableProperties); IcebergToGlueConverter.setTableInputInformation(actualTableInputBuilder, tableMetadata); TableInput actualTableInput = actualTableInputBuilder.build(); assertThat(actualTableInput.description()) .as("description should match") .isEqualTo(tableDescription); }
public XAConnectionFactory xaConnectionFactory(XAConnectionFactory xaConnectionFactory) { return TracingXAConnectionFactory.create(xaConnectionFactory, this); }
@Test void xaConnectionFactory_doesntDoubleWrap() { XAConnectionFactory wrapped = jmsTracing.xaConnectionFactory(mock(XAConnectionFactory.class)); assertThat(jmsTracing.xaConnectionFactory(wrapped)) .isSameAs(wrapped); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if(directory.isRoot()) { try { if(log.isDebugEnabled()) { log.debug("Attempt to list available shares"); } // An SRVSVC_HANDLE pointer that identifies the server. final RPCTransport transport = SMBTransportFactories.SRVSVC.getTransport(context); if(log.isDebugEnabled()) { log.debug(String.format("Obtained transport %s", transport)); } final ServerService lookup = new ServerService(transport); final List<NetShareInfo0> info = lookup.getShares0(); if(log.isDebugEnabled()) { log.debug(String.format("Retrieved share info %s", info)); } final AttributedList<Path> result = new AttributedList<>(); for(final String s : info.stream().map(NetShareInfo::getNetName).collect(Collectors.toSet())) { final Path share = new Path(s, EnumSet.of(AbstractPath.Type.directory, AbstractPath.Type.volume)); try { result.add(share.withAttributes(new SMBAttributesFinderFeature(session).find(share))); } catch(NotfoundException | AccessDeniedException | UnsupportedException e) { if(log.isWarnEnabled()) { log.warn(String.format("Skip unsupported share %s with failure %s", s, e)); } } listener.chunk(directory, result); } return result; } catch(SMB2Exception e) { if(log.isWarnEnabled()) { log.warn(String.format("Failure %s getting share info from server", e)); } final Credentials name = prompt.prompt(session.getHost(), LocaleFactory.localizedString("SMB Share"), LocaleFactory.localizedString("Enter the pathname to list:", "Goto"), new LoginOptions().icon(session.getHost().getProtocol().disk()).keychain(false) .passwordPlaceholder(LocaleFactory.localizedString("SMB Share")) .password(false)); if(log.isDebugEnabled()) { log.debug(String.format("Connect to share %s from user input", name.getPassword())); } final Path share = new Path(name.getPassword(), EnumSet.of(Path.Type.directory, Path.Type.volume)); final AttributedList<Path> result = new AttributedList<>(Collections.singleton(share.withAttributes(new SMBAttributesFinderFeature(session).find(share)))); listener.chunk(directory, result); return result; } catch(IOException e) { throw new SMBTransportExceptionMappingService().map("Cannot read container configuration", e); } } return new SMBListService(session).list(directory, listener); }
@Test public void testListAllShares() throws Exception { final Path root = Home.ROOT; final AttributedList<Path> result = session.getFeature(ListService.class)/*SMBRootListService*/.list(root, new DisabledListProgressListener()); for(Path f : result) { assertTrue(f.isVolume()); assertNotEquals(TransferStatus.UNKNOWN_LENGTH, f.attributes().getSize()); assertNotEquals(Quota.unknown, f.attributes().getQuota()); } session.close(); }
@Override public void execute(SensorContext context) { for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) { processFileHighlighting(file, context); } }
@Test public void testExecution() throws IOException { File symbol = new File(baseDir, "src/foo.xoo.highlighting"); FileUtils.write(symbol, "1:1:1:4:k\n2:7:2:10:cd\n\n#comment"); DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo") .setLanguage("xoo") .setModuleBaseDir(baseDir.toPath()) .initMetadata(" xoo\nazertyazer\nfoo") .build(); context.fileSystem().add(inputFile); sensor.execute(context); assertThat(context.highlightingTypeAt("foo:src/foo.xoo", 1, 2)).containsOnly(TypeOfText.KEYWORD); assertThat(context.highlightingTypeAt("foo:src/foo.xoo", 2, 8)).containsOnly(TypeOfText.COMMENT); }
@Override public String handlePlaceHolder() { return handlePlaceHolder(inlineExpression); }
@Test void assertHandlePlaceHolder() { String expectdString = "t_${[\"new${1+2}\"]}"; assertThat(createInlineExpressionParser("t_$->{[\"new$->{1+2}\"]}").handlePlaceHolder(), is(expectdString)); assertThat(createInlineExpressionParser("t_${[\"new$->{1+2}\"]}").handlePlaceHolder(), is(expectdString)); }
public static void validate(BugPattern pattern) throws ValidationException { if (pattern == null) { throw new ValidationException("No @BugPattern provided"); } // name must not contain spaces if (CharMatcher.whitespace().matchesAnyOf(pattern.name())) { throw new ValidationException("Name must not contain whitespace: " + pattern.name()); } // linkType must be consistent with link element. switch (pattern.linkType()) { case CUSTOM: if (pattern.link().isEmpty()) { throw new ValidationException("Expected a custom link but none was provided"); } break; case AUTOGENERATED: case NONE: if (!pattern.link().isEmpty()) { throw new ValidationException("Expected no custom link but found: " + pattern.link()); } break; } }
@Test public void linkTypeCustomAndIncludesLink() throws Exception { @BugPattern( name = "LinkTypeCustomAndIncludesLink", summary = "linkType custom and includes link", explanation = "linkType custom and includes link", severity = SeverityLevel.ERROR, linkType = LinkType.CUSTOM, link = "http://foo") final class BugPatternTestClass {} BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class); BugPatternValidator.validate(annotation); }
public JsonElement get() { if (!stack.isEmpty()) { throw new IllegalStateException("Expected one JSON element but was " + stack); } return product; }
@Test public void testEmptyWriter() { JsonTreeWriter writer = new JsonTreeWriter(); assertThat(writer.get()).isEqualTo(JsonNull.INSTANCE); }
@Deprecated public static GeoPoint fromIntString(final String s) { final int commaPos1 = s.indexOf(','); final int commaPos2 = s.indexOf(',', commaPos1 + 1); if (commaPos2 == -1) { return new GeoPoint( Integer.parseInt(s.substring(0, commaPos1)), Integer.parseInt(s.substring(commaPos1 + 1, s.length()))); } else { return new GeoPoint( Integer.parseInt(s.substring(0, commaPos1)), Integer.parseInt(s.substring(commaPos1 + 1, commaPos2)), Integer.parseInt(s.substring(commaPos2 + 1, s.length())) ); } }
@Test public void test_toFromString_withoutAltitude() { final GeoPoint in = new GeoPoint(52387524, 4891604); final GeoPoint out = GeoPoint.fromIntString("52387524,4891604"); assertEquals("toFromString without altitude", in, out); }
@ScalarOperator(CAST) @LiteralParameters("x") @SqlType("varchar(x)") public static Slice castToVarchar(@SqlType(StandardTypes.TINYINT) long value) { // todo optimize me return utf8Slice(String.valueOf(value)); }
@Test public void testCastToVarchar() { assertFunction("cast(TINYINT'37' as varchar)", VARCHAR, "37"); assertFunction("cast(TINYINT'17' as varchar)", VARCHAR, "17"); }
@Override public WebSocketExtensionData newRequestData() { return new WebSocketExtensionData( useWebkitExtensionName ? X_WEBKIT_DEFLATE_FRAME_EXTENSION : DEFLATE_FRAME_EXTENSION, Collections.<String, String>emptyMap()); }
@Test public void testDeflateFrameData() { DeflateFrameClientExtensionHandshaker handshaker = new DeflateFrameClientExtensionHandshaker(false); WebSocketExtensionData data = handshaker.newRequestData(); assertEquals(DEFLATE_FRAME_EXTENSION, data.name()); assertTrue(data.parameters().isEmpty()); }
public static Double getDouble(Object x) { if (x == null) { return null; } if (x instanceof Double) { return (Double) x; } if (x instanceof String) { String s = x.toString(); if (s == null || s.isEmpty()) { return null; } } /* * This is the last and probably expensive fallback. This should be avoided by * only passing in Doubles, Integers, Longs or stuff that can be parsed from it's String * representation. You might have to build cached objects that did a safe conversion * once for example. There is no way around for the actual values we compare if the * user sent them in as non-numerical type. */ return Doubles.tryParse(x.toString()); }
@Test public void testGetDouble() throws Exception { assertEquals(null, Tools.getDouble(null)); assertEquals(null, Tools.getDouble("")); assertEquals(0.0, Tools.getDouble(0), 0); assertEquals(1.0, Tools.getDouble(1), 0); assertEquals(1.42, Tools.getDouble(1.42), 0); assertEquals(9001.0, Tools.getDouble(9001), 0); assertEquals(9001.23, Tools.getDouble(9001.23), 0); assertEquals(1253453.0, Tools.getDouble((long) 1253453), 0); assertEquals(88.0, Tools.getDouble("88"), 0); assertEquals(1.42, Tools.getDouble("1.42"), 0); assertEquals(null, Tools.getDouble("lol NOT A NUMBER")); assertEquals(null, Tools.getDouble(new HashMap<String, String>())); assertEquals(42.23, Tools.getDouble(new Object() { @Override public String toString() { return "42.23"; } }), 0); }
public static String evaluate(final co.elastic.logstash.api.Event event, final String template) throws JsonProcessingException { if (event instanceof Event) { return evaluate((Event) event, template); } else { throw new IllegalStateException("Unknown event concrete class: " + event.getClass().getName()); } }
@Test public void TestEpoch() throws IOException { Event event = getTestEvent(); String path = "%{+%s}"; assertEquals("1443657600", StringInterpolation.evaluate(event, path)); }
public ConfigResponse getServerConfig(String dataId, String group, String tenant, long readTimeout, boolean notify) throws NacosException { if (StringUtils.isBlank(group)) { group = Constants.DEFAULT_GROUP; } return this.agent.queryConfig(dataId, group, tenant, readTimeout, notify); }
@Test void testGeConfigConfigConflict() throws NacosException { Properties prop = new Properties(); ServerListManager agent = Mockito.mock(ServerListManager.class); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); ClientWorker clientWorker = new ClientWorker(null, agent, nacosClientProperties); String dataId = "a"; String group = "b"; String tenant = "c"; ConfigQueryResponse configQueryResponse = new ConfigQueryResponse(); configQueryResponse.setErrorInfo(ConfigQueryResponse.CONFIG_QUERY_CONFLICT, "config is being modified"); Mockito.when(rpcClient.request(any(ConfigQueryRequest.class), anyLong())).thenReturn(configQueryResponse); try { clientWorker.getServerConfig(dataId, group, tenant, 100, true); fail(); } catch (NacosException e) { assertEquals(NacosException.CONFLICT, e.getErrCode()); } }
public static LookupDefaultSingleValue create(String valueString, LookupDefaultValue.Type valueType) { requireNonNull(valueString, "valueString cannot be null"); requireNonNull(valueType, "valueType cannot be null"); Object value; try { switch (valueType) { case STRING: value = valueString; break; case NUMBER: value = OBJECT_MAPPER.convertValue(valueString, Number.class); break; case BOOLEAN: value = Boolean.parseBoolean(valueString); break; case NULL: value = null; break; default: throw new IllegalArgumentException("Could not convert <" + valueString + "> to single value type <" + valueType + ">"); } } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Could not parse JSON "+ valueType.toString().toLowerCase(Locale.ENGLISH) + " value <" + valueString + ">", e); } return builder() .valueString(valueString) .valueType(valueType) .value(value) .build(); }
@Test public void createMultiObject() throws Exception { expectedException.expect(IllegalArgumentException.class); LookupDefaultSingleValue.create("{\"hello\":\"world\",\"number\":42}", LookupDefaultSingleValue.Type.OBJECT); }
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test public void testSimpleFunctionDecode() { Function function = new Function( "test", Collections.<Type>emptyList(), Collections.singletonList(new TypeReference<Uint>() {})); assertEquals( FunctionReturnDecoder.decode( "0x0000000000000000000000000000000000000000000000000000000000000037", function.getOutputParameters()), (Collections.singletonList(new Uint(BigInteger.valueOf(55))))); }
public FEELFnResult<TemporalAccessor> invoke(@ParameterName( "from" ) String val) { if ( val == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null")); } if (!BEGIN_YEAR.matcher(val).find()) { // please notice the regex strictly requires the beginning, so we can use find. return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "year not compliant with XML Schema Part 2 Datatypes")); } try { return FEELFnResult.ofResult(LocalDate.from(FEEL_DATE.parse(val))); } catch (DateTimeException e) { return manageDateTimeException(e, val); } }
@Test void invokeParamYearMonthDayNulls() { FunctionTestUtil.assertResultError(dateFunction.invoke(null, null, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(10, null, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(null, 10, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(null, null, 10), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(10, 10, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(10, null, 10), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(dateFunction.invoke(null, 10, 10), InvalidParametersEvent.class); }
@Override public boolean open(final String url) { // Only print out URL console.printf("%n%s", url); return true; }
@Test public void open() { assertTrue(new TerminalBrowserLauncher().open("https://cyberduck.io")); }
@Override public void writeInt(final int v) throws IOException { ensureAvailable(INT_SIZE_IN_BYTES); MEM.putInt(buffer, ARRAY_BYTE_BASE_OFFSET + pos, v); pos += INT_SIZE_IN_BYTES; }
@Test(expected = IllegalArgumentException.class) public void testCheckAvailable_negativePos() throws Exception { out.writeInt(-1, 1); }
public static InetAddress getLocalAddress() { return getLocalAddress(null); }
@Test public void testGetLocalAddress() { InetAddress address = NetUtils.getLocalAddress(); Assert.assertNotNull(address); Assert.assertTrue(NetUtils.isValidAddress(address)); try { if(NetUtils.isValidAddress(InetAddress.getLocalHost())){ Assert.assertEquals(InetAddress.getLocalHost(), address); } } catch (UnknownHostException e) { e.printStackTrace(); } }
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromString(source); FEEL_1_1Lexer lexer = new FEEL_1_1Lexer( input ); CommonTokenStream tokens = new CommonTokenStream( lexer ); FEEL_1_1Parser parser = new FEEL_1_1Parser( tokens ); ParserHelper parserHelper = new ParserHelper(eventsManager); additionalFunctions.forEach(f -> parserHelper.getSymbolTable().getBuiltInScope().define(f.getSymbol())); parser.setHelper(parserHelper); parser.setErrorHandler( new FEELErrorHandler() ); parser.removeErrorListeners(); // removes the error listener that prints to the console parser.addErrorListener( new FEELParserErrorListener( eventsManager ) ); // pre-loads the parser with symbols defineVariables( inputVariableTypes, inputVariables, parser ); if (typeRegistry != null) { parserHelper.setTypeRegistry(typeRegistry); } return parser; }
@Test void inUnaryTestStrings() { final String inputExpression = "name in [\"A\"..\"Z...\")"; final BaseNode inNode = parse( inputExpression ); assertThat( inNode).isInstanceOf(InNode.class); assertThat( inNode.getResultType()).isEqualTo(BuiltInType.BOOLEAN); assertThat( inNode.getText()).isEqualTo(inputExpression); final InNode in = (InNode) inNode; assertThat( in.getExprs()).isInstanceOf(RangeNode.class); final RangeNode range = (RangeNode) in.getExprs(); assertThat( range.getStart().getText()).isEqualTo( "\"A\""); assertThat( range.getEnd().getText()).isEqualTo( "\"Z...\""); }
public static SqlDecimal widen(final SqlType t0, final SqlType t1) { final SqlDecimal lDecimal = DecimalUtil.toSqlDecimal(t0); final SqlDecimal rDecimal = DecimalUtil.toSqlDecimal(t1); final int wholePrecision = Math.max( lDecimal.getPrecision() - lDecimal.getScale(), rDecimal.getPrecision() - rDecimal.getScale() ); final int scale = Math.max(lDecimal.getScale(), rDecimal.getScale()); return SqlTypes.decimal(wholePrecision + scale, scale); }
@Test public void shouldWidenIntAndLong() { assertThat( DecimalUtil.widen(SqlTypes.BIGINT, SqlTypes.INTEGER), is(SqlTypes.BIGINT_UPCAST_TO_DECIMAL) ); assertThat( DecimalUtil.widen(SqlTypes.INTEGER, SqlTypes.BIGINT), is(SqlTypes.BIGINT_UPCAST_TO_DECIMAL) ); }
protected static void initAndStartAppMaster(final MRAppMaster appMaster, final JobConf conf, String jobUserName) throws IOException, InterruptedException { UserGroupInformation.setConfiguration(conf); // MAPREDUCE-6565: need to set configuration for SecurityUtil. SecurityUtil.setConfiguration(conf); // Security framework already loaded the tokens into current UGI, just use // them Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials(); LOG.info("Executing with tokens: {}", credentials.getAllTokens()); UserGroupInformation appMasterUgi = UserGroupInformation .createRemoteUser(jobUserName); appMasterUgi.addCredentials(credentials); // Now remove the AM->RM token so tasks don't have it Iterator<Token<?>> iter = credentials.getAllTokens().iterator(); while (iter.hasNext()) { Token<?> token = iter.next(); if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) { iter.remove(); } } conf.getCredentials().addAll(credentials); appMasterUgi.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { appMaster.init(conf); appMaster.start(); if(appMaster.errorHappenedShutDown) { throw new IOException("Was asked to shut down."); } return null; } }); }
@Test public void testMRAppMasterForDifferentUser() throws IOException, InterruptedException { String applicationAttemptIdStr = "appattempt_1317529182569_0004_000001"; String containerIdStr = "container_1317529182569_0004_000001_1"; String userName = "TestAppMasterUser"; ApplicationAttemptId applicationAttemptId = ApplicationAttemptId.fromString( applicationAttemptIdStr); ContainerId containerId = ContainerId.fromString(containerIdStr); MRAppMasterTest appMaster = new MRAppMasterTest(applicationAttemptId, containerId, "host", -1, -1, System.currentTimeMillis()); JobConf conf = new JobConf(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, stagingDir); MRAppMaster.initAndStartAppMaster(appMaster, conf, userName); Path userPath = new Path(stagingDir, userName); Path userStagingPath = new Path(userPath, ".staging"); assertEquals(userStagingPath.toString(), appMaster.stagingDirPath.toString()); }
public static boolean shouldEnablePushdownForTable(ConnectorSession session, Table table, String path, Optional<Partition> optionalPartition) { if (!isS3SelectPushdownEnabled(session)) { return false; } if (path == null) { return false; } // Hive table partitions could be on different storages, // as a result, we have to check each individual optionalPartition Properties schema = optionalPartition .map(partition -> getHiveSchema(partition, table)) .orElseGet(() -> getHiveSchema(table)); return shouldEnablePushdownForTable(table, path, schema); }
@Test public void testShouldNotEnableSelectPushdownWhenInputFormatIsNotSupported() { Storage newStorage = Storage.builder() .setStorageFormat(StorageFormat.create(LazySimpleSerDe.class.getName(), "inputFormat", "outputFormat")) .setLocation("location") .build(); Table newTable = new Table( "db", "table", "owner", EXTERNAL_TABLE, newStorage, singletonList(column), emptyList(), emptyMap(), Optional.empty(), Optional.empty()); assertFalse(shouldEnablePushdownForTable(session, newTable, "s3://fakeBucket/fakeObject", Optional.empty())); }
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { if(containerService.isContainer(folder)) { final B2BucketResponse response = session.getClient().createBucket(containerService.getContainer(folder).getName(), null == status.getRegion() ? BucketType.valueOf(new B2BucketTypeFeature(session, fileid).getDefault().getIdentifier()) : BucketType.valueOf(status.getRegion())); final EnumSet<Path.Type> type = EnumSet.copyOf(folder.getType()); type.add(Path.Type.volume); return folder.withType(type).withAttributes(new B2AttributesFinderFeature(session, fileid).toAttributes(response)); } else { final EnumSet<Path.Type> type = EnumSet.copyOf(folder.getType()); type.add(Path.Type.placeholder); return new B2TouchFeature(session, fileid).touch(folder.withType(type), status .withMime(MimeTypeService.DEFAULT_CONTENT_TYPE) .withChecksum(writer.checksum(folder, status).compute(new NullInputStream(0L), status))); } } catch(B2ApiException e) { throw new B2ExceptionMappingService(fileid).map("Cannot create folder {0}", e, folder); } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Cannot create folder {0}", e, folder); } }
@Test public void testModificationDate() throws Exception { final Path bucket = new Path("/test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final TransferStatus status = new TransferStatus(); final long timestamp = 1509959502930L; status.setModified(timestamp); final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path directory = new B2DirectoryFeature(session, fileid, new B2WriteFeature(session, fileid)).mkdir( new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), status); assertEquals(timestamp, new B2AttributesFinderFeature(session, fileid).find(directory).getModificationDate()); new B2DeleteFeature(session, fileid).delete(Collections.singletonList(directory), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public long encode(int x, int y) { int EIGHTBITMASK = 0xff; return (MortonTable256[(y >> 8) & EIGHTBITMASK] << 17 | MortonTable256[(x >> 8) & EIGHTBITMASK] << 16 | MortonTable256[y & EIGHTBITMASK] << 1 | MortonTable256[x & EIGHTBITMASK]); }
@Test public void testEncode() { SpatialKeyAlgo algo = new SpatialKeyAlgo(32, new BBox(-180, 180, -90, 90)); long val = algo.encodeLatLon(-24.235345f, 47.234234f); assertEquals("01100110101000111100000110010100", BitUtil.LITTLE.toLastBitString(val, 32)); }
@GET @Operation(summary = "List all active connectors") public Response listConnectors( final @Context UriInfo uriInfo, final @Context HttpHeaders headers ) { if (uriInfo.getQueryParameters().containsKey("expand")) { Map<String, Map<String, Object>> out = new HashMap<>(); for (String connector : herder.connectors()) { try { Map<String, Object> connectorExpansions = new HashMap<>(); for (String expansion : uriInfo.getQueryParameters().get("expand")) { switch (expansion) { case "status": connectorExpansions.put("status", herder.connectorStatus(connector)); break; case "info": connectorExpansions.put("info", herder.connectorInfo(connector)); break; default: log.info("Ignoring unknown expansion type {}", expansion); } } out.put(connector, connectorExpansions); } catch (NotFoundException e) { // this likely means that a connector has been removed while we look its info up // we can just not include this connector in the return entity log.debug("Unable to get connector info for {} on this worker", connector); } } return Response.ok(out).build(); } else { return Response.ok(herder.connectors()).build(); } }
@Test public void testExpandConnectorsStatus() { when(herder.connectors()).thenReturn(Arrays.asList(CONNECTOR2_NAME, CONNECTOR_NAME)); ConnectorStateInfo connector = mock(ConnectorStateInfo.class); ConnectorStateInfo connector2 = mock(ConnectorStateInfo.class); when(herder.connectorStatus(CONNECTOR2_NAME)).thenReturn(connector2); when(herder.connectorStatus(CONNECTOR_NAME)).thenReturn(connector); forward = mock(UriInfo.class); MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>(); queryParams.putSingle("expand", "status"); when(forward.getQueryParameters()).thenReturn(queryParams); Map<String, Map<String, Object>> expanded = (Map<String, Map<String, Object>>) connectorsResource.listConnectors(forward, NULL_HEADERS).getEntity(); // Ordering isn't guaranteed, compare sets assertEquals(new HashSet<>(Arrays.asList(CONNECTOR_NAME, CONNECTOR2_NAME)), expanded.keySet()); assertEquals(connector2, expanded.get(CONNECTOR2_NAME).get("status")); assertEquals(connector, expanded.get(CONNECTOR_NAME).get("status")); }
public void isInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (actual == null) { failWithActual("expected instance of", clazz.getName()); return; } if (!isInstanceOfType(actual, clazz)) { if (Platform.classMetadataUnsupported()) { throw new UnsupportedOperationException( actualCustomStringRepresentation() + ", an instance of " + actual.getClass().getName() + ", may or may not be an instance of " + clazz.getName() + ". Under -XdisableClassMetadata, we do not have enough information to tell."); } failWithoutActual( fact("expected instance of", clazz.getName()), fact("but was instance of", actual.getClass().getName()), fact("with value", actualCustomStringRepresentation())); } }
@SuppressWarnings("IsInstanceInteger") // test is an intentional trivially true check @Test public void isInstanceOfSuperclass() { assertThat(3).isInstanceOf(Number.class); }
@VisibleForTesting static DateRangeBucket buildDateRangeBuckets(TimeRange timeRange, long searchWithinMs, long executeEveryMs) { final ImmutableList.Builder<DateRange> ranges = ImmutableList.builder(); DateTime from = timeRange.getFrom(); DateTime to; do { // The smallest configurable unit is 1 sec. // By dividing it before casting we avoid a potential int overflow to = from.plusSeconds((int) (searchWithinMs / 1000)); ranges.add(DateRange.builder().from(from).to(to).build()); from = from.plusSeconds((int) executeEveryMs / 1000); } while (to.isBefore(timeRange.getTo())); return DateRangeBucket.builder().field("timestamp").ranges(ranges.build()).build(); }
@Test public void testDateRangeBucketWithCatchUpSlidingWindows() { final int processingWindowSizeSec = 120; final int processingHopSizeSec = 60; final DateTime now = DateTime.now(DateTimeZone.UTC); final DateTime from = now; // We are 3 full processingWindows behind final DateTime to = now.plusSeconds(processingWindowSizeSec * 3); TimeRange timeRange = AbsoluteRange.create(from, to); final DateRangeBucket rangeBucket = PivotAggregationSearch.buildDateRangeBuckets(timeRange, processingWindowSizeSec * 1000, processingHopSizeSec * 1000); assertThat(rangeBucket.ranges()).containsExactly( DateRange.create(from.plusSeconds(processingHopSizeSec * 0), from.plusSeconds(processingWindowSizeSec)), DateRange.create(from.plusSeconds(processingHopSizeSec * 1), from.plusSeconds(processingHopSizeSec * 1).plusSeconds(processingWindowSizeSec)), DateRange.create(from.plusSeconds(processingHopSizeSec * 2), from.plusSeconds(processingHopSizeSec * 2).plusSeconds(processingWindowSizeSec)), DateRange.create(from.plusSeconds(processingHopSizeSec * 3), from.plusSeconds(processingHopSizeSec * 3).plusSeconds(processingWindowSizeSec)), DateRange.create(from.plusSeconds(processingHopSizeSec * 4), to) ); }
@Udf public <T> String toJsonString(@UdfParameter final T input) { return toJson(input); }
@Test public void shouldSerializeDouble() { // When: final String result = udf.toJsonString(123.456d); // Then: assertEquals("123.456", result); }
@Override public int hashCode() { return Objects.hash(taskId, topicPartitions); }
@Test public void shouldBeEqualsIfOnlyDifferInEndOffsets() { final TaskMetadataImpl stillSameDifferEndOffsets = new TaskMetadataImpl( TASK_ID, TOPIC_PARTITIONS, COMMITTED_OFFSETS, mkMap(mkEntry(TP_1, 1000000L), mkEntry(TP_1, 2L)), TIME_CURRENT_IDLING_STARTED); assertThat(taskMetadata, equalTo(stillSameDifferEndOffsets)); assertThat(taskMetadata.hashCode(), equalTo(stillSameDifferEndOffsets.hashCode())); }
public static <T> CompressedSource<T> from(FileBasedSource<T> sourceDelegate) { return new CompressedSource<>(sourceDelegate, CompressionMode.AUTO); }
@Test public void testEmptyGzipProgress() throws IOException { File tmpFile = tmpFolder.newFile("empty.gz"); String filename = tmpFile.toPath().toString(); writeFile(tmpFile, new byte[0], Compression.GZIP); PipelineOptions options = PipelineOptionsFactory.create(); CompressedSource<Byte> source = CompressedSource.from(new ByteSource(filename, 1)); try (BoundedReader<Byte> readerOrig = source.createReader(options)) { assertThat(readerOrig, instanceOf(CompressedReader.class)); CompressedReader<Byte> reader = (CompressedReader<Byte>) readerOrig; // before starting assertEquals(0.0, reader.getFractionConsumed(), delta); assertEquals(0, reader.getSplitPointsConsumed()); assertEquals(1, reader.getSplitPointsRemaining()); // confirm empty assertFalse(reader.start()); // after reading empty source assertEquals(1.0, reader.getFractionConsumed(), delta); assertEquals(0, reader.getSplitPointsConsumed()); assertEquals(0, reader.getSplitPointsRemaining()); } }
public static double div(float v1, float v2) { return div(v1, v2, DEFAULT_DIV_SCALE); }
@Test public void divBigDecimalTest() { final BigDecimal result = NumberUtil.div(BigDecimal.ZERO, BigDecimal.ONE); assertEquals(BigDecimal.ZERO, result.stripTrailingZeros()); }
@Override protected int rsv(WebSocketFrame msg) { return msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame? msg.rsv() | WebSocketExtension.RSV1 : msg.rsv(); }
@Test public void testEmptyFrameCompression() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false)); TextWebSocketFrame emptyFrame = new TextWebSocketFrame(""); assertTrue(encoderChannel.writeOutbound(emptyFrame)); TextWebSocketFrame emptyDeflateFrame = encoderChannel.readOutbound(); assertEquals(WebSocketExtension.RSV1, emptyDeflateFrame.rsv()); assertTrue(ByteBufUtil.equals(EMPTY_DEFLATE_BLOCK, emptyDeflateFrame.content())); // Unreleasable buffer assertFalse(emptyDeflateFrame.release()); assertFalse(encoderChannel.finish()); }
@Override public int wipeWritePermOfBroker(final String namesrvAddr, String brokerName) throws RemotingCommandException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQClientException { return defaultMQAdminExtImpl.wipeWritePermOfBroker(namesrvAddr, brokerName); }
@Test public void testWipeWritePermOfBroker() throws InterruptedException, RemotingCommandException, RemotingSendRequestException, RemotingTimeoutException, MQClientException, RemotingConnectException { int result = defaultMQAdminExt.wipeWritePermOfBroker("127.0.0.1:9876", "default-broker"); assertThat(result).isEqualTo(6); }
public Cookie decode(String header) { final int headerLen = checkNotNull(header, "header").length(); if (headerLen == 0) { return null; } CookieBuilder cookieBuilder = null; loop: for (int i = 0;;) { // Skip spaces and separators. for (;;) { if (i == headerLen) { break loop; } char c = header.charAt(i); if (c == ',') { // Having multiple cookies in a single Set-Cookie header is // deprecated, modern browsers only parse the first one break loop; } else if (c == '\t' || c == '\n' || c == 0x0b || c == '\f' || c == '\r' || c == ' ' || c == ';') { i++; continue; } break; } int nameBegin = i; int nameEnd; int valueBegin; int valueEnd; for (;;) { char curChar = header.charAt(i); if (curChar == ';') { // NAME; (no value till ';') nameEnd = i; valueBegin = valueEnd = -1; break; } else if (curChar == '=') { // NAME=VALUE nameEnd = i; i++; if (i == headerLen) { // NAME= (empty value, i.e. nothing after '=') valueBegin = valueEnd = 0; break; } valueBegin = i; // NAME=VALUE; int semiPos = header.indexOf(';', i); valueEnd = i = semiPos > 0 ? semiPos : headerLen; break; } else { i++; } if (i == headerLen) { // NAME (no value till the end of string) nameEnd = headerLen; valueBegin = valueEnd = -1; break; } } if (valueEnd > 0 && header.charAt(valueEnd - 1) == ',') { // old multiple cookies separator, skipping it valueEnd--; } if (cookieBuilder == null) { // cookie name-value pair DefaultCookie cookie = initCookie(header, nameBegin, nameEnd, valueBegin, valueEnd); if (cookie == null) { return null; } cookieBuilder = new CookieBuilder(cookie, header); } else { // cookie attribute cookieBuilder.appendAttribute(nameBegin, nameEnd, valueBegin, valueEnd); } } return cookieBuilder != null ? cookieBuilder.cookie() : null; }
@Test public void testDecodingLongDates() { Calendar cookieDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cookieDate.set(9999, Calendar.DECEMBER, 31, 23, 59, 59); long expectedMaxAge = (cookieDate.getTimeInMillis() - System .currentTimeMillis()) / 1000; String source = "Format=EU; expires=Fri, 31-Dec-9999 23:59:59 GMT; path=/"; Cookie cookie = ClientCookieDecoder.STRICT.decode(source); assertTrue(Math.abs(expectedMaxAge - cookie.maxAge()) < 2); }
@SuppressWarnings("unchecked") public static <K, V> Map<K, V> mapByKey(String key, List<?> list) { Map<K, V> map = new HashMap<>(); if (CollectionUtils.isEmpty(list)) { return map; } try { Class<?> clazz = list.get(0).getClass(); Field field = deepFindField(clazz, key); if (field == null) { throw new IllegalArgumentException("Could not find the key"); } field.setAccessible(true); for (Object o : list) { map.put((K) field.get(o), (V) o); } } catch (Exception e) { throw new BeanUtilsException(e); } return map; }
@Test(expected = BeanUtilsException.class) public void testMapByKeyNotEmptyListThrowsEx() { someAnotherList.add(new KeyClass()); assertNotNull(BeanUtils.mapByKey("wrongKey", someAnotherList)); }
void writeLogs(OutputStream out, Instant from, Instant to, long maxLines, Optional<String> hostname) { double fromSeconds = from.getEpochSecond() + from.getNano() / 1e9; double toSeconds = to.getEpochSecond() + to.getNano() / 1e9; long linesWritten = 0; BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); for (List<Path> logs : getMatchingFiles(from, to)) { List<LogLineIterator> logLineIterators = new ArrayList<>(); try { // Logs in each sub-list contain entries covering the same time interval, so do a merge sort while reading for (Path log : logs) logLineIterators.add(new LogLineIterator(log, fromSeconds, toSeconds, hostname)); Iterator<LineWithTimestamp> lines = Iterators.mergeSorted(logLineIterators, Comparator.comparingDouble(LineWithTimestamp::timestamp)); PriorityQueue<LineWithTimestamp> heap = new PriorityQueue<>(Comparator.comparingDouble(LineWithTimestamp::timestamp)); while (lines.hasNext()) { heap.offer(lines.next()); if (heap.size() > 1000) { if (linesWritten++ >= maxLines) return; writer.write(heap.poll().line); writer.newLine(); } } while ( ! heap.isEmpty()) { if (linesWritten++ >= maxLines) return; writer.write(heap.poll().line); writer.newLine(); } } catch (IOException e) { throw new UncheckedIOException(e); } finally { for (LogLineIterator ll : logLineIterators) { try { ll.close(); } catch (IOException ignored) { } } Exceptions.uncheck(writer::flush); } } }
@Test void logsLimitedToMaxLines() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*")); logReader.writeLogs(baos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), 2, Optional.of("node2.com")); assertEquals(log101 + log100b, baos.toString(UTF_8)); }
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, Object> maMap = null; Map<String,Object> apMap = null; Map<Object, Object> footerMap = null; Section body = convertBody(message); if (message.isPersistent()) { if (header == null) { header = new Header(); } header.setDurable(true); } byte priority = message.getPriority(); if (priority != Message.DEFAULT_PRIORITY) { if (header == null) { header = new Header(); } header.setPriority(UnsignedByte.valueOf(priority)); } String type = message.getType(); if (type != null) { if (properties == null) { properties = new Properties(); } properties.setSubject(type); } MessageId messageId = message.getMessageId(); if (messageId != null) { if (properties == null) { properties = new Properties(); } properties.setMessageId(getOriginalMessageId(message)); } ActiveMQDestination destination = message.getDestination(); if (destination != null) { if (properties == null) { properties = new Properties(); } properties.setTo(destination.getQualifiedName()); if (maMap == null) { maMap = new HashMap<>(); } maMap.put(JMS_DEST_TYPE_MSG_ANNOTATION, destinationType(destination)); } ActiveMQDestination replyTo = message.getReplyTo(); if (replyTo != null) { if (properties == null) { properties = new Properties(); } properties.setReplyTo(replyTo.getQualifiedName()); if (maMap == null) { maMap = new HashMap<>(); } maMap.put(JMS_REPLY_TO_TYPE_MSG_ANNOTATION, destinationType(replyTo)); } String correlationId = message.getCorrelationId(); if (correlationId != null) { if (properties == null) { properties = new Properties(); } try { properties.setCorrelationId(AMQPMessageIdHelper.INSTANCE.toIdObject(correlationId)); } catch (AmqpProtocolException e) { properties.setCorrelationId(correlationId); } } long expiration = message.getExpiration(); if (expiration != 0) { long ttl = expiration - System.currentTimeMillis(); if (ttl < 0) { ttl = 1; } if (header == null) { header = new Header(); } header.setTtl(new UnsignedInteger((int) ttl)); if (properties == null) { properties = new Properties(); } properties.setAbsoluteExpiryTime(new Date(expiration)); } long timeStamp = message.getTimestamp(); if (timeStamp != 0) { if (properties == null) { properties = new Properties(); } properties.setCreationTime(new Date(timeStamp)); } // JMSX Message Properties int deliveryCount = message.getRedeliveryCounter(); if (deliveryCount > 0) { if (header == null) { header = new Header(); } header.setDeliveryCount(UnsignedInteger.valueOf(deliveryCount)); } String userId = message.getUserID(); if (userId != null) { if (properties == null) { properties = new Properties(); } properties.setUserId(new Binary(userId.getBytes(StandardCharsets.UTF_8))); } String groupId = message.getGroupID(); if (groupId != null) { if (properties == null) { properties = new Properties(); } properties.setGroupId(groupId); } int groupSequence = message.getGroupSequence(); if (groupSequence > 0) { if (properties == null) { properties = new Properties(); } properties.setGroupSequence(UnsignedInteger.valueOf(groupSequence)); } final Map<String, Object> entries; try { entries = message.getProperties(); } catch (IOException e) { throw JMSExceptionSupport.create(e); } for (Map.Entry<String, Object> entry : entries.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.startsWith(JMS_AMQP_PREFIX)) { if (key.startsWith(NATIVE, JMS_AMQP_PREFIX_LENGTH)) { // skip transformer appended properties continue; } else if (key.startsWith(ORIGINAL_ENCODING, JMS_AMQP_PREFIX_LENGTH)) { // skip transformer appended properties continue; } else if (key.startsWith(MESSAGE_FORMAT, JMS_AMQP_PREFIX_LENGTH)) { messageFormat = (long) TypeConversionSupport.convert(entry.getValue(), Long.class); continue; } else if (key.startsWith(HEADER, JMS_AMQP_PREFIX_LENGTH)) { if (header == null) { header = new Header(); } continue; } else if (key.startsWith(PROPERTIES, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } continue; } else if (key.startsWith(MESSAGE_ANNOTATION_PREFIX, JMS_AMQP_PREFIX_LENGTH)) { if (maMap == null) { maMap = new HashMap<>(); } String name = key.substring(JMS_AMQP_MESSAGE_ANNOTATION_PREFIX.length()); maMap.put(Symbol.valueOf(name), value); continue; } else if (key.startsWith(FIRST_ACQUIRER, JMS_AMQP_PREFIX_LENGTH)) { if (header == null) { header = new Header(); } header.setFirstAcquirer((boolean) TypeConversionSupport.convert(value, Boolean.class)); continue; } else if (key.startsWith(CONTENT_TYPE, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } properties.setContentType(Symbol.getSymbol((String) TypeConversionSupport.convert(value, String.class))); continue; } else if (key.startsWith(CONTENT_ENCODING, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } properties.setContentEncoding(Symbol.getSymbol((String) TypeConversionSupport.convert(value, String.class))); continue; } else if (key.startsWith(REPLYTO_GROUP_ID, JMS_AMQP_PREFIX_LENGTH)) { if (properties == null) { properties = new Properties(); } properties.setReplyToGroupId((String) TypeConversionSupport.convert(value, String.class)); continue; } else if (key.startsWith(DELIVERY_ANNOTATION_PREFIX, JMS_AMQP_PREFIX_LENGTH)) { if (daMap == null) { daMap = new HashMap<>(); } String name = key.substring(JMS_AMQP_DELIVERY_ANNOTATION_PREFIX.length()); daMap.put(Symbol.valueOf(name), value); continue; } else if (key.startsWith(FOOTER_PREFIX, JMS_AMQP_PREFIX_LENGTH)) { if (footerMap == null) { footerMap = new HashMap<>(); } String name = key.substring(JMS_AMQP_FOOTER_PREFIX.length()); footerMap.put(Symbol.valueOf(name), value); continue; } } else if (key.startsWith(AMQ_SCHEDULED_MESSAGE_PREFIX )) { // strip off the scheduled message properties continue; } // The property didn't map into any other slot so we store it in the // Application Properties section of the message. if (apMap == null) { apMap = new HashMap<>(); } apMap.put(key, value); int messageType = message.getDataStructureType(); if (messageType == CommandTypes.ACTIVEMQ_MESSAGE) { // Type of command to recognize advisory message Object data = message.getDataStructure(); if(data != null) { apMap.put("ActiveMqDataStructureType", data.getClass().getSimpleName()); } } } final AmqpWritableBuffer buffer = new AmqpWritableBuffer(); encoder.setByteBuffer(buffer); if (header != null) { encoder.writeObject(header); } if (daMap != null) { encoder.writeObject(new DeliveryAnnotations(daMap)); } if (maMap != null) { encoder.writeObject(new MessageAnnotations(maMap)); } if (properties != null) { encoder.writeObject(properties); } if (apMap != null) { encoder.writeObject(new ApplicationProperties(apMap)); } if (body != null) { encoder.writeObject(body); } if (footerMap != null) { encoder.writeObject(new Footer(footerMap)); } return new EncodedMessage(messageFormat, buffer.getArray(), 0, buffer.getArrayLength()); }
@Test public void testConvertStreamMessageToAmqpMessageWithAmqpValueBody() throws Exception { ActiveMQStreamMessage outbound = createStreamMessage(); outbound.onSend(); outbound.storeContent(); JMSMappingOutboundTransformer transformer = new JMSMappingOutboundTransformer(); EncodedMessage encoded = transformer.transform(outbound); assertNotNull(encoded); Message amqp = encoded.decode(); assertNotNull(amqp.getBody()); assertTrue(amqp.getBody() instanceof AmqpValue); assertTrue(((AmqpValue) amqp.getBody()).getValue() instanceof List); }
public OffsetAndMetadata findNextCommitOffset(final String commitMetadata) { boolean found = false; long currOffset; long nextCommitOffset = committedOffset; for (KafkaSpoutMessageId currAckedMsg : ackedMsgs) { // complexity is that of a linear scan on a TreeMap currOffset = currAckedMsg.offset(); if (currOffset == nextCommitOffset) { // found the next offset to commit found = true; nextCommitOffset = currOffset + 1; } else if (currOffset > nextCommitOffset) { if (emittedOffsets.contains(nextCommitOffset)) { LOG.debug("topic-partition [{}] has non-sequential offset [{}]." + " It will be processed in a subsequent batch.", tp, currOffset); break; } else { /* This case will arise in case of non-sequential offset being processed. So, if the topic doesn't contain offset = nextCommitOffset (possible if the topic is compacted or deleted), the consumer should jump to the next logical point in the topic. Next logical offset should be the first element after nextCommitOffset in the ascending ordered emitted set. */ LOG.debug("Processed non-sequential offset." + " The earliest uncommitted offset is no longer part of the topic." + " Missing offset: [{}], Processed: [{}]", nextCommitOffset, currOffset); final Long nextEmittedOffset = emittedOffsets.ceiling(nextCommitOffset); if (nextEmittedOffset != null && currOffset == nextEmittedOffset) { LOG.debug("Found committable offset: [{}] after missing offset: [{}], skipping to the committable offset", currOffset, nextCommitOffset); found = true; nextCommitOffset = currOffset + 1; } else { LOG.debug("Topic-partition [{}] has non-sequential offset [{}]." + " Next offset to commit should be [{}]", tp, currOffset, nextCommitOffset); break; } } } else { throw new IllegalStateException("The offset [" + currOffset + "] is below the current nextCommitOffset " + "[" + nextCommitOffset + "] for [" + tp + "]." + " This should not be possible, and likely indicates a bug in the spout's acking or emit logic."); } } OffsetAndMetadata nextCommitOffsetAndMetadata = null; if (found) { nextCommitOffsetAndMetadata = new OffsetAndMetadata(nextCommitOffset, commitMetadata); LOG.debug("Topic-partition [{}] has offsets [{}-{}] ready to be committed." + " Processing will resume at offset [{}] upon spout restart", tp, committedOffset, nextCommitOffsetAndMetadata.offset() - 1, nextCommitOffsetAndMetadata.offset()); } else { LOG.debug("Topic-partition [{}] has no offsets ready to be committed", tp); } LOG.trace("{}", this); return nextCommitOffsetAndMetadata; }
@Test public void testFindNextCommitOffsetWithMultipleOutOfOrderAcks() { emitAndAckMessage(getMessageId(initialFetchOffset + 1)); emitAndAckMessage(getMessageId(initialFetchOffset)); OffsetAndMetadata nextCommitOffset = manager.findNextCommitOffset(COMMIT_METADATA); assertThat("The next commit offset should be one past the processed message offset", nextCommitOffset.offset(), is(initialFetchOffset + 2)); }
@Override public void cleanup() { executor.shutdown(); }
@Test public void cleanupShutsDownExecutor() { factory.cleanup(); assertThat(factory.executor.isShutdown(), is(true)); }
public String generateBadge(String label, String value, Color backgroundValueColor) { int labelWidth = computeWidth(label); int valueWidth = computeWidth(value); Map<String, String> values = ImmutableMap.<String, String>builder() .put(PARAMETER_TOTAL_WIDTH, valueOf(MARGIN * 4 + ICON_WIDTH + labelWidth + valueWidth)) .put(PARAMETER_LABEL_WIDTH, valueOf(labelWidth)) .put(PARAMETER_VALUE_WIDTH, valueOf(valueWidth)) .put(PARAMETER_LEFT_WIDTH, valueOf(MARGIN * 2 + ICON_WIDTH + labelWidth)) .put(PARAMETER_LEFT_WIDTH_PLUS_MARGIN, valueOf(MARGIN * 3 + ICON_WIDTH + labelWidth)) .put(PARAMETER_RIGHT_WIDTH, valueOf(MARGIN * 2 + valueWidth)) .put(PARAMETER_ICON_WIDTH_PLUS_MARGIN, valueOf(MARGIN + ICON_WIDTH)) .put(PARAMETER_COLOR, backgroundValueColor.getValue()) .put(PARAMETER_LABEL, label) .put(PARAMETER_VALUE, value) .build(); StringSubstitutor strSubstitutor = new StringSubstitutor(values); return strSubstitutor.replace(badgeTemplate); }
@Test public void generate_badge() { initSvgGenerator(); String result = underTest.generateBadge("label", "10", DEFAULT); checkBadge(result, "label", "10", DEFAULT); }
@Override public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException { checkParameterCount(parameters, MIN_PARAMETER_COUNT, MAX_PARAMETER_COUNT); values = parameters.toArray(new CompoundVariable[parameters.size()]); }
@Test public void testIsVarDefinedError() throws Exception { Assertions.assertThrows( InvalidVariableException.class, () -> isVarDefined.setParameters(params)); }
@Override public int addFirst(V... elements) { return get(addFirstAsync(elements)); }
@Test public void testAddFirstOrigin() { Deque<Integer> queue = new ArrayDeque<Integer>(); queue.addFirst(1); queue.addFirst(2); queue.addFirst(3); assertThat(queue).containsExactly(3, 2, 1); }
public static String[] parseKey(String groupKey) { StringBuilder sb = new StringBuilder(); String dataId = null; String group = null; String tenant = null; for (int i = 0; i < groupKey.length(); ++i) { char c = groupKey.charAt(i); if ('+' == c) { if (null == dataId) { dataId = sb.toString(); sb.setLength(0); } else if (null == group) { group = sb.toString(); sb.setLength(0); } else { throw new IllegalArgumentException("invalid groupkey:" + groupKey); } } else if ('%' == c) { char next = groupKey.charAt(++i); char nextnext = groupKey.charAt(++i); if ('2' == next && 'B' == nextnext) { sb.append('+'); } else if ('2' == next && '5' == nextnext) { sb.append('%'); } else { throw new IllegalArgumentException("invalid groupkey:" + groupKey); } } else { sb.append(c); } } if (StringUtils.isBlank(group)) { group = sb.toString(); } else { tenant = sb.toString(); } if (group.length() == 0) { throw new IllegalArgumentException("invalid groupkey:" + groupKey); } return new String[] {dataId, group, tenant}; }
@Test void testParseKeyForPercentIllegalArgumentException() { assertThrows(IllegalArgumentException.class, () -> { GroupKey.parseKey("%%%5\u0000??????????????"); // Method is not expected to return due to exception thrown }); // Method is not expected to return due to exception thrown }
public static Set<File> findJsonFiles(File rootDir, Set<File> files) { return findJsonFiles(rootDir, files, (f) -> true); }
@Test public void testFindJsonFiles() throws Exception { Path dir = ResourceUtils.getResourceAsFile("json").toPath(); List<String> jsonFiles; try (Stream<Path> stream = PackageHelper.findJsonFiles(dir)) { jsonFiles = stream .map(PackageHelper::asName) .toList(); } assertTrue(jsonFiles.contains("a"), "Files a.json must be found"); assertTrue(jsonFiles.contains("b"), "Files b.json must be found"); assertFalse(jsonFiles.contains("c"), "File c.txt must not be found"); }
@Override public File getCanonicalFile() { throw new UnsupportedOperationException("Not implemented"); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testGetCanonicalFile() throws IOException { fs.getFile("nonsuch.txt").getCanonicalFile(); }
@Override public void handle(ContainerLauncherEvent event) { try { eventQueue.put(event); } catch (InterruptedException e) { throw new YarnRuntimeException(e); } }
@Test(timeout = 5000) public void testMyShutdown() throws Exception { LOG.info("in test Shutdown"); AppContext mockContext = mock(AppContext.class); @SuppressWarnings("unchecked") EventHandler<Event> mockEventHandler = mock(EventHandler.class); when(mockContext.getEventHandler()).thenReturn(mockEventHandler); ContainerManagementProtocolClient mockCM = mock(ContainerManagementProtocolClient.class); ContainerLauncherImplUnderTest ut = new ContainerLauncherImplUnderTest(mockContext, mockCM); Configuration conf = new Configuration(); ut.init(conf); ut.start(); try { ContainerId contId = makeContainerId(0l, 0, 0, 1); TaskAttemptId taskAttemptId = makeTaskAttemptId(0l, 0, 0, TaskType.MAP, 0); String cmAddress = "127.0.0.1:8000"; StartContainersResponse startResp = recordFactory.newRecordInstance(StartContainersResponse.class); startResp.setAllServicesMetaData(serviceResponse); LOG.info("inserting launch event"); ContainerRemoteLaunchEvent mockLaunchEvent = mock(ContainerRemoteLaunchEvent.class); when(mockLaunchEvent.getType()) .thenReturn(EventType.CONTAINER_REMOTE_LAUNCH); when(mockLaunchEvent.getContainerID()) .thenReturn(contId); when(mockLaunchEvent.getTaskAttemptID()).thenReturn(taskAttemptId); when(mockLaunchEvent.getContainerMgrAddress()).thenReturn(cmAddress); when(mockCM.startContainers(any(StartContainersRequest.class))).thenReturn(startResp); when(mockLaunchEvent.getContainerToken()).thenReturn( createNewContainerToken(contId, cmAddress)); ut.handle(mockLaunchEvent); ut.waitForPoolToIdle(); verify(mockCM).startContainers(any(StartContainersRequest.class)); // skip cleanup and make sure stop kills the container } finally { ut.stop(); verify(mockCM).stopContainers(any(StopContainersRequest.class)); } }
@Override protected CompletableFuture<Void> respondToRequest( ChannelHandlerContext ctx, HttpRequest httpRequest, HandlerRequest<EmptyRequestBody> handlerRequest, RestfulGateway gateway) throws RestHandlerException { final ResourceID taskManagerId = handlerRequest.getPathParameter(TaskManagerIdPathParameter.class); String filename = getFileName(handlerRequest); final Tuple2<ResourceID, String> taskManagerIdAndFileName = new Tuple2<>(taskManagerId, filename); final CompletableFuture<TransientBlobKey> blobKeyFuture; try { blobKeyFuture = fileBlobKeys.get(taskManagerIdAndFileName); } catch (ExecutionException e) { final Throwable cause = ExceptionUtils.stripExecutionException(e); throw new RestHandlerException( "Could not retrieve file blob key future.", HttpResponseStatus.INTERNAL_SERVER_ERROR, cause); } final CompletableFuture<Void> resultFuture = blobKeyFuture.thenAcceptAsync( (TransientBlobKey blobKey) -> { final File file; try { file = transientBlobService.getFile(blobKey); } catch (IOException e) { throw new CompletionException( new FlinkException( "Could not retrieve file from transient blob store.", e)); } try { HandlerUtils.transferFile(ctx, file, httpRequest); } catch (FlinkException e) { throw new CompletionException( new FlinkException( "Could not transfer file to client.", e)); } }, ctx.executor()); return resultFuture .handle( (Void ignored, Throwable throwable) -> { if (throwable != null) { return handleException(ctx, httpRequest, throwable, taskManagerId); } return CompletableFuture.<Void>completedFuture(null); }) .thenCompose(Function.identity()); }
@Test void testFileServing() throws Exception { final Time cacheEntryDuration = Time.milliseconds(1000L); final Queue<CompletableFuture<TransientBlobKey>> requestFileUploads = new ArrayDeque<>(1); requestFileUploads.add(CompletableFuture.completedFuture(transientBlobKey1)); final TestingTaskManagerFileHandler testingTaskManagerFileHandler = createTestTaskManagerFileHandler( cacheEntryDuration, requestFileUploads, EXPECTED_TASK_MANAGER_ID); final File outputFile = TempDirUtils.newFile(temporaryFolder.toPath()); final TestingChannelHandlerContext testingContext = new TestingChannelHandlerContext(outputFile); testingTaskManagerFileHandler.respondToRequest( testingContext, HTTP_REQUEST, handlerRequest, null); assertThat(outputFile).isNotEmpty(); assertThat(FileUtils.readFileUtf8(outputFile)).isEqualTo(fileContent1); }
public static List<String> parse(String unixPath) { List<String> pathComponents = new ArrayList<>(); // -1 limit for Guava Splitter behavior: https://errorprone.info/bugpattern/StringSplitter for (String component : unixPath.split("/", -1)) { if (!component.isEmpty()) { pathComponents.add(component); } } return pathComponents; }
@Test public void testParse() { Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("/some/path")); Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("some/path/")); Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("some///path///")); // Windows-style paths are resolved in Unix semantics. Assert.assertEquals( ImmutableList.of("\\windows\\path"), UnixPathParser.parse("\\windows\\path")); Assert.assertEquals(ImmutableList.of("T:\\dir"), UnixPathParser.parse("T:\\dir")); Assert.assertEquals( ImmutableList.of("T:\\dir", "real", "path"), UnixPathParser.parse("T:\\dir/real/path")); }
@Override public SmileResponse<T> handle(Request request, Response response) { byte[] bytes = readResponseBytes(response); String contentType = response.getHeader(CONTENT_TYPE); if ((contentType == null) || !MediaType.parse(contentType).is(MEDIA_TYPE_SMILE)) { return new SmileResponse<>(response.getStatusCode(), response.getHeaders(), bytes); } return new SmileResponse<>(response.getStatusCode(), response.getHeaders(), smileCodec, bytes); }
@Test public void testNonSmileResponse() { SmileResponse<User> response = handler.handle(null, TestingResponse.mockResponse(OK, PLAIN_TEXT_UTF_8, "hello")); assertFalse(response.hasValue()); assertNull(response.getException()); assertNull(response.getSmileBytes()); assertEquals(response.getResponseBytes(), "hello".getBytes(UTF_8)); }
public static DefaultProcessCommands main(File directory, int processNumber) { return new DefaultProcessCommands(directory, processNumber, true); }
@Test public void main_fails_if_processNumber_is_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES; expectProcessNumberNoValidIAE(() -> { try (DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber)) { } }, processNumber); }