focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static IndexIterationPointer union(IndexIterationPointer left, IndexIterationPointer right, Comparator comparator) { assert left.isDescending() == right.isDescending(); assert left.getLastEntryKeyData() == null && right.lastEntryKeyData == null : "Can merge only initial pointers"; Tuple2<Comparable<?>, Boolean> newFrom = min(left.getFrom(), left.isFromInclusive(), right.getFrom(), right.isFromInclusive(), comparator); Tuple2<Comparable<?>, Boolean> newTo = max(left.getTo(), left.isToInclusive(), right.getTo(), right.isToInclusive(), comparator); return IndexIterationPointer.create(newFrom.f0(), newFrom.f1(), newTo.f0(), newTo.f1(), left.isDescending(), null); }
@Test void unionAdjacentSingletonRange() { assertThat(union(pointer(singleton(5)), pointer(singleton(5)), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)).isEqualTo(pointer(singleton(5))); assertThat(union(pointer(singleton(5)), pointer(greaterThan(5)), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)).isEqualTo(pointer(atLeast(5))); // reverse order is also allowed assertThat(union(pointer(greaterThan(5)), pointer(singleton(5)), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)).isEqualTo(pointer(atLeast(5))); assertThat(union(pointer(singleton(5)), pointer(lessThan(5)), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)).isEqualTo(pointer(atMost(5))); // reverse order is also allowed assertThat(union(pointer(lessThan(5)), pointer(singleton(5)), OrderedIndexStore.SPECIAL_AWARE_COMPARATOR)).isEqualTo(pointer(atMost(5))); }
@Override public void reconcileExecutionDeployments( ResourceID taskExecutorHost, ExecutionDeploymentReport executionDeploymentReport, Map<ExecutionAttemptID, ExecutionDeploymentState> expectedDeployedExecutions) { final Set<ExecutionAttemptID> unknownExecutions = new HashSet<>(executionDeploymentReport.getExecutions()); final Set<ExecutionAttemptID> missingExecutions = new HashSet<>(); for (Map.Entry<ExecutionAttemptID, ExecutionDeploymentState> execution : expectedDeployedExecutions.entrySet()) { boolean deployed = unknownExecutions.remove(execution.getKey()); if (!deployed && execution.getValue() != ExecutionDeploymentState.PENDING) { missingExecutions.add(execution.getKey()); } } if (!unknownExecutions.isEmpty()) { handler.onUnknownDeploymentsOf(unknownExecutions, taskExecutorHost); } if (!missingExecutions.isEmpty()) { handler.onMissingDeploymentsOf(missingExecutions, taskExecutorHost); } }
@Test void testMatchingDeployments() { TestingExecutionDeploymentReconciliationHandler handler = new TestingExecutionDeploymentReconciliationHandler(); DefaultExecutionDeploymentReconciler reconciler = new DefaultExecutionDeploymentReconciler(handler); ResourceID resourceId = generate(); ExecutionAttemptID attemptId = createExecutionAttemptId(); reconciler.reconcileExecutionDeployments( resourceId, new ExecutionDeploymentReport(Collections.singleton(attemptId)), Collections.singletonMap(attemptId, ExecutionDeploymentState.DEPLOYED)); assertThat(handler.getMissingExecutions()).isEmpty(); assertThat(handler.getUnknownExecutions()).isEmpty(); }
public static Applications toApplications(Map<String, Application> applicationMap) { Applications applications = new Applications(); for (Application application : applicationMap.values()) { applications.addApplication(application); } return updateMeta(applications); }
@Test public void testToApplicationsIfNotNullReturnApplicationsFromInstances() { InstanceInfo instanceInfo1 = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED).getByInstanceId("foo"); InstanceInfo instanceInfo2 = createSingleInstanceApp("bar", "bar", InstanceInfo.ActionType.ADDED).getByInstanceId("bar"); InstanceInfo instanceInfo3 = createSingleInstanceApp("baz", "baz", InstanceInfo.ActionType.ADDED).getByInstanceId("baz"); Assert.assertEquals(3, EurekaEntityFunctions.toApplications( instanceInfo1, instanceInfo2, instanceInfo3).size()); }
@Override public List<Object> getParameters() { List<Object> result = new LinkedList<>(); for (int i = 0; i < parameterBuilders.size(); i++) { result.addAll(getParameters(i)); } result.addAll(genericParameterBuilder.getParameters()); return result; }
@Test void assertGetParametersWithGenericParameters() { GroupedParameterBuilder actual = new GroupedParameterBuilder(createGroupedParameters(), createGenericParameters()); assertThat(actual.getParameters(), is(Arrays.<Object>asList(3, 4, 5, 6, 7, 8))); assertThat(actual.getGenericParameterBuilder().getParameters(), is(Arrays.<Object>asList(7, 8))); }
public Status listSnapshots(List<String> snapshotNames) { // list with prefix: // eg. __starrocks_repository_repo_name/__ss_* String listPath = Joiner.on(PATH_DELIMITER).join(location, joinPrefix(prefixRepo, name), PREFIX_SNAPSHOT_DIR) + "*"; List<RemoteFile> result = Lists.newArrayList(); Status st = storage.list(listPath, result); if (!st.ok()) { return st; } for (RemoteFile remoteFile : result) { if (remoteFile.isFile()) { LOG.debug("get snapshot path{} which is not a dir", remoteFile); continue; } snapshotNames.add(disjoinPrefix(PREFIX_SNAPSHOT_DIR, remoteFile.getName())); } return Status.OK; }
@Test public void testListSnapshots() { new Expectations() { { storage.list(anyString, (List<RemoteFile>) any); minTimes = 0; result = new Delegate() { public Status list(String remotePath, List<RemoteFile> result) { result.add(new RemoteFile(Repository.PREFIX_SNAPSHOT_DIR + "a", false, 100)); result.add(new RemoteFile("_ss_b", true, 100)); return Status.OK; } }; } }; repo = new Repository(10000, "repo", false, location, storage); List<String> snapshotNames = Lists.newArrayList(); Status st = repo.listSnapshots(snapshotNames); Assert.assertTrue(st.ok()); Assert.assertEquals(1, snapshotNames.size()); Assert.assertEquals("a", snapshotNames.get(0)); }
public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "Rotate"; case INTVAR_EVENT: return "Intvar"; case LOAD_EVENT: return "Load"; case NEW_LOAD_EVENT: return "New_load"; case SLAVE_EVENT: return "Slave"; case CREATE_FILE_EVENT: return "Create_file"; case APPEND_BLOCK_EVENT: return "Append_block"; case DELETE_FILE_EVENT: return "Delete_file"; case EXEC_LOAD_EVENT: return "Exec_load"; case RAND_EVENT: return "RAND"; case XID_EVENT: return "Xid"; case USER_VAR_EVENT: return "User var"; case FORMAT_DESCRIPTION_EVENT: return "Format_desc"; case TABLE_MAP_EVENT: return "Table_map"; case PRE_GA_WRITE_ROWS_EVENT: return "Write_rows_event_old"; case PRE_GA_UPDATE_ROWS_EVENT: return "Update_rows_event_old"; case PRE_GA_DELETE_ROWS_EVENT: return "Delete_rows_event_old"; case WRITE_ROWS_EVENT_V1: return "Write_rows_v1"; case UPDATE_ROWS_EVENT_V1: return "Update_rows_v1"; case DELETE_ROWS_EVENT_V1: return "Delete_rows_v1"; case BEGIN_LOAD_QUERY_EVENT: return "Begin_load_query"; case EXECUTE_LOAD_QUERY_EVENT: return "Execute_load_query"; case INCIDENT_EVENT: return "Incident"; case HEARTBEAT_LOG_EVENT: case HEARTBEAT_LOG_EVENT_V2: return "Heartbeat"; case IGNORABLE_LOG_EVENT: return "Ignorable"; case ROWS_QUERY_LOG_EVENT: return "Rows_query"; case WRITE_ROWS_EVENT: return "Write_rows"; case UPDATE_ROWS_EVENT: return "Update_rows"; case DELETE_ROWS_EVENT: return "Delete_rows"; case GTID_LOG_EVENT: return "Gtid"; case ANONYMOUS_GTID_LOG_EVENT: return "Anonymous_Gtid"; case PREVIOUS_GTIDS_LOG_EVENT: return "Previous_gtids"; case PARTIAL_UPDATE_ROWS_EVENT: return "Update_rows_partial"; case TRANSACTION_CONTEXT_EVENT : return "Transaction_context"; case VIEW_CHANGE_EVENT : return "view_change"; case XA_PREPARE_LOG_EVENT : return "Xa_prepare"; case TRANSACTION_PAYLOAD_EVENT : return "transaction_payload"; default: return "Unknown type:" + type; } }
@Test public void getTypeNameInputPositiveOutputNotNull25() { // Arrange final int type = 25; // Act final String actual = LogEvent.getTypeName(type); // Assert result Assert.assertEquals("Delete_rows_v1", actual); }
@SuppressWarnings({"BooleanExpressionComplexity", "CyclomaticComplexity"}) public static boolean isScalablePushQuery( final Statement statement, final KsqlExecutionContext ksqlEngine, final KsqlConfig ksqlConfig, final Map<String, Object> overrides ) { if (!isPushV2Enabled(ksqlConfig, overrides)) { return false; } if (! (statement instanceof Query)) { return false; } final Query query = (Query) statement; final SourceFinder sourceFinder = new SourceFinder(); sourceFinder.process(query.getFrom(), null); // It will be present if it's not a join, which we don't handle if (!sourceFinder.getSourceName().isPresent()) { return false; } // Find all of the writers to this particular source. final SourceName sourceName = sourceFinder.getSourceName().get(); final Set<QueryId> upstreamQueries = ksqlEngine.getQueriesWithSink(sourceName); // See if the config or override have set the stream to be "latest" final boolean isLatest = isLatest(ksqlConfig, overrides); // Cannot be a pull query, i.e. must be a push return !query.isPullQuery() // Group by is not supported && !query.getGroupBy().isPresent() // Windowing is not supported && !query.getWindow().isPresent() // Having clause is not supported && !query.getHaving().isPresent() // Partition by is not supported && !query.getPartitionBy().isPresent() // There must be an EMIT CHANGES clause && (query.getRefinement().isPresent() && query.getRefinement().get().getOutputRefinement() == OutputRefinement.CHANGES) // Must be reading from "latest" && isLatest // We only handle a single sink source at the moment from a CTAS/CSAS && upstreamQueries.size() == 1 // ROWPARTITION and ROWOFFSET are not currently supported in SPQs && !containsDisallowedColumns(query); }
@Test public void isScalablePushQuery_false_hasHaving() { try(MockedStatic<ColumnExtractor> columnExtractor = mockStatic(ColumnExtractor.class)) { // When: expectIsSPQ(ColumnName.of("foo"), columnExtractor); when(query.getHaving()).thenReturn(Optional.of(new IntegerLiteral(1))); // Then: assertThat(ScalablePushUtil.isScalablePushQuery(query, ksqlEngine, ksqlConfig, ImmutableMap.of(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest")), equalTo(false)); } }
public static void checkMapConfig(Config config, MapConfig mapConfig, SplitBrainMergePolicyProvider mergePolicyProvider) { checkNotNativeWhenOpenSource(mapConfig.getInMemoryFormat()); checkNotBitmapIndexWhenNativeMemory(mapConfig.getInMemoryFormat(), mapConfig.getIndexConfigs()); checkTSEnabledOnEnterpriseJar(mapConfig.getTieredStoreConfig()); if (getBuildInfo().isEnterprise()) { checkTieredStoreMapConfig(config, mapConfig); checkMapNativeConfig(mapConfig, config.getNativeMemoryConfig()); } checkMapEvictionConfig(mapConfig.getEvictionConfig()); checkMapMaxSizePolicyPerInMemoryFormat(mapConfig); checkMapMergePolicy(mapConfig, mapConfig.getMergePolicyConfig().getPolicy(), mergePolicyProvider); }
@Test public void checkMapConfig_OBJECT() { checkMapConfig(new Config(), getMapConfig(OBJECT), splitBrainMergePolicyProvider); }
@Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { try { final FilesApi files = new FilesApi(session.getClient()); status.setResponse(new StoregateAttributesFinderFeature(session, fileid).toAttributes(files.filesUpdateFile(fileid.getFileId(file), new UpdateFilePropertiesRequest() .created(null != status.getCreated() ? new DateTime(status.getCreated()) : null) .modified(null != status.getModified() ? new DateTime(status.getModified()) : null) ) ) ); } catch(ApiException e) { throw new StoregateExceptionMappingService(fileid).map("Failure to write attributes of {0}", e, file); } }
@Test public void testSetTimestampDirectory() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir(new Path( String.format("/My files/%s", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus()); final Path test = new Path(room, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); new StoregateDirectoryFeature(session, nodeid).mkdir(test, null); assertNotNull(new StoregateAttributesFinderFeature(session, nodeid).find(test)); final long modified = Instant.now().minusSeconds(5 * 24 * 60 * 60).getEpochSecond() * 1000; new StoregateTimestampFeature(session, nodeid).setTimestamp(test, modified); assertEquals(modified, new StoregateAttributesFinderFeature(session, nodeid).find(test).getModificationDate()); new StoregateDeleteFeature(session, nodeid).delete(Arrays.asList(test, room), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public Metric(final MetricType type, final String name, final String document, final List<String> labels) { this.type = type; this.name = name; this.document = document; this.labels = labels; }
@Test public void testMetric() { labels = new ArrayList<>(); labels.add("shenyu_request_total"); metric = new Metric(MetricType.COUNTER, NAME, DOCUMENT, labels); Assertions.assertEquals(metric.getType(), MetricType.COUNTER); Assertions.assertEquals(metric.getName(), "testName"); Assertions.assertEquals(metric.getDocument(), "testDocument"); Assertions.assertEquals(metric.getLabels().get(0), "shenyu_request_total"); }
@SuppressWarnings("UnstableApiUsage") @Override public Stream<ColumnName> resolveSelectStar( final Optional<SourceName> sourceName ) { final Stream<ColumnName> names = Stream.of(left, right) .flatMap(JoinNode::getPreJoinProjectDataSources) .filter(s -> !sourceName.isPresent() || sourceName.equals(s.getSourceName())) .flatMap(s -> s.resolveSelectStar(sourceName)); if (sourceName.isPresent() || !joinKey.isSynthetic() || !finalJoin) { return names; } // if we use a synthetic key, we know there's only a single key element final Column syntheticKey = getOnlyElement(getSchema().key()); return Streams.concat(Stream.of(syntheticKey.name()), names); }
@Test public void shouldResolveUnaliasedSelectStarWithMultipleJoinsOnLeftSide() { // Given: final JoinNode inner = new JoinNode(new PlanNodeId("foo"), LEFT, joinKey, true, right, right2, empty(), "KAFKA"); final JoinNode joinNode = new JoinNode(nodeId, LEFT, joinKey, true, inner, left, empty(), "KAFKA"); when(left.resolveSelectStar(any())).thenReturn(Stream.of(ColumnName.of("l"))); when(right.resolveSelectStar(any())).thenReturn(Stream.of(ColumnName.of("r"))); when(right2.resolveSelectStar(any())).thenReturn(Stream.of(ColumnName.of("r2"))); // When: final Stream<ColumnName> result = joinNode.resolveSelectStar(empty()); // Then: final List<ColumnName> columns = result.collect(Collectors.toList()); assertThat(columns, contains(ColumnName.of("r"), ColumnName.of("r2"), ColumnName.of("l"))); verify(left).resolveSelectStar(empty()); verify(right).resolveSelectStar(empty()); verify(right2).resolveSelectStar(empty()); }
public String anonymize(final ParseTree tree) { return build(tree); }
@Test public void shouldLeaveListAndPrintStatementsAsTheyAre() { Assert.assertEquals("LIST PROPERTIES;", anon.anonymize("LIST PROPERTIES;")); Assert.assertEquals("SHOW PROPERTIES;", anon.anonymize("SHOW PROPERTIES;")); Assert.assertEquals("LIST TOPICS;", anon.anonymize("LIST TOPICS;")); Assert.assertEquals("SHOW ALL TOPICS EXTENDED;", anon.anonymize("SHOW ALL TOPICS EXTENDED;")); Assert.assertEquals("LIST STREAMS EXTENDED;", anon.anonymize("LIST STREAMS EXTENDED;")); Assert.assertEquals("LIST FUNCTIONS;", anon.anonymize("LIST FUNCTIONS;")); Assert.assertEquals("LIST CONNECTORS;", anon.anonymize("LIST CONNECTORS;")); Assert.assertEquals("LIST SOURCE CONNECTORS;", anon.anonymize("LIST SOURCE CONNECTORS;")); Assert.assertEquals("LIST TYPES;", anon.anonymize("LIST TYPES;")); Assert.assertEquals("LIST VARIABLES;", anon.anonymize("LIST VARIABLES;")); Assert.assertEquals("LIST QUERIES;", anon.anonymize("LIST QUERIES;")); }
@Override public boolean test(Pickle pickle) { URI picklePath = pickle.getUri(); if (!lineFilters.containsKey(picklePath)) { return true; } for (Integer line : lineFilters.get(picklePath)) { if (Objects.equals(line, pickle.getLocation().getLine()) || Objects.equals(line, pickle.getScenarioLocation().getLine()) || pickle.getExamplesLocation().map(Location::getLine).map(line::equals).orElse(false) || pickle.getRuleLocation().map(Location::getLine).map(line::equals).orElse(false) || pickle.getFeatureLocation().map(Location::getLine).map(line::equals).orElse(false)) { return true; } } return false; }
@Test void matches_scenario() { LinePredicate predicate = new LinePredicate(singletonMap( featurePath, singletonList(3))); assertTrue(predicate.test(firstPickle)); assertTrue(predicate.test(secondPickle)); assertTrue(predicate.test(thirdPickle)); assertTrue(predicate.test(fourthPickle)); }
@Override public String telnet(Channel channel, String message) { if (StringUtils.isEmpty(message)) { return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService"; } StringBuilder buf = new StringBuilder(); if ("/".equals(message) || "..".equals(message)) { String service = (String) channel.getAttribute(SERVICE_KEY); channel.removeAttribute(SERVICE_KEY); buf.append("Cancelled default service ").append(service).append('.'); } else { boolean found = false; for (Exporter<?> exporter : DubboProtocol.getDubboProtocol().getExporters()) { if (message.equals(exporter.getInvoker().getInterface().getSimpleName()) || message.equals(exporter.getInvoker().getInterface().getName()) || message.equals(exporter.getInvoker().getUrl().getPath())) { found = true; break; } } if (found) { channel.setAttribute(SERVICE_KEY, message); buf.append("Used the ") .append(message) .append(" as default.\r\nYou can cancel default service by command: cd /"); } else { buf.append("No such service ").append(message); } } return buf.toString(); }
@Test void testChangeCancel() throws RemotingException { String result = change.telnet(mockChannel, ".."); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); }
@Override public String pluginNamed() { return PluginEnum.KEY_AUTH.getName(); }
@Test public void testPluginNamed() { assertEquals(keyAuthPluginDataHandler.pluginNamed(), PluginEnum.KEY_AUTH.getName()); }
@NonNull public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) { Comparator<FeedItem> comparator = null; Permutor<FeedItem> permutor = null; switch (sortOrder) { case EPISODE_TITLE_A_Z: comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTitle(f2)); break; case EPISODE_TITLE_Z_A: comparator = (f1, f2) -> itemTitle(f2).compareTo(itemTitle(f1)); break; case DATE_OLD_NEW: comparator = (f1, f2) -> pubDate(f1).compareTo(pubDate(f2)); break; case DATE_NEW_OLD: comparator = (f1, f2) -> pubDate(f2).compareTo(pubDate(f1)); break; case DURATION_SHORT_LONG: comparator = (f1, f2) -> Integer.compare(duration(f1), duration(f2)); break; case DURATION_LONG_SHORT: comparator = (f1, f2) -> Integer.compare(duration(f2), duration(f1)); break; case EPISODE_FILENAME_A_Z: comparator = (f1, f2) -> itemLink(f1).compareTo(itemLink(f2)); break; case EPISODE_FILENAME_Z_A: comparator = (f1, f2) -> itemLink(f2).compareTo(itemLink(f1)); break; case FEED_TITLE_A_Z: comparator = (f1, f2) -> feedTitle(f1).compareTo(feedTitle(f2)); break; case FEED_TITLE_Z_A: comparator = (f1, f2) -> feedTitle(f2).compareTo(feedTitle(f1)); break; case RANDOM: permutor = Collections::shuffle; break; case SMART_SHUFFLE_OLD_NEW: permutor = (queue) -> smartShuffle(queue, true); break; case SMART_SHUFFLE_NEW_OLD: permutor = (queue) -> smartShuffle(queue, false); break; case SIZE_SMALL_LARGE: comparator = (f1, f2) -> Long.compare(size(f1), size(f2)); break; case SIZE_LARGE_SMALL: comparator = (f1, f2) -> Long.compare(size(f2), size(f1)); break; case COMPLETION_DATE_NEW_OLD: comparator = (f1, f2) -> f2.getMedia().getPlaybackCompletionDate() .compareTo(f1.getMedia().getPlaybackCompletionDate()); break; default: throw new IllegalArgumentException("Permutor not implemented"); } if (comparator != null) { final Comparator<FeedItem> comparator2 = comparator; permutor = (queue) -> Collections.sort(queue, comparator2); } return permutor; }
@Test public void testPermutorForRule_DURATION_ASC() { Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.DURATION_SHORT_LONG); List<FeedItem> itemList = getTestList(); assertTrue(checkIdOrder(itemList, 1, 3, 2)); // before sorting permutor.reorder(itemList); assertTrue(checkIdOrder(itemList, 1, 2, 3)); // after sorting }
@Override public void encode(Event event, OutputStream output) throws IOException { String outputString = (format == null ? JSON_MAPPER.writeValueAsString(event.getData()) : StringInterpolation.evaluate(event, format)) + delimiter; output.write(outputString.getBytes(charset)); }
@Test public void testEncodeWithUtf8() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String delimiter = "z"; String message = new String("München 安装中文输入法".getBytes(), Charset.forName("UTF-8")); Map<String, Object> config = new HashMap<>(); config.put("delimiter", delimiter); config.put("format", "%{message}"); Line line = new Line(new ConfigurationImpl(config), new TestContext()); Event e1 = new Event(Collections.singletonMap("message", message)); line.encode(e1, outputStream); String expectedResult = message + delimiter; Assert.assertEquals(expectedResult, new String(outputStream.toByteArray(), Charset.forName("UTF-8"))); }
public static Map<String, String> getSegmentSourcesMap(final SegmentCompilationDTO segmentCompilationDTO, final List<KiePMMLModel> nestedModels) { logger.debug(GET_SEGMENT, segmentCompilationDTO.getSegment()); final KiePMMLModel nestedModel = getFromCommonDataAndTransformationDictionaryAndModelWithSources(segmentCompilationDTO) .orElseThrow(() -> new KiePMMLException("Failed to get the KiePMMLModel for segment " + segmentCompilationDTO.getModel().getModelName())); final Map<String, String> toReturn = getSegmentSourcesMapCommon(segmentCompilationDTO, nestedModels, nestedModel); segmentCompilationDTO.addFields(getFieldsFromModel(segmentCompilationDTO.getModel())); return toReturn; }
@Test void getSegmentSourcesMap() { final Segment segment = MINING_MODEL.getSegmentation().getSegments().get(0); final List<KiePMMLModel> nestedModels = new ArrayList<>(); final CommonCompilationDTO<MiningModel> source = CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME, pmml, MINING_MODEL, new PMMLCompilationContextMock(), "FILENAME"); final MiningModelCompilationDTO compilationDTO = MiningModelCompilationDTO.fromCompilationDTO(source); final SegmentCompilationDTO segmentCompilationDTO = SegmentCompilationDTO.fromGeneratedPackageNameAndFields(compilationDTO, segment, compilationDTO.getFields()); final Map<String, String> retrieved = KiePMMLSegmentFactory.getSegmentSourcesMap(segmentCompilationDTO, nestedModels); commonEvaluateNestedModels(nestedModels); commonEvaluateMap(retrieved, segment); }
public ProtocolBuilder exchanger(String exchanger) { this.exchanger = exchanger; return getThis(); }
@Test void exchanger() { ProtocolBuilder builder = new ProtocolBuilder(); builder.exchanger("mockexchanger"); Assertions.assertEquals("mockexchanger", builder.build().getExchanger()); }
public <T extends ShardingSphereRule> Optional<T> findSingleRule(final Class<T> clazz) { Collection<T> foundRules = findRules(clazz); return foundRules.isEmpty() ? Optional.empty() : Optional.of(foundRules.iterator().next()); }
@Test void assertFindSingleRule() { assertTrue(ruleMetaData.findSingleRule(ShardingSphereRuleFixture.class).isPresent()); }
@Override public DefaultJwtRuleHandle parseHandleJson(final String handleJson) { try { return GsonUtils.getInstance().fromJson(handleJson, DefaultJwtRuleHandle.class); } catch (Exception exception) { LOG.error("Failed to parse json , please check json format", exception); return null; } }
@Test public void testParseHandleJson() { String handleJson = "{\"converter\":[{\"jwtVal\":\"sub\",\"headerVal\":\"id\"}]}"; assertThat(defaultJwtConvertStrategy.parseHandleJson(handleJson), notNullValue(DefaultJwtRuleHandle.class)); assertThat(defaultJwtConvertStrategy.parseHandleJson(null), nullValue()); }
public SearchJob executeSync(String searchId, SearchUser searchUser, ExecutionState executionState) { return searchDomain.getForUser(searchId, searchUser) .map(s -> executeSync(s, searchUser, executionState)) .orElseThrow(() -> new NotFoundException("No search found with id <" + searchId + ">.")); }
@Test void appliesQueryStringDecorators() { final SearchUser searchUser = TestSearchUser.builder() .allowStream("foo") .build(); final Search search = Search.builder() .queries(ImmutableSet.of( Query.builder() .query(ElasticsearchQueryString.of("*")) .build() )) .build(); final SearchJob searchJob = this.searchExecutor.executeSync(search, searchUser, ExecutionState.empty()); assertThat(searchJob.getSearch().queries()) .are(new Condition<>(query -> query.query().queryString().equals("decorated"), "Query string is decorated")); }
@Override public long extract(final ConsumerRecord<Object, Object> record, final long previousTimestamp) { try { return delegate.extract(record, previousTimestamp); } catch (final RuntimeException e) { return handleFailure(record.key(), record.value(), e); } }
@Test public void shouldLogExceptionsAndNotFailOnExtractFromRecord() { // Given: final KsqlException e = new KsqlException("foo"); final LoggingTimestampExtractor extractor = new LoggingTimestampExtractor( (k, v) -> { throw e; }, logger, false ); // When: final long result = extractor.extract(record, PREVIOUS_TS); // Then (did not throw): verify(logger).error(RecordProcessingError .recordProcessingError("Failed to extract timestamp from row", e, () -> "key:" + KEY + ", value:" + VALUE)); assertThat(result, is(-1L)); }
@Override public Double getValue() { return getRatio().getValue(); }
@Test public void handlesDivideByZeroIssues() { final RatioGauge divByZero = new RatioGauge() { @Override protected Ratio getRatio() { return Ratio.of(100, 0); } }; assertThat(divByZero.getValue()) .isNaN(); }
@Override public ResultSet getProcedures(final String catalog, final String schemaPattern, final String procedureNamePattern) { return null; }
@Test void assertGetProcedures() { assertNull(metaData.getProcedures("", "", "")); }
@Deprecated public void sendMessageBack(MessageExt msg, int delayLevel, final String brokerName) throws RemotingException, MQBrokerException, InterruptedException, MQClientException { sendMessageBack(msg, delayLevel, brokerName, null); }
@Test public void testSendMessageBack() throws InterruptedException, MQClientException, MQBrokerException, RemotingException { defaultMQPushConsumerImpl.sendMessageBack(createMessageExt(), 1, createMessageQueue()); verify(mqClientAPIImpl).consumerSendMessageBack( eq(defaultBrokerAddr), any(), any(MessageExt.class), any(), eq(1), eq(5000L), eq(0)); }
public boolean addToken(Token<? extends TokenIdentifier> token) { return (token != null) ? addToken(token.getService(), token) : false; }
@SuppressWarnings("unchecked") // from Mockito mocks @Test (timeout = 30000) public <T extends TokenIdentifier> void testAddToken() throws Exception { UserGroupInformation ugi = UserGroupInformation.createRemoteUser("someone"); Token<T> t1 = mock(Token.class); Token<T> t2 = mock(Token.class); Token<T> t3 = mock(Token.class); // add token to ugi ugi.addToken(t1); checkTokens(ugi, t1); // replace token t1 with t2 - with same key (null) ugi.addToken(t2); checkTokens(ugi, t2); // change t1 service and add token when(t1.getService()).thenReturn(new Text("t1")); ugi.addToken(t1); checkTokens(ugi, t1, t2); // overwrite t1 token with t3 - same key (!null) when(t3.getService()).thenReturn(new Text("t1")); ugi.addToken(t3); checkTokens(ugi, t2, t3); // just try to re-add with new name when(t1.getService()).thenReturn(new Text("t1.1")); ugi.addToken(t1); checkTokens(ugi, t1, t2, t3); // just try to re-add with new name again ugi.addToken(t1); checkTokens(ugi, t1, t2, t3); }
public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) { HttpHeaders inHeaders = in.headers(); final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size()); if (in instanceof HttpRequest) { HttpRequest request = (HttpRequest) in; String host = inHeaders.getAsString(HttpHeaderNames.HOST); if (isOriginForm(request.uri()) || isAsteriskForm(request.uri())) { out.path(new AsciiString(request.uri())); setHttp2Scheme(inHeaders, out); } else { URI requestTargetUri = URI.create(request.uri()); out.path(toHttp2Path(requestTargetUri)); // Take from the request-line if HOST header was empty host = isNullOrEmpty(host) ? requestTargetUri.getAuthority() : host; setHttp2Scheme(inHeaders, requestTargetUri, out); } setHttp2Authority(host, out); out.method(request.method().asciiName()); } else if (in instanceof HttpResponse) { HttpResponse response = (HttpResponse) in; out.status(response.status().codeAsText()); } // Add the HTTP headers which have not been consumed above toHttp2Headers(inHeaders, out); return out; }
@Test public void stripTEHeadersAccountsForValueSimilarToTrailers() { HttpHeaders inHeaders = new DefaultHttpHeaders(); inHeaders.add(TE, TRAILERS + "foo"); Http2Headers out = new DefaultHttp2Headers(); HttpConversionUtil.toHttp2Headers(inHeaders, out); assertFalse(out.contains(TE)); }
@Udf public Long trunc(@UdfParameter final Long val) { return val; }
@Test public void shouldTruncateLong() { assertThat(udf.trunc(123L), is(123L)); }
void updateActivityState(DeviceId deviceId, DeviceStateData stateData, long lastReportedActivity) { log.trace("updateActivityState - fetched state {} for device {}, lastReportedActivity {}", stateData, deviceId, lastReportedActivity); if (stateData != null) { save(deviceId, LAST_ACTIVITY_TIME, lastReportedActivity); DeviceState state = stateData.getState(); state.setLastActivityTime(lastReportedActivity); if (!state.isActive()) { state.setActive(true); if (lastReportedActivity <= state.getLastInactivityAlarmTime()) { state.setLastInactivityAlarmTime(0); save(deviceId, INACTIVITY_ALARM_TIME, 0); } onDeviceActivityStatusChange(deviceId, true, stateData); } } else { log.debug("updateActivityState - fetched state IS NULL for device {}, lastReportedActivity {}", deviceId, lastReportedActivity); cleanupEntity(deviceId); } }
@Test public void givenStateDataIsNull_whenUpdateActivityState_thenShouldCleanupDevice() { // GIVEN service.deviceStates.put(deviceId, deviceStateDataMock); // WHEN service.updateActivityState(deviceId, null, System.currentTimeMillis()); // THEN assertThat(service.deviceStates.get(deviceId)).isNull(); assertThat(service.deviceStates.size()).isEqualTo(0); assertThat(service.deviceStates.isEmpty()).isTrue(); }
public Optional<PluginMatchingResult<ServiceFingerprinter>> getServiceFingerprinter( NetworkService networkService) { return tsunamiPlugins.entrySet().stream() .filter(entry -> entry.getKey().type().equals(PluginType.SERVICE_FINGERPRINT)) .filter(entry -> hasMatchingServiceName(networkService, entry.getKey())) .map( entry -> PluginMatchingResult.<ServiceFingerprinter>builder() .setPluginDefinition(entry.getKey()) .setTsunamiPlugin((ServiceFingerprinter) entry.getValue().get()) .addMatchedService(networkService) .build()) .findFirst(); }
@Test public void getServiceFingerprinter_whenFingerprinterNotAnnotated_returnsEmpty() { NetworkService httpService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80)) .setTransportProtocol(TransportProtocol.TCP) .setServiceName("http") .build(); PluginManager pluginManager = Guice.createInjector( new FakePortScannerBootstrapModule(), NoAnnotationFingerprinter.getModule()) .getInstance(PluginManager.class); Optional<PluginMatchingResult<ServiceFingerprinter>> fingerprinter = pluginManager.getServiceFingerprinter(httpService); assertThat(fingerprinter).isEmpty(); }
public static List<URL> parseConfigurators(String rawConfig) { // compatible url JsonArray, such as [ "override://xxx", "override://xxx" ] List<URL> compatibleUrls = parseJsonArray(rawConfig); if (CollectionUtils.isNotEmpty(compatibleUrls)) { return compatibleUrls; } List<URL> urls = new ArrayList<>(); ConfiguratorConfig configuratorConfig = parseObject(rawConfig); String scope = configuratorConfig.getScope(); List<ConfigItem> items = configuratorConfig.getConfigs(); if (ConfiguratorConfig.SCOPE_APPLICATION.equals(scope)) { items.forEach(item -> urls.addAll(appItemToUrls(item, configuratorConfig))); } else { // service scope by default. items.forEach(item -> urls.addAll(serviceItemToUrls(item, configuratorConfig))); } return urls; }
@Test void parseConfiguratorsServiceMultiAppsTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceMultiApps.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(4, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertNotNull(url.getApplication()); } }
public void setWriteTimeout(int writeTimeout) { this.writeTimeout = writeTimeout; }
@Test public void testErrorCodeForbidden() throws IOException { MockLowLevelHttpResponse[] responses = createMockResponseWithStatusCode( 403, // Non-retryable error. 200); // Shouldn't happen. when(mockLowLevelRequest.execute()).thenReturn(responses[0], responses[1]); try { Storage.Buckets.Get result = storage.buckets().get("test"); HttpResponse response = result.executeUnparsed(); assertNotNull(response); } catch (HttpResponseException e) { assertThat(e.getMessage(), Matchers.containsString("403")); } verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class)); verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString()); verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt()); verify(mockLowLevelRequest).setWriteTimeout(anyInt()); verify(mockLowLevelRequest).execute(); verify(responses[0], atLeastOnce()).getStatusCode(); verify(responses[1], never()).getStatusCode(); expectedLogs.verifyWarn("Request failed with code 403"); }
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuffer buf = new StringBuffer(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_STATE: handleLiteralState(c, tokenList, buf); break; case FORMAT_MODIFIER_STATE: handleFormatModifierState(c, tokenList, buf); break; case OPTION_STATE: processOption(c, tokenList, buf); break; case KEYWORD_STATE: handleKeywordState(c, tokenList, buf); break; case RIGHT_PARENTHESIS_STATE: handleRightParenthesisState(c, tokenList, buf); break; default: } } // EOS switch (state) { case LITERAL_STATE: addValuedToken(Token.LITERAL, buf, tokenList); break; case KEYWORD_STATE: tokenList.add(new Token(Token.SIMPLE_KEYWORD, buf.toString())); break; case RIGHT_PARENTHESIS_STATE: tokenList.add(Token.RIGHT_PARENTHESIS_TOKEN); break; case FORMAT_MODIFIER_STATE: case OPTION_STATE: throw new ScanException("Unexpected end of pattern string"); } return tokenList; }
@Test public void testLiteralWithPercent() throws ScanException { { List<Token> tl = new TokenStream("hello\\%world").tokenize(); List<Token> witness = new ArrayList<Token>(); witness.add(new Token(Token.LITERAL, "hello%world")); assertEquals(witness, tl); } { List<Token> tl = new TokenStream("hello\\%").tokenize(); List<Token> witness = new ArrayList<Token>(); witness.add(new Token(Token.LITERAL, "hello%")); assertEquals(witness, tl); } { List<Token> tl = new TokenStream("\\%").tokenize(); List<Token> witness = new ArrayList<Token>(); witness.add(new Token(Token.LITERAL, "%")); assertEquals(witness, tl); } }
@Override public List<MicroServiceInstance> getServerList(String serviceId) { if (!isRegistered.get()) { LOGGER.warning("Query instance must be at the stage that finish registry!"); return Collections.emptyList(); } if (serviceId == null) { // Unable to perform a replacement LOGGER.warning("Can not acquire the name of service, the process to replace instance won't be finished!"); return Collections.emptyList(); } return RegisterManager.INSTANCE.getServerList(serviceId); }
@Test public void getServerList() { Assert.assertTrue(registerCenterService.getServerList("test").isEmpty()); }
static File getFileFromResource(URL retrieved) throws IOException { logger.debug("getFileFromResource {}", retrieved); File toReturn = new MemoryFile(retrieved); logger.debug(TO_RETURN_TEMPLATE, toReturn); logger.debug(TO_RETURN_GETABSOLUTEPATH_TEMPLATE, toReturn.getAbsolutePath()); return toReturn; }
@Test void getFileFromResource() throws IOException { URL resourceUrl = getResourceUrl(); File retrieved = MemoryFileUtils.getFileFromResource(resourceUrl); assertThat(retrieved).isNotNull(); assertThat(retrieved).isInstanceOf(MemoryFile.class); assertThat(retrieved).canRead(); }
public Map<String, Object> sanitizeConnectorConfig(@Nullable Map<String, Object> original) { var result = new HashMap<String, Object>(); //null-values supporting map! if (original != null) { original.forEach((k, v) -> result.put(k, sanitize(k, v))); } return result; }
@Test void sanitizeConnectorConfigDoNotFailOnNullableValues() { Map<String, Object> originalConfig = new HashMap<>(); originalConfig.put("password", "secret"); originalConfig.put("asIs", "normal"); originalConfig.put("nullVal", null); var sanitizedConfig = new KafkaConfigSanitizer(true, List.of()) .sanitizeConnectorConfig(originalConfig); assertThat(sanitizedConfig) .hasSize(3) .containsEntry("password", "******") .containsEntry("asIs", "normal") .containsEntry("nullVal", null); }
protected UrlData extractUrlData(String nvdDataFeedUrl) { String url; String pattern = null; if (nvdDataFeedUrl.endsWith(".json.gz")) { final int lio = nvdDataFeedUrl.lastIndexOf("/"); pattern = nvdDataFeedUrl.substring(lio + 1); url = nvdDataFeedUrl.substring(0, lio); } else { url = nvdDataFeedUrl; } if (!url.endsWith("/")) { url += "/"; } return new UrlData(url, pattern); }
@Test public void testExtractUrlData() { String nvdDataFeedUrl = "https://internal.server/nist/nvdcve-{0}.json.gz"; NvdApiDataSource instance = new NvdApiDataSource(); String expectedUrl = "https://internal.server/nist/"; String expectedPattern = "nvdcve-{0}.json.gz"; NvdApiDataSource.UrlData result = instance.extractUrlData(nvdDataFeedUrl); nvdDataFeedUrl = "https://internal.server/nist/"; expectedUrl = "https://internal.server/nist/"; result = instance.extractUrlData(nvdDataFeedUrl); assertEquals(expectedUrl, result.getUrl()); assertNull(result.getPattern()); nvdDataFeedUrl = "https://internal.server/nist"; expectedUrl = "https://internal.server/nist/"; result = instance.extractUrlData(nvdDataFeedUrl); assertEquals(expectedUrl, result.getUrl()); assertNull(result.getPattern()); }
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } return results; }
@Test public void jvm32() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/jvm_32bit.txt")), CrashReportAnalyzer.Rule.JVM_32BIT); }
public DataCache<List<MavenArtifact>> getCentralCache() { try { final ICompositeCacheAttributes attr = new CompositeCacheAttributes(); attr.setUseDisk(true); attr.setUseLateral(false); attr.setUseRemote(false); final CacheAccess<String, List<MavenArtifact>> ca = JCS.getInstance("CENTRAL", attr); final DataCache<List<MavenArtifact>> dc = new DataCache<>(ca); return dc; } catch (Throwable ex) { //some reports of class not found exception, log and disable the cache. if (ex instanceof CacheException) { throw ex; } //TODO we may want to instrument w/ jdiagnostics per #2509 LOGGER.debug("Error constructing cache for Central files", ex); throw new CacheException(ex); } }
@Test public void testGetCache() throws IOException { DataCacheFactory instance = new DataCacheFactory(getSettings()); DataCache<List<MavenArtifact>> result = instance.getCentralCache(); assertNotNull(result); File f = new File(getSettings().getDataDirectory(), "cache"); assertTrue(f.isDirectory()); FilenameFilter filter = (File f1, String name) -> name.startsWith("CENTRAL"); assertTrue(f.listFiles(filter).length > 0); }
public ScalarFn loadScalarFunction(List<String> functionPath, String jarPath) { String functionFullName = String.join(".", functionPath); try { FunctionDefinitions functionDefinitions = loadJar(jarPath); if (!functionDefinitions.scalarFunctions().containsKey(functionPath)) { throw new IllegalArgumentException( String.format( "No implementation of scalar function %s found in %s.%n" + " 1. Create a class implementing %s and annotate it with @AutoService(%s.class).%n" + " 2. Add function %s to the class's userDefinedScalarFunctions implementation.", functionFullName, jarPath, UdfProvider.class.getSimpleName(), UdfProvider.class.getSimpleName(), functionFullName)); } return functionDefinitions.scalarFunctions().get(functionPath); } catch (IOException e) { throw new RuntimeException( String.format( "Failed to load user-defined scalar function %s from %s", functionFullName, jarPath), e); } }
@Test public void testJarMissingUdfProviderThrowsProviderNotFoundException() { JavaUdfLoader udfLoader = new JavaUdfLoader(); thrown.expect(ProviderNotFoundException.class); thrown.expectMessage(String.format("No UdfProvider implementation found in %s.", emptyJarPath)); // Load from an inhabited jar first so we can make sure we load UdfProviders in isolation // from other jars. udfLoader.loadScalarFunction(Collections.singletonList("helloWorld"), jarPath); udfLoader.loadScalarFunction(Collections.singletonList("helloWorld"), emptyJarPath); }
@SuppressWarnings("all") public <T> T searchStateValue(String stateName, T defaultValue) { T result = null; for (ModuleState each : getAllModuleStates()) { if (each.getStates().containsKey(stateName)) { result = (T) each.getStates().get(stateName); break; } } return null == result ? defaultValue : result; }
@Test void testSearchStateValue() { assertEquals("test", ModuleStateHolder.getInstance().searchStateValue("test", "aaa")); assertEquals("aaa", ModuleStateHolder.getInstance().searchStateValue("non-exist", "aaa")); }
public static Schema inferSchema(Object value) { if (value instanceof String) { return Schema.STRING_SCHEMA; } else if (value instanceof Boolean) { return Schema.BOOLEAN_SCHEMA; } else if (value instanceof Byte) { return Schema.INT8_SCHEMA; } else if (value instanceof Short) { return Schema.INT16_SCHEMA; } else if (value instanceof Integer) { return Schema.INT32_SCHEMA; } else if (value instanceof Long) { return Schema.INT64_SCHEMA; } else if (value instanceof Float) { return Schema.FLOAT32_SCHEMA; } else if (value instanceof Double) { return Schema.FLOAT64_SCHEMA; } else if (value instanceof byte[] || value instanceof ByteBuffer) { return Schema.BYTES_SCHEMA; } else if (value instanceof List) { return inferListSchema((List<?>) value); } else if (value instanceof Map) { return inferMapSchema((Map<?, ?>) value); } else if (value instanceof Struct) { return ((Struct) value).schema(); } return null; }
@Test public void shouldInferStructSchema() { Struct struct = new Struct(SchemaBuilder.struct().build()); Schema structSchema = Values.inferSchema(struct); assertEquals(struct.schema(), structSchema); }
public BrokerStatsData viewBrokerStatsData(String brokerAddr, String statsName, String statsKey, long timeoutMillis) throws MQClientException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException { ViewBrokerStatsDataRequestHeader requestHeader = new ViewBrokerStatsDataRequestHeader(); requestHeader.setStatsName(statsName); requestHeader.setStatsKey(statsKey); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.VIEW_BROKER_STATS_DATA, requestHeader); RemotingCommand response = this.remotingClient .invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis); assert response != null; switch (response.getCode()) { case ResponseCode.SUCCESS: { byte[] body = response.getBody(); if (body != null) { return BrokerStatsData.decode(body, BrokerStatsData.class); } } default: break; } throw new MQClientException(response.getCode(), response.getRemark()); }
@Test public void assertViewBrokerStatsData() throws RemotingException, InterruptedException, MQClientException { mockInvokeSync(); BrokerStatsData responseBody = new BrokerStatsData(); responseBody.setStatsDay(new BrokerStatsItem()); setResponseBody(responseBody); BrokerStatsData actual = mqClientAPI.viewBrokerStatsData(defaultBrokerAddr, "", "", defaultTimeout); assertNotNull(actual); assertNotNull(actual.getStatsDay()); }
@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 testSlaughterActivate() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", ACTIVATE_BRACELET_OF_SLAUGHTER, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BRACELET_OF_SLAUGHTER, 16); }
protected static String buildRequestBody(String query, String operationName, JsonObject variables) { JsonObject jsonObject = new JsonObject(); jsonObject.put("query", query); jsonObject.put("operationName", operationName); jsonObject.put("variables", variables != null ? variables : new JsonObject()); return jsonObject.toJson(); }
@Test public void shouldBuildRequestBodyWithQueryOperationNameAndVariables() { String query = "queryText"; String operationName = "queryName"; JsonObject variables = new JsonObject(); variables.put("key1", "value1"); variables.put("key2", "value2"); String body = GraphqlProducer.buildRequestBody(query, operationName, variables); String expectedBody = "{" + "\"query\":\"queryText\"," + "\"operationName\":\"queryName\"," + "\"variables\":{\"key1\":\"value1\",\"key2\":\"value2\"}" + "}"; assertEquals(expectedBody, body); }
private static void serializeProperties(CheckpointProperties properties, DataOutputStream dos) throws IOException { new ObjectOutputStream(dos).writeObject(properties); // closed outside }
@Test void testSerializeProperties() throws IOException { CheckpointMetadata metadata = new CheckpointMetadata( 1L, emptyList(), emptyList(), CheckpointProperties.forSavepoint(false, SavepointFormatType.NATIVE)); MetadataSerializer instance = MetadataV4Serializer.INSTANCE; try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(out)) { instance.serialize(metadata, dos); try (DataInputStream dis = new DataInputStream(new ByteArrayInputStream(out.toByteArray()))) { assertThat( instance.deserialize(dis, metadata.getClass().getClassLoader(), "") .getCheckpointProperties()) .isEqualTo(metadata.getCheckpointProperties()); } } }
public static BytesInput fromZigZagVarInt(int intValue) { int zigZag = (intValue << 1) ^ (intValue >> 31); return new UnsignedVarIntBytesInput(zigZag); }
@Test public void testFromZigZagVarInt() throws IOException { int value = RANDOM.nextInt() % Short.MAX_VALUE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); BytesUtils.writeZigZagVarInt(value, baos); byte[] data = baos.toByteArray(); Supplier<BytesInput> factory = () -> BytesInput.fromZigZagVarInt(value); validate(data, factory); }
public synchronized void addFunction(Function function) throws UserException { addFunction(function, false); }
@Test public void testAddFunction() throws UserException { // Add addIntInt function to database FunctionName name = new FunctionName(null, "addIntInt"); name.setDb(db.getCatalogName()); final Type[] argTypes = {Type.INT, Type.INT}; Function f = new Function(name, argTypes, Type.INT, false); db.addFunction(f); // Add addDoubleDouble function to database FunctionName name2 = new FunctionName(null, "addDoubleDouble"); name2.setDb(db.getCatalogName()); final Type[] argTypes2 = {Type.DOUBLE, Type.DOUBLE}; Function f2 = new Function(name2, argTypes2, Type.DOUBLE, false); db.addFunction(f2); }
public void convertLambdas() { if (isParallel) { convertLambdasWithForkJoinPool(); } else { convertLambdasWithStream(); } }
@Test public void convertPatternLambda() throws Exception { CompilationUnit inputCU = parseResource("org/drools/model/codegen/execmodel/util/lambdareplace/PatternTestHarness.java"); CompilationUnit clone = inputCU.clone(); new ExecModelLambdaPostProcessor("mypackage", "rulename", new ArrayList<>(), new ArrayList<>(), new HashMap<>(), new HashMap<>(), clone, true).convertLambdas(); String PATTERN_HARNESS = "PatternTestHarness"; MethodDeclaration expectedResult = getMethodChangingName(inputCU, PATTERN_HARNESS, "expectedOutput"); MethodDeclaration actual = getMethodChangingName(clone, PATTERN_HARNESS, "inputMethod"); verifyCreatedClass(expectedResult, actual); }
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final byte[] payload = rawMessage.getPayload(); final Map<String, Object> event; try { event = objectMapper.readValue(payload, TypeReferences.MAP_STRING_OBJECT); } catch (IOException e) { LOG.error("Couldn't decode raw message {}", rawMessage); return null; } return parseEvent(event); }
@Test public void decodeMessagesHandlesWinlogbeatMessages() throws Exception { final Message message = codec.decode(messageFromJson("winlogbeat.json")); assertThat(message).isNotNull(); assertThat(message.getSource()).isEqualTo("example.local"); assertThat(message.getTimestamp()).isEqualTo(new DateTime(2016, 11, 24, 12, 13, DateTimeZone.UTC)); assertThat(message.getField("facility")).isEqualTo("winlogbeat"); assertThat(message.getField("type")).isEqualTo("wineventlog"); assertThat(message.getField("winlogbeat_level")).isEqualTo("Information"); assertThat(message.getField("winlogbeat_event_id")).isEqualTo(5024); assertThat(message.getField("winlogbeat_process_id")).isEqualTo(500); assertThat(message.getField("winlogbeat_log_name")).isEqualTo("Security"); }
public void createMapping(Mapping mapping, boolean replace, boolean ifNotExists, SqlSecurityContext securityContext) { Mapping resolved = resolveMapping(mapping, securityContext); String name = resolved.name(); if (ifNotExists) { relationsStorage.putIfAbsent(name, resolved); } else if (replace) { relationsStorage.put(name, resolved); listeners.forEach(TableListener::onTableChanged); } else if (!relationsStorage.putIfAbsent(name, resolved)) { throw QueryException.error("Mapping or view already exists: " + name); } }
@Test public void when_createsDuplicateMapping_then_throws() { // given Mapping mapping = mapping(); given(connectorCache.forType(mapping.connectorType())).willReturn(connector); given(connector.resolveAndValidateFields(nodeEngine, new SqlExternalResource(mapping.externalName(), mapping.dataConnection(), "Dummy", null, mapping.options()), mapping.fields() )) .willReturn(singletonList(new MappingField("field_name", INT))); given(connector.typeName()).willReturn("Dummy"); given(connector.defaultObjectType()).willReturn("Dummy"); given(relationsStorage.putIfAbsent(eq(mapping.name()), isA(Mapping.class))).willReturn(false); // when // then assertThatThrownBy(() -> catalog.createMapping(mapping, false, false, null)) .isInstanceOf(QueryException.class) .hasMessageContaining("Mapping or view already exists: name"); verifyNoInteractions(listener); }
private RemotingCommand getAllConsumerOffset(ChannelHandlerContext ctx, RemotingCommand request) { final RemotingCommand response = RemotingCommand.createResponseCommand(null); String content = this.brokerController.getConsumerOffsetManager().encode(); if (content != null && content.length() > 0) { try { response.setBody(content.getBytes(MixAll.DEFAULT_CHARSET)); } catch (UnsupportedEncodingException e) { LOGGER.error("get all consumer offset from master error.", e); response.setCode(ResponseCode.SYSTEM_ERROR); response.setRemark("UnsupportedEncodingException " + e.getMessage()); return response; } } else { LOGGER.error("No consumer offset in this broker, client: {} ", ctx.channel().remoteAddress()); response.setCode(ResponseCode.SYSTEM_ERROR); response.setRemark("No consumer offset in this broker"); return response; } response.setCode(ResponseCode.SUCCESS); response.setRemark(null); return response; }
@Test public void testGetAllConsumerOffset() throws RemotingCommandException { consumerOffsetManager = mock(ConsumerOffsetManager.class); when(brokerController.getConsumerOffsetManager()).thenReturn(consumerOffsetManager); ConsumerOffsetManager consumerOffset = new ConsumerOffsetManager(); when(consumerOffsetManager.encode()).thenReturn(JSON.toJSONString(consumerOffset, false)); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_CONSUMER_OFFSET, null); RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); }
@Nonnull @Override public Sketch getResult() { return unionAll(); }
@Test public void testUnionWithEmptyInput() { ThetaSketchAccumulator accumulator = new ThetaSketchAccumulator(_setOperationBuilder, 3); ThetaSketchAccumulator emptyAccumulator = new ThetaSketchAccumulator(_setOperationBuilder, 3); accumulator.merge(emptyAccumulator); Assert.assertTrue(accumulator.isEmpty()); Assert.assertEquals(accumulator.getResult().getEstimate(), 0.0); }
public Set<Integer> toLines() { Set<Integer> lines = new LinkedHashSet<>(to - from + 1); for (int index = from; index <= to; index++) { lines.add(index); } return lines; }
@Test public void shouldConvertLineRangeToLines() { LineRange range = new LineRange(12, 15); assertThat(range.toLines()).containsOnly(12, 13, 14, 15); }
@Override public ConfigInfoBetaWrapper findConfigInfo4Beta(final String dataId, final String group, final String tenant) { String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_BETA); final String sql = configInfoBetaMapper.select( Arrays.asList("id", "data_id", "group_id", "tenant_id", "app_name", "content", "beta_ips", "encrypted_data_key", "gmt_modified"), Arrays.asList("data_id", "group_id", "tenant_id")); return databaseOperate.queryOne(sql, new Object[] {dataId, group, tenantTmp}, CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER); }
@Test void testFindConfigInfo4Beta() { String dataId = "dataId456789"; String group = "group4567"; String tenant = "tenant56789o0"; //mock exist beta ConfigInfoBetaWrapper mockedConfigInfoStateWrapper = new ConfigInfoBetaWrapper(); mockedConfigInfoStateWrapper.setDataId(dataId); mockedConfigInfoStateWrapper.setGroup(group); mockedConfigInfoStateWrapper.setTenant(tenant); mockedConfigInfoStateWrapper.setId(123456L); mockedConfigInfoStateWrapper.setLastModified(System.currentTimeMillis()); Mockito.when( databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant}), eq(CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER))) .thenReturn(mockedConfigInfoStateWrapper); ConfigInfoBetaWrapper configInfo4BetaReturn = embeddedConfigInfoBetaPersistService.findConfigInfo4Beta(dataId, group, tenant); assertEquals(mockedConfigInfoStateWrapper, configInfo4BetaReturn); }
@Override public List<Intent> compile(LinkCollectionIntent intent, List<Intent> installable) { SetMultimap<DeviceId, PortNumber> inputPorts = HashMultimap.create(); SetMultimap<DeviceId, PortNumber> outputPorts = HashMultimap.create(); Map<ConnectPoint, Identifier<?>> labels = ImmutableMap.of(); Optional<EncapsulationConstraint> encapConstraint = this.getIntentEncapConstraint(intent); computePorts(intent, inputPorts, outputPorts); if (encapConstraint.isPresent()) { labels = labelAllocator.assignLabelToPorts(intent.links(), intent.key(), encapConstraint.get().encapType(), encapConstraint.get().suggestedIdentifier()); } ImmutableList.Builder<Intent> intentList = ImmutableList.builder(); if (this.isDomainProcessingEnabled(intent)) { intentList.addAll(this.getDomainIntents(intent, domainService)); } List<FlowRule> rules = new ArrayList<>(); for (DeviceId deviceId : outputPorts.keySet()) { // add only flows that are not inside of a domain if (LOCAL.equals(domainService.getDomain(deviceId))) { rules.addAll(createRules( intent, deviceId, inputPorts.get(deviceId), outputPorts.get(deviceId), labels) ); } } // if any rules have been created if (!rules.isEmpty()) { intentList.add(new FlowRuleIntent(appId, intent.key(), rules, intent.resources(), PathIntent.ProtectionType.PRIMARY, null)); } return intentList.build(); }
@Test public void testCompile() { sut.activate(); List<Intent> compiled = sut.compile(intent, Collections.emptyList()); assertThat(compiled, hasSize(1)); assertThat("key is inherited", compiled.stream().map(Intent::key).collect(Collectors.toList()), everyItem(is(intent.key()))); Collection<FlowRule> rules = ((FlowRuleIntent) compiled.get(0)).flowRules(); assertThat(rules, hasSize(links.size())); // if not found, get() raises an exception FlowRule rule1 = rules.stream() .filter(rule -> rule.deviceId().equals(d1p10.deviceId())) .findFirst() .get(); assertThat(rule1.selector(), is( DefaultTrafficSelector.builder(intent.selector()).matchInPort(d1p1.port()).build() )); assertThat(rule1.treatment(), is( DefaultTrafficTreatment.builder(intent.treatment()).setOutput(d1p1.port()).build() )); assertThat(rule1.priority(), is(intent.priority())); FlowRule rule2 = rules.stream() .filter(rule -> rule.deviceId().equals(d2p0.deviceId())) .findFirst() .get(); assertThat(rule2.selector(), is( DefaultTrafficSelector.builder(intent.selector()).matchInPort(d2p0.port()).build() )); assertThat(rule2.treatment(), is( DefaultTrafficTreatment.builder().setOutput(d2p1.port()).build() )); assertThat(rule2.priority(), is(intent.priority())); FlowRule rule3 = rules.stream() .filter(rule -> rule.deviceId().equals(d3p0.deviceId())) .findFirst() .get(); assertThat(rule3.selector(), is( DefaultTrafficSelector.builder(intent.selector()).matchInPort(d3p1.port()).build() )); assertThat(rule3.treatment(), is( DefaultTrafficTreatment.builder().setOutput(d3p1.port()).build() )); assertThat(rule3.priority(), is(intent.priority())); sut.deactivate(); }
public static String convertLikePatternToRegex(final String pattern) { String result = pattern; if (pattern.contains("_")) { result = SINGLE_CHARACTER_PATTERN.matcher(result).replaceAll("$1."); result = SINGLE_CHARACTER_ESCAPE_PATTERN.matcher(result).replaceAll("_"); } if (pattern.contains("%")) { result = ANY_CHARACTER_PATTERN.matcher(result).replaceAll("$1.*"); result = ANY_CHARACTER_ESCAPE_PATTERN.matcher(result).replaceAll("%"); } return result; }
@Test void assertConvertLikePatternToRegexWhenContainsPattern() { assertThat(RegexUtils.convertLikePatternToRegex("sharding_db"), is("sharding.db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding%db"), is("sharding.*db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding%_db"), is("sharding.*.db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding\\_db"), is("sharding_db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding\\%db"), is("sharding%db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding\\%\\_db"), is("sharding%_db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding_\\_db"), is("sharding._db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding%\\%db"), is("sharding.*%db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding_\\%db"), is("sharding.%db")); assertThat(RegexUtils.convertLikePatternToRegex("sharding\\_%db"), is("sharding_.*db")); }
public static byte[] doubleToBytesBE(double d, byte[] bytes, int off) { return longToBytesBE(Double.doubleToLongBits(d), bytes, off); }
@Test public void testDoubleToBytesBE() { assertArrayEquals(DOUBLE_PI_BE , ByteUtils.doubleToBytesBE(Math.PI, new byte[8], 0)); }
public static IntArrayList reverse(IntArrayList list) { final int[] buffer = list.buffer; int tmp; for (int start = 0, end = list.size() - 1; start < end; start++, end--) { // swap the values tmp = buffer[start]; buffer[start] = buffer[end]; buffer[end] = tmp; } return list; }
@Test public void testReverse() { assertEquals(from(), ArrayUtil.reverse(from())); assertEquals(from(1), ArrayUtil.reverse(from(1))); assertEquals(from(9, 5), ArrayUtil.reverse(from(5, 9))); assertEquals(from(7, 1, 3), ArrayUtil.reverse(from(3, 1, 7))); assertEquals(from(4, 3, 2, 1), ArrayUtil.reverse(from(1, 2, 3, 4))); assertEquals(from(5, 4, 3, 2, 1), ArrayUtil.reverse(from(1, 2, 3, 4, 5))); }
public Map<MetricId, Number> metrics() { return metrics; }
@Test public void builder_can_retain_subset_of_metrics() { MetricsPacket packet = new MetricsPacket.Builder(toServiceId("foo")) .putMetrics(List.of( new Metric(toMetricId("remove"), 1), new Metric(toMetricId("keep"), 2))) .retainMetrics(Set.of(toMetricId("keep"), toMetricId("non-existent"))) .build(); assertFalse("should not contain 'remove'", packet.metrics().containsKey(toMetricId("remove"))); assertTrue("should contain 'keep'", packet.metrics().containsKey(toMetricId("keep"))); assertFalse("should not contain 'non-existent'", packet.metrics().containsKey(toMetricId("non-existent"))); }
@Nullable @Override public Message decode(@Nonnull final RawMessage rawMessage) { final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress()); final String json = gelfMessage.getJSON(decompressSizeLimit, charset); final JsonNode node; try { node = objectMapper.readTree(json); if (node == null) { throw new IOException("null result"); } } catch (final Exception e) { log.error("Could not parse JSON, first 400 characters: " + StringUtils.abbreviate(json, 403), e); throw new IllegalStateException("JSON is null/could not be parsed (invalid JSON)", e); } try { validateGELFMessage(node, rawMessage.getId(), rawMessage.getRemoteAddress()); } catch (IllegalArgumentException e) { log.trace("Invalid GELF message <{}>", node); throw e; } // Timestamp. final double messageTimestamp = timestampValue(node); final DateTime timestamp; if (messageTimestamp <= 0) { timestamp = rawMessage.getTimestamp(); } else { // we treat this as a unix timestamp timestamp = Tools.dateTimeFromDouble(messageTimestamp); } final Message message = messageFactory.createMessage( stringValue(node, "short_message"), stringValue(node, "host"), timestamp ); message.addField(Message.FIELD_FULL_MESSAGE, stringValue(node, "full_message")); final String file = stringValue(node, "file"); if (file != null && !file.isEmpty()) { message.addField("file", file); } final long line = longValue(node, "line"); if (line > -1) { message.addField("line", line); } // Level is set by server if not specified by client. final int level = intValue(node, "level"); if (level > -1) { message.addField("level", level); } // Facility is set by server if not specified by client. final String facility = stringValue(node, "facility"); if (facility != null && !facility.isEmpty()) { message.addField("facility", facility); } // Add additional data if there is some. final Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { final Map.Entry<String, JsonNode> entry = fields.next(); String key = entry.getKey(); // Do not index useless GELF "version" field. if ("version".equals(key)) { continue; } // Don't include GELF syntax underscore in message field key. if (key.startsWith("_") && key.length() > 1) { key = key.substring(1); } // We already set short_message and host as message and source. Do not add as fields again. if ("short_message".equals(key) || "host".equals(key)) { continue; } // Skip standard or already set fields. if (message.getField(key) != null || Message.RESERVED_FIELDS.contains(key) && !Message.RESERVED_SETTABLE_FIELDS.contains(key)) { continue; } // Convert JSON containers to Strings, and pick a suitable number representation. final JsonNode value = entry.getValue(); final Object fieldValue; if (value.isContainerNode()) { fieldValue = value.toString(); } else if (value.isFloatingPointNumber()) { fieldValue = value.asDouble(); } else if (value.isIntegralNumber()) { fieldValue = value.asLong(); } else if (value.isNull()) { log.debug("Field [{}] is NULL. Skipping.", key); continue; } else if (value.isTextual()) { fieldValue = value.asText(); } else { log.debug("Field [{}] has unknown value type. Skipping.", key); continue; } message.addField(key, fieldValue); } return message; }
@Test public void decodeFailsWithEmptyMessage() throws Exception { final String json = "{" + "\"version\": \"1.1\"," + "\"host\": \"example.org\"," + "\"message\": \"\"" + "}"; final RawMessage rawMessage = new RawMessage(json.getBytes(StandardCharsets.UTF_8)); assertThatIllegalArgumentException().isThrownBy(() -> codec.decode(rawMessage)) .withNoCause() .withMessageMatching("GELF message <[0-9a-f-]+> has empty mandatory \"message\" field."); }
public static boolean deleteFile(String path, String fileName) { File file = Paths.get(path, fileName).toFile(); if (file.exists()) { return file.delete(); } return false; }
@Test void testDeleteFile() throws IOException { File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut"); assertTrue(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); assertFalse(DiskUtils.deleteFile(tmpFile.getParent(), tmpFile.getName())); }
@Override public String toString() { return "PathSpecSet{" + (_allInclusive ? "all inclusive" : StringUtils.join(_pathSpecs, ',')) + "}"; }
@Test public void testToString() { Assert.assertEquals(PathSpecSet.of(THREE_FIELD_MODEL_FIELD1).toString(), "PathSpecSet{/field1}"); Assert.assertEquals(PathSpecSet.allInclusive().toString(), "PathSpecSet{all inclusive}"); }
public static S3SignResponse fromJson(String json) { return JsonUtil.parse(json, S3SignResponseParser::fromJson); }
@Test public void missingFields() { assertThatThrownBy(() -> S3SignResponseParser.fromJson("{}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing string: uri"); assertThatThrownBy( () -> S3SignResponseParser.fromJson( "{\"uri\" : \"http://localhost:49208/iceberg-signer-test\"}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing field: headers"); }
public T findOne(Bson filter) throws MongoException { return delegate.findOne(filter); }
@Test void findOne() { final var collection = jacksonCollection("simple", Simple.class); final List<Simple> items = List.of( new Simple("000000000000000000000001", "foo"), new Simple("000000000000000000000002", "bar") ); collection.insert(items); assertThat(collection.findOne(new BasicDBObjectBuilder().add("name", "bar").get())) .isEqualTo(items.get(1)); assertThat(collection.findOne(DBQuery.is("name", "bar"))).isEqualTo(items.get(1)); }
@Override public String select(List<String> columns, List<String> where) { StringBuilder sql = new StringBuilder(); String method = "SELECT "; sql.append(method); for (int i = 0; i < columns.size(); i++) { sql.append(columns.get(i)); if (i == columns.size() - 1) { sql.append(" "); } else { sql.append(","); } } sql.append("FROM "); sql.append(getTableName()); sql.append(" "); if (CollectionUtils.isEmpty(where)) { return sql.toString(); } appendWhereClause(where, sql); return sql.toString(); }
@Test void testSelect() { String sql = abstractMapper.select(Arrays.asList("id", "name"), Arrays.asList("id")); assertEquals("SELECT id,name FROM tenant_info WHERE id = ?", sql); }
@Override public SCMUploaderNotifyResponse notify(SCMUploaderNotifyRequest request) throws YarnException, IOException { SCMUploaderNotifyResponse response = recordFactory.newRecordInstance(SCMUploaderNotifyResponse.class); // TODO (YARN-2774): proper security/authorization needs to be implemented String filename = store.addResource(request.getResourceKey(), request.getFileName()); boolean accepted = filename.equals(request.getFileName()); if (accepted) { this.metrics.incAcceptedUploads(); } else { this.metrics.incRejectedUploads(); } response.setAccepted(accepted); return response; }
@Test void testNotify_entryExists_differentName() throws Exception { long rejected = SharedCacheUploaderMetrics.getInstance().getRejectUploads(); store.addResource("key1", "foo.jar"); SCMUploaderNotifyRequest request = recordFactory.newRecordInstance(SCMUploaderNotifyRequest.class); request.setResourceKey("key1"); request.setFilename("foobar.jar"); assertFalse(proxy.notify(request).getAccepted()); Collection<SharedCacheResourceReference> set = store.getResourceReferences("key1"); assertNotNull(set); assertEquals(0, set.size()); assertEquals( 1, SharedCacheUploaderMetrics.getInstance().getRejectUploads() - rejected, "NM upload metrics aren't updated."); }
public List<String> toPrefix(String in) { List<String> tokens = buildTokens(alignINClause(in)); List<String> output = new ArrayList<>(); List<String> stack = new ArrayList<>(); for (String token : tokens) { if (isOperand(token)) { if (token.equals(")")) { while (openParanthesesFound(stack)) { output.add(stack.remove(stack.size() - 1)); } if (!stack.isEmpty()) { // temporarily fix for issue #189 stack.remove(stack.size() - 1); } } else { while (openParanthesesFound(stack) && !hasHigherPrecedence(token, stack.get(stack.size() - 1))) { output.add(stack.remove(stack.size() - 1)); } stack.add(token); } } else { output.add(token); } } while (!stack.isEmpty()) { output.add(stack.remove(stack.size() - 1)); } return output; }
@Test public void testComplexStatement() { String query = "age > 5 AND ( ( ( active = true ) AND ( age = 23 ) ) OR age > 40 ) AND ( salary > 10 ) OR age = 10"; List<String> list = parser.toPrefix(query); assertEquals(Arrays.asList("age", "5", ">", "active", "true", "=", "age", "23", "=", "AND", "age", "40", ">", "OR", "AND", "salary", "10", ">", "AND", "age", "10", "=", "OR"), list); }
public static OffsetBasedPageRequest fromString(String offsetBasedPageRequestAsString) { if (isNullOrEmpty(offsetBasedPageRequestAsString)) return null; String order = lenientSubstringBetween(offsetBasedPageRequestAsString, "order=", "&"); String offset = lenientSubstringBetween(offsetBasedPageRequestAsString, "offset=", "&"); String limit = lenientSubstringBetween(offsetBasedPageRequestAsString, "limit=", "&"); return new OffsetBasedPageRequest( order, isNotNullOrEmpty(offset) ? Integer.parseInt(offset) : 0L, isNotNullOrEmpty(limit) ? Integer.parseInt(limit) : DEFAULT_LIMIT ); }
@Test void testOffsetBasedPageRequestWithEmptyString() { OffsetBasedPageRequest offsetBasedPageRequest = OffsetBasedPageRequest.fromString(""); assertThat(offsetBasedPageRequest).isNull(); }
@Override public Num getValue(int index) { return values.get(index); }
@Test public void cashFlowShortSellWith20PercentLoss() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 90, 100, 110, 120); TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(1, sampleBarSeries), Trade.buyAt(3, sampleBarSeries)); CashFlow cashFlow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, cashFlow.getValue(0)); assertNumEquals(1, cashFlow.getValue(1)); assertNumEquals(0.9, cashFlow.getValue(2)); assertNumEquals(0.8, cashFlow.getValue(3)); }
public <T> HttpResponse<T> httpRequest(String url, String method, HttpHeaders headers, Object requestBodyData, TypeReference<T> responseFormat) { return httpRequest(url, method, headers, requestBodyData, responseFormat, null, null); }
@Test public void testRuntimeExceptionCausesInternalServerError() { when(httpClient.newRequest(anyString())).thenThrow(new RuntimeException()); ConnectRestException e = assertThrows(ConnectRestException.class, () -> httpRequest( httpClient, MOCK_URL, TEST_METHOD, TEST_TYPE, TEST_SIGNATURE_ALGORITHM )); assertIsInternalServerError(e); }
public PlanNodeStatsEstimate addStatsAndSumDistinctValues(PlanNodeStatsEstimate left, PlanNodeStatsEstimate right) { return addStats(left, right, RangeAdditionStrategy.ADD_AND_SUM_DISTINCT); }
@Test public void testAddTotalSize() { PlanNodeStatsEstimate unknownStats = statistics(NaN, NaN, NaN, NaN, StatisticRange.empty()); PlanNodeStatsEstimate first = statistics(NaN, 10, NaN, NaN, StatisticRange.empty()); PlanNodeStatsEstimate second = statistics(NaN, 20, NaN, NaN, StatisticRange.empty()); assertEquals(calculator.addStatsAndSumDistinctValues(unknownStats, unknownStats), PlanNodeStatsEstimate.unknown()); assertEquals(calculator.addStatsAndSumDistinctValues(first, unknownStats), PlanNodeStatsEstimate.unknown()); assertEquals(calculator.addStatsAndSumDistinctValues(unknownStats, second), PlanNodeStatsEstimate.unknown()); assertEquals(calculator.addStatsAndSumDistinctValues(first, second).getTotalSize(), 30.0); }
ControllerResult<Map<String, ApiError>> updateFeatures( Map<String, Short> updates, Map<String, FeatureUpdate.UpgradeType> upgradeTypes, boolean validateOnly ) { TreeMap<String, ApiError> results = new TreeMap<>(); List<ApiMessageAndVersion> records = BoundedList.newArrayBacked(MAX_RECORDS_PER_USER_OP); for (Entry<String, Short> entry : updates.entrySet()) { results.put(entry.getKey(), updateFeature(entry.getKey(), entry.getValue(), upgradeTypes.getOrDefault(entry.getKey(), FeatureUpdate.UpgradeType.UPGRADE), records)); } if (validateOnly) { return ControllerResult.of(Collections.emptyList(), results); } else { return ControllerResult.atomicOf(records, results); } }
@Test public void testCannotUpgradeToLowerVersion() { FeatureControlManager manager = TEST_MANAGER_BUILDER1.build(); assertEquals(ControllerResult.of(Collections.emptyList(), singletonMap(MetadataVersion.FEATURE_NAME, new ApiError(Errors.INVALID_UPDATE_VERSION, "Invalid update version 4 for feature metadata.version. Can't downgrade the " + "version of this feature without setting the upgrade type to either safe or " + "unsafe downgrade."))), manager.updateFeatures( singletonMap(MetadataVersion.FEATURE_NAME, MetadataVersion.IBP_3_3_IV0.featureLevel()), singletonMap(MetadataVersion.FEATURE_NAME, FeatureUpdate.UpgradeType.UPGRADE), true)); }
public String getContractAddress() { return contractAddress; }
@Test public void testGetContractAddress() { assertEquals(ADDRESS, contract.getContractAddress()); }
@VisibleForTesting @Override public boolean allocateSlot( int index, JobID jobId, AllocationID allocationId, Duration slotTimeout) { return allocateSlot(index, jobId, allocationId, defaultSlotResourceProfile, slotTimeout); }
@Test void testAllocateSlot() throws Exception { final JobID jobId = new JobID(); final AllocationID allocationId = new AllocationID(); try (final TaskSlotTable<TaskSlotPayload> taskSlotTable = createTaskSlotTableWithAllocatedSlot( jobId, allocationId, new TestingSlotActionsBuilder().build())) { Iterator<TaskSlot<TaskSlotPayload>> allocatedSlots = taskSlotTable.getAllocatedSlots(jobId); TaskSlot<TaskSlotPayload> nextSlot = allocatedSlots.next(); assertThat(nextSlot.getIndex()).isZero(); assertThat(nextSlot.getAllocationId()).isEqualTo(allocationId); assertThat(nextSlot.getJobId()).isEqualTo(jobId); assertThat(allocatedSlots.hasNext()).isFalse(); } }
public static JSONObject parseObj(String jsonStr) { return new JSONObject(jsonStr); }
@Test public void toJsonStrTest3() { // 验证某个字段为JSON字符串时转义是否规范 final JSONObject object = new JSONObject(true); object.set("name", "123123"); object.set("value", "\\"); object.set("value2", "</"); final HashMap<String, String> map = MapUtil.newHashMap(); map.put("user", object.toString()); final JSONObject json = JSONUtil.parseObj(map); assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json.get("user")); assertEquals("{\"user\":\"{\\\"name\\\":\\\"123123\\\",\\\"value\\\":\\\"\\\\\\\\\\\",\\\"value2\\\":\\\"</\\\"}\"}", json.toString()); final JSONObject json2 = JSONUtil.parseObj(json.toString()); assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"</\"}", json2.get("user")); }
public Set<String> getSources() { return Collections.unmodifiableSet(sources); }
@Test public void testIterationOrder() { String[] hosts = new String[]{"primary", "fallback", "last-resort"}; ConfigSourceSet css = new ConfigSourceSet(hosts); Set<String> sources = css.getSources(); assertEquals(hosts.length, sources.size()); int i = 0; for (String s : sources) { assertEquals(hosts[i++], s); } }
public boolean hasAdminOrViewPermissions(final CaseInsensitiveString userName, List<Role> memberRoles) { return isUserAnAdmin(userName, memberRoles) || isViewUser(userName, memberRoles); }
@Test public void shouldReturnFalseForUserNotInAdminOrViewConfig() { CaseInsensitiveString viewUser = new CaseInsensitiveString("view"); Authorization authorization = new Authorization(); assertThat(authorization.hasAdminOrViewPermissions(viewUser, null), is(false)); }
public Map<String, Object> convertValue(final Object entity, final Class<?> entityClass) { if (entityClass.equals(String.class)) { return Collections.singletonMap("data", objectMapper.convertValue(entity, String.class)); } else if (!entityClass.equals(Void.class) && !entityClass.equals(void.class)) { final TypeReference<Map<String, Object>> typeRef = new TypeReference<>() { }; try { return objectMapper.convertValue(entity, typeRef); } catch (IllegalArgumentException e) { // Try to convert the response to a list if converting to a map failed. final TypeReference<List<Object>> arrayTypeRef = new TypeReference<>() { }; return Collections.singletonMap("data", objectMapper.convertValue(entity, arrayTypeRef)); } } return null; }
@Test public void returnsNullOnVoidEntityClass() { assertNull(toTest.convertValue(new Object(), Void.class)); assertNull(toTest.convertValue("Lalala", void.class)); }
public Ce.Task formatActivity(DbSession dbSession, CeActivityDto dto, @Nullable String scannerContext) { return formatActivity(dto, DtoCache.forActivityDtos(dbClient, dbSession, singletonList(dto)), scannerContext); }
@Test public void formatActivity_with_both_error_message_and_stacktrace() { CeActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, null) .setErrorMessage("error msg") .setErrorStacktrace("error stacktrace") .setErrorType("anErrorType"); Ce.Task task = underTest.formatActivity(db.getSession(), Collections.singletonList(dto)).iterator().next(); assertThat(task.getErrorMessage()).isEqualTo(dto.getErrorMessage()); assertThat(task.getErrorStacktrace()).isEqualTo(dto.getErrorStacktrace()); assertThat(task.getErrorType()).isEqualTo(dto.getErrorType()); }
@Override public void publish(ScannerReportWriter writer) { Optional<String> targetBranch = getTargetBranch(); if (targetBranch.isPresent()) { Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG); int count = writeChangedLines(scmConfiguration.provider(), writer, targetBranch.get()); LOG.debug("SCM reported changed lines for {} {} in the branch", count, ScannerUtils.pluralize("file", count)); profiler.stopInfo(); } }
@Test public void skip_if_scm_is_disabled() { when(scmConfiguration.isDisabled()).thenReturn(true); publisher.publish(writer); verifyNoInteractions(inputComponentStore, inputModuleHierarchy, provider); assertNotPublished(); }
@Override protected int command() { if (!validateConfigFilePresent()) { return 1; } final MigrationConfig config; try { config = MigrationConfig.load(getConfigFile()); } catch (KsqlException | MigrationException e) { LOGGER.error(e.getMessage()); return 1; } return command( config, MigrationsUtil::getKsqlClient, getMigrationsDir(getConfigFile(), config), Clock.systemDefaultZone() ); }
@Test public void shouldApplyUntilVersion() throws Exception { // Given: command = PARSER.parse("-u", "2"); createMigrationFile(1, NAME, migrationsDir, COMMAND); createMigrationFile(2, NAME, migrationsDir, COMMAND); // extra migration to ensure only the first two are applied createMigrationFile(3, NAME, migrationsDir, COMMAND); when(versionQueryResult.get()).thenReturn(ImmutableList.of()); givenAppliedMigration(1, NAME, MigrationState.MIGRATED); // When: final int result = command.command(config, (cfg, headers) -> ksqlClient, migrationsDir, Clock.fixed( Instant.ofEpochMilli(1000), ZoneId.systemDefault())); // Then: assertThat(result, is(0)); final InOrder inOrder = inOrder(ksqlClient); verifyMigratedVersion(inOrder, 1, "<none>", MigrationState.MIGRATED); verifyMigratedVersion(inOrder, 2, "1", MigrationState.MIGRATED); inOrder.verify(ksqlClient).close(); inOrder.verifyNoMoreInteractions(); }
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testAnalysis() throws Exception { File f = BaseTest.getResourceAsFile(this, "log4net.dll"); Dependency d = new Dependency(f); analyzer.analyze(d, null); assertTrue(d.contains(EvidenceType.VERSION, new Evidence("PE Header", "FileVersion", "1.2.13.0", Confidence.HIGH))); assertEquals("1.2.13.0", d.getVersion()); assertTrue(d.contains(EvidenceType.VENDOR, new Evidence("PE Header", "CompanyName", "The Apache Software Foundation", Confidence.HIGHEST))); assertTrue(d.contains(EvidenceType.PRODUCT, new Evidence("PE Header", "ProductName", "log4net", Confidence.HIGHEST))); assertEquals("log4net", d.getName()); }
public static Builder builder() { return new Builder(); }
@Test public void embeddedTcp() { final ByteBuf pcapBuffer = Unpooled.buffer(); final ByteBuf payload = Unpooled.wrappedBuffer("Meow".getBytes()); InetSocketAddress serverAddr = new InetSocketAddress("1.1.1.1", 1234); InetSocketAddress clientAddr = new InetSocketAddress("2.2.2.2", 3456); EmbeddedChannel embeddedChannel = new EmbeddedChannel( PcapWriteHandler.builder() .forceTcpChannel(serverAddr, clientAddr, true) .build(new ByteBufOutputStream(pcapBuffer)) ); assertTrue(embeddedChannel.writeInbound(payload)); assertEquals(payload, embeddedChannel.readInbound()); assertTrue(embeddedChannel.writeOutbound(payload)); assertEquals(payload, embeddedChannel.readOutbound()); // Verify the capture data verifyTcpCapture(true, pcapBuffer, serverAddr, clientAddr); assertFalse(embeddedChannel.finishAndReleaseAll()); }
@ProcessElement public void processElement(ProcessContext c) throws IOException, InterruptedException { Instant firstInstant = c.sideInput(firstInstantSideInput); T element = c.element(); BackOff backoff = fluentBackoff.backoff(); while (true) { Instant instant = Instant.now(); int maxOpsBudget = calcMaxOpsBudget(firstInstant, instant, this.numWorkers.get()); long currentOpCount = successfulOps.get(instant.getMillis()); long availableOps = maxOpsBudget - currentOpCount; if (maxOpsBudget >= Integer.MAX_VALUE || availableOps > 0) { c.output(element); successfulOps.add(instant.getMillis(), 1); return; } long backoffMillis = backoff.nextBackOffMillis(); LOG.info("Delaying by {}ms to conform to gradual ramp-up.", backoffMillis); throttlingMsecs.inc(backoffMillis); sleeper.sleep(backoffMillis); } }
@Test public void testRampupThrottler() throws Exception { Map<Duration, Integer> rampupSchedule = ImmutableMap.<Duration, Integer>builder() .put(Duration.ZERO, 500) .put(Duration.millis(1), 0) .put(Duration.standardSeconds(1), 500) .put(Duration.standardSeconds(1).plus(Duration.millis(1)), 0) .put(Duration.standardMinutes(5), 500) .put(Duration.standardMinutes(10), 750) .put(Duration.standardMinutes(15), 1125) .put(Duration.standardMinutes(30), 3796) .put(Duration.standardMinutes(60), 43248) .build(); for (Map.Entry<Duration, Integer> entry : rampupSchedule.entrySet()) { DateTimeUtils.setCurrentMillisFixed(entry.getKey().getMillis()); for (int i = 0; i < entry.getValue(); i++) { rampupThrottlingFnTester.processElement(UUID.randomUUID().toString()); } assertThrows(RampupDelayException.class, () -> rampupThrottlingFnTester.processElement(null)); } }
@Override public ByteBuf copy() { return copy(readerIndex, readableBytes()); }
@Test public void testCopyAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().copy(); } }); }
@Override public String toString() { return "[" + from + "-" + to + "]"; }
@Test public void testToString() { assertThat(new LineRange(12, 15)).hasToString("[12-15]"); }
public static Number jsToNumber( Object value, String classType ) { if ( classType.equalsIgnoreCase( JS_UNDEFINED ) ) { return null; } else if ( classType.equalsIgnoreCase( JS_NATIVE_JAVA_OBJ ) ) { try { // Is it a java Value class ? Value v = (Value) Context.jsToJava( value, Value.class ); return v.getNumber(); } catch ( Exception e ) { String string = Context.toString( value ); return Double.parseDouble( Const.trim( string ) ); } } else if ( classType.equalsIgnoreCase( JS_NATIVE_NUM ) ) { Number nb = Context.toNumber( value ); return nb.doubleValue(); } else { Number nb = (Number) value; return nb.doubleValue(); } }
@Test public void jsToNumber_NativeJavaObject_Double() throws Exception { Scriptable value = getDoubleValue(); Number number = JavaScriptUtils.jsToNumber( value, JAVA_OBJECT ); assertEquals( DOUBLE_ONE, number ); }
@Override public int run(String[] args) throws Exception { try { webServiceClient = WebServiceClient.getWebServiceClient().createClient(); return runCommand(args); } finally { if (yarnClient != null) { yarnClient.close(); } if (webServiceClient != null) { webServiceClient.destroy(); } } }
@Test (timeout = 5000) public void testWithExclusiveArguments() throws Exception { ApplicationId appId1 = ApplicationId.newInstance(0, 1); LogsCLI cli = createCli(); // Specify show_container_log_info and show_application_log_info // at the same time int exitCode = cli.run(new String[] {"-applicationId", appId1.toString(), "-show_container_log_info", "-show_application_log_info"}); assertTrue(exitCode == -1); assertTrue(sysErrStream.toString().contains("Invalid options. " + "Can only accept one of show_application_log_info/" + "show_container_log_info.")); sysErrStream.reset(); // Specify log_files and log_files_pattern // at the same time exitCode = cli.run(new String[] {"-applicationId", appId1.toString(), "-log_files", "*", "-log_files_pattern", ".*"}); assertTrue(exitCode == -1); assertTrue(sysErrStream.toString().contains("Invalid options. " + "Can only accept one of log_files/" + "log_files_pattern.")); sysErrStream.reset(); }
@Override public ExecutionMode getExecutionMode() { return jobType == JobType.STREAMING ? ExecutionMode.STREAMING : ExecutionMode.BATCH; }
@Test void testGetExecutionMode() { DefaultJobInfo batchJob = createDefaultJobInfo(JobType.BATCH); assertThat(batchJob.getExecutionMode()).isEqualTo(JobInfo.ExecutionMode.BATCH); DefaultJobInfo streamingJob = createDefaultJobInfo(JobType.STREAMING); assertThat(streamingJob.getExecutionMode()).isEqualTo(JobInfo.ExecutionMode.STREAMING); }
public long toLong(String name) { return toLong(name, 0); }
@Test public void testToLong_String() { System.out.println("toLong"); long expResult; long result; Properties props = new Properties(); props.put("value1", "12345678900"); props.put("value2", "-9000001"); props.put("empty", ""); props.put("str", "abc"); props.put("boolean", "true"); props.put("float", "24.98"); props.put("int", "12"); props.put("char", "a"); PropertyParser instance = new PropertyParser(props); expResult = 12345678900L; result = instance.toLong("value1"); assertEquals(expResult, result); expResult = -9000001L; result = instance.toLong("value2"); assertEquals(expResult, result); expResult = 0L; result = instance.toLong("empty"); assertEquals(expResult, result); expResult = 0L; result = instance.toLong("str"); assertEquals(expResult, result); expResult = 0L; result = instance.toLong("boolean"); assertEquals(expResult, result); expResult = 0L; result = instance.toLong("float"); assertEquals(expResult, result); expResult = 12L; result = instance.toLong("int"); assertEquals(expResult, result); expResult = 0L; result = instance.toLong("char"); assertEquals(expResult, result); expResult = 0L; result = instance.toLong("nonexistent"); assertEquals(expResult, result); }
public static String getMethodName(final String methodName) { return "promise_" + methodName; }
@Test public void testGetMethodName() { assertEquals("promise_methodName", PrxInfoUtil.getMethodName("methodName")); }
@POST @Path(RMWSConsts.SCHEDULER_CONF_VALIDATE) @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public synchronized Response validateAndGetSchedulerConfiguration( SchedConfUpdateInfo mutationInfo, @Context HttpServletRequest hsr) throws AuthorizationException { // Only admin user is allowed to read scheduler conf, // in order to avoid leaking sensitive info, such as ACLs UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true); initForWritableEndpoints(callerUGI, true); ResourceScheduler scheduler = rm.getResourceScheduler(); if (isConfigurationMutable(scheduler)) { try { MutableConfigurationProvider mutableConfigurationProvider = ((MutableConfScheduler) scheduler).getMutableConfProvider(); Configuration schedulerConf = mutableConfigurationProvider .getConfiguration(); Configuration newSchedulerConf = mutableConfigurationProvider .applyChanges(schedulerConf, mutationInfo); Configuration yarnConf = ((CapacityScheduler) scheduler).getConf(); Configuration newConfig = new Configuration(yarnConf); Iterator<Map.Entry<String, String>> iter = newSchedulerConf.iterator(); Entry<String, String> e = null; while (iter.hasNext()) { e = iter.next(); newConfig.set(e.getKey(), e.getValue()); } CapacitySchedulerConfigValidator.validateCSConfiguration(yarnConf, newConfig, rm.getRMContext()); return Response.status(Status.OK) .entity(new ConfInfo(newSchedulerConf)) .build(); } catch (Exception e) { String errorMsg = "CapacityScheduler configuration validation failed:" + e.toString(); LOG.warn(errorMsg); return Response.status(Status.BAD_REQUEST) .entity(errorMsg) .build(); } } else { String errorMsg = String.format("Configuration change validation only supported by %s.", MutableConfScheduler.class.getSimpleName()); LOG.warn(errorMsg); return Response.status(Status.BAD_REQUEST) .entity(errorMsg) .build(); } }
@Test public void testValidateAndGetSchedulerConfigurationValidScheduler() throws IOException { Configuration config = CapacitySchedulerConfigGeneratorForTest .createBasicCSConfiguration(); config.set("yarn.scheduler.capacity.root.test1.state", "STOPPED"); config.set("yarn.scheduler.capacity.queue-mappings", "u:test2:test2"); ResourceScheduler scheduler = prepareCSForValidation(config); SchedConfUpdateInfo mutationInfo = new SchedConfUpdateInfo(); ArrayList<String> queuesToRemove = new ArrayList(); queuesToRemove.add("root.test1"); mutationInfo.setRemoveQueueInfo(queuesToRemove); ArrayList<QueueConfigInfo> updateQueueInfo = new ArrayList<>(); String queueToUpdate = "root.test2"; Map<String, String> propertiesToUpdate = new HashMap<>(); propertiesToUpdate.put("capacity", "100"); updateQueueInfo.add(new QueueConfigInfo(queueToUpdate, propertiesToUpdate)); mutationInfo.setUpdateQueueInfo(updateQueueInfo); RMWebServices webService = prepareWebServiceForValidation(scheduler); HttpServletRequest mockHsr = prepareServletRequestForValidation(); Response response = webService .validateAndGetSchedulerConfiguration(mutationInfo, mockHsr); Assert.assertEquals(Status.OK .getStatusCode(), response.getStatus()); }
public String generateShortUuid() { return String.valueOf(ID_WORKER_UTILS.nextId()); }
@Test public void testGenerateShortUuid() { String shortUuid = UUIDUtils.getInstance().generateShortUuid(); assertTrue(StringUtils.isNotEmpty(shortUuid)); assertEquals(19, shortUuid.length()); }
@Override public ObjectName createName(String type, String domain, String name) { try { ObjectName objectName; Hashtable<String, String> properties = new Hashtable<>(); properties.put("name", name); properties.put("type", type); objectName = new ObjectName(domain, properties); /* * The only way we can find out if we need to quote the properties is by * checking an ObjectName that we've constructed. */ if (objectName.isDomainPattern()) { domain = ObjectName.quote(domain); } if (objectName.isPropertyValuePattern("name") || shouldQuote(objectName.getKeyProperty("name"))) { properties.put("name", ObjectName.quote(name)); } if (objectName.isPropertyValuePattern("type") || shouldQuote(objectName.getKeyProperty("type"))) { properties.put("type", ObjectName.quote(type)); } objectName = new ObjectName(domain, properties); return objectName; } catch (MalformedObjectNameException e) { try { return new ObjectName(domain, "name", ObjectName.quote(name)); } catch (MalformedObjectNameException e1) { LOGGER.warn("Unable to register {} {}", type, name, e1); throw new RuntimeException(e1); } } }
@Test public void createsObjectNameWithNameWithDisallowedUnquotedCharacters() { DefaultObjectNameFactory f = new DefaultObjectNameFactory(); ObjectName on = f.createName("type", "com.domain", "something.with.quotes(\"ABcd\")"); assertThatCode(() -> new ObjectName(on.toString())).doesNotThrowAnyException(); assertThat(on.getKeyProperty("name")).isEqualTo("\"something.with.quotes(\\\"ABcd\\\")\""); }
static void validateConnectors(KafkaMirrorMaker2 kafkaMirrorMaker2) { if (kafkaMirrorMaker2.getSpec() == null) { throw new InvalidResourceException(".spec section is required for KafkaMirrorMaker2 resource"); } else { if (kafkaMirrorMaker2.getSpec().getClusters() == null || kafkaMirrorMaker2.getSpec().getMirrors() == null) { throw new InvalidResourceException(".spec.clusters and .spec.mirrors sections are required in KafkaMirrorMaker2 resource"); } else { Set<String> existingClusterAliases = kafkaMirrorMaker2.getSpec().getClusters().stream().map(KafkaMirrorMaker2ClusterSpec::getAlias).collect(Collectors.toSet()); Set<String> errorMessages = new HashSet<>(); String connectCluster = kafkaMirrorMaker2.getSpec().getConnectCluster(); for (KafkaMirrorMaker2MirrorSpec mirror : kafkaMirrorMaker2.getSpec().getMirrors()) { if (mirror.getSourceCluster() == null) { errorMessages.add("Each MirrorMaker 2 mirror definition has to specify the source cluster alias"); } else if (!existingClusterAliases.contains(mirror.getSourceCluster())) { errorMessages.add("Source cluster alias " + mirror.getSourceCluster() + " is used in a mirror definition, but cluster with this alias does not exist in cluster definitions"); } if (mirror.getTargetCluster() == null) { errorMessages.add("Each MirrorMaker 2 mirror definition has to specify the target cluster alias"); } else if (!existingClusterAliases.contains(mirror.getTargetCluster())) { errorMessages.add("Target cluster alias " + mirror.getTargetCluster() + " is used in a mirror definition, but cluster with this alias does not exist in cluster definitions"); } if (!mirror.getTargetCluster().equals(connectCluster)) { errorMessages.add("Connect cluster alias (currently set to " + connectCluster + ") has to be the same as the target cluster alias " + mirror.getTargetCluster()); } } if (!errorMessages.isEmpty()) { throw new InvalidResourceException("KafkaMirrorMaker2 resource validation failed: " + errorMessages); } } } }
@Test public void testMirrorTargetClusterNotSameAsConnectCluster() { // The most obvious error case, where connect cluster is set to the source cluster instead of target KafkaMirrorMaker2 kmm2 = new KafkaMirrorMaker2Builder(KMM2) .editSpec() .withConnectCluster("source") .endSpec() .build(); InvalidResourceException ex = assertThrows(InvalidResourceException.class, () -> KafkaMirrorMaker2Connectors.validateConnectors(kmm2)); assertThat(ex.getMessage(), is("KafkaMirrorMaker2 resource validation failed: " + "[Connect cluster alias (currently set to source) has to be the same as the target cluster alias target]")); // A case where one mirror has the correct target cluster, but the other does not KafkaMirrorMaker2 kmm2CorrectAndIncorrectMirror = new KafkaMirrorMaker2Builder(KMM2) .editSpec() .addToClusters(new KafkaMirrorMaker2ClusterSpecBuilder() .withAlias("third") .withBootstrapServers("third:9092") .build()) .addToMirrors(new KafkaMirrorMaker2MirrorSpecBuilder() .withSourceCluster("source") .withTargetCluster("third").build()) .endSpec() .build(); ex = assertThrows(InvalidResourceException.class, () -> KafkaMirrorMaker2Connectors.validateConnectors(kmm2CorrectAndIncorrectMirror)); assertThat(ex.getMessage(), is("KafkaMirrorMaker2 resource validation failed: " + "[Connect cluster alias (currently set to target) has to be the same as the target cluster alias third]")); }
public static ImmutableSet<HttpUrl> allSubPaths(String url) { return allSubPaths(HttpUrl.parse(url)); }
@Test public void allSubPaths_whenNoSubPathWithTrailingSlash_returnsSingleUrl() { assertThat(allSubPaths("http://localhost/")) .containsExactly(HttpUrl.parse("http://localhost/")); }
public Optional<String> findGenerateKeyColumnName(final String logicTableName) { return Optional.ofNullable(shardingTables.get(logicTableName)).filter(each -> each.getGenerateKeyColumn().isPresent()).flatMap(ShardingTable::getGenerateKeyColumn); }
@Test void assertFindGenerateKeyColumn() { assertTrue(createMaximumShardingRule().findGenerateKeyColumnName("logic_table").isPresent()); }
public static org.apache.avro.Schema.Field toAvroField(Field field, String namespace) { org.apache.avro.Schema fieldSchema = getFieldSchema(field.getType(), field.getName(), namespace); return new org.apache.avro.Schema.Field( field.getName(), fieldSchema, field.getDescription(), (Object) null); }
@Test public void testNullableBeamArrayFieldToAvroField() { Field beamField = Field.nullable("arrayField", FieldType.array(FieldType.INT32)); org.apache.avro.Schema.Field expectedAvroField = new org.apache.avro.Schema.Field( "arrayField", ReflectData.makeNullable( org.apache.avro.Schema.createArray(org.apache.avro.Schema.create(Type.INT))), "", (Object) null); org.apache.avro.Schema.Field avroField = AvroUtils.toAvroField(beamField, "ignored"); assertEquals(expectedAvroField, avroField); }