focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void release() { try { releasedStateLock.writeLock().lock(); isReleased = true; } finally { releasedStateLock.writeLock().unlock(); } if (executor != null) { executor.shutdown(); try { if (!executor.awaitTermination(5L, TimeUnit.MINUTES)) { throw new TimeoutException( "Timeout for shutting down the buffer reclaim checker executor."); } } catch (Exception e) { ExceptionUtils.rethrow(e); } } while (!bufferQueue.isEmpty()) { MemorySegment segment = bufferQueue.poll(); bufferPool.recycle(segment); numRequestedBuffers.decrementAndGet(); } }
@Test void testRelease() throws IOException { int numBuffers = 5; BufferPool bufferPool = globalPool.createBufferPool(numBuffers, numBuffers); TieredStorageMemoryManagerImpl storageMemoryManager = createStorageMemoryManager( bufferPool, Collections.singletonList(new TieredStorageMemorySpec(this, 0))); requestedBuffers.add(storageMemoryManager.requestBufferBlocking(this)); assertThat(storageMemoryManager.numOwnerRequestedBuffer(this)).isOne(); recycleRequestedBuffers(); storageMemoryManager.release(); assertThat(storageMemoryManager.numOwnerRequestedBuffer(this)).isZero(); assertThat(bufferPool.bestEffortGetNumOfUsedBuffers()).isZero(); }
@VisibleForTesting static IndexRange computeConsumedSubpartitionRange( int consumerSubtaskIndex, int numConsumers, Supplier<Integer> numOfSubpartitionsSupplier, boolean isDynamicGraph, boolean isBroadcast) { int consumerIndex = consumerSubtaskIndex % numConsumers; if (!isDynamicGraph) { return new IndexRange(consumerIndex, consumerIndex); } else { int numSubpartitions = numOfSubpartitionsSupplier.get(); if (isBroadcast) { // broadcast results have only one subpartition, and be consumed multiple times. checkArgument(numSubpartitions == 1); return new IndexRange(0, 0); } else { checkArgument(consumerIndex < numConsumers); checkArgument(numConsumers <= numSubpartitions); int start = consumerIndex * numSubpartitions / numConsumers; int nextStart = (consumerIndex + 1) * numSubpartitions / numConsumers; return new IndexRange(start, nextStart - 1); } } }
@Test void testComputeConsumedSubpartitionRange3to2() { final IndexRange range1 = computeConsumedSubpartitionRange(0, 2, 3); assertThat(range1).isEqualTo(new IndexRange(0, 0)); final IndexRange range2 = computeConsumedSubpartitionRange(1, 2, 3); assertThat(range2).isEqualTo(new IndexRange(1, 2)); }
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowStatement) { return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) sqlStatement)); } return Optional.empty(); }
@Test void assertCreateWithShowSQLStatement() { Optional<DatabaseAdminExecutor> actual = new PostgreSQLAdminExecutorCreator().create(new UnknownSQLStatementContext(new PostgreSQLShowStatement("client_encoding"))); assertTrue(actual.isPresent()); assertThat(actual.get(), instanceOf(PostgreSQLShowVariableExecutor.class)); }
public FEELFnResult<List<Object>> invoke(@ParameterName( "list" ) Object list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } // spec requires us to return a new list final List<Object> result = new ArrayList<>(); if ( list instanceof Collection ) { for (Object o : (Collection) list) { if ( !result.contains( o ) ) { result.add(o); } } } else { result.add( list ); } return FEELFnResult.ofResult( result ); }
@Test void invokeList() { final List testValues = Arrays.asList(1, BigDecimal.valueOf(10.1), "test", 1, "test", BigDecimal.valueOf(10.1)); FunctionTestUtil.assertResultList( distinctValuesFunction.invoke(testValues), Arrays.asList(1, BigDecimal.valueOf(10.1), "test")); }
public static Builder builder() { return new Builder(); }
@Test public void testEqualsAndHashCode() { SpringCloudSelectorHandle selectorHandle1 = SpringCloudSelectorHandle.builder().serviceId("serviceId").build(); SpringCloudSelectorHandle selectorHandle2 = SpringCloudSelectorHandle.builder().serviceId("serviceId").build(); assertThat(ImmutableSet.of(selectorHandle1, selectorHandle2), hasSize(1)); }
public static Object getValueOrCachedValue(Record record, SerializationService serializationService) { Object cachedValue = record.getCachedValueUnsafe(); if (cachedValue == NOT_CACHED) { //record does not support caching at all return record.getValue(); } for (; ; ) { if (cachedValue == null) { Object valueBeforeCas = record.getValue(); if (!shouldCache(valueBeforeCas)) { //it's either a null or value which we do not want to cache. let's just return it. return valueBeforeCas; } Object fromCache = tryStoreIntoCache(record, valueBeforeCas, serializationService); if (fromCache != null) { return fromCache; } } else if (cachedValue instanceof Thread) { //the cachedValue is either locked by another thread or it contains a wrapped thread cachedValue = ThreadWrapper.unwrapOrNull(cachedValue); if (cachedValue != null) { //exceptional case: the cachedValue is not locked, it just contains an instance of Thread. //this can happen when user put an instance of Thread into a map //(=it should never happen, but never say never...) return cachedValue; } //it looks like some other thread actually locked the cachedValue. let's give it another try (iteration) } else { //it's not the 'in-progress' marker/lock && it's not a null -> it has to be the actual cachedValue return cachedValue; } Thread.yield(); cachedValue = record.getCachedValueUnsafe(); } }
@Test public void givenCachedDataRecord_whenThreadIsInside_thenGetValueOrCachedValueReturnsTheThread() { // given Record record = new CachedDataRecordWithStats(); // when SerializableThread objectPayload = new SerializableThread(); Data dataPayload = serializationService.toData(objectPayload); record.setValue(dataPayload); // then Object cachedValue = Records.getValueOrCachedValue(record, serializationService); assertInstanceOf(SerializableThread.class, cachedValue); }
@Override public void changeLogLevel(LoggerLevel level) { requireNonNull(level, "level can't be null"); call(new ChangeLogLevelActionClient(level)); }
@Test public void changeLogLevel_does_not_fail_when_http_code_is_200() { server.enqueue(new MockResponse().setResponseCode(200)); setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE); underTest.changeLogLevel(LoggerLevel.TRACE); }
@VisibleForTesting static AbsoluteUnixPath getAppRootChecked( RawConfiguration rawConfiguration, ProjectProperties projectProperties) throws InvalidAppRootException { String appRoot = rawConfiguration.getAppRoot(); if (appRoot.isEmpty()) { appRoot = projectProperties.isWarProject() ? DEFAULT_JETTY_APP_ROOT : JavaContainerBuilder.DEFAULT_APP_ROOT; } try { return AbsoluteUnixPath.get(appRoot); } catch (IllegalArgumentException ex) { throw new InvalidAppRootException(appRoot, appRoot, ex); } }
@Test public void testGetAppRootChecked_defaultWarProject() throws InvalidAppRootException { when(rawConfiguration.getAppRoot()).thenReturn(""); when(projectProperties.isWarProject()).thenReturn(true); assertThat(PluginConfigurationProcessor.getAppRootChecked(rawConfiguration, projectProperties)) .isEqualTo(AbsoluteUnixPath.get("/var/lib/jetty/webapps/ROOT")); }
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter, MetricsRecorder metricsRecorder, BufferSupplier bufferSupplier) { if (sourceCompressionType == CompressionType.NONE && targetCompression.type() == CompressionType.NONE) { // check the magic value if (!records.hasMatchingMagic(toMagic)) return convertAndAssignOffsetsNonCompressed(offsetCounter, metricsRecorder); else // Do in-place validation, offset assignment and maybe set timestamp return assignOffsetsNonCompressed(offsetCounter, metricsRecorder); } else return validateMessagesAndAssignOffsetsCompressed(offsetCounter, metricsRecorder, bufferSupplier); }
@Test public void testRecordWithFutureTimestampIsRejected() { long timestampBeforeMaxConfig = Duration.ofHours(24).toMillis(); // 24 hrs long timestampAfterMaxConfig = Duration.ofHours(1).toMillis(); // 1 hr long now = System.currentTimeMillis(); long fiveMinutesAfterThreshold = now + timestampAfterMaxConfig + Duration.ofMinutes(5).toMillis(); Compression compression = Compression.gzip().build(); MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V2, fiveMinutesAfterThreshold, compression); RecordValidationException e = assertThrows(RecordValidationException.class, () -> new LogValidator( records, topicPartition, time, CompressionType.GZIP, compression, false, RecordBatch.MAGIC_VALUE_V2, TimestampType.CREATE_TIME, timestampBeforeMaxConfig, timestampAfterMaxConfig, RecordBatch.NO_PARTITION_LEADER_EPOCH, AppendOrigin.CLIENT, MetadataVersion.latestTesting() ).validateMessagesAndAssignOffsets( PrimitiveRef.ofLong(0L), metricsRecorder, RequestLocal.withThreadConfinedCaching().bufferSupplier() ) ); assertInstanceOf(InvalidTimestampException.class, e.invalidException()); assertFalse(e.recordErrors().isEmpty()); assertEquals(3, e.recordErrors().size()); }
@Override public JCParens inline(Inliner inliner) throws CouldNotResolveImportException { return inliner.maker().Parens(getExpression().inline(inliner)); }
@Test public void inline() { assertInlines("(5L)", UParens.create(ULiteral.longLit(5L))); }
public String process(final Expression expression) { return formatExpression(expression); }
@Test public void shouldGenerateCorrectCodeForDate() { // Given: final DateLiteral time = new DateLiteral(new Date(864000000)); // When: final String java = sqlToJavaVisitor.process(time); // Then: assertThat(java, is("1970-01-11")); }
public static boolean isWebService(Optional<String> serviceName) { return serviceName.isPresent() && IS_PLAIN_HTTP_BY_KNOWN_WEB_SERVICE_NAME.containsKey( Ascii.toLowerCase(serviceName.get())); }
@Test public void isWebService_whenSslHttpService_returnsTrue() { assertThat( NetworkServiceUtils.isWebService( NetworkService.newBuilder().setServiceName("ssl/http").build())) .isTrue(); }
public static InetSocketAddress parseHostPortAddress(String hostPort) { URL url = validateHostPortString(hostPort); return new InetSocketAddress(url.getHost(), url.getPort()); }
@Test void testParseHostPortAddress() { final InetSocketAddress socketAddress = new InetSocketAddress("foo.com", 8080); assertThat(NetUtils.parseHostPortAddress("foo.com:8080")).isEqualTo(socketAddress); }
JavaClasses getClassesToAnalyzeFor(Class<?> testClass, ClassAnalysisRequest classAnalysisRequest) { checkNotNull(testClass); checkNotNull(classAnalysisRequest); if (cachedByTest.containsKey(testClass)) { return cachedByTest.get(testClass); } LocationsKey locations = RequestedLocations.by(classAnalysisRequest, testClass).asKey(); JavaClasses classes = classAnalysisRequest.getCacheMode() == FOREVER ? cachedByLocations.getUnchecked(locations).get() : new LazyJavaClasses(locations.locations, locations.importOptionTypes).get(); cachedByTest.put(testClass, classes); return classes; }
@Test public void gets_all_classes_relative_to_class() { JavaClasses classes = cache.getClassesToAnalyzeFor(TestClass.class, analyzePackagesOf(getClass())); assertThat(classes).isNotEmpty(); assertThat(classes.contain(getClass())).as("root class is contained itself").isTrue(); }
@Override public void onHeartbeatSuccess(ConsumerGroupHeartbeatResponseData response) { if (response.errorCode() != Errors.NONE.code()) { String errorMessage = String.format( "Unexpected error in Heartbeat response. Expected no error, but received: %s", Errors.forCode(response.errorCode()) ); throw new IllegalArgumentException(errorMessage); } MemberState state = state(); if (state == MemberState.LEAVING) { log.debug("Ignoring heartbeat response received from broker. Member {} with epoch {} is " + "already leaving the group.", memberId, memberEpoch); return; } if (state == MemberState.UNSUBSCRIBED && maybeCompleteLeaveInProgress()) { log.debug("Member {} with epoch {} received a successful response to the heartbeat " + "to leave the group and completed the leave operation. ", memberId, memberEpoch); return; } if (isNotInGroup()) { log.debug("Ignoring heartbeat response received from broker. Member {} is in {} state" + " so it's not a member of the group. ", memberId, state); return; } // Update the group member id label in the client telemetry reporter if the member id has // changed. Initially the member id is empty, and it is updated when the member joins the // group. This is done here to avoid updating the label on every heartbeat response. Also // check if the member id is null, as the schema defines it as nullable. if (response.memberId() != null && !response.memberId().equals(memberId)) { clientTelemetryReporter.ifPresent(reporter -> reporter.updateMetricsLabels( Collections.singletonMap(ClientTelemetryProvider.GROUP_MEMBER_ID, response.memberId()))); } this.memberId = response.memberId(); updateMemberEpoch(response.memberEpoch()); ConsumerGroupHeartbeatResponseData.Assignment assignment = response.assignment(); if (assignment != null) { if (!state.canHandleNewAssignment()) { // New assignment received but member is in a state where it cannot take new // assignments (ex. preparing to leave the group) log.debug("Ignoring new assignment {} received from server because member is in {} state.", assignment, state); return; } Map<Uuid, SortedSet<Integer>> newAssignment = new HashMap<>(); assignment.topicPartitions().forEach(topicPartition -> newAssignment.put(topicPartition.topicId(), new TreeSet<>(topicPartition.partitions()))); processAssignmentReceived(newAssignment); } }
@Test public void testRebalanceMetricsOnFailedRebalance() { ConsumerMembershipManager membershipManager = createMembershipManagerJoiningGroup(); ConsumerGroupHeartbeatResponse heartbeatResponse = createConsumerGroupHeartbeatResponse(new Assignment()); membershipManager.onHeartbeatSuccess(heartbeatResponse.data()); Uuid topicId = Uuid.randomUuid(); receiveAssignment(topicId, Arrays.asList(0, 1), membershipManager); // sleep for an arbitrary amount time.sleep(2300); assertTrue(rebalanceMetricsManager.rebalanceStarted()); membershipManager.onHeartbeatFailure(false); assertEquals((double) 0, getMetricValue(metrics, rebalanceMetricsManager.rebalanceLatencyTotal)); assertEquals(0d, getMetricValue(metrics, rebalanceMetricsManager.rebalanceTotal)); assertEquals(120d, getMetricValue(metrics, rebalanceMetricsManager.failedRebalanceRate)); assertEquals(1d, getMetricValue(metrics, rebalanceMetricsManager.failedRebalanceTotal)); assertEquals(-1d, getMetricValue(metrics, rebalanceMetricsManager.lastRebalanceSecondsAgo)); }
public void removeMap(String mapId) { IndexInformation info = cache.get(mapId); if (info == null || isUnderConstruction(info)) { return; } info = cache.remove(mapId); if (info != null) { totalMemoryUsed.addAndGet(-info.getSize()); if (!queue.remove(mapId)) { LOG.warn("Map ID" + mapId + " not found in queue!!"); } } else { LOG.info("Map ID " + mapId + " not found in cache"); } }
@Test public void testRemoveMap() throws Exception { // This test case use two thread to call getIndexInformation and // removeMap concurrently, in order to construct race condition. // This test case may not repeatable. But on my macbook this test // fails with probability of 100% on code before MAPREDUCE-2541, // so it is repeatable in practice. fs.delete(p, true); conf.setInt(MRJobConfig.SHUFFLE_INDEX_CACHE, 10); // Make a big file so removeMapThread almost surely runs faster than // getInfoThread final int partsPerMap = 100000; final int bytesPerFile = partsPerMap * 24; final IndexCache cache = new IndexCache(conf); final Path big = new Path(p, "bigIndex"); final String user = UserGroupInformation.getCurrentUser().getShortUserName(); writeFile(fs, big, bytesPerFile, partsPerMap); // run multiple times for (int i = 0; i < 20; ++i) { Thread getInfoThread = new Thread() { @Override public void run() { try { cache.getIndexInformation("bigIndex", partsPerMap, big, user); } catch (Exception e) { // should not be here } } }; Thread removeMapThread = new Thread() { @Override public void run() { cache.removeMap("bigIndex"); } }; if (i%2==0) { getInfoThread.start(); removeMapThread.start(); } else { removeMapThread.start(); getInfoThread.start(); } getInfoThread.join(); removeMapThread.join(); assertTrue(cache.checkTotalMemoryUsed()); } }
@Deprecated protected DBSort.SortBuilder getSortBuilder(String order, String field) { DBSort.SortBuilder sortBuilder; if ("desc".equalsIgnoreCase(order)) { sortBuilder = DBSort.desc(field); } else { sortBuilder = DBSort.asc(field); } return sortBuilder; }
@Test public void sortBuilder() { assertThat(dbService.getSortBuilder("asc", "f")).isEqualTo(DBSort.asc("f")); assertThat(dbService.getSortBuilder("aSc", "f")).isEqualTo(DBSort.asc("f")); assertThat(dbService.getSortBuilder("desc", "f")).isEqualTo(DBSort.desc("f")); assertThat(dbService.getSortBuilder("dEsC", "f")).isEqualTo(DBSort.desc("f")); }
public <T> void compareSupplierResult(final T expected, final Supplier<T> experimentSupplier) { final Timer.Sample sample = Timer.start(); try { final T result = experimentSupplier.get(); recordResult(expected, result, sample); } catch (final Exception e) { recordError(e, sample); } }
@Test void compareSupplierResultError() { experiment.compareSupplierResult(12, () -> { throw new RuntimeException("OH NO"); }); verify(errorTimer).record(anyLong(), eq(TimeUnit.NANOSECONDS)); }
public static String convertToString(Object parsedValue, Type type) { if (parsedValue == null) { return null; } if (type == null) { return parsedValue.toString(); } switch (type) { case BOOLEAN: case SHORT: case INT: case LONG: case DOUBLE: case STRING: case PASSWORD: return parsedValue.toString(); case LIST: List<?> valueList = (List<?>) parsedValue; return valueList.stream().map(Object::toString).collect(Collectors.joining(",")); case CLASS: Class<?> clazz = (Class<?>) parsedValue; return clazz.getName(); default: throw new IllegalStateException("Unknown type."); } }
@Test public void testConvertValueToStringPassword() { assertEquals(Password.HIDDEN, ConfigDef.convertToString(new Password("foobar"), Type.PASSWORD)); assertEquals("foobar", ConfigDef.convertToString("foobar", Type.PASSWORD)); assertNull(ConfigDef.convertToString(null, Type.PASSWORD)); }
public static Traits parseTraits(String[] traits) { if (traits == null || traits.length == 0) { return new Traits(); } Map<String, Map<String, Object>> traitConfigMap = new HashMap<>(); for (String traitExpression : traits) { //traitName.key=value final String[] trait = traitExpression.split("\\.", 2); final String[] traitConfig = trait[1].split("=", 2); // the CRD api is in CamelCase, then we have to // convert the kebab-case to CamelCase final String traitKey = StringHelper.dashToCamelCase(traitConfig[0]); final Object traitValue = resolveTraitValue(traitKey, traitConfig[1].trim()); if (traitConfigMap.containsKey(trait[0])) { Map<String, Object> config = traitConfigMap.get(trait[0]); if (config.containsKey(traitKey)) { Object existingValue = config.get(traitKey); if (existingValue instanceof List) { List<String> values = (List<String>) existingValue; if (traitValue instanceof List) { List<String> traitValueList = (List<String>) traitValue; values.addAll(traitValueList); } else { values.add(traitValue.toString()); } } else if (existingValue instanceof Map) { Map<String, String> values = (Map<String, String>) existingValue; if (traitValue instanceof Map) { Map<String, String> traitValueList = (Map<String, String>) traitValue; values.putAll(traitValueList); } else { final String[] traitValueConfig = traitValue.toString().split("=", 2); values.put(traitValueConfig[0], traitValueConfig[1]); } } else if (traitValue instanceof List) { List<String> traitValueList = (List<String>) traitValue; traitValueList.add(0, existingValue.toString()); config.put(traitKey, traitValueList); } else if (traitValue instanceof Map) { Map<String, String> traitValueMap = (Map<String, String>) traitValue; final String[] existingValueConfig = existingValue.toString().split("=", 2); traitValueMap.put(existingValueConfig[0], existingValueConfig[1]); config.put(traitKey, traitValueMap); } else { if (traitKey.endsWith("annotations")) { Map<String, String> map = new LinkedHashMap<>(); final String[] traitValueConfig = traitValue.toString().split("=", 2); final String[] existingValueConfig = existingValue.toString().split("=", 2); map.put(traitValueConfig[0], traitValueConfig[1]); map.put(existingValueConfig[0], existingValueConfig[1]); config.put(traitKey, map); } else { config.put(traitKey, Arrays.asList(existingValue.toString(), traitValue)); } } } else { config.put(traitKey, traitValue); } } else { Map<String, Object> config = new HashMap<>(); config.put(traitKey, traitValue); traitConfigMap.put(trait[0], config); } } Traits traitModel = KubernetesHelper.json().convertValue(traitConfigMap, Traits.class); // Handle leftover traits as addons Set<?> knownTraits = KubernetesHelper.json().convertValue(traitModel, Map.class).keySet(); if (knownTraits.size() < traitConfigMap.size()) { traitModel.setAddons(new HashMap<>()); for (Map.Entry<String, Map<String, Object>> traitConfig : traitConfigMap.entrySet()) { if (!knownTraits.contains(traitConfig.getKey())) { traitModel.getAddons().put(traitConfig.getKey(), new AddonsBuilder().addToAdditionalProperties(traitConfig.getValue()).build()); } } } return traitModel; }
@Test public void parseTraitsTest() { String[] traits = new String[] { "custom.property=custom", "container.port=8080", "container.port-name=custom" }; Traits traitsSpec = TraitHelper.parseTraits(traits); Assertions.assertNotNull(traitsSpec); Assertions.assertEquals(8080L, traitsSpec.getContainer().getPort()); Assertions.assertNotNull(traitsSpec.getAddons().get("custom")); Traits traitsSpecEmpty = TraitHelper.parseTraits(new String[0]); Assertions.assertNotNull(traitsSpecEmpty); Traits traitsSpecNull = TraitHelper.parseTraits(null); Assertions.assertNotNull(traitsSpecNull); }
@Override public int countWords(Note note) { int count = 0; String[] fields = {note.getTitle(), note.getContent()}; for (String field : fields) { field = sanitizeTextForWordsAndCharsCount(note, field); boolean word = false; int endOfLine = field.length() - 1; for (int i = 0; i < field.length(); i++) { // if the char is a letter, word = true. if (Character.isLetter(field.charAt(i)) && i != endOfLine) { word = true; // if char isn't a letter and there have been letters before, counter goes up. } else if (!Character.isLetter(field.charAt(i)) && word) { count++; word = false; // last word of String; if it doesn't end with a non letter, it wouldn't count without this. } else if (Character.isLetter(field.charAt(i)) && i == endOfLine) { count++; } } } return count; }
@Test public void getWords() { Note note = getNote(1L, "one two", "three\n four five"); assertEquals(5, new DefaultWordCounter().countWords(note)); note.setTitle("singleword"); assertEquals(4, new DefaultWordCounter().countWords(note)); }
static byte[] adaptArray(byte[] ftdiData) { int length = ftdiData.length; if(length > 64) { int n = 1; int p = 64; // Precalculate length without FTDI headers while(p < length) { n++; p = n*64; } int realLength = length - n*2; byte[] data = new byte[realLength]; copyData(ftdiData, data); return data; } else if (length == 2) // special case optimization that returns the same instance. { return EMPTY_BYTE_ARRAY; } else { return Arrays.copyOfRange(ftdiData, 2, length); } }
@Test public void testMultipleFull() { byte[] withHeaders = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64}; byte[] wanted = {3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, 3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64}; Assert.assertArrayEquals(wanted, FTDISerialDevice.adaptArray(withHeaders)); }
@Nullable public PlanCoordinator getCoordinator(long jobId) { return mCoordinators.get(jobId); }
@Test public void testGetCoordinator() throws Exception { long jobId = addJob(100); assertNull("job id should not exist", mTracker.getCoordinator(-1)); assertNotNull("job should exist", mTracker.getCoordinator(jobId)); assertFalse("job should not be finished", mTracker.getCoordinator(jobId).isJobFinished()); finishAllJobs(); assertTrue("job should be finished", mTracker.getCoordinator(jobId).isJobFinished()); assertEquals("finished should be of size 1", 1, ((Queue) AlluxioMockUtil.getInternalState(mTracker, "mFinished")).size()); }
@Override public void close() { getListener().onClose(this); }
@Test public void shouldNotCloseKafkaStreamsOnClose() { // When: sandbox.close(); // Then: verifyNoMoreInteractions(kafkaStreams); }
@SneakyThrows(GeneralSecurityException.class) @Override public String encrypt(final Object plainValue) { if (null == plainValue) { return null; } byte[] result = getCipher(Cipher.ENCRYPT_MODE).doFinal(String.valueOf(plainValue).getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(result); }
@Test void assertEncryptNullValue() { assertNull(cryptographicAlgorithm.encrypt(null)); }
@Override public TypeDefinition build( ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); getDeclaredFields(type, FieldUtils::isEnumMemberField).stream() .map(Element::getSimpleName) .map(Name::toString) .forEach(typeDefinition.getEnums()::add); return typeDefinition; }
@Test void testBuild() { TypeElement typeElement = getType(Color.class); Map<String, TypeDefinition> typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, typeElement, typeCache); assertEquals(Color.class.getName(), typeDefinition.getType()); assertEquals(asList("RED", "YELLOW", "BLUE"), typeDefinition.getEnums()); // assertEquals(typeDefinition.getTypeBuilderName(), builder.getClass().getName()); }
@Override public List<Integer> applyTransforms(List<Integer> originalGlyphIds) { List<Integer> intermediateGlyphsFromGsub = adjustRephPosition(originalGlyphIds); intermediateGlyphsFromGsub = repositionGlyphs(intermediateGlyphsFromGsub); for (String feature : FEATURES_IN_ORDER) { if (!gsubData.isFeatureSupported(feature)) { if (feature.equals(RKRF_FEATURE) && gsubData.isFeatureSupported(VATU_FEATURE)) { // Create your own rkrf feature from vatu feature intermediateGlyphsFromGsub = applyRKRFFeature( gsubData.getFeature(VATU_FEATURE), intermediateGlyphsFromGsub); } LOG.debug("the feature {} was not found", feature); continue; } LOG.debug("applying the feature {}", feature); ScriptFeature scriptFeature = gsubData.getFeature(feature); intermediateGlyphsFromGsub = applyGsubFeature(scriptFeature, intermediateGlyphsFromGsub); } return Collections.unmodifiableList(intermediateGlyphsFromGsub); }
@Disabled @Test void testApplyTransforms_cjct() { // given List<Integer> glyphsAfterGsub = Arrays.asList(638,688,636,640,639); // when List<Integer> result = gsubWorkerForDevanagari.applyTransforms(getGlyphIds("द्मद्ध्र्यब्दद्वद्य")); // then assertEquals(glyphsAfterGsub, result); }
public static <UserT, DestinationT, OutputT> WriteFiles<UserT, DestinationT, OutputT> to( FileBasedSink<UserT, DestinationT, OutputT> sink) { checkArgument(sink != null, "sink can not be null"); return new AutoValue_WriteFiles.Builder<UserT, DestinationT, OutputT>() .setSink(sink) .setComputeNumShards(null) .setNumShardsProvider(null) .setWindowedWrites(false) .setWithAutoSharding(false) .setMaxNumWritersPerBundle(DEFAULT_MAX_NUM_WRITERS_PER_BUNDLE) .setSideInputs(sink.getDynamicDestinations().getSideInputs()) .setSkipIfEmpty(false) .setBadRecordErrorHandler(new DefaultErrorHandler<>()) .setBadRecordRouter(BadRecordRouter.THROWING_ROUTER) .build(); }
@Test @Category(NeedsRunner.class) public void testWrite() throws IOException { List<String> inputs = Arrays.asList( "Critical canary", "Apprehensive eagle", "Intimidating pigeon", "Pedantic gull", "Frisky finch"); runWrite(inputs, IDENTITY_MAP, getBaseOutputFilename(), WriteFiles.to(makeSimpleSink())); }
public static String get(@NonNull SymbolRequest request) { String name = request.getName(); String title = request.getTitle(); String tooltip = request.getTooltip(); String htmlTooltip = request.getHtmlTooltip(); String classes = request.getClasses(); String pluginName = request.getPluginName(); String id = request.getId(); String identifier = (pluginName == null || pluginName.isBlank()) ? "core" : pluginName; String symbol = SYMBOLS .computeIfAbsent(identifier, key -> new ConcurrentHashMap<>()) .computeIfAbsent(name, key -> loadSymbol(identifier, key)); if ((tooltip != null && !tooltip.isBlank()) && (htmlTooltip == null || htmlTooltip.isBlank())) { symbol = symbol.replaceAll("<svg", Matcher.quoteReplacement("<svg tooltip=\"" + Functions.htmlAttributeEscape(tooltip) + "\"")); } if (htmlTooltip != null && !htmlTooltip.isBlank()) { symbol = symbol.replaceAll("<svg", Matcher.quoteReplacement("<svg data-html-tooltip=\"" + Functions.htmlAttributeEscape(htmlTooltip) + "\"")); } if (id != null && !id.isBlank()) { symbol = symbol.replaceAll("<svg", Matcher.quoteReplacement("<svg id=\"" + Functions.htmlAttributeEscape(id) + "\"")); } if (classes != null && !classes.isBlank()) { symbol = symbol.replaceAll("<svg", "<svg class=\"" + Functions.htmlAttributeEscape(classes) + "\""); } if (title != null && !title.isBlank()) { symbol = "<span class=\"jenkins-visually-hidden\">" + Util.xmlEscape(title) + "</span>" + symbol; } return symbol; }
@Test @DisplayName("When resolving a missing symbol, a placeholder is generated instead") void missingSymbolDefaultsToPlaceholder() { String symbol = Symbol.get(new SymbolRequest.Builder() .withName("missing-icon") .build() ); assertThat(symbol, not(containsString(SCIENCE_PATH))); assertThat(symbol, containsString(Symbol.PLACEHOLDER_MATCHER)); }
void readOperatingSystemList(String initialOperatingSystemJson) throws IOException { JSONArray systems = JSONArray.fromObject(initialOperatingSystemJson); if (systems.isEmpty()) { throw new IOException("Empty data set"); } for (Object systemObj : systems) { if (!(systemObj instanceof JSONObject)) { throw new IOException("Wrong object type in data file"); } JSONObject system = (JSONObject) systemObj; if (!system.has("pattern")) { throw new IOException("Missing pattern in definition file"); } String pattern = system.getString("pattern"); if (!system.has("endOfLife")) { throw new IOException("No end of life date for " + pattern); } LocalDate endOfLife = LocalDate.parse(system.getString("endOfLife")); /* Start date defaults to 6 months before end of life */ LocalDate startDate = system.has("start") ? LocalDate.parse(system.getString("start")) : endOfLife.minusMonths(6); File dataFile = getDataFile(system); LOGGER.log(Level.FINEST, "Pattern {0} starts {1} and reaches end of life {2} from file {3}", new Object[]{pattern, startDate, endOfLife, dataFile}); String name = readOperatingSystemName(dataFile, pattern); if (name.isEmpty()) { LOGGER.log(Level.FINE, "Pattern {0} did not match from file {1}", new Object[]{pattern, dataFile}); continue; } if (startDate.isBefore(warningsStartDate)) { warningsStartDate = startDate; LOGGER.log(Level.FINE, "Warnings start date is now {0}", warningsStartDate); } LOGGER.log(Level.FINE, "Matched operating system {0}", name); if (startDate.isBefore(LocalDate.now())) { this.operatingSystemName = name; this.documentationUrl = buildDocumentationUrl(this.operatingSystemName); this.endOfLifeDate = endOfLife.toString(); if (endOfLife.isBefore(LocalDate.now())) { LOGGER.log(Level.FINE, "Operating system {0} is after end of life {1}", new Object[]{name, endOfLife}); afterEndOfLifeDate = true; } else { LOGGER.log(Level.FINE, "Operating system {0} started warnings {1} and reaches end of life {2}", new Object[]{name, startDate, endOfLife}); } } } if (lastLines != null) { // Discard the cached contents of the last read file lastLines.clear(); } }
@Test public void testReadOperatingSystemListNoPattern() { IOException e = assertThrows(IOException.class, () -> monitor.readOperatingSystemList("[{\"endOfLife\": \"2029-03-31\"}]")); assertThat(e.getMessage(), is("Missing pattern in definition file")); }
@Override public int getMaxRowSize() { return 0; }
@Test void assertGetMaxRowSize() { assertThat(metaData.getMaxRowSize(), is(0)); }
@Override public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final SelectionParameters other = (SelectionParameters) obj; if ( !equals( this.qualifiers, other.qualifiers ) ) { return false; } if ( !Objects.equals( this.qualifyingNames, other.qualifyingNames ) ) { return false; } if ( !Objects.equals( this.conditionQualifiers, other.conditionQualifiers ) ) { return false; } if ( !Objects.equals( this.conditionQualifyingNames, other.conditionQualifyingNames ) ) { return false; } if ( !Objects.equals( this.sourceRHS, other.sourceRHS ) ) { return false; } return equals( this.resultType, other.resultType ); }
@Test public void testEqualsWitNull() { List<String> qualifyingNames = Arrays.asList( "language", "german" ); TypeMirror resultType = new TestTypeMirror( "resultType" ); List<TypeMirror> qualifiers = new ArrayList<>(); qualifiers.add( new TestTypeMirror( "org.mapstruct.test.SomeType" ) ); qualifiers.add( new TestTypeMirror( "org.mapstruct.test.SomeOtherType" ) ); SelectionParameters params = new SelectionParameters( qualifiers, qualifyingNames, resultType, typeUtils ); assertThat( params.equals( null ) ).as( "Equals with null" ).isFalse(); }
@InvokeOnHeader(CONTROL_ACTION_UNSUBSCRIBE) public void performUnsubscribe(final Message message, AsyncCallback callback) { Map<String, Object> headers = message.getHeaders(); String subscriptionId = (String) headers.getOrDefault(CONTROL_SUBSCRIPTION_ID, configuration.getSubscriptionId()); String subscribeChannel = (String) headers.getOrDefault(CONTROL_SUBSCRIBE_CHANNEL, configuration.getSubscribeChannel()); boolean result = dynamicRouterControlService.removeSubscription(subscribeChannel, subscriptionId); message.setBody(result, boolean.class); callback.done(false); }
@Test void performUnsubscribeAction() { String subscriptionId = "testId"; String subscribeChannel = "testChannel"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_UNSUBSCRIBE, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel, CONTROL_SUBSCRIPTION_ID, subscriptionId); when(message.getHeaders()).thenReturn(headers); Mockito.doNothing().when(callback).done(false); producer.performUnsubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)) .removeSubscription(subscribeChannel, subscriptionId); }
@ShellMethod(key = {"temp_query", "temp query"}, value = "query against created temp view") public String query( @ShellOption(value = {"--sql"}, help = "select query to run against view") final String sql) { try { HoodieCLI.getTempViewProvider().runQuery(sql); return QUERY_SUCCESS; } catch (HoodieException ex) { return QUERY_FAIL; } }
@Test public void testQuery() { Object result = shell.evaluate((MockCommandLineInput) () -> String.format("temp query --sql 'select * from %s'", tableName)); assertEquals(TempViewCommand.QUERY_SUCCESS, result.toString()); }
@Override protected ReadableByteChannel open(LocalResourceId resourceId) throws IOException { LOG.debug("opening file {}", resourceId); @SuppressWarnings("resource") // The caller is responsible for closing the channel. FileInputStream inputStream = new FileInputStream(resourceId.getPath().toFile()); // Use this method for creating the channel (rather than new FileChannel) so that we get // regular FileNotFoundException. Closing the underyling channel will close the inputStream. return inputStream.getChannel(); }
@Test public void testReadNonExistentFile() throws Exception { thrown.expect(FileNotFoundException.class); localFileSystem .open( LocalResourceId.fromPath( temporaryFolder.getRoot().toPath().resolve("non-existent-file.txt"), false /* isDirectory */)) .close(); }
public Set<String> getSearchableTags() { return searchableTags.get(); }
@Test public void testGetDefaultSearchableTags() { Assertions.assertEquals(searchableTracesTagsWatcher.getSearchableTags(), Arrays.stream(moduleConfig.getSearchableTracesTags().split(",")).collect(Collectors.toSet())); }
private synchronized boolean validateClientAcknowledgement(long h) { if (h < 0) { throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h); } if (h > MASK) { throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but was: " + h); } final long oldH = clientProcessedStanzas.get(); final Long lastUnackedX = unacknowledgedServerStanzas.isEmpty() ? null : unacknowledgedServerStanzas.getLast().x; return validateClientAcknowledgement(h, oldH, lastUnackedX); }
@Test public void testValidateClientAcknowledgement_rollover_edgecase3() throws Exception { // Setup test fixture. final long MAX = new BigInteger( "2" ).pow( 32 ).longValue() - 1; final long h = 0; final long oldH = MAX-2; final Long lastUnackedX = 0L; // Execute system under test. final boolean result = StreamManager.validateClientAcknowledgement(h, oldH, lastUnackedX); // Verify results. assertTrue(result); }
@SuppressWarnings("unchecked") public static String encode(Type parameter) { if (parameter instanceof NumericType) { return encodeNumeric(((NumericType) parameter)); } else if (parameter instanceof Address) { return encodeAddress((Address) parameter); } else if (parameter instanceof Bool) { return encodeBool((Bool) parameter); } else if (parameter instanceof Bytes) { return encodeBytes((Bytes) parameter); } else if (parameter instanceof DynamicBytes) { return encodeDynamicBytes((DynamicBytes) parameter); } else if (parameter instanceof Utf8String) { return encodeString((Utf8String) parameter); } else if (parameter instanceof StaticArray) { if (DynamicStruct.class.isAssignableFrom( ((StaticArray) parameter).getComponentType())) { return encodeStaticArrayWithDynamicStruct((StaticArray) parameter); } else { return encodeArrayValues((StaticArray) parameter); } } else if (parameter instanceof DynamicStruct) { return encodeDynamicStruct((DynamicStruct) parameter); } else if (parameter instanceof DynamicArray) { return encodeDynamicArray((DynamicArray) parameter); } else if (parameter instanceof PrimitiveType) { return encode(((PrimitiveType) parameter).toSolidityType()); } else { throw new UnsupportedOperationException( "Type cannot be encoded: " + parameter.getClass()); } }
@Test public void testPrimitiveChar() { assertEquals( encode(new Char('a')), ("0000000000000000000000000000000000000000000000000000000000000001" + "6100000000000000000000000000000000000000000000000000000000000000")); assertEquals( encode(new Char(' ')), ("0000000000000000000000000000000000000000000000000000000000000001" + "2000000000000000000000000000000000000000000000000000000000000000")); }
public static String getPackageName(Class<?> clazz) { return getPackageName(clazz.getName()); }
@Test public void testGetPackageNameForSimpleName() { String packageName = ClassUtils.getPackageName(AbstractMap.class.getSimpleName()); assertEquals("", packageName); }
public static List<String> extractLinks(String content) { if (content == null || content.length() == 0) { return Collections.emptyList(); } List<String> extractions = new ArrayList<>(); final Matcher matcher = LINKS_PATTERN.matcher(content); while (matcher.find()) { extractions.add(matcher.group()); } return extractions; }
@Test public void testExtractLinksHttp() { List<String> links = RegexUtils.extractLinks( "Test with http://www.nutch.org/index.html is it found? " + "What about www.google.com at http://www.google.de " + "A longer URL could be http://www.sybit.com/solutions/portals.html"); assertTrue(links.size() == 3, "Url not found!"); assertEquals("http://www.nutch.org/index.html", links.get(0), "Wrong URL"); assertEquals("http://www.google.de", links.get(1), "Wrong URL"); assertEquals("http://www.sybit.com/solutions/portals.html", links.get(2), "Wrong URL"); }
public static PTransform<PCollection<String>, PCollection<Row>> withSchemaAndNullBehavior( Schema rowSchema, NullBehavior nullBehavior) { RowJson.verifySchemaSupported(rowSchema); return new JsonToRowFn(rowSchema, nullBehavior); }
@Test @Category(NeedsRunner.class) public void testParsesRowsMissing() throws Exception { PCollection<String> jsonPersons = pipeline.apply("jsonPersons", Create.of(JSON_PERSON_WITH_IMPLICIT_NULLS)); PCollection<Row> personRows = jsonPersons .apply( ((JsonToRowFn) JsonToRow.withSchemaAndNullBehavior( PERSON_SCHEMA_WITH_NULLABLE_FIELD, NullBehavior.ACCEPT_MISSING_OR_NULL))) .setRowSchema(PERSON_SCHEMA_WITH_NULLABLE_FIELD); PAssert.that(personRows).containsInAnyOrder(PERSON_ROWS_WITH_NULLS); pipeline.run(); }
public boolean watch(String vGroup) { String namingAddr = getNamingAddr(); String clientAddr = NetUtil.getLocalHost(); StringBuilder watchAddrBuilder = new StringBuilder(HTTP_PREFIX) .append(namingAddr) .append("/naming/v1/watch?") .append(VGROUP_KEY).append("=").append(vGroup) .append("&").append(CLIENT_TERM_KEY).append("=").append(term) .append("&").append(TIME_OUT_KEY).append("=").append(LONG_POLL_TIME_OUT_PERIOD) .append("&clientAddr=").append(clientAddr); String watchAddr = watchAddrBuilder.toString(); try (CloseableHttpResponse response = HttpClientUtil.doPost(watchAddr, (String) null, null, 30000)) { if (response != null) { StatusLine statusLine = response.getStatusLine(); return statusLine != null && statusLine.getStatusCode() == HttpStatus.SC_OK; } } catch (Exception e) { LOGGER.error("watch failed: {}", e.getMessage()); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException ignored) { } } return false; }
@Test public void testWatch() throws Exception { NamingserverRegistryServiceImpl registryService = (NamingserverRegistryServiceImpl) new NamingserverRegistryProvider().provide(); //1.注册cluster1下的一个节点 InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8088); registryService.register(inetSocketAddress1); ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); int delaySeconds = 500; //2.延迟0.5s后在cluster1下创建事务分组group1 executor.schedule(() -> { try { String namespace = FILE_CONFIG.getConfig("registry.namingserver.namespace"); createGroupInCluster(namespace, "group1", "cluster1"); } catch (Exception e) { throw new RuntimeException(e); } executor.shutdown(); // 任务执行后关闭执行器 }, delaySeconds, TimeUnit.MILLISECONDS); //3.watch事务分组group1 long timestamp1 = System.currentTimeMillis(); boolean needFetch = registryService.watch("group1"); long timestamp2 = System.currentTimeMillis(); //4. 0.5s后group1被映射到cluster1下,应该有数据在1s内推送到client端 assert timestamp2 - timestamp1 < 1500; //5. 获取实例 List<InetSocketAddress> list = registryService.lookup("group1"); registryService.unsubscribe("group1"); assertEquals(list.size(), 1); InetSocketAddress inetSocketAddress = list.get(0); assertEquals(inetSocketAddress.getAddress().getHostAddress(), "127.0.0.1"); assertEquals(inetSocketAddress.getPort(), 8088); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof OutboundPacket) { final DefaultOutboundPacket other = (DefaultOutboundPacket) obj; return Objects.equals(this.sendThrough, other.sendThrough) && Objects.equals(this.treatment, other.treatment) && Objects.equals(this.data, other.data) && Objects.equals(this.inPort, other.inPort); } return false; }
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(packet1, sameAsPacket1) .addEqualityGroup(packet2) .addEqualityGroup(packet1WithInPort) .testEquals(); }
@Override public int size() { return unmodifiableList.size(); }
@Test public void testPrimaryConstructor() { HDPath path = new HDPath(true, Collections.emptyList()); assertTrue("Has private key returns false incorrectly", path.hasPrivateKey); assertEquals("Path not empty", path.size(), 0); }
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@SuppressWarnings({"unchecked", "rawtypes"}) @Test void testGenericsNotInSuperclassWithNonGenericClassAtEnd() { // use TypeExtractor RichMapFunction<?, ?> function = new RichMapFunction<ChainedFour, ChainedFour>() { private static final long serialVersionUID = 1L; @Override public ChainedFour map(ChainedFour value) throws Exception { return null; } }; TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, (TypeInformation) TypeInformation.of( new TypeHint<Tuple3<String, Long, String>>() {})); assertThat(ti.isTupleType()).isTrue(); assertThat(ti.getArity()).isEqualTo(3); TupleTypeInfo<?> tti = (TupleTypeInfo<?>) ti; assertThat(tti.getTypeClass()).isEqualTo(ChainedFour.class); assertThat(tti.getTypeAt(0)).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); assertThat(tti.getTypeAt(1)).isEqualTo(BasicTypeInfo.LONG_TYPE_INFO); assertThat(tti.getTypeAt(2)).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); }
MethodSpec buildFunction(AbiDefinition functionDefinition) throws ClassNotFoundException { return buildFunction(functionDefinition, true); }
@Test public void testBuildFunctionStructArrayParameterAndReturn() throws Exception { AbiDefinition functionDefinition = new AbiDefinition( true, Arrays.asList( new NamedType( "a", "tuple[3]", Arrays.asList( new NamedType( "nuu", "tuple", Arrays.asList( new NamedType( "foo", "tuple", Arrays.asList( new NamedType( "id", "string", null, "string", false), new NamedType( "name", "string", null, "string", false)), "struct ComplexStorage.Foo", false)), "struct ComplexStorage.Nuu", false)), "struct ComplexStorage.Nar[3]", false), new NamedType( "b", "tuple[3]", Arrays.asList( new NamedType( "id", "uint256", null, "uint256", false), new NamedType( "data", "uint256", null, "uint256", false)), "struct ComplexStorage.Bar[3]", false), new NamedType( "c", "tuple[]", Arrays.asList( new NamedType( "id", "string", null, "string", false), new NamedType( "name", "string", null, "string", false)), "struct ComplexStorage.Foo[]", false), new NamedType( "d", "tuple[]", Arrays.asList( new NamedType( "nuu", "tuple", Arrays.asList( new NamedType( "foo", "tuple", Arrays.asList( new NamedType( "id", "string", null, "string", false), new NamedType( "name", "string", null, "string", false)), "struct ComplexStorage.Foo", false)), "struct ComplexStorage.Nuu", false)), "struct ComplexStorage.Nar[]", false), new NamedType( "e", "tuple[3]", Arrays.asList( new NamedType( "id", "string", null, "string", false), new NamedType( "name", "string", null, "string", false)), "struct ComplexStorage.Foo[3]", false)), "idNarBarFooArrays", Arrays.asList( new NamedType( "", "tuple[3]", Arrays.asList( new NamedType( "nuu", "tuple", Arrays.asList( new NamedType( "foo", "tuple", Arrays.asList( new NamedType( "id", "string", null, "string", false), new NamedType( "name", "string", null, "string", false)), "struct ComplexStorage.Foo", false)), "struct ComplexStorage.Nuu", false)), "struct ComplexStorage.Nar[3]", false), new NamedType( "", "tuple[3]", Arrays.asList( new NamedType( "id", "uint256", null, "uint256", false), new NamedType( "data", "uint256", null, "uint256", false)), "struct ComplexStorage.Bar[3]", false), new NamedType( "", "tuple[]", Arrays.asList( new NamedType( "id", "string", null, "string", false), new NamedType( "name", "string", null, "string", false)), "struct ComplexStorage.Foo[]", false), new NamedType( "", "tuple[]", Arrays.asList( new NamedType( "nuu", "tuple", Arrays.asList( new NamedType( "foo", "tuple", Arrays.asList( new NamedType( "id", "string", null, "string", false), new NamedType( "name", "string", null, "string", false)), "struct ComplexStorage.Foo", false)), "struct ComplexStorage.Nuu", false)), "struct ComplexStorage.Nar[]", false), new NamedType( "", "tuple[3]", Arrays.asList( new NamedType( "id", "string", null, "string", false), new NamedType( "name", "string", null, "string", false)), "struct ComplexStorage.Foo[3]", false)), "function", false, "pure"); MethodSpec methodSpec = solidityFunctionWrapper.buildFunction(functionDefinition); String expected = "public org.web3j.protocol.core.RemoteFunctionCall<org.web3j.tuples.generated.Tuple5<java.util.List<Nar>, java.util.List<Bar>, java.util.List<Foo>, java.util.List<Nar>, java.util.List<Foo>>> idNarBarFooArrays(\n" + " java.util.List<Nar> a, java.util.List<Bar> b, java.util.List<Foo> c, java.util.List<Nar> d,\n" + " java.util.List<Foo> e) {\n" + " final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_IDNARBARFOOARRAYS, \n" + " java.util.Arrays.<org.web3j.abi.datatypes.Type>asList(new org.web3j.abi.datatypes.generated.StaticArray3<Nar>(\n" + " Nar.class,\n" + " org.web3j.abi.Utils.typeMap(a, Nar.class)), \n" + " new org.web3j.abi.datatypes.generated.StaticArray3<Bar>(\n" + " Bar.class,\n" + " org.web3j.abi.Utils.typeMap(b, Bar.class)), \n" + " new org.web3j.abi.datatypes.DynamicArray<Foo>(\n" + " Foo.class,\n" + " org.web3j.abi.Utils.typeMap(c, Foo.class)), \n" + " new org.web3j.abi.datatypes.DynamicArray<Nar>(\n" + " Nar.class,\n" + " org.web3j.abi.Utils.typeMap(d, Nar.class)), \n" + " new org.web3j.abi.datatypes.generated.StaticArray3<Foo>(\n" + " Foo.class,\n" + " org.web3j.abi.Utils.typeMap(e, Foo.class))), \n" + " java.util.Arrays.<org.web3j.abi.TypeReference<?>>asList(new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.generated.StaticArray3<Nar>>() {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.generated.StaticArray3<Bar>>() {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.DynamicArray<Foo>>() {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.DynamicArray<Nar>>() {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.generated.StaticArray3<Foo>>() {}));\n" + " return new org.web3j.protocol.core.RemoteFunctionCall<org.web3j.tuples.generated.Tuple5<java.util.List<Nar>, java.util.List<Bar>, java.util.List<Foo>, java.util.List<Nar>, java.util.List<Foo>>>(function,\n" + " new java.util.concurrent.Callable<org.web3j.tuples.generated.Tuple5<java.util.List<Nar>, java.util.List<Bar>, java.util.List<Foo>, java.util.List<Nar>, java.util.List<Foo>>>() {\n" + " @java.lang.Override\n" + " public org.web3j.tuples.generated.Tuple5<java.util.List<Nar>, java.util.List<Bar>, java.util.List<Foo>, java.util.List<Nar>, java.util.List<Foo>> call(\n" + " ) throws java.lang.Exception {\n" + " java.util.List<org.web3j.abi.datatypes.Type> results = executeCallMultipleValueReturn(function);\n" + " return new org.web3j.tuples.generated.Tuple5<java.util.List<Nar>, java.util.List<Bar>, java.util.List<Foo>, java.util.List<Nar>, java.util.List<Foo>>(\n" + " convertToNative((java.util.List<Nar>) results.get(0).getValue()), \n" + " convertToNative((java.util.List<Bar>) results.get(1).getValue()), \n" + " convertToNative((java.util.List<Foo>) results.get(2).getValue()), \n" + " convertToNative((java.util.List<Nar>) results.get(3).getValue()), \n" + " convertToNative((java.util.List<Foo>) results.get(4).getValue()));\n" + " }\n" + " });\n" + "}\n"; assertEquals(expected, methodSpec.toString()); }
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = DODGY_PROTECT_PATTERN.matcher(message); Matcher dodgyBreakMatcher = DODGY_BREAK_PATTERN.matcher(message); Matcher bindingNecklaceCheckMatcher = BINDING_CHECK_PATTERN.matcher(message); Matcher bindingNecklaceUsedMatcher = BINDING_USED_PATTERN.matcher(message); Matcher ringOfForgingCheckMatcher = RING_OF_FORGING_CHECK_PATTERN.matcher(message); Matcher amuletOfChemistryCheckMatcher = AMULET_OF_CHEMISTRY_CHECK_PATTERN.matcher(message); Matcher amuletOfChemistryUsedMatcher = AMULET_OF_CHEMISTRY_USED_PATTERN.matcher(message); Matcher amuletOfChemistryBreakMatcher = AMULET_OF_CHEMISTRY_BREAK_PATTERN.matcher(message); Matcher amuletOfBountyCheckMatcher = AMULET_OF_BOUNTY_CHECK_PATTERN.matcher(message); Matcher amuletOfBountyUsedMatcher = AMULET_OF_BOUNTY_USED_PATTERN.matcher(message); Matcher chronicleAddMatcher = CHRONICLE_ADD_PATTERN.matcher(message); Matcher chronicleUseAndCheckMatcher = CHRONICLE_USE_AND_CHECK_PATTERN.matcher(message); Matcher slaughterActivateMatcher = BRACELET_OF_SLAUGHTER_ACTIVATE_PATTERN.matcher(message); Matcher slaughterCheckMatcher = BRACELET_OF_SLAUGHTER_CHECK_PATTERN.matcher(message); Matcher expeditiousActivateMatcher = EXPEDITIOUS_BRACELET_ACTIVATE_PATTERN.matcher(message); Matcher expeditiousCheckMatcher = EXPEDITIOUS_BRACELET_CHECK_PATTERN.matcher(message); Matcher bloodEssenceCheckMatcher = BLOOD_ESSENCE_CHECK_PATTERN.matcher(message); Matcher bloodEssenceExtractMatcher = BLOOD_ESSENCE_EXTRACT_PATTERN.matcher(message); Matcher braceletOfClayCheckMatcher = BRACELET_OF_CLAY_CHECK_PATTERN.matcher(message); if (message.contains(RING_OF_RECOIL_BREAK_MESSAGE)) { notifier.notify(config.recoilNotification(), "Your Ring of Recoil has shattered"); } else if (dodgyBreakMatcher.find()) { notifier.notify(config.dodgyNotification(), "Your dodgy necklace has crumbled to dust."); updateDodgyNecklaceCharges(MAX_DODGY_CHARGES); } else if (dodgyCheckMatcher.find()) { updateDodgyNecklaceCharges(Integer.parseInt(dodgyCheckMatcher.group(1))); } else if (dodgyProtectMatcher.find()) { updateDodgyNecklaceCharges(Integer.parseInt(dodgyProtectMatcher.group(1))); } else if (amuletOfChemistryCheckMatcher.find()) { updateAmuletOfChemistryCharges(Integer.parseInt(amuletOfChemistryCheckMatcher.group(1))); } else if (amuletOfChemistryUsedMatcher.find()) { final String match = amuletOfChemistryUsedMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateAmuletOfChemistryCharges(charges); } else if (amuletOfChemistryBreakMatcher.find()) { notifier.notify(config.amuletOfChemistryNotification(), "Your amulet of chemistry has crumbled to dust."); updateAmuletOfChemistryCharges(MAX_AMULET_OF_CHEMISTRY_CHARGES); } else if (amuletOfBountyCheckMatcher.find()) { updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyCheckMatcher.group(1))); } else if (amuletOfBountyUsedMatcher.find()) { updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyUsedMatcher.group(1))); } else if (message.equals(AMULET_OF_BOUNTY_BREAK_TEXT)) { updateAmuletOfBountyCharges(MAX_AMULET_OF_BOUNTY_CHARGES); } else if (message.contains(BINDING_BREAK_TEXT)) { notifier.notify(config.bindingNotification(), BINDING_BREAK_TEXT); // This chat message triggers before the used message so add 1 to the max charges to ensure proper sync updateBindingNecklaceCharges(MAX_BINDING_CHARGES + 1); } else if (bindingNecklaceUsedMatcher.find()) { final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); if (equipment.contains(ItemID.BINDING_NECKLACE)) { updateBindingNecklaceCharges(getItemCharges(ItemChargeConfig.KEY_BINDING_NECKLACE) - 1); } } else if (bindingNecklaceCheckMatcher.find()) { final String match = bindingNecklaceCheckMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateBindingNecklaceCharges(charges); } else if (ringOfForgingCheckMatcher.find()) { final String match = ringOfForgingCheckMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateRingOfForgingCharges(charges); } else if (message.equals(RING_OF_FORGING_USED_TEXT) || message.equals(RING_OF_FORGING_VARROCK_PLATEBODY)) { final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY); final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); // Determine if the player smelted with a Ring of Forging equipped. if (equipment == null) { return; } if (equipment.contains(ItemID.RING_OF_FORGING) && (message.equals(RING_OF_FORGING_USED_TEXT) || inventory.count(ItemID.IRON_ORE) > 1)) { int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_RING_OF_FORGING) - 1, 0, MAX_RING_OF_FORGING_CHARGES); updateRingOfForgingCharges(charges); } } else if (message.equals(RING_OF_FORGING_BREAK_TEXT)) { notifier.notify(config.ringOfForgingNotification(), "Your ring of forging has melted."); // This chat message triggers before the used message so add 1 to the max charges to ensure proper sync updateRingOfForgingCharges(MAX_RING_OF_FORGING_CHARGES + 1); } else if (chronicleAddMatcher.find()) { final String match = chronicleAddMatcher.group(1); if (match.equals("one")) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1); } else { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(match)); } } else if (chronicleUseAndCheckMatcher.find()) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(chronicleUseAndCheckMatcher.group(1))); } else if (message.equals(CHRONICLE_ONE_CHARGE_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1); } else if (message.equals(CHRONICLE_EMPTY_TEXT) || message.equals(CHRONICLE_NO_CHARGES_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 0); } else if (message.equals(CHRONICLE_FULL_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1000); } else if (slaughterActivateMatcher.find()) { final String found = slaughterActivateMatcher.group(1); if (found == null) { updateBraceletOfSlaughterCharges(MAX_SLAYER_BRACELET_CHARGES); notifier.notify(config.slaughterNotification(), BRACELET_OF_SLAUGHTER_BREAK_TEXT); } else { updateBraceletOfSlaughterCharges(Integer.parseInt(found)); } } else if (slaughterCheckMatcher.find()) { updateBraceletOfSlaughterCharges(Integer.parseInt(slaughterCheckMatcher.group(1))); } else if (expeditiousActivateMatcher.find()) { final String found = expeditiousActivateMatcher.group(1); if (found == null) { updateExpeditiousBraceletCharges(MAX_SLAYER_BRACELET_CHARGES); notifier.notify(config.expeditiousNotification(), EXPEDITIOUS_BRACELET_BREAK_TEXT); } else { updateExpeditiousBraceletCharges(Integer.parseInt(found)); } } else if (expeditiousCheckMatcher.find()) { updateExpeditiousBraceletCharges(Integer.parseInt(expeditiousCheckMatcher.group(1))); } else if (bloodEssenceCheckMatcher.find()) { updateBloodEssenceCharges(Integer.parseInt(bloodEssenceCheckMatcher.group(1))); } else if (bloodEssenceExtractMatcher.find()) { updateBloodEssenceCharges(getItemCharges(ItemChargeConfig.KEY_BLOOD_ESSENCE) - Integer.parseInt(bloodEssenceExtractMatcher.group(1))); } else if (message.contains(BLOOD_ESSENCE_ACTIVATE_TEXT)) { updateBloodEssenceCharges(MAX_BLOOD_ESSENCE_CHARGES); } else if (braceletOfClayCheckMatcher.find()) { updateBraceletOfClayCharges(Integer.parseInt(braceletOfClayCheckMatcher.group(1))); } else if (message.equals(BRACELET_OF_CLAY_USE_TEXT) || message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN)) { final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); // Determine if the player mined with a Bracelet of Clay equipped. if (equipment != null && equipment.contains(ItemID.BRACELET_OF_CLAY)) { final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY); // Charge is not used if only 1 inventory slot is available when mining in Prifddinas boolean ignore = inventory != null && inventory.count() == 27 && message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN); if (!ignore) { int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_BRACELET_OF_CLAY) - 1, 0, MAX_BRACELET_OF_CLAY_CHARGES); updateBraceletOfClayCharges(charges); } } } else if (message.equals(BRACELET_OF_CLAY_BREAK_TEXT)) { notifier.notify(config.braceletOfClayNotification(), "Your bracelet of clay has crumbled to dust"); updateBraceletOfClayCharges(MAX_BRACELET_OF_CLAY_CHARGES); } } }
@Test public void testChemistryCheck() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_AMULET_OF_CHEMISTRY, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_AMULET_OF_CHEMISTRY, 5); }
@Override public boolean match(Message msg, StreamRule rule) { if (msg.getField(rule.getField()) == null) return rule.getInverted(); try { final Pattern pattern = patternCache.get(rule.getValue()); final CharSequence charSequence = new InterruptibleCharSequence(msg.getField(rule.getField()).toString()); return rule.getInverted() ^ pattern.matcher(charSequence).find(); } catch (ExecutionException e) { LOG.error("Unable to get pattern from regex cache: ", e); } return false; }
@Test public void testSuccessfulMatch() { StreamRule rule = getSampleRule(); rule.setValue("^foo"); Message msg = getSampleMessage(); msg.addField("something", "foobar"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, rule)); }
public static ProducingResult createProducingResult( ResolvedSchema inputSchema, @Nullable Schema declaredSchema) { // no schema has been declared by the user, // the schema will be entirely derived from the input if (declaredSchema == null) { // go through data type to erase time attributes final DataType physicalDataType = inputSchema.toSourceRowDataType(); final Schema schema = Schema.newBuilder().fromRowDataType(physicalDataType).build(); return new ProducingResult(null, schema, null); } final List<UnresolvedColumn> declaredColumns = declaredSchema.getColumns(); // the declared schema does not contain physical information, // thus, it only replaces physical columns with metadata rowtime or adds a primary key if (declaredColumns.stream().noneMatch(SchemaTranslator::isPhysical)) { // go through data type to erase time attributes final DataType sourceDataType = inputSchema.toSourceRowDataType(); final DataType physicalDataType = patchDataTypeWithoutMetadataRowtime(sourceDataType, declaredColumns); final Schema.Builder builder = Schema.newBuilder(); builder.fromRowDataType(physicalDataType); builder.fromSchema(declaredSchema); return new ProducingResult(null, builder.build(), null); } return new ProducingResult(null, declaredSchema, null); }
@Test void testOutputToRowDataType() { final ResolvedSchema inputSchema = ResolvedSchema.of( Column.physical("c", INT()), Column.physical("a", BOOLEAN()), Column.physical("B", DOUBLE())); // case-insensitive mapping final DataType physicalDataType = ROW(FIELD("a", BOOLEAN()), FIELD("b", DOUBLE()), FIELD("c", INT())); final ProducingResult result = SchemaTranslator.createProducingResult( dataTypeFactory(), inputSchema, physicalDataType); assertThat(result.getProjections()).hasValue(Arrays.asList("a", "B", "c")); assertThat(result.getSchema()) .isEqualTo( Schema.newBuilder() .column("a", BOOLEAN()) .column("b", DOUBLE()) .column("c", INT()) .build()); assertThat(result.getPhysicalDataType()).hasValue(physicalDataType); }
public HttpHost[] getHttpHosts() { return httpHosts; }
@Test public void usesElasticsearchDefaults() { EsConfig esConfig = new EsConfig(); HttpHost[] httpHosts = esConfig.getHttpHosts(); assertEquals(1, httpHosts.length); assertEquals("http", httpHosts[0].getSchemeName()); assertEquals(9200, httpHosts[0].getPort()); assertEquals("localhost", httpHosts[0].getHostName()); }
@Override public void registerProvider(TableProvider provider) { if (providers.containsKey(provider.getTableType())) { throw new IllegalArgumentException( "Provider is already registered for table type: " + provider.getTableType()); } initTablesFromProvider(provider); this.providers.put(provider.getTableType(), provider); }
@Test(expected = IllegalArgumentException.class) public void testRegisterProvider_duplicatedTableType() throws Exception { store.registerProvider(new MockTableProvider("mock")); store.registerProvider(new MockTableProvider("mock")); }
@Override public String apply(Object lambda) { if (lambda.toString().equals("INSTANCE")) { // Materialized lambda return getExpressionHash(lambda); } if (lambda instanceof Supplier) { lambda = (( Supplier ) lambda).get(); } SerializedLambda extracted = extractLambda( (Serializable) lambda ); String result = getFingerprintsForClass( lambda, extracted ).get( extracted.getImplMethodName() ); if (result == null) { if ( !extracted.getCapturingClass().equals( extracted.getImplClass() ) ) { // the lambda is a method reference result = extracted.getCapturingClass().replace( '/', '.' ) + "::" + extracted.getImplMethodName(); } else { throw new UnsupportedOperationException( "Unable to introspect lambda " + lambda ); } } return result; }
@Test public void testMaterializedLambdaFingerprint() { LambdaIntrospector lambdaIntrospector = new LambdaIntrospector(); String fingerprint = lambdaIntrospector.apply(LambdaPredicate21D56248F6A2E8DA3990031D77D229DD.INSTANCE); assertThat(fingerprint).isEqualTo("4DEB93975D9859892B1A5FD4B38E2155"); }
@Override public boolean put(K key, V value) { return get(putAsync(key, value)); }
@Test public void testValues() { RListMultimap<SimpleKey, SimpleValue> map = redisson.getListMultimap("test1"); map.put(new SimpleKey("0"), new SimpleValue("1")); map.put(new SimpleKey("0"), new SimpleValue("1")); map.put(new SimpleKey("0"), new SimpleValue("3")); map.put(new SimpleKey("2"), new SimpleValue("5")); map.put(new SimpleKey("3"), new SimpleValue("4")); assertThat(map.values().size()).isEqualTo(5); assertThat(map.values()).containsOnly(new SimpleValue("1"), new SimpleValue("1"), new SimpleValue("3"), new SimpleValue("5"), new SimpleValue("4")); }
@Override public YamlMaskTableRuleConfiguration swapToYamlConfiguration(final MaskTableRuleConfiguration data) { YamlMaskTableRuleConfiguration result = new YamlMaskTableRuleConfiguration(); for (MaskColumnRuleConfiguration each : data.getColumns()) { result.getColumns().put(each.getLogicColumn(), columnSwapper.swapToYamlConfiguration(each)); } result.setName(data.getName()); return result; }
@Test void assertSwapToYamlConfiguration() { Collection<MaskColumnRuleConfiguration> encryptColumnRuleConfigs = Arrays.asList( new MaskColumnRuleConfiguration("mask_column_1", "md5_mask"), new MaskColumnRuleConfiguration("mask_column_2", "keep_from_x_to_y"), new MaskColumnRuleConfiguration("mask_column_3", "keep_first_m_last_m")); MaskTableRuleConfiguration encryptTableRuleConfig = new MaskTableRuleConfiguration("test_table", encryptColumnRuleConfigs); YamlMaskTableRuleConfiguration actualYamlMaskTableRuleConfig = swapper.swapToYamlConfiguration(encryptTableRuleConfig); assertThat(actualYamlMaskTableRuleConfig.getName(), is("test_table")); Map<String, YamlMaskColumnRuleConfiguration> actualColumns = actualYamlMaskTableRuleConfig.getColumns(); assertThat(actualColumns.size(), is(3)); YamlMaskColumnRuleConfiguration actualYamlMaskColumnRuleConfigFirst = actualColumns.get("mask_column_1"); assertThat(actualYamlMaskColumnRuleConfigFirst.getMaskAlgorithm(), is("md5_mask")); YamlMaskColumnRuleConfiguration actualYamlMaskColumnRuleConfigSecond = actualColumns.get("mask_column_2"); assertThat(actualYamlMaskColumnRuleConfigSecond.getMaskAlgorithm(), is("keep_from_x_to_y")); YamlMaskColumnRuleConfiguration actualYamlMaskColumnRuleConfigThird = actualColumns.get("mask_column_3"); assertThat(actualYamlMaskColumnRuleConfigThird.getMaskAlgorithm(), is("keep_first_m_last_m")); }
public KsqlTarget target(final URI server) { return target(server, Collections.emptyMap()); }
@Test public void shouldExecutePrintTopic() throws Exception { // Given: int numRows = 10; List<String> expectedResponse = setupPrintTopicResponse(numRows); String command = "print topic whatever"; // When: KsqlTarget target = ksqlClient.target(serverUri); RestResponse<StreamPublisher<String>> response = target .postPrintTopicRequest(command, Optional.of(123L)); // Then: assertThat(server.getHttpMethod(), is(HttpMethod.POST)); assertThat(server.getPath(), is("/query")); assertThat(server.getHeaders().get("Accept"), is("application/json")); assertThat(getKsqlRequest(), is(new KsqlRequest(command, properties, Collections.emptyMap(), 123L))); List<String> lines = getElementsFromPublisher(numRows, response.getResponse()); assertThat(lines, is(expectedResponse)); }
@Override public Set<KubevirtPort> ports(String networkId) { checkArgument(!Strings.isNullOrEmpty(networkId), ERR_NULL_PORT_NET_ID); return ImmutableSet.copyOf(kubevirtPortStore.ports().stream() .filter(p -> p.networkId().equals(networkId)) .collect(Collectors.toSet())); }
@Test public void testGetPorts() { createBasicPorts(); assertEquals("Number of port did not match", 1, target.ports().size()); }
@Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { try { final SoftwareVersionData version = session.softwareVersion(); final Matcher matcher = Pattern.compile(SDSSession.VERSION_REGEX).matcher(version.getRestApiVersion()); if(matcher.matches()) { if(new Version(matcher.group(1)).compareTo(new Version("4.22")) < 0) { throw new UnsupportedException(); } } final Node latest; if(containerService.isContainer(file)) { latest = new NodesApi(session.getClient()).updateRoom(new UpdateRoomRequest() .timestampCreation(null != status.getCreated() ? new DateTime(status.getCreated()) : null) .timestampModification(null != status.getModified() ? new DateTime(status.getModified()) : null), Long.parseLong(nodeid.getVersionId(file)), StringUtils.EMPTY, null); } else if(file.isDirectory()) { latest = new NodesApi(session.getClient()).updateFolder(new UpdateFolderRequest() .timestampCreation(null != status.getCreated() ? new DateTime(status.getCreated()) : null) .timestampModification(null != status.getModified() ? new DateTime(status.getModified()) : null), Long.parseLong(nodeid.getVersionId(file)), StringUtils.EMPTY, null); } else { latest = new NodesApi(session.getClient()).updateFile(new UpdateFileRequest() .timestampCreation(null != status.getCreated() ? new DateTime(status.getCreated()) : null) .timestampModification(null != status.getModified() ? new DateTime(status.getModified()) : null), Long.parseLong(nodeid.getVersionId(file)), StringUtils.EMPTY, null); } status.setResponse(new SDSAttributesAdapter(session).toAttributes(latest)); } catch(ApiException e) { throw new SDSExceptionMappingService(nodeid).map("Failure to write attributes of {0}", e, file); } }
@Test public void testWriteTimestampFolder() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus()); final Path test = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(room, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus()); new SDSTimestampFeature(session, nodeid).setTimestamp(test, 1599047952805L); final SDSAttributesFinderFeature f = new SDSAttributesFinderFeature(session, nodeid); final PathAttributes attributes = f.find(test); assertEquals(1599047952805L, attributes.getModificationDate()); new SDSDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public static HttpRequestMessage getRequestFromChannel(Channel ch) { return ch.attr(ATTR_ZUUL_REQ).get(); }
@Test void maxHeaderSizeExceeded_setBadRequestStatus() { int maxInitialLineLength = BaseZuulChannelInitializer.MAX_INITIAL_LINE_LENGTH.get(); int maxHeaderSize = 10; int maxChunkSize = BaseZuulChannelInitializer.MAX_CHUNK_SIZE.get(); ClientRequestReceiver receiver = new ClientRequestReceiver(null); EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestEncoder()); PassportLoggingHandler loggingHandler = new PassportLoggingHandler(new DefaultRegistry()); // Required for messages channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); channel.pipeline().addLast(new HttpServerCodec(maxInitialLineLength, maxHeaderSize, maxChunkSize, false)); channel.pipeline().addLast(receiver); channel.pipeline().addLast(loggingHandler); String str = "test-header-value"; ByteBuf buf = Unpooled.buffer(1); HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post", buf); for (int i = 0; i < 100; i++) { httpRequest.headers().add("test-header" + i, str); } channel.writeOutbound(httpRequest); ByteBuf byteBuf = channel.readOutbound(); channel.writeInbound(byteBuf); channel.readInbound(); channel.close(); HttpRequestMessage request = ClientRequestReceiver.getRequestFromChannel(channel); assertEquals( ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST, StatusCategoryUtils.getStatusCategory(request.getContext())); assertEquals( "Invalid request provided: Decode failure", StatusCategoryUtils.getStatusCategoryReason(request.getContext())); }
void finishReport() { List<StepDefContainer> stepDefContainers = new ArrayList<>(); for (Map.Entry<String, List<StepContainer>> usageEntry : usageMap.entrySet()) { StepDefContainer stepDefContainer = new StepDefContainer( usageEntry.getKey(), createStepContainers(usageEntry.getValue())); stepDefContainers.add(stepDefContainer); } try { Jackson.OBJECT_MAPPER.writeValue(out, stepDefContainers); out.close(); } catch (IOException e) { throw new RuntimeException(e); } }
@Test @Disabled("TODO") void doneWithUsageStatisticStrategies() throws JSONException { OutputStream out = new ByteArrayOutputStream(); UsageFormatter usageFormatter = new UsageFormatter(out); UsageFormatter.StepContainer stepContainer = new UsageFormatter.StepContainer("a step"); UsageFormatter.StepDuration stepDuration = new UsageFormatter.StepDuration(Duration.ofNanos(12345678L), "location.feature"); stepContainer.getDurations().addAll(singletonList(stepDuration)); usageFormatter.usageMap.put("a (.*)", singletonList(stepContainer)); usageFormatter.finishReport(); assertThat(out.toString(), containsString("0.012345678")); String json = "[\n" + " {\n" + " \"source\": \"a (.*)\",\n" + " \"steps\": [\n" + " {\n" + " \"name\": \"a step\",\n" + " \"aggregatedDurations\": {\n" + " \"median\": 0.012345678,\n" + " \"average\": 0.012345678\n" + " },\n" + " \"durations\": [\n" + " {\n" + " \"duration\": 0.012345678,\n" + " \"location\": \"location.feature\"\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + " }\n" + "]"; assertEquals(json, out.toString(), true); }
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void ensure_order_type_random_with_seed_is_used() { RuntimeOptions options = parser .parse("--order", "random:5000") .build(); Pickle a = createPickle("file:path/file1.feature", "a"); Pickle b = createPickle("file:path/file2.feature", "b"); Pickle c = createPickle("file:path/file3.feature", "c"); assertThat(options.getPickleOrder() .orderPickles(Arrays.asList(a, b, c)), contains(c, a, b)); }
public static Status unblock( final UnsafeBuffer logMetaDataBuffer, final UnsafeBuffer termBuffer, final int blockedOffset, final int tailOffset, final int termId) { Status status = NO_ACTION; int frameLength = frameLengthVolatile(termBuffer, blockedOffset); if (frameLength < 0) { resetHeader(logMetaDataBuffer, termBuffer, blockedOffset, termId, -frameLength); status = UNBLOCKED; } else if (0 == frameLength) { int currentOffset = blockedOffset + FRAME_ALIGNMENT; while (currentOffset < tailOffset) { frameLength = frameLengthVolatile(termBuffer, currentOffset); if (frameLength != 0) { if (scanBackToConfirmZeroed(termBuffer, currentOffset, blockedOffset)) { final int length = currentOffset - blockedOffset; resetHeader(logMetaDataBuffer, termBuffer, blockedOffset, termId, length); status = UNBLOCKED; } break; } currentOffset += FRAME_ALIGNMENT; } if (currentOffset == termBuffer.capacity()) { if (0 == frameLengthVolatile(termBuffer, blockedOffset)) { final int length = currentOffset - blockedOffset; resetHeader(logMetaDataBuffer, termBuffer, blockedOffset, termId, length); status = UNBLOCKED_TO_END; } } } return status; }
@Test void shouldTakeNoActionIfMessageCompleteAfterScan() { final int messageLength = HEADER_LENGTH * 4; final int termOffset = 0; final int tailOffset = messageLength * 2; when(mockTermBuffer.getIntVolatile(termOffset)) .thenReturn(0) .thenReturn(messageLength); when(mockTermBuffer.getIntVolatile(messageLength)) .thenReturn(messageLength); assertEquals( NO_ACTION, TermUnblocker.unblock(mockLogMetaDataBuffer, mockTermBuffer, termOffset, tailOffset, TERM_ID)); }
public static FormValidation validateRequired(String value) { if (Util.fixEmptyAndTrim(value) == null) return error(Messages.FormValidation_ValidateRequired()); return ok(); }
@Test public void testValidateRequired_Empty() { FormValidation actual = FormValidation.validateRequired(" "); assertNotNull(actual); assertEquals(FormValidation.Kind.ERROR, actual.kind); }
private static Forest createForest() { Plant grass = new Plant("Grass", "Herb"); Plant oak = new Plant("Oak", "Tree"); Animal zebra = new Animal("Zebra", Set.of(grass), Collections.emptySet()); Animal buffalo = new Animal("Buffalo", Set.of(grass), Collections.emptySet()); Animal lion = new Animal("Lion", Collections.emptySet(), Set.of(zebra, buffalo)); return new Forest("Amazon", Set.of(lion, buffalo, zebra), Set.of(grass, oak)); }
@Test void blobSerializerTest() { Forest forest = createForest(); try (LobSerializer serializer = new BlobSerializer()) { Object serialized = serializer.serialize(forest); int id = serializer.persistToDb(1, forest.getName(), serialized); Object fromDb = serializer.loadFromDb(id, Forest.class.getSimpleName()); Forest forestFromDb = serializer.deSerialize(fromDb); Assertions.assertEquals(forest.hashCode(), forestFromDb.hashCode(), "Hashes of objects after Serializing and Deserializing are the same"); } catch (SQLException | IOException | TransformerException | ParserConfigurationException | SAXException | ClassNotFoundException e) { throw new RuntimeException(e); } }
@Override public Void call() { RemoteLogReadResult result; try { LOGGER.debug("Reading records from remote storage for topic partition {}", fetchInfo.topicPartition); FetchDataInfo fetchDataInfo = remoteReadTimer.time(() -> rlm.read(fetchInfo)); brokerTopicStats.topicStats(fetchInfo.topicPartition.topic()).remoteFetchBytesRate().mark(fetchDataInfo.records.sizeInBytes()); brokerTopicStats.allTopicsStats().remoteFetchBytesRate().mark(fetchDataInfo.records.sizeInBytes()); result = new RemoteLogReadResult(Optional.of(fetchDataInfo), Optional.empty()); } catch (OffsetOutOfRangeException e) { result = new RemoteLogReadResult(Optional.empty(), Optional.of(e)); } catch (Exception e) { brokerTopicStats.topicStats(fetchInfo.topicPartition.topic()).failedRemoteFetchRequestRate().mark(); brokerTopicStats.allTopicsStats().failedRemoteFetchRequestRate().mark(); LOGGER.error("Error occurred while reading the remote data for {}", fetchInfo.topicPartition, e); result = new RemoteLogReadResult(Optional.empty(), Optional.of(e)); } LOGGER.debug("Finished reading records from remote storage for topic partition {}", fetchInfo.topicPartition); quotaManager.record(result.fetchDataInfo.map(fetchDataInfo -> fetchDataInfo.records.sizeInBytes()).orElse(0)); callback.accept(result); return null; }
@Test public void testRemoteLogReaderWithError() throws RemoteStorageException, IOException { when(mockRLM.read(any(RemoteStorageFetchInfo.class))).thenThrow(new RuntimeException("error")); Consumer<RemoteLogReadResult> callback = mock(Consumer.class); RemoteStorageFetchInfo remoteStorageFetchInfo = new RemoteStorageFetchInfo(0, false, new TopicPartition(TOPIC, 0), null, null, false); RemoteLogReader remoteLogReader = new RemoteLogReader(remoteStorageFetchInfo, mockRLM, callback, brokerTopicStats, mockQuotaManager, timer); remoteLogReader.call(); // verify the callback did get invoked with the expected remoteLogReadResult ArgumentCaptor<RemoteLogReadResult> remoteLogReadResultArg = ArgumentCaptor.forClass(RemoteLogReadResult.class); verify(callback, times(1)).accept(remoteLogReadResultArg.capture()); RemoteLogReadResult actualRemoteLogReadResult = remoteLogReadResultArg.getValue(); assertTrue(actualRemoteLogReadResult.error.isPresent()); assertFalse(actualRemoteLogReadResult.fetchDataInfo.isPresent()); // verify the record method on quota manager was called with the expected value ArgumentCaptor<Double> recordedArg = ArgumentCaptor.forClass(Double.class); verify(mockQuotaManager, times(1)).record(recordedArg.capture()); assertEquals(0, recordedArg.getValue()); // Verify metrics for remote reads are updated correctly assertEquals(1, brokerTopicStats.topicStats(TOPIC).remoteFetchRequestRate().count()); assertEquals(0, brokerTopicStats.topicStats(TOPIC).remoteFetchBytesRate().count()); assertEquals(1, brokerTopicStats.topicStats(TOPIC).failedRemoteFetchRequestRate().count()); // Verify aggregate metrics assertEquals(1, brokerTopicStats.allTopicsStats().remoteFetchRequestRate().count()); assertEquals(0, brokerTopicStats.allTopicsStats().remoteFetchBytesRate().count()); assertEquals(1, brokerTopicStats.allTopicsStats().failedRemoteFetchRequestRate().count()); }
@Override public String name() { return icebergTable.toString(); }
@TestTemplate public void testTableEquality() throws NoSuchTableException { CatalogManager catalogManager = spark.sessionState().catalogManager(); TableCatalog catalog = (TableCatalog) catalogManager.catalog(catalogName); Identifier identifier = Identifier.of(tableIdent.namespace().levels(), tableIdent.name()); SparkTable table1 = (SparkTable) catalog.loadTable(identifier); SparkTable table2 = (SparkTable) catalog.loadTable(identifier); // different instances pointing to the same table must be equivalent assertThat(table1).as("References must be different").isNotSameAs(table2); assertThat(table1).as("Tables must be equivalent").isEqualTo(table2); }
public static <T> ExtensionLoader<T> getExtensionLoader(final Class<T> clazz, final ClassLoader cl) { Objects.requireNonNull(clazz, "extension clazz is null"); if (!clazz.isInterface()) { throw new IllegalArgumentException("extension clazz (" + clazz + ") is not interface!"); } if (!clazz.isAnnotationPresent(SPI.class)) { throw new IllegalArgumentException("extension clazz (" + clazz + ") without @" + SPI.class + " Annotation"); } ExtensionLoader<T> extensionLoader = (ExtensionLoader<T>) LOADERS.get(clazz); if (Objects.nonNull(extensionLoader)) { return extensionLoader; } LOADERS.putIfAbsent(clazz, new ExtensionLoader<>(clazz, cl)); return (ExtensionLoader<T>) LOADERS.get(clazz); }
@Test public void testLoadClassDuplicateKey() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method loadClassMethod = getLoadClassMethod(); ExtensionLoader<JdbcSPI> extensionLoader = ExtensionLoader.getExtensionLoader(JdbcSPI.class); Map<String, Class<?>> classes = new HashMap<>(); loadClassMethod.invoke(extensionLoader, classes, "mysql", "org.apache.shenyu.spi.fixture.MysqlSPI"); try { loadClassMethod.invoke(extensionLoader, classes, "mysql", "org.apache.shenyu.spi.fixture.OracleSPI"); fail(); } catch (InvocationTargetException expect) { assertThat(expect.getTargetException().getMessage(), containsString( "load extension resources error,Duplicate class org.apache.shenyu.spi.fixture.JdbcSPI name mysql on " + "org.apache.shenyu.spi.fixture.MysqlSPI or org.apache.shenyu.spi.fixture.OracleSPI")); } }
public boolean filterMatchesEntry(String filter, FeedEntry entry) throws FeedEntryFilterException { if (StringUtils.isBlank(filter)) { return true; } Script script; try { script = ENGINE.createScript(filter); } catch (JexlException e) { throw new FeedEntryFilterException("Exception while parsing expression " + filter, e); } JexlContext context = new MapContext(); context.set("title", entry.getContent().getTitle() == null ? "" : Jsoup.parse(entry.getContent().getTitle()).text().toLowerCase()); context.set("author", entry.getContent().getAuthor() == null ? "" : entry.getContent().getAuthor().toLowerCase()); context.set("content", entry.getContent().getContent() == null ? "" : Jsoup.parse(entry.getContent().getContent()).text().toLowerCase()); context.set("url", entry.getUrl() == null ? "" : entry.getUrl().toLowerCase()); context.set("categories", entry.getContent().getCategories() == null ? "" : entry.getContent().getCategories().toLowerCase()); context.set("year", Year.now().getValue()); Callable<Object> callable = script.callable(context); Future<Object> future = executor.submit(callable); Object result; try { result = future.get(config.feedRefresh().filteringExpressionEvaluationTimeout().toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new FeedEntryFilterException("interrupted while evaluating expression " + filter, e); } catch (ExecutionException e) { throw new FeedEntryFilterException("Exception while evaluating expression " + filter, e); } catch (TimeoutException e) { throw new FeedEntryFilterException("Took too long evaluating expression " + filter, e); } try { return (boolean) result; } catch (ClassCastException e) { throw new FeedEntryFilterException(e.getMessage(), e); } }
@Test void newIsDisabled() { Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("null eq new ('java.lang.String', 'athou')", entry)); }
public Transfer deserialize(final T serialized) { final Deserializer<T> dict = factory.create(serialized); final T hostObj = dict.objectForKey("Host"); if(null == hostObj) { log.warn("Missing host in transfer"); return null; } final Host host = new HostDictionary<>(protocols, factory).deserialize(hostObj); if(null == host) { log.warn("Invalid host in transfer"); return null; } host.setWorkdir(null); final List<T> itemsObj = dict.listForKey("Items"); final List<TransferItem> roots = new ArrayList<>(); if(itemsObj != null) { for(T rootDict : itemsObj) { final TransferItem item = new TransferItemDictionary<>(factory).deserialize(rootDict); if(null == item) { log.warn("Invalid item in transfer"); continue; } roots.add(item); } } // Legacy final List<T> rootsObj = dict.listForKey("Roots"); if(rootsObj != null) { for(T rootDict : rootsObj) { final Path remote = new PathDictionary<>(factory).deserialize(rootDict); if(null == remote) { log.warn("Invalid remote in transfer"); continue; } final TransferItem item = new TransferItem(remote); // Legacy final String localObjDeprecated = factory.create(rootDict).stringForKey("Local"); if(localObjDeprecated != null) { Local local = LocalFactory.get(localObjDeprecated); item.setLocal(local); } final T localObj = factory.create(rootDict).objectForKey("Local Dictionary"); if(localObj != null) { Local local = new LocalDictionary<>(factory).deserialize(localObj); if(null == local) { log.warn("Invalid local in transfer item"); continue; } item.setLocal(local); } roots.add(item); } } if(roots.isEmpty()) { log.warn("No files in transfer"); return null; } final Transfer transfer; Transfer.Type type = null; final String kindObj = dict.stringForKey("Kind"); if(kindObj != null) { // Legacy type = Transfer.Type.values()[Integer.parseInt(kindObj)]; } final String typeObj = dict.stringForKey("Type"); if(typeObj != null) { type = Transfer.Type.valueOf(typeObj); } if(null == type) { log.warn("Missing transfer type"); return null; } switch(type) { case download: case upload: case sync: // Verify we have valid items for(TransferItem item : roots) { if(null == item.remote) { log.warn(String.format("Missing remote in transfer item %s", item)); return null; } if(null == item.local) { log.warn(String.format("Missing local in transfer item %s", item)); return null; } } } switch(type) { case download: transfer = new DownloadTransfer(host, roots); break; case upload: transfer = new UploadTransfer(host, roots); break; case sync: final String actionObj = dict.stringForKey("Action"); if(null == actionObj) { transfer = new SyncTransfer(host, roots.iterator().next()); } else { transfer = new SyncTransfer(host, roots.iterator().next(), TransferAction.forName(actionObj)); } break; case copy: final T destinationObj = dict.objectForKey("Destination"); if(null == destinationObj) { log.warn("Missing destination for copy transfer"); return null; } final List<T> destinations = dict.listForKey("Destinations"); if(destinations.isEmpty()) { log.warn("No destinations in copy transfer"); return null; } if(roots.size() == destinations.size()) { final Map<Path, Path> files = new HashMap<>(); for(int i = 0; i < roots.size(); i++) { final Path target = new PathDictionary<>(factory).deserialize(destinations.get(i)); if(null == target) { continue; } files.put(roots.get(i).remote, target); } final Host target = new HostDictionary<>(protocols, factory).deserialize(destinationObj); if(null == target) { log.warn("Missing target host in copy transfer"); return null; } transfer = new CopyTransfer(host, target, files); } else { log.warn("Invalid file mapping for copy transfer"); return null; } break; default: log.warn(String.format("Unknown transfer type %s", kindObj)); return null; } final Object uuidObj = dict.stringForKey("UUID"); if(uuidObj != null) { transfer.setUuid(uuidObj.toString()); } final Object sizeObj = dict.stringForKey("Size"); if(sizeObj != null) { transfer.setSize((long) Double.parseDouble(sizeObj.toString())); } final Object timestampObj = dict.stringForKey("Timestamp"); if(timestampObj != null) { transfer.setTimestamp(new Date(Long.parseLong(timestampObj.toString()))); } final Object currentObj = dict.stringForKey("Current"); if(currentObj != null) { transfer.setTransferred((long) Double.parseDouble(currentObj.toString())); } final Object bandwidthObj = dict.stringForKey("Bandwidth"); if(bandwidthObj != null) { transfer.getBandwidth().setRate(Float.parseFloat(bandwidthObj.toString())); } return transfer; }
@Test public void testSerializeLastSelectedAction() throws Exception { final Path p = new Path("t", EnumSet.of(Path.Type.directory)); final SyncTransfer transfer = new SyncTransfer(new Host(new TestProtocol()), new TransferItem(p, new NullLocal("p", "t") { @Override public boolean exists() { return true; } @Override public AttributedList<Local> list() { return new AttributedList<>(Collections.singletonList(new NullLocal("p", "a"))); } })); transfer.action(null, null, true, false, new DisabledTransferPrompt() { @Override public TransferAction prompt(final TransferItem file) { return TransferAction.upload; } }, new DisabledListProgressListener()); final Transfer serialized = new TransferDictionary<>().deserialize(transfer.serialize(SerializerFactory.get())); assertNotSame(transfer, serialized); assertEquals(TransferAction.upload, serialized.action(null, null, true, false, new DisabledTransferPrompt() { @Override public TransferAction prompt(final TransferItem file) { fail(); return null; } }, new DisabledListProgressListener())); }
public static Map<String, Type> getStrKeyMap(Type type){ return Convert.toMap(String.class, Type.class, get(type)); }
@Test public void getTypeArgumentStrKeyTest(){ final Map<String, Type> typeTypeMap = ActualTypeMapperPool.getStrKeyMap(FinalClass.class); typeTypeMap.forEach((key, value)->{ if("A".equals(key)){ assertEquals(Character.class, value); } else if("B".equals(key)){ assertEquals(Boolean.class, value); } else if("C".equals(key)){ assertEquals(String.class, value); } else if("D".equals(key)){ assertEquals(Double.class, value); } else if("E".equals(key)){ assertEquals(Integer.class, value); } }); }
@Override public void loadData(Priority priority, DataCallback<? super T> callback) { this.callback = callback; serializer.startRequest(priority, url, this); }
@Test public void testLoadData_createsAndStartsRequest() { when(cronetRequestFactory.newRequest( eq(glideUrl.toStringUrl()), eq(UrlRequest.Builder.REQUEST_PRIORITY_LOWEST), anyHeaders(), any(UrlRequest.Callback.class))) .thenReturn(builder); fetcher.loadData(Priority.LOW, callback); verify(request).start(); }
public static Field p(String fieldName) { return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName); }
@Test void test_programmability() { Map<String, String> map = stringStringMap("a", "1", "b", "2", "c", "3"); Query q = map .entrySet() .stream() .map(entry -> Q.p(entry.getKey()).contains(entry.getValue())) .reduce(Query::and) .get(); assertEquals(q.build(), "yql=select * from sources * where a contains \"1\" and b contains \"2\" and c contains \"3\""); }
public static void getSemanticPropsDualFromString( DualInputSemanticProperties result, String[] forwardedFirst, String[] forwardedSecond, String[] nonForwardedFirst, String[] nonForwardedSecond, String[] readFieldsFirst, String[] readFieldsSecond, TypeInformation<?> inType1, TypeInformation<?> inType2, TypeInformation<?> outType) { getSemanticPropsDualFromString( result, forwardedFirst, forwardedSecond, nonForwardedFirst, nonForwardedSecond, readFieldsFirst, readFieldsSecond, inType1, inType2, outType, false); }
@Test void testNonForwardedDualInvalidTypes2() { String[] nonForwardedFieldsSecond = {"f1"}; DualInputSemanticProperties dsp = new DualInputSemanticProperties(); assertThatThrownBy( () -> SemanticPropUtil.getSemanticPropsDualFromString( dsp, null, null, null, nonForwardedFieldsSecond, null, null, threeIntTupleType, pojoInTupleType, threeIntTupleType)) .isInstanceOf(InvalidSemanticAnnotationException.class); }
public Collection<PluginUpdateAggregate> aggregate(@Nullable Collection<PluginUpdate> pluginUpdates) { if (pluginUpdates == null || pluginUpdates.isEmpty()) { return Collections.emptyList(); } Map<Plugin, PluginUpdateAggregateBuilder> builders = new HashMap<>(); for (PluginUpdate pluginUpdate : pluginUpdates) { Plugin plugin = pluginUpdate.getPlugin(); PluginUpdateAggregateBuilder builder = builders.get(plugin); if (builder == null) { builder = PluginUpdateAggregateBuilder.builderFor(plugin); builders.put(plugin, builder); } builder.add(pluginUpdate); } return Lists.newArrayList(transform(builders.values(), PluginUpdateAggregateBuilder::build)); }
@Test public void aggregates_returns_an_empty_collection_when_plugin_collection_is_null() { assertThat(underTest.aggregate(null)).isEmpty(); }
public static <T> CsvReaderFormat<T> forSchema( CsvSchema schema, TypeInformation<T> typeInformation) { return forSchema(JacksonMapperFactory::createCsvMapper, ignored -> schema, typeInformation); }
@Test void testForSchemaWithMapperSerializability() throws IOException, ClassNotFoundException { final CsvReaderFormat<Pojo> format = CsvReaderFormat.forSchema( () -> new CsvMapper(), mapper -> mapper.schemaFor(Pojo.class), TypeInformation.of(Pojo.class)); final byte[] bytes = InstantiationUtil.serializeObject(format); InstantiationUtil.deserializeObject(bytes, CsvReaderFormatTest.class.getClassLoader()); }
@Override public Collection<DatabasePacket> execute() throws SQLException { return Collections.emptyList(); }
@Test void assertNewInstance() throws SQLException { PostgreSQLComFlushExecutor actual = new PostgreSQLComFlushExecutor(); assertThat(actual.execute(), is(Collections.emptyList())); }
public boolean includes(String ipAddress) { if (all) { return true; } if (ipAddress == null) { throw new IllegalArgumentException("ipAddress is null."); } try { return includes(addressFactory.getByName(ipAddress)); } catch (UnknownHostException e) { return false; } }
@Test public void testHostNames() throws UnknownHostException { // create MachineList with a list of of Hostnames TestAddressFactory addressFactory = new TestAddressFactory(); addressFactory.put("1.2.3.1", "host1"); addressFactory.put("1.2.3.4", "host4", "differentname"); addressFactory.put("1.2.3.5", "host5"); MachineList ml = new MachineList( StringUtils.getTrimmedStringCollection(HOST_LIST), addressFactory ); //test for inclusion with an known IP assertTrue(ml.includes("1.2.3.4")); //test for exclusion with an unknown IP assertFalse(ml.includes("1.2.3.5")); }
@Around("dataPermissionCut()") public Object around(final ProceedingJoinPoint point) { // CHECKSTYLE:OFF try { return point.proceed(getFilterSQLData(point)); } catch (Throwable throwable) { throw new ShenyuException(throwable); } // CHECKSTYLE:ON }
@Test public void aroundTest() throws NoSuchMethodException { ProceedingJoinPoint point = mock(ProceedingJoinPoint.class); final MethodSignature signature = mock(MethodSignature.class); when(point.getSignature()).thenReturn(signature); final Method method = DataPermissionAspectTest.class.getMethod("nullMethod"); when(signature.getMethod()).thenReturn(method); assertDoesNotThrow(() -> dataPermissionAspect.around(point)); when(point.getArgs()).thenReturn(null); assertDoesNotThrow(() -> dataPermissionAspect.around(point)); try (MockedStatic<JwtUtils> jwtUtilsMockedStatic = mockStatic(JwtUtils.class)) { when(signature.getMethod()).thenReturn(DataPermissionAspectTest.class.getMethod("selectorMethod")); final Object[] objects = new Object[2]; objects[0] = new FilterQuery(); when(point.getArgs()).thenReturn(objects); jwtUtilsMockedStatic.when(JwtUtils::getUserInfo).thenReturn(new UserInfo()); when(dataPermissionService.getDataPermission(any())).thenReturn(new ArrayList<>()); assertDoesNotThrow(() -> dataPermissionAspect.around(point)); List<String> stringList = new ArrayList<>(); stringList.add("permission"); when(dataPermissionService.getDataPermission(any())).thenReturn(stringList); assertDoesNotThrow(() -> dataPermissionAspect.around(point)); when(signature.getMethod()).thenReturn(DataPermissionAspectTest.class.getMethod("ruleMethod")); assertDoesNotThrow(() -> dataPermissionAspect.around(point)); when(signature.getMethod()).thenReturn(DataPermissionAspectTest.class.getMethod("otherMethod")); assertDoesNotThrow(() -> dataPermissionAspect.around(point)); } }
@Override public JobVertexMetricsMessageParameters getUnresolvedMessageParameters() { return new JobVertexMetricsMessageParameters(); }
@Test void testMessageParameters() { assertThat(jobVertexMetricsHeaders.getUnresolvedMessageParameters()) .isInstanceOf(JobVertexMetricsMessageParameters.class); }
@Override public void initialize(ServiceConfiguration config) throws IOException { String data = config.getProperties().getProperty(CONF_PULSAR_PROPERTY_KEY); if (StringUtils.isEmpty(data)) { data = System.getProperty(CONF_SYSTEM_PROPERTY_KEY); } if (StringUtils.isEmpty(data)) { throw new IOException("No basic authentication config provided"); } @Cleanup BufferedReader reader = null; try { byte[] bytes = readData(data); reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes))); } catch (Exception e) { throw new IllegalArgumentException(e); } users = new HashMap<>(); for (String line : reader.lines().toArray(s -> new String[s])) { List<String> splitLine = Arrays.asList(line.split(":")); if (splitLine.size() != 2) { throw new IOException("The format of the password auth conf file is invalid"); } users.put(splitLine.get(0), splitLine.get(1)); } }
@Test public void testLoadFileFromSystemProperties() throws Exception { @Cleanup AuthenticationProviderBasic provider = new AuthenticationProviderBasic(); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(); System.setProperty("pulsar.auth.basic.conf", basicAuthConf); provider.initialize(serviceConfiguration); testAuthenticate(provider); }
static BlockStmt getInlineTableVariableDeclaration(final String variableName, final InlineTable inlineTable) { final MethodDeclaration methodDeclaration = INLINETABLE_TEMPLATE.getMethodsByName(GETKIEPMMLINLINETABLE).get(0).clone(); final BlockStmt inlineTableBody = methodDeclaration.getBody().orElseThrow(() -> new KiePMMLException(String.format(MISSING_BODY_TEMPLATE, methodDeclaration))); final VariableDeclarator variableDeclarator = getVariableDeclarator(inlineTableBody, INLINETABLE) .orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_IN_BODY, INLINETABLE, inlineTableBody))); variableDeclarator.setName(variableName); final BlockStmt toReturn = new BlockStmt(); int counter = 0; final NodeList<Expression> arguments = new NodeList<>(); for (Row row : inlineTable.getRows()) { String nestedVariableName = String.format(VARIABLE_NAME_TEMPLATE, variableName, counter); arguments.add(new NameExpr(nestedVariableName)); BlockStmt toAdd = getRowVariableDeclaration(nestedVariableName, row); toAdd.getStatements().forEach(toReturn::addStatement); counter ++; } final ObjectCreationExpr objectCreationExpr = variableDeclarator.getInitializer() .orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_INITIALIZER_TEMPLATE, INLINETABLE, toReturn))) .asObjectCreationExpr(); objectCreationExpr.getArguments().set(0, new StringLiteralExpr(variableName)); objectCreationExpr.getArguments().get(2).asMethodCallExpr().setArguments(arguments); inlineTableBody.getStatements().forEach(toReturn::addStatement); return toReturn; }
@Test void getInlineTableVariableDeclaration() throws IOException { String variableName = "variableName"; BlockStmt retrieved = KiePMMLInlineTableFactory.getInlineTableVariableDeclaration(variableName, INLINETABLE); String text = getFileContent(TEST_01_SOURCE); Statement expected = JavaParserUtils.parseBlock(String.format(text, variableName)); assertThat(JavaParserUtils.equalsNode(expected, retrieved)).isTrue(); List<Class<?>> imports = Arrays.asList(Arrays.class, Collections.class, Collectors.class, KiePMMLInlineTable.class, KiePMMLRow.class, Map.class, Stream.class); commonValidateCompilationWithImports(retrieved, imports); }
@ScalarOperator(ADD) @SqlType(StandardTypes.INTEGER) public static long add(@SqlType(StandardTypes.INTEGER) long left, @SqlType(StandardTypes.INTEGER) long right) { try { return Math.addExact((int) left, (int) right); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, format("integer addition overflow: %s + %s", left, right), e); } }
@Test public void testAdd() { assertFunction("INTEGER'37' + INTEGER'37'", INTEGER, 37 + 37); assertFunction("INTEGER'37' + INTEGER'17'", INTEGER, 37 + 17); assertFunction("INTEGER'17' + INTEGER'37'", INTEGER, 17 + 37); assertFunction("INTEGER'17' + INTEGER'17'", INTEGER, 17 + 17); assertNumericOverflow(format("INTEGER'%s' + INTEGER'1'", Integer.MAX_VALUE), "integer addition overflow: 2147483647 + 1"); }
NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId) throws IOException, InterruptedException { // We map the input ConnectionID to a new value to restrict the number of tcp connections connectionId = new ConnectionID( connectionId.getResourceID(), connectionId.getAddress(), connectionId.getConnectionIndex() % maxNumberOfConnections); while (true) { final CompletableFuture<NettyPartitionRequestClient> newClientFuture = new CompletableFuture<>(); final CompletableFuture<NettyPartitionRequestClient> clientFuture = clients.putIfAbsent(connectionId, newClientFuture); final NettyPartitionRequestClient client; if (clientFuture == null) { try { client = connectWithRetries(connectionId); } catch (Throwable e) { newClientFuture.completeExceptionally( new IOException("Could not create Netty client.", e)); clients.remove(connectionId, newClientFuture); throw e; } newClientFuture.complete(client); } else { try { client = clientFuture.get(); } catch (ExecutionException e) { ExceptionUtils.rethrowIOException(ExceptionUtils.stripExecutionException(e)); return null; } } // Make sure to increment the reference count before handing a client // out to ensure correct bookkeeping for channel closing. if (client.validateClientAndIncrementReferenceCounter()) { return client; } else if (client.canBeDisposed()) { client.closeConnection(); } else { destroyPartitionRequestClient(connectionId, client); } } }
@TestTemplate void testFailureReportedToSubsequentRequests() { PartitionRequestClientFactory factory = new PartitionRequestClientFactory( new FailingNettyClient(), 2, 1, connectionReuseEnabled); assertThatThrownBy( () -> factory.createPartitionRequestClient( new ConnectionID( ResourceID.generate(), new InetSocketAddress(InetAddress.getLocalHost(), 8080), 0))); assertThatThrownBy( () -> factory.createPartitionRequestClient( new ConnectionID( ResourceID.generate(), new InetSocketAddress( InetAddress.getLocalHost(), 8080), 0))) .isInstanceOf(IOException.class); }
@Override public Iterator<InternalFactHandle> iterateFactHandles() { return new CompositeFactHandleIterator(concreteStores, true); }
@Test public void iteratingOverFactHandlesHasSameNumberOfResultsAsIteratingOverObjects() throws Exception { insertObjectWithFactHandle(new SuperClass()); insertObjectWithFactHandle(new SubClass()); assertThat(collect(underTest.iterateFactHandles(SubClass.class))).hasSize(1); assertThat(collect(underTest.iterateFactHandles(SuperClass.class))).hasSize(2); }
@Override public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) { if (context.validate()) { try { String accessKey = context.getAccessKey(); String secretKey = context.getSecretKey(); // STS 临时凭证鉴权的优先级高于 AK/SK 鉴权 if (StsConfig.getInstance().isStsOn()) { StsCredential stsCredential = StsCredentialHolder.getInstance().getStsCredential(); accessKey = stsCredential.getAccessKeyId(); secretKey = stsCredential.getAccessKeySecret(); result.setParameter(IdentifyConstants.SECURITY_TOKEN_HEADER, stsCredential.getSecurityToken()); } String signatureKey = secretKey; if (StringUtils.isNotEmpty(context.getRegionId())) { signatureKey = CalculateV4SigningKeyUtil .finalSigningKeyStringWithDefaultInfo(secretKey, context.getRegionId()); result.setParameter(RamConstants.SIGNATURE_VERSION, RamConstants.V4); } String signData = getSignData(getGroupedServiceName(resource)); String signature = SignUtil.sign(signData, signatureKey); result.setParameter(SIGNATURE_FILED, signature); result.setParameter(DATA_FILED, signData); result.setParameter(AK_FILED, accessKey); } catch (Exception e) { NAMING_LOGGER.error("inject ak/sk failed.", e); } } }
@Test void testDoInjectWithEmpty() throws Exception { resource = RequestResource.namingBuilder().setResource("").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); assertEquals(3, actual.getAllKey().size()); assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); assertTrue(Long.parseLong(actual.getParameter("data")) - System.currentTimeMillis() < 100); String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); assertEquals(expectSign, actual.getParameter("signature")); }
public boolean asBoolean() { checkState(type == Type.BOOLEAN, "Value is not a boolean"); return Boolean.parseBoolean(value); }
@Test public void asBoolean() { ConfigProperty p = defineProperty("foo", BOOLEAN, "true", "Foo Prop"); validate(p, "foo", BOOLEAN, "true", "true"); assertEquals("incorrect value", true, p.asBoolean()); }
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) { final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps()); map.put( MetricCollectors.RESOURCE_LABEL_PREFIX + StreamsConfig.APPLICATION_ID_CONFIG, applicationId ); // Streams client metrics aren't used in Confluent deployment possiblyConfigureConfluentTelemetry(map); return Collections.unmodifiableMap(map); }
@Test public void shouldSetStreamsConfigProperties() { final KsqlConfig ksqlConfig = new KsqlConfig( Collections.singletonMap(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, "128")); final Object result = ksqlConfig.getKsqlStreamConfigProps().get( StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG); assertThat(result, equalTo(128L)); }
File decompress() throws IOException { return decompress(uncheck(() -> java.nio.file.Files.createTempDirectory("decompress")).toFile()); }
@Test public void require_that_nested_app_can_be_unpacked() throws IOException, InterruptedException { File gzFile = createTarGz("src/test/resources/deploy/advancedapp"); assertTrue(gzFile.exists()); File outApp; try (CompressedApplicationInputStream unpacked = streamFromTarGz(gzFile)) { outApp = unpacked.decompress(); } List<File> files = List.of(Objects.requireNonNull(outApp.listFiles())); assertEquals(5, files.size()); assertTrue(files.contains(new File(outApp, "services.xml"))); assertTrue(files.contains(new File(outApp, "hosts.xml"))); assertTrue(files.contains(new File(outApp, "deployment.xml"))); assertTrue(files.contains(new File(outApp, "schemas"))); assertTrue(files.contains(new File(outApp, "external"))); File sd = files.get(files.indexOf(new File(outApp, "schemas"))); assertTrue(sd.isDirectory()); assertEquals(1, sd.listFiles().length); assertEquals(new File(sd, "keyvalue.sd").getAbsolutePath(), sd.listFiles()[0].getAbsolutePath()); File ext = files.get(files.indexOf(new File(outApp, "external"))); assertTrue(ext.isDirectory()); assertEquals(1, ext.listFiles().length); assertEquals(new File(ext, "foo").getAbsolutePath(), ext.listFiles()[0].getAbsolutePath()); files = List.of(ext.listFiles()); File foo = files.get(files.indexOf(new File(ext, "foo"))); assertTrue(foo.isDirectory()); assertEquals(1, foo.listFiles().length); assertEquals(new File(foo, "bar").getAbsolutePath(), foo.listFiles()[0].getAbsolutePath()); files = List.of(foo.listFiles()); File bar = files.get(files.indexOf(new File(foo, "bar"))); assertTrue(bar.isDirectory()); assertEquals(1, bar.listFiles().length); assertTrue(bar.listFiles()[0].isFile()); assertEquals(new File(bar, "lol").getAbsolutePath(), bar.listFiles()[0].getAbsolutePath()); }
public GroupInformation createGroup(DbSession dbSession, String name, @Nullable String description) { validateGroupName(name); checkNameDoesNotExist(dbSession, name); GroupDto group = new GroupDto() .setUuid(uuidFactory.create()) .setName(name) .setDescription(description); return groupDtoToGroupInformation(dbClient.groupDao().insert(dbSession, group), dbSession); }
@Test public void createGroup_whenNameAndDescriptionIsProvided_createsGroup() { when(uuidFactory.create()).thenReturn("1234"); GroupDto createdGroup = mockGroupDto(); when(dbClient.groupDao().insert(eq(dbSession), any())).thenReturn(createdGroup); mockDefaultGroup(); groupService.createGroup(dbSession, "Name", "Description"); ArgumentCaptor<GroupDto> groupCaptor = ArgumentCaptor.forClass(GroupDto.class); verify(dbClient.groupDao()).insert(eq(dbSession), groupCaptor.capture()); GroupDto groupToCreate = groupCaptor.getValue(); assertThat(groupToCreate.getName()).isEqualTo("Name"); assertThat(groupToCreate.getDescription()).isEqualTo("Description"); assertThat(groupToCreate.getUuid()).isEqualTo("1234"); }
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) { if (list == null) { return FEELFnResult.ofResult(false); } boolean result = false; for (final Object element : list) { if (element != null && !(element instanceof Boolean)) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not" + " a Boolean")); } else { if (element != null) { result |= (Boolean) element; } } } return FEELFnResult.ofResult(result); }
@Test void invokeArrayParamReturnFalse() { FunctionTestUtil.assertResult(anyFunction.invoke(new Object[]{Boolean.FALSE, Boolean.FALSE}), false); }
@Override public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback) { //This code path cannot accept content types or accept types that contain //multipart/related. This is because these types of requests will usually have very large payloads and therefore //would degrade server performance since RestRequest reads everything into memory. if (!isMultipart(request, requestContext, callback)) { _restRestLiServer.handleRequest(request, requestContext, callback); } }
@Test public void testMultipartRelatedRequestNoUserAttachments() throws Exception { //This test verifies the server's ability to handle a multipart related request that has only one part which is //the rest.li payload; meaning there are no user defined attachments. Technically the client builders shouldn't do //this but we allow this to keep the protocol somewhat flexible. final AsyncStatusCollectionResource statusResource = getMockResource(AsyncStatusCollectionResource.class); statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(), EasyMock.<Callback<Long>> anyObject()); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { //Verify there are no attachments. final RestLiAttachmentReader attachmentReader = (RestLiAttachmentReader)EasyMock.getCurrentArguments()[1]; Assert.assertNull(attachmentReader); //Verify the action param. Assert.assertEquals((String)EasyMock.getCurrentArguments()[0], "someMetadata"); //Now respond back to the request. @SuppressWarnings("unchecked") Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2]; callback.onSuccess(1234l); return null; } }); replay(statusResource); //Now we create a multipart/related payload. final String payload = "{\"metadata\": \"someMetadata\"}"; final ByteStringWriter byteStringWriter = new ByteStringWriter(ByteString.copyString(payload, Charset.defaultCharset())); final MultiPartMIMEWriter.Builder builder = new MultiPartMIMEWriter.Builder(); final MultiPartMIMEWriter writer = AttachmentUtils.createMultiPartMIMEWriter(byteStringWriter, "application/json", builder); final StreamRequest streamRequest = MultiPartMIMEStreamRequestFactory.generateMultiPartMIMEStreamRequest(new URI("/asyncstatuses/?action=streamingAction"), "related", writer, Collections.<String, String>emptyMap(), "POST", ImmutableMap.of(RestConstants.HEADER_ACCEPT, RestConstants.HEADER_VALUE_MULTIPART_RELATED), Collections.emptyList()); final Callback<StreamResponse> callback = new Callback<StreamResponse>() { @Override public void onSuccess(StreamResponse streamResponse) { Messages.toRestResponse(streamResponse, new Callback<RestResponse>() { @Override public void onError(Throwable e) { Assert.fail(); } @Override public void onSuccess(RestResponse result) { Assert.assertEquals(result.getStatus(), 200); try { ContentType contentType = new ContentType(streamResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE)); Assert.assertEquals(contentType.getBaseType(), RestConstants.HEADER_VALUE_APPLICATION_JSON); } catch (ParseException parseException) { Assert.fail(); } //Verify the response body Assert.assertEquals(result.getEntity().asAvroString(), "{\"value\":1234}"); EasyMock.verify(statusResource); EasyMock.reset(statusResource); } }); } @Override public void onError(Throwable e) { fail(); } }; _server.handleRequest(streamRequest, new RequestContext(), callback); }
@VisibleForTesting void validateRoleDuplicate(String name, String code, Long id) { // 0. 超级管理员,不允许创建 if (RoleCodeEnum.isSuperAdmin(code)) { throw exception(ROLE_ADMIN_CODE_ERROR, code); } // 1. 该 name 名字被其它角色所使用 RoleDO role = roleMapper.selectByName(name); if (role != null && !role.getId().equals(id)) { throw exception(ROLE_NAME_DUPLICATE, name); } // 2. 是否存在相同编码的角色 if (!StringUtils.hasText(code)) { return; } // 该 code 编码被其它角色所使用 role = roleMapper.selectByCode(code); if (role != null && !role.getId().equals(id)) { throw exception(ROLE_CODE_DUPLICATE, code); } }
@Test public void testValidateRoleDuplicate_success() { // 调用,不会抛异常 roleService.validateRoleDuplicate(randomString(), randomString(), null); }
public Map<Long, ProducerStateEntry> activeProducers() { return Collections.unmodifiableMap(producers); }
@Test public void testAcceptAppendWithSequenceGapsOnReplica() { appendClientEntry(stateManager, producerId, epoch, defaultSequence, 0L, 0, false); int outOfOrderSequence = 3; // First we ensure that we raise an OutOfOrderSequenceException is raised when to append comes from a client. assertThrows(OutOfOrderSequenceException.class, () -> appendClientEntry(stateManager, producerId, epoch, outOfOrderSequence, 1L, 1, false)); assertTrue(stateManager.activeProducers().containsKey(producerId)); ProducerStateEntry producerStateEntry = stateManager.activeProducers().get(producerId); assertNotNull(producerStateEntry); assertEquals(0L, producerStateEntry.lastSeq()); appendReplicationEntry(stateManager, epoch, outOfOrderSequence, 1L, 1); ProducerStateEntry producerStateEntryForReplication = stateManager.activeProducers().get(producerId); assertNotNull(producerStateEntryForReplication); assertEquals(outOfOrderSequence, producerStateEntryForReplication.lastSeq()); }
public TemplateAnswerResponse getReviewDetail(long reviewId, String reviewRequestCode, String groupAccessCode) { ReviewGroup reviewGroup = reviewGroupRepository.findByReviewRequestCode(reviewRequestCode) .orElseThrow(() -> new ReviewGroupNotFoundByReviewRequestCodeException(reviewRequestCode)); if (!reviewGroup.matchesGroupAccessCode(groupAccessCode)) { throw new ReviewGroupUnauthorizedException(reviewGroup.getId()); } Review review = reviewRepository.findByIdAndReviewGroupId(reviewId, reviewGroup.getId()) .orElseThrow(() -> new ReviewNotFoundByIdAndGroupException(reviewId, reviewGroup.getId())); long templateId = review.getTemplateId(); List<Section> sections = sectionRepository.findAllByTemplateId(templateId); List<SectionAnswerResponse> sectionResponses = new ArrayList<>(); for (Section section : sections) { addSectionResponse(review, reviewGroup, section, sectionResponses); } return new TemplateAnswerResponse( templateId, reviewGroup.getReviewee(), reviewGroup.getProjectName(), review.getCreatedDate(), sectionResponses ); }
@Test void 잘못된_리뷰_요청_코드로_리뷰를_조회할_경우_예외를_발생한다() { // given String reviewRequestCode = "reviewRequestCode"; String groupAccessCode = "groupAccessCode"; ReviewGroup reviewGroup = reviewGroupRepository.save( new ReviewGroup("테드", "리뷰미 프로젝트", reviewRequestCode, groupAccessCode)); Review review = reviewRepository.save(new Review(0, reviewGroup.getId(), List.of(), List.of())); // when, then assertThatThrownBy(() -> reviewDetailLookupService.getReviewDetail( review.getId(), "wrong" + reviewRequestCode, groupAccessCode )).isInstanceOf(ReviewGroupNotFoundByReviewRequestCodeException.class); }
@ExecuteOn(TaskExecutors.IO) @Post(uri = "{namespace}/files/directory") @Operation(tags = {"Files"}, summary = "Create a directory") public void createDirectory( @Parameter(description = "The namespace id") @PathVariable String namespace, @Parameter(description = "The internal storage uri") @Nullable @QueryValue URI path ) throws IOException, URISyntaxException { forbiddenPathsGuard(path); storageInterface.createDirectory(tenantService.resolveTenant(), NamespaceFile.of(namespace, path).uri()); }
@Test void createDirectory() throws IOException { client.toBlocking().exchange(HttpRequest.POST("/api/v1/namespaces/" + NAMESPACE + "/files/directory?path=/test", null)); FileAttributes res = storageInterface.getAttributes(null, toNamespacedStorageUri(NAMESPACE, URI.create("/test"))); assertThat(res.getFileName(), is("test")); assertThat(res.getType(), is(FileAttributes.FileType.Directory)); }
static PMMLRuntimeContext getPMMLRuntimeContext(PMMLRequestData pmmlRequestData, final Map<String, GeneratedResources> generatedResourcesMap) { String fileName = (String) pmmlRequestData.getMappedRequestParams().get(PMML_FILE_NAME).getValue(); PMMLRequestData cleaned = new PMMLRequestData(pmmlRequestData.getCorrelationId(), pmmlRequestData.getModelName()); pmmlRequestData.getRequestParams().stream() .filter(parameterInfo -> !parameterInfo.getName().equals(PMML_FILE_NAME) && !parameterInfo.getName().equals(PMML_MODEL_NAME)) .forEach(cleaned::addRequestParam); PMMLRuntimeContext toReturn = new PMMLRuntimeContextImpl(cleaned, fileName, new KieMemoryCompiler.MemoryCompilerClassLoader(Thread.currentThread().getContextClassLoader())); toReturn.getGeneratedResourcesMap().putAll(generatedResourcesMap); return toReturn; }
@Test void getPMMLRuntimeContextFromMap() { Map<String, Object> inputData = getInputData(MODEL_NAME, FILE_NAME); final Random random = new Random(); IntStream.range(0, 3).forEach(value -> inputData.put("Variable_" + value, random.nextInt(10))); final Map<String, GeneratedResources> generatedResourcesMap = new HashMap<>(); IntStream.range(0, 3).forEach(value -> generatedResourcesMap.put("GenRes_" + value, new GeneratedResources())); PMMLRuntimeContext retrieved = PMMLRuntimeHelper.getPMMLRuntimeContext(inputData, generatedResourcesMap); assertThat(retrieved).isNotNull(); PMMLRequestData pmmlRequestDataRetrieved = retrieved.getRequestData(); assertThat(pmmlRequestDataRetrieved).isNotNull(); assertThat(pmmlRequestDataRetrieved.getMappedRequestParams()).hasSize(inputData.size() - 2); // Removing // PMML_FILE_NAME and PMML_MODEL_NAME assertThat(pmmlRequestDataRetrieved.getMappedRequestParams().entrySet()) .allMatch(entry -> inputData.containsKey(entry.getKey()) && entry.getValue().getValue().equals(inputData.get(entry.getKey()))); Map<String, GeneratedResources> generatedResourcesMapRetrieved = retrieved.getGeneratedResourcesMap(); assertThat(generatedResourcesMapRetrieved).hasSize(generatedResourcesMap.size() + 1); // PMMLRuntimeContext // already contains "pmml" GeneratedResources assertThat(generatedResourcesMap.entrySet()) .allMatch(entry -> generatedResourcesMapRetrieved.containsKey(entry.getKey()) && entry.getValue().equals(generatedResourcesMapRetrieved.get(entry.getKey()))); }
public void dropIndexes() { delegate.dropIndexes(); }
@Test void dropIndexes() { final var collection = jacksonCollection("simple", Simple.class); collection.createIndex(new BasicDBObject("name", 1)); collection.createIndex(new BasicDBObject("name", 1).append("_id", 1)); assertThat(mongoCollection("simple").listIndexes()).extracting("name") .containsExactlyInAnyOrder("_id_", "name_1", "name_1__id_1"); collection.dropIndexes(); assertThat(mongoCollection("simple").listIndexes()).extracting("name") .containsExactlyInAnyOrder("_id_"); }
@Retries.RetryTranslated public void retry(String action, String path, boolean idempotent, Retried retrying, InvocationRaisingIOE operation) throws IOException { retry(action, path, idempotent, retrying, () -> { operation.apply(); return null; }); }
@Test public void testSdkXmlParsingExceptionIsTranslatable() throws Throwable { final AtomicInteger counter = new AtomicInteger(0); invoker.retry("test", null, false, () -> { if (counter.incrementAndGet() < ACTIVE_RETRY_LIMIT) { throw SdkClientException.builder() .message(EOF_MESSAGE_IN_XML_PARSER) .build(); } }); assertEquals(ACTIVE_RETRY_LIMIT, counter.get()); }
public static int checkMaxCollectionLength(long existing, long items) { long length = existing + items; if (existing < 0) { throw new AvroRuntimeException("Malformed data. Length is negative: " + existing); } if (items < 0) { throw new AvroRuntimeException("Malformed data. Length is negative: " + items); } if (length > MAX_ARRAY_VM_LIMIT || length < existing) { throw new UnsupportedOperationException( "Cannot read collections larger than " + MAX_ARRAY_VM_LIMIT + " items in Java library"); } if (length > maxCollectionLength) { throw new SystemLimitException("Collection length " + length + " exceeds maximum allowed"); } return (int) length; }
@Test void testCheckMaxCollectionLengthFromZero() { helpCheckSystemLimits(l -> checkMaxCollectionLength(0L, l), MAX_COLLECTION_LENGTH_PROPERTY, ERROR_VM_LIMIT_COLLECTION, "Collection length 1024 exceeds maximum allowed"); }
@Override public PageResult<SocialClientDO> getSocialClientPage(SocialClientPageReqVO pageReqVO) { return socialClientMapper.selectPage(pageReqVO); }
@Test public void testGetSocialClientPage() { // mock 数据 SocialClientDO dbSocialClient = randomPojo(SocialClientDO.class, o -> { // 等会查询到 o.setName("芋头"); o.setSocialType(SocialTypeEnum.GITEE.getType()); o.setUserType(UserTypeEnum.ADMIN.getValue()); o.setClientId("yudao"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); }); socialClientMapper.insert(dbSocialClient); // 测试 name 不匹配 socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setName(randomString()))); // 测试 socialType 不匹配 socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setSocialType(SocialTypeEnum.DINGTALK.getType()))); // 测试 userType 不匹配 socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setUserType(UserTypeEnum.MEMBER.getValue()))); // 测试 clientId 不匹配 socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setClientId("dao"))); // 测试 status 不匹配 socialClientMapper.insert(cloneIgnoreId(dbSocialClient, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 准备参数 SocialClientPageReqVO reqVO = new SocialClientPageReqVO(); reqVO.setName("芋"); reqVO.setSocialType(SocialTypeEnum.GITEE.getType()); reqVO.setUserType(UserTypeEnum.ADMIN.getValue()); reqVO.setClientId("yu"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 调用 PageResult<SocialClientDO> pageResult = socialClientService.getSocialClientPage(reqVO); // 断言 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); assertPojoEquals(dbSocialClient, pageResult.getList().get(0)); }
public static void appendLines(File file, String[] lines) throws IOException { if (file == null) { throw new IOException("File is null."); } writeLines(new FileOutputStream(file, true), lines); }
@Test void testAppendLines(@TempDir Path tmpDir) throws Exception { File file = tmpDir.getFileName().toAbsolutePath().toFile(); IOUtils.appendLines(file, new String[] {"a", "b", "c"}); String[] lines = IOUtils.readLines(file); assertThat(lines.length, equalTo(3)); assertThat(lines[0], equalTo("a")); assertThat(lines[1], equalTo("b")); assertThat(lines[2], equalTo("c")); tmpDir.getFileName().toAbsolutePath().toFile().delete(); }