focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void addPartitions(String dbName, String tableName, List<HivePartitionWithStats> partitions) { try { metastore.addPartitions(dbName, tableName, partitions); } catch (Exception e) { LOG.warn("Failed to execute metastore.addPartitions", e); throw e; } finally { if (!(metastore instanceof CachingHiveMetastore)) { List<HivePartitionName> partitionNames = partitions.stream() .map(name -> HivePartitionName.of(dbName, tableName, name.getPartitionName())) .collect(Collectors.toList()); refreshPartition(partitionNames); } } }
@Test public void testAddPartitionFailed() { CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore( metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false); HivePartition hivePartition = HivePartition.builder() // Unsupported type .setColumns(Lists.newArrayList(new Column("c1", Type.BITMAP))) .setStorageFormat(HiveStorageFormat.PARQUET) .setDatabaseName("db") .setTableName("table") .setLocation("location") .setValues(Lists.newArrayList("p1=1")) .setParameters(new HashMap<>()).build(); HivePartitionStats hivePartitionStats = HivePartitionStats.empty(); HivePartitionWithStats hivePartitionWithStats = new HivePartitionWithStats("p1=1", hivePartition, hivePartitionStats); Assert.assertThrows(StarRocksConnectorException.class, () -> { cachingHiveMetastore.addPartitions("db", "table", Lists.newArrayList(hivePartitionWithStats)); }); }
@ScalarOperator(BETWEEN) @SqlType(StandardTypes.BOOLEAN) public static boolean between(@SqlType(StandardTypes.BOOLEAN) boolean value, @SqlType(StandardTypes.BOOLEAN) boolean min, @SqlType(StandardTypes.BOOLEAN) boolean max) { return (value && max) || (!value && !min); }
@Test public void testBetween() { assertFunction("true BETWEEN true AND true", BOOLEAN, true); assertFunction("true BETWEEN true AND false", BOOLEAN, false); assertFunction("true BETWEEN false AND true", BOOLEAN, true); assertFunction("true BETWEEN false AND false", BOOLEAN, false); assertFunction("false BETWEEN true AND true", BOOLEAN, false); assertFunction("false BETWEEN true AND false", BOOLEAN, false); assertFunction("false BETWEEN false AND true", BOOLEAN, true); assertFunction("false BETWEEN false AND false", BOOLEAN, true); }
static boolean acknowledge(MessageIdAdv msgId, boolean individual) { if (!isBatch(msgId)) { return true; } final BitSet ackSet = msgId.getAckSet(); if (ackSet == null) { // The internal MessageId implementation should never reach here. If users have implemented their own // MessageId and getAckSet() is not override, return false to avoid acknowledge current entry. return false; } int batchIndex = msgId.getBatchIndex(); synchronized (ackSet) { if (individual) { ackSet.clear(batchIndex); } else { ackSet.clear(0, batchIndex + 1); } return ackSet.isEmpty(); } }
@Test public void testAcknowledgeIndividualConcurrently() throws InterruptedException { ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("pulsar-consumer-%d").build(); @Cleanup("shutdown") ExecutorService executorService = Executors.newCachedThreadPool(threadFactory); for (int i = 0; i < 100; i++) { int batchSize = 32; BitSet bitSet = new BitSet(batchSize); bitSet.set(0, batchSize); AtomicInteger individualAcked = new AtomicInteger(); Phaser phaser = new Phaser(1); CountDownLatch finishLatch = new CountDownLatch(batchSize); for (int batchIndex = 0; batchIndex < batchSize; batchIndex++) { phaser.register(); BatchMessageIdImpl messageId = new BatchMessageIdImpl(1, 0, 0, batchIndex, batchSize, bitSet); executorService.execute(() -> { try { phaser.arriveAndAwaitAdvance(); if (MessageIdAdvUtils.acknowledge(messageId, true)) { individualAcked.incrementAndGet(); } } finally { finishLatch.countDown(); } }); } phaser.arriveAndDeregister(); finishLatch.await(); assertEquals(individualAcked.get(), 1); } }
@Override public Optional<WorkItem> getWorkItem() throws IOException { List<String> workItemTypes = ImmutableList.of( WORK_ITEM_TYPE_MAP_TASK, WORK_ITEM_TYPE_SEQ_MAP_TASK, WORK_ITEM_TYPE_REMOTE_SOURCE_TASK); // All remote sources require the "remote_source" capability. Dataflow's // custom sources are further tagged with the format "custom_source". List<String> capabilities = new ArrayList<String>( Arrays.asList( options.getWorkerId(), CAPABILITY_REMOTE_SOURCE, PropertyNames.CUSTOM_SOURCE_FORMAT)); if (options.getWorkerPool() != null) { capabilities.add(options.getWorkerPool()); } Optional<WorkItem> workItem = getWorkItemInternal(workItemTypes, capabilities); if (!workItem.isPresent()) { // Normal case, this means that the response contained no work, i.e. no work is available // at this time. return Optional.empty(); } if (workItem.get().getId() == null) { logger.debug("Discarding invalid work item {}", workItem.get()); return Optional.empty(); } WorkItem work = workItem.get(); final String stage; if (work.getMapTask() != null) { stage = work.getMapTask().getStageName(); logger.info("Starting MapTask stage {}", stage); } else if (work.getSeqMapTask() != null) { stage = work.getSeqMapTask().getStageName(); logger.info("Starting SeqMapTask stage {}", stage); } else if (work.getSourceOperationTask() != null) { stage = work.getSourceOperationTask().getStageName(); logger.info("Starting SourceOperationTask stage {}", stage); } else { stage = null; } DataflowWorkerLoggingMDC.setStageName(stage); stageStartTime.set(DateTime.now()); DataflowWorkerLoggingMDC.setWorkId(Long.toString(work.getId())); return workItem; }
@Test public void testCloudServiceCallNoWorkItem() throws Exception { MockLowLevelHttpResponse response = generateMockResponse(); MockLowLevelHttpRequest request = new MockLowLevelHttpRequest().setResponse(response); MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpRequest(request).build(); DataflowWorkerHarnessOptions pipelineOptions = createPipelineOptionsWithTransport(transport); WorkUnitClient client = new DataflowWorkUnitClient(pipelineOptions, LOG); assertEquals(Optional.empty(), client.getWorkItem()); LeaseWorkItemRequest actualRequest = Transport.getJsonFactory() .fromString(request.getContentAsString(), LeaseWorkItemRequest.class); assertEquals(WORKER_ID, actualRequest.getWorkerId()); assertEquals( ImmutableList.of(WORKER_ID, "remote_source", "custom_source"), actualRequest.getWorkerCapabilities()); assertEquals( ImmutableList.of("map_task", "seq_map_task", "remote_source_task"), actualRequest.getWorkItemTypes()); }
@Override public InterpreterResult interpret(String st, InterpreterContext context) { return helper.interpret(session, st, context); }
@Test void should_exception_when_executing_unknown_bound_statement() { // Given String queries = "@bind[select_users]='jdoe'"; // When final InterpreterResult actual = interpreter.interpret(queries, intrContext); // Then assertEquals(Code.ERROR, actual.code()); assertEquals("The statement 'select_users' can not be bound to values. " + "Are you sure you did prepare it with @prepare[select_users] ?", actual.message().get(0).getData()); }
@Override public void addConfiguration(String configName, C configuration) { if (configName.equals(DEFAULT_CONFIG)) { throw new IllegalArgumentException( "You cannot use 'default' as a configuration name as it is preserved for default configuration"); } this.configurations.put(configName, configuration); }
@Test public void shouldNotAllowToOverwriteDefaultConfiguration() { TestRegistry testRegistry = new TestRegistry(); assertThatThrownBy(() -> testRegistry.addConfiguration("default", "test")) .isInstanceOf(IllegalArgumentException.class); }
@VisibleForTesting protected void copyFromHost(MapHost host) throws IOException { // reset retryStartTime for a new host retryStartTime = 0; // Get completed maps on 'host' List<TaskAttemptID> maps = scheduler.getMapsForHost(host); // Sanity check to catch hosts with only 'OBSOLETE' maps, // especially at the tail of large jobs if (maps.size() == 0) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Fetcher " + id + " going to fetch from " + host + " for: " + maps); } // List of maps to be fetched yet Set<TaskAttemptID> remaining = new HashSet<TaskAttemptID>(maps); // Construct the url and connect URL url = getMapOutputURL(host, maps); DataInputStream input = null; try { input = openShuffleUrl(host, remaining, url); if (input == null) { return; } // Loop through available map-outputs and fetch them // On any error, faildTasks is not null and we exit // after putting back the remaining maps to the // yet_to_be_fetched list and marking the failed tasks. TaskAttemptID[] failedTasks = null; while (!remaining.isEmpty() && failedTasks == null) { try { failedTasks = copyMapOutput(host, input, remaining, fetchRetryEnabled); } catch (IOException e) { IOUtils.cleanupWithLogger(LOG, input); // // Setup connection again if disconnected by NM connection.disconnect(); // Get map output from remaining tasks only. url = getMapOutputURL(host, remaining); input = openShuffleUrl(host, remaining, url); if (input == null) { return; } } } if(failedTasks != null && failedTasks.length > 0) { LOG.warn("copyMapOutput failed for tasks "+Arrays.toString(failedTasks)); scheduler.hostFailed(host.getHostName()); for(TaskAttemptID left: failedTasks) { scheduler.copyFailed(left, host, true, false); } } // Sanity check if (failedTasks == null && !remaining.isEmpty()) { throw new IOException("server didn't return all expected map outputs: " + remaining.size() + " left."); } input.close(); input = null; } finally { if (input != null) { IOUtils.cleanupWithLogger(LOG, input); input = null; } for (TaskAttemptID left : remaining) { scheduler.putBackKnownMapOutput(host, left); } } }
@Test public void testCopyFromHostConnectionRejected() throws Exception { when(connection.getResponseCode()) .thenReturn(Fetcher.TOO_MANY_REQ_STATUS_CODE); Fetcher<Text, Text> fetcher = new FakeFetcher<>(job, id, ss, mm, r, metrics, except, key, connection); fetcher.copyFromHost(host); assertThat(ss.hostFailureCount(host.getHostName())) .withFailMessage("No host failure is expected.").isEqualTo(0); assertThat(ss.fetchFailureCount(map1ID)) .withFailMessage("No fetch failure is expected.").isEqualTo(0); assertThat(ss.fetchFailureCount(map2ID)) .withFailMessage("No fetch failure is expected.").isEqualTo(0); verify(ss).penalize(eq(host), anyLong()); verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map1ID)); verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map2ID)); }
public String getId(String name) { // Use the id directly if it is unique and the length is less than max if (name.length() <= maxHashLength && usedIds.add(name)) { return name; } // Pick the last bytes of hashcode and use hex format final String hexString = Integer.toHexString(name.hashCode()); final String origId = hexString.length() <= maxHashLength ? hexString : hexString.substring(Math.max(0, hexString.length() - maxHashLength)); String id = origId; int suffixNum = 2; while (!usedIds.add(id)) { // A duplicate! Retry. id = origId + "-" + suffixNum++; } LOG.info("Name {} is mapped to id {}", name, id); return id; }
@Test public void testSameNames() { final HashIdGenerator idGenerator = new HashIdGenerator(); String id1 = idGenerator.getId(Count.perKey().getName()); String id2 = idGenerator.getId(Count.perKey().getName()); Assert.assertNotEquals(id1, id2); }
@Override public TableBuilder buildTable(TableIdentifier identifier, Schema schema) { return new ViewAwareTableBuilder(identifier, schema); }
@Test public void testCreateTableCustomSortOrder() { TableIdentifier tableIdent = TableIdentifier.of("db", "ns1", "ns2", "tbl"); SortOrder order = SortOrder.builderFor(SCHEMA).asc("id", NULLS_FIRST).build(); Table table = catalog .buildTable(tableIdent, SCHEMA) .withPartitionSpec(PARTITION_SPEC) .withSortOrder(order) .create(); SortOrder sortOrder = table.sortOrder(); assertThat(sortOrder.orderId()).as("Order ID must match").isEqualTo(1); assertThat(sortOrder.fields()).as("Order must have 1 field").hasSize(1); assertThat(sortOrder.fields().get(0).direction()).as("Direction must match ").isEqualTo(ASC); assertThat(sortOrder.fields().get(0).nullOrder()) .as("Null order must match ") .isEqualTo(NULLS_FIRST); Transform<?, ?> transform = Transforms.identity(); assertThat(sortOrder.fields().get(0).transform()) .as("Transform must match") .isEqualTo(transform); }
protected void createNewWorkerId() { type.assertFull(); if (workerId != null) { String err = "Incorrect usage of createNewWorkerId(), current workerId is " + workerId + ", expecting null"; LOG.error(err); throw new AssertionError(err); } synchronized (localState) { workerId = Utils.uuid(); Map<String, Integer> workerToPort = localState.getApprovedWorkers(); if (workerToPort == null) { workerToPort = new HashMap<>(1); } removeWorkersOn(workerToPort, port); workerToPort.put(workerId, port); localState.setApprovedWorkers(workerToPort); LOG.info("Created Worker ID {}", workerId); } }
@Test public void testCreateNewWorkerId() throws Exception { final String topoId = "test_topology"; final int supervisorPort = 6628; final int port = 8080; LocalAssignment la = new LocalAssignment(); la.set_topology_id(topoId); Map<String, Object> superConf = new HashMap<>(); AdvancedFSOps ops = mock(AdvancedFSOps.class); when(ops.doRequiredTopoFilesExist(superConf, topoId)).thenReturn(true); LocalState ls = mock(LocalState.class); ResourceIsolationInterface iso = mock(ResourceIsolationInterface.class); MockBasicContainer mc = new MockBasicContainer(ContainerType.LAUNCH, superConf, "SUPERVISOR", supervisorPort, port, la, iso, ls, null, new StormMetricsRegistry(), new HashMap<>(), ops, "profile"); //null worker id means generate one... assertNotNull(mc.workerId); verify(ls).getApprovedWorkers(); Map<String, Integer> expectedNewState = new HashMap<>(); expectedNewState.put(mc.workerId, port); verify(ls).setApprovedWorkers(expectedNewState); }
public static Optional<Object> getAdjacentValue(Type type, Object value, boolean isPrevious) { if (!type.isOrderable()) { throw new IllegalStateException("Type is not orderable: " + type); } requireNonNull(value, "value is null"); if (type.equals(BIGINT) || type instanceof TimestampType) { return getBigintAdjacentValue(value, isPrevious); } if (type.equals(INTEGER) || type.equals(DATE)) { return getIntegerAdjacentValue(value, isPrevious); } if (type.equals(SMALLINT)) { return getSmallIntAdjacentValue(value, isPrevious); } if (type.equals(TINYINT)) { return getTinyIntAdjacentValue(value, isPrevious); } if (type.equals(DOUBLE)) { return getDoubleAdjacentValue(value, isPrevious); } if (type.equals(REAL)) { return getRealAdjacentValue(value, isPrevious); } return Optional.empty(); }
@Test public void testPreviousValueForTimestamp() { long minValue = Long.MIN_VALUE; long maxValue = Long.MAX_VALUE; assertThat(getAdjacentValue(TIMESTAMP, minValue, true)) .isEqualTo(Optional.empty()); assertThat(getAdjacentValue(TIMESTAMP, minValue + 1, true)) .isEqualTo(Optional.of(minValue)); assertThat(getAdjacentValue(TIMESTAMP_MICROSECONDS, minValue, true)) .isEqualTo(Optional.empty()); assertThat(getAdjacentValue(TIMESTAMP_MICROSECONDS, minValue + 1, true)) .isEqualTo(Optional.of(minValue)); assertThat(getAdjacentValue(TIMESTAMP, 1234L, true)) .isEqualTo(Optional.of(1233L)); assertThat(getAdjacentValue(TIMESTAMP_MICROSECONDS, 1234L, true)) .isEqualTo(Optional.of(1233L)); assertThat(getAdjacentValue(TIMESTAMP, maxValue - 1, true)) .isEqualTo(Optional.of(maxValue - 2)); assertThat(getAdjacentValue(TIMESTAMP, maxValue, true)) .isEqualTo(Optional.of(maxValue - 1)); assertThat(getAdjacentValue(TIMESTAMP_MICROSECONDS, maxValue - 1, true)) .isEqualTo(Optional.of(maxValue - 2)); assertThat(getAdjacentValue(TIMESTAMP_MICROSECONDS, maxValue, true)) .isEqualTo(Optional.of(maxValue - 1)); }
@InterfaceAudience.Private public static String bashQuote(String arg) { StringBuilder buffer = new StringBuilder(arg.length() + 2); buffer.append('\'') .append(arg.replace("'", "'\\''")) .append('\''); return buffer.toString(); }
@Test public void testBashQuote() { assertEquals("'foobar'", Shell.bashQuote("foobar")); assertEquals("'foo'\\''bar'", Shell.bashQuote("foo'bar")); assertEquals("''\\''foo'\\''bar'\\'''", Shell.bashQuote("'foo'bar'")); }
@Override public String buildRemoteURL(String baseRepositoryURL, String referencePath) { // https://gitlab.com/api/v4/projects/35980862/repository/files/folder%2Fsubfolder%2Ffilename/raw?ref=branch // https://gitlab.com/api/v4/projects/35980862/repository/files String rootURL = baseRepositoryURL.substring(0, baseRepositoryURL.indexOf(REPOSITORY_FILES_MARKER) + REPOSITORY_FILES_MARKER.length() - 1); // folder%2Fsubfolder%2Ffilename String basePath = baseRepositoryURL.substring( baseRepositoryURL.indexOf(REPOSITORY_FILES_MARKER) + REPOSITORY_FILES_MARKER.length(), baseRepositoryURL.lastIndexOf("/")); // raw?ref=branch String formatOptions = baseRepositoryURL.substring(baseRepositoryURL.lastIndexOf("/") + 1); // Now do a simple reference url build. We need to ensure that there's a root // by adding a starting /. We'll remove it after the build when recomposing result. String pathFragment = super.buildRemoteURL("/" + URLDecoder.decode(basePath, StandardCharsets.UTF_8), referencePath); return rootURL + "/" + URLEncoder.encode(pathFragment.substring(1), StandardCharsets.UTF_8) + "/" + formatOptions; }
@Test void testBuildRemoteURL() { GitLabReferenceURLBuilder builder = new GitLabReferenceURLBuilder(); assertEquals("https://gitlab.com/api/v4/projects/35980862/repository/files/pastry%2Fschema-ref.yml/raw?ref=main", builder.buildRemoteURL(BASE_URL, "schema-ref.yml")); assertEquals("https://gitlab.com/api/v4/projects/35980862/repository/files/pastry%2Fschema-ref.yml/raw?ref=main", builder.buildRemoteURL(BASE_URL, "./schema-ref.yml")); assertEquals("https://gitlab.com/api/v4/projects/35980862/repository/files/refs%2Fschema-ref.yml/raw?ref=main", builder.buildRemoteURL(BASE_URL, "../refs/schema-ref.yml")); }
public static void validate( FederationPolicyInitializationContext policyContext, String myType) throws FederationPolicyInitializationException { if (myType == null) { throw new FederationPolicyInitializationException( "The myType parameter" + " should not be null."); } if (policyContext == null) { throw new FederationPolicyInitializationException( "The FederationPolicyInitializationContext provided is null. Cannot" + " reinitialize " + "successfully."); } if (policyContext.getFederationStateStoreFacade() == null) { throw new FederationPolicyInitializationException( "The FederationStateStoreFacade provided is null. Cannot" + " reinitialize successfully."); } if (policyContext.getFederationSubclusterResolver() == null) { throw new FederationPolicyInitializationException( "The FederationSubclusterResolver provided is null. Cannot" + " reinitialize successfully."); } if (policyContext.getSubClusterPolicyConfiguration() == null) { throw new FederationPolicyInitializationException( "The SubClusterPolicyConfiguration provided is null. Cannot " + "reinitialize successfully."); } String intendedType = policyContext.getSubClusterPolicyConfiguration().getType(); if (!myType.equals(intendedType)) { throw new FederationPolicyInitializationException( "The FederationPolicyConfiguration carries a type (" + intendedType + ") different then mine (" + myType + "). Cannot reinitialize successfully."); } }
@Test(expected = FederationPolicyInitializationException.class) public void nullConf() throws Exception { context.setSubClusterPolicyConfiguration(null); FederationPolicyInitializationContextValidator.validate(context, MockPolicyManager.class.getCanonicalName()); }
@Override public Long incrementCounter(String name) { return incrementCounter(name, 1L); }
@Test @org.junit.Ignore("flaky test HIVE-23692") public void testFileReporting() throws Exception { int runs = 5; String counterName = "count2"; // on the first write the metrics writer should initialize stuff MetricsFactory.getInstance().incrementCounter(counterName); sleep(5 * REPORT_INTERVAL_MS); for (int i = 1; i <= runs; i++) { MetricsFactory.getInstance().incrementCounter(counterName); sleep(REPORT_INTERVAL_MS + REPORT_INTERVAL_MS / 2); Assert.assertEquals(i + 1, getCounterValue(counterName)); } }
@Override public Set<String> names() { if (isEmpty()) { return Collections.emptySet(); } Set<String> names = new LinkedHashSet<String>(size()); for (int i = 0; i < nameValuePairs.length; i += 2) { names.add(nameValuePairs[i].toString()); } return names; }
@Test public void names() { ReadOnlyHttpHeaders headers = new ReadOnlyHttpHeaders(true, ACCEPT, APPLICATION_JSON, CONTENT_LENGTH, ZERO, CONNECTION, CLOSE); assertFalse(headers.isEmpty()); assertEquals(3, headers.size()); Set<String> names = headers.names(); assertEquals(3, names.size()); assertTrue(names.contains(ACCEPT.toString())); assertTrue(names.contains(CONTENT_LENGTH.toString())); assertTrue(names.contains(CONNECTION.toString())); }
public static Transaction read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return Transaction.read(payload, ProtocolVersion.CURRENT.intValue()); }
@Test public void parseTransactionWithHugeDeclaredOutputsSize() { Transaction tx = new HugeDeclaredSizeTransaction(false, true, false); byte[] serializedTx = tx.serialize(); try { Transaction.read(ByteBuffer.wrap(serializedTx)); fail("We expect BufferUnderflowException with the fixed code and OutOfMemoryError with the buggy code, so this is weird"); } catch (BufferUnderflowException e) { //Expected, do nothing } }
public static int bytesToInt(byte[] ary) { return (ary[3] & 0xFF) | ((ary[2] << 8) & 0xFF00) | ((ary[1] << 16) & 0xFF0000) | ((ary[0] << 24) & 0xFF000000); }
@Test public void bytesToInt() { int i = CodecUtils.bytesToInt(new byte[] { 0, 0, 0, 0 }); Assert.assertEquals(0, i); i = CodecUtils.bytesToInt(new byte[] { 0, 0, 3, -24 }); Assert.assertEquals(1000, i); int s = CodecUtils.bytesToInt(new byte[] { 1, 0, 0, 2 }); Assert.assertEquals(s, 16777218); }
@VisibleForTesting static void instantiateHeapMemoryMetrics(final MetricGroup metricGroup) { instantiateMemoryUsageMetrics( metricGroup, () -> ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()); }
@Test void testHeapMetricUsageNotStatic() throws Exception { final InterceptingOperatorMetricGroup heapMetrics = new InterceptingOperatorMetricGroup(); MetricUtils.instantiateHeapMemoryMetrics(heapMetrics); @SuppressWarnings("unchecked") final Gauge<Long> used = (Gauge<Long>) heapMetrics.get(MetricNames.MEMORY_USED); runUntilMetricChanged("Heap", 10, () -> new byte[1024 * 1024 * 8], used); }
@Private @VisibleForTesting static void checkResourceRequestAgainstAvailableResource(Resource reqResource, Resource availableResource) throws InvalidResourceRequestException { for (int i = 0; i < ResourceUtils.getNumberOfCountableResourceTypes(); i++) { final ResourceInformation requestedRI = reqResource.getResourceInformation(i); final String reqResourceName = requestedRI.getName(); if (requestedRI.getValue() < 0) { throwInvalidResourceException(reqResource, availableResource, reqResourceName, InvalidResourceType.LESS_THAN_ZERO); } boolean valid = checkResource(requestedRI, availableResource); if (!valid) { throwInvalidResourceException(reqResource, availableResource, reqResourceName, InvalidResourceType.GREATER_THEN_MAX_ALLOCATION); } } }
@Test public void testCustomResourceRequestedUnitIsSameAsAvailableUnit2() throws InvalidResourceRequestException { Resource requestedResource = ResourceTypesTestHelper.newResource(1, 1, ImmutableMap.of("custom-resource-1", "110M")); Resource availableResource = ResourceTypesTestHelper.newResource(1, 1, ImmutableMap.of("custom-resource-1", "100M")); exception.expect(InvalidResourceRequestException.class); exception.expectMessage(InvalidResourceRequestExceptionMessageGenerator .create().withRequestedResourceType("custom-resource-1") .withRequestedResource(requestedResource) .withAvailableAllocation(availableResource) .withInvalidResourceType(GREATER_THEN_MAX_ALLOCATION) .withMaxAllocation(configuredMaxAllocation) .build()); SchedulerUtils.checkResourceRequestAgainstAvailableResource( requestedResource, availableResource); }
public static String getRelativePath(Path sourceRootPath, Path childPath) { String childPathString = childPath.toUri().getPath(); String sourceRootPathString = sourceRootPath.toUri().getPath(); return sourceRootPathString.equals("/") ? childPathString : childPathString.substring(sourceRootPathString.length()); }
@Test public void testGetRelativePath() { Path root = new Path("/tmp/abc"); Path child = new Path("/tmp/abc/xyz/file"); assertThat(DistCpUtils.getRelativePath(root, child)).isEqualTo("/xyz/file"); }
static RequestConfigElement parse(String property, String key, Object value) throws RequestConfigKeyParsingException { RequestConfigKeyParsingErrorListener errorListener = new RequestConfigKeyParsingErrorListener(); ANTLRInputStream input = new ANTLRInputStream(key); RequestConfigKeyLexer lexer = new RequestConfigKeyLexer(input); lexer.removeErrorListeners(); lexer.addErrorListener(errorListener); CommonTokenStream tokens = new CommonTokenStream(lexer); RequestConfigKeyParser parser = new RequestConfigKeyParser(tokens); parser.removeErrorListeners(); parser.addErrorListener(errorListener); KeyContext keyTree = parser.key(); if (!errorListener.hasErrors()) { InboundContext inbound = keyTree.inbound(); OutboundContext outbound = keyTree.outbound(); Optional<String> inboundName = handlingWildcard(inbound.restResource()); Optional<String> outboundName = handlingWildcard(outbound.restResource()); Optional<String> inboundOp = getOpIn(inbound.operationIn()); Optional<ResourceMethod> outboundOp = getOpOut(outbound.operationOut()); Optional<String> inboundOpName = inboundOp.flatMap(method -> getOpInName(method, inbound.operationIn())); Optional<String> outboundOpName = outboundOp.flatMap(method -> getOpOutName(method, outbound.operationOut())); return new RequestConfigElement(key, coerceValue(property, value), property, inboundName, outboundName, inboundOpName, outboundOpName, inboundOp, outboundOp); } else { throw new RequestConfigKeyParsingException( "Error" + ((errorListener.errorsSize() > 1) ? "s" : "") + " parsing key: " + key + "\n" + errorListener); } }
@Test(expectedExceptions = {RequestConfigKeyParsingException.class}) public void testParsingInvalidValue() throws RequestConfigKeyParsingException { RequestConfigElement.parse("timeoutMs", "*.*/*.*", true); }
protected String buildSearch(Map<String, MutableInt> vendor, Map<String, MutableInt> product, Set<String> vendorWeighting, Set<String> productWeightings) { final StringBuilder sb = new StringBuilder(); if (!appendWeightedSearch(sb, Fields.PRODUCT, product, productWeightings)) { return null; } sb.append(" AND "); if (!appendWeightedSearch(sb, Fields.VENDOR, vendor, vendorWeighting)) { return null; } return sb.toString(); }
@Test public void testBuildSearch() { Map<String, MutableInt> vendor = new HashMap<>(); Map<String, MutableInt> product = new HashMap<>(); vendor.put("apache software foundation", new MutableInt(1)); product.put("lucene index", new MutableInt(1)); Set<String> vendorWeighting = new HashSet<>(); Set<String> productWeightings = new HashSet<>(); CPEAnalyzer instance = new CPEAnalyzer(); String expResult = "product:(lucene index) AND vendor:(apache software foundation)"; String result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); vendorWeighting.add("apache"); expResult = "product:(lucene index) AND vendor:(apache^2 software foundation)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); productWeightings.add("lucene"); expResult = "product:(lucene^2 index) AND vendor:(apache^2 software foundation)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); productWeightings.add("ignored"); expResult = "product:(lucene^2 index) AND vendor:(apache^2 software foundation)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); vendorWeighting.clear(); expResult = "product:(lucene^2 index) AND vendor:(apache software foundation)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); vendorWeighting.add("ignored"); productWeightings.clear(); expResult = "product:(lucene index) AND vendor:(apache software foundation)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); vendor.put("apache software foundation", new MutableInt(3)); product.put("lucene index", new MutableInt(2)); expResult = "product:(lucene^2 index^2) AND vendor:(apache^3 software^3 foundation^3)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); vendorWeighting.add("apache"); expResult = "product:(lucene^2 index^2) AND vendor:(apache^4 software^3 foundation^3)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); productWeightings.add("lucene"); expResult = "product:(lucene^3 index^2) AND vendor:(apache^4 software^3 foundation^3)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); productWeightings.clear(); productWeightings.add("lucene2"); expResult = "product:(lucene^3 index^2 lucene2^3) AND vendor:(apache^4 software^3 foundation^3)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); vendor.put("apache software foundation", new MutableInt(1)); vendor.put("apache", new MutableInt(2)); product.put("lucene index", new MutableInt(1)); product.put("lucene", new MutableInt(2)); vendorWeighting.clear(); productWeightings.clear(); productWeightings.add("lucene2"); expResult = "product:(lucene^3 lucene2^3 lucene^2 index lucene2^2) AND vendor:(apache^2 apache software foundation)"; result = instance.buildSearch(vendor, product, vendorWeighting, productWeightings); assertEquals(expResult, result); }
protected static void validate(final String name) { if (name.isEmpty()) throw new TopologyException("Name is illegal, it can't be empty"); if (name.equals(".") || name.equals("..")) throw new TopologyException("Name cannot be \".\" or \"..\""); if (name.length() > MAX_NAME_LENGTH) throw new TopologyException("Name is illegal, it can't be longer than " + MAX_NAME_LENGTH + " characters, name: " + name); if (!containsValidPattern(name)) throw new TopologyException("Name \"" + name + "\" is illegal, it contains a character other than " + "ASCII alphanumerics, '.', '_' and '-'"); }
@Test public void shouldThrowExceptionOnInvalidTopicNames() { final char[] longString = new char[250]; Arrays.fill(longString, 'a'); final String[] invalidNames = {"", "foo bar", "..", "foo:bar", "foo=bar", ".", new String(longString)}; for (final String name : invalidNames) { try { Named.validate(name); fail("No exception was thrown for named with invalid name: " + name); } catch (final TopologyException e) { // success } } }
@Override public void update(Service service, ServiceMetadata metadata) throws NacosException { if (!ServiceManager.getInstance().containSingleton(service)) { throw new NacosApiException(NacosException.INVALID_PARAM, ErrorCode.SERVICE_NOT_EXIST, String.format("service %s not found!", service.getGroupedServiceName())); } metadataOperateService.updateServiceMetadata(service, metadata); }
@Test void testUpdate() throws NacosException { serviceOperatorV2.update(Service.newService("A", "B", "C"), new ServiceMetadata()); Mockito.verify(metadataOperateService).updateServiceMetadata(Mockito.any(), Mockito.any()); }
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void creates_default_summary_printer_if_not_disabled() { RuntimeOptions options = parser .parse() .addDefaultSummaryPrinterIfNotDisabled() .build(); Plugins plugins = new Plugins(new PluginFactory(), options); plugins.setEventBusOnEventListenerPlugins(new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID)); assertThat(plugins.getPlugins(), hasItem(plugin("io.cucumber.core.plugin.DefaultSummaryPrinter"))); }
@Udf(description = "Returns the base 10 logarithm of an INT value.") public Double log( @UdfParameter( value = "value", description = "the value get the base 10 logarithm of." ) final Integer value ) { return log(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleZeroBase() { assertThat(Double.isNaN(udf.log(0, 13)), is(true)); assertThat(Double.isNaN(udf.log(0L, 13L)), is(true)); assertThat(Double.isNaN(udf.log(0.0, 13.0)), is(true)); }
@Override public boolean isResponsibleClient(Client client) { return true; }
@Test void testIsResponsibleClient() { assertTrue(persistentIpPortClientManager.isResponsibleClient(client)); }
public void addMetadataUpdateRequest(String schemaName, String tableName, Optional<String> partitionName, int writerIndex) { UUID requestId = UUID.randomUUID(); requestFutureMap.put(requestId, SettableFuture.create()); writerRequestMap.put(writerIndex, requestId); // create a request and add it to the queue hiveMetadataRequestQueue.add(new HiveMetadataUpdateHandle(requestId, new SchemaTableName(schemaName, tableName), partitionName, Optional.empty())); }
@Test public void testAddMetadataUpdateRequest() { HiveMetadataUpdater hiveMetadataUpdater = new HiveMetadataUpdater(EXECUTOR); // add Request hiveMetadataUpdater.addMetadataUpdateRequest(TEST_SCHEMA_NAME, TEST_TABLE_NAME, Optional.of(TEST_PARTITION_NAME), TEST_WRITER_INDEX); List<ConnectorMetadataUpdateHandle> hiveMetadataUpdateRequests = hiveMetadataUpdater.getPendingMetadataUpdateRequests(); // assert the pending request queue size assertEquals(hiveMetadataUpdateRequests.size(), 1); // assert that request in queue is same as the request added HiveMetadataUpdateHandle request = (HiveMetadataUpdateHandle) hiveMetadataUpdateRequests.get(0); assertEquals(request.getSchemaTableName(), TEST_SCHEMA_TABLE_NAME); assertEquals(request.getPartitionName(), Optional.of(TEST_PARTITION_NAME)); }
public static String localHostIP() { if (PREFER_IPV6_ADDRESSES) { return LOCAL_HOST_IP_V6; } return LOCAL_HOST_IP_V4; }
@Test void testLocalHostIP() throws NoSuchFieldException, IllegalAccessException { Field field = InternetAddressUtil.class.getField("PREFER_IPV6_ADDRESSES"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, false); assertEquals("127.0.0.1", InternetAddressUtil.localHostIP()); field.set(null, true); assertEquals("[::1]", InternetAddressUtil.localHostIP()); }
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final StoregateApiClient client = session.getClient(); final HttpUriRequest request = new HttpGet(String.format("%s/v4.2/download/files/%s?stream=true", client.getBasePath(), fileid.getFileId(file))); if(status.isAppend()) { final HttpRange range = HttpRange.withStatus(status); final String header; if(TransferStatus.UNKNOWN_LENGTH == range.getEnd()) { header = String.format("bytes=%d-", range.getStart()); } else { header = String.format("bytes=%d-%d", range.getStart(), range.getEnd()); } if(log.isDebugEnabled()) { log.debug(String.format("Add range header %s for file %s", header, file)); } request.addHeader(new BasicHeader(HttpHeaders.RANGE, header)); // Disable compression request.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "identity")); } final HttpResponse response = client.getClient().execute(request); switch(response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_PARTIAL_CONTENT: return new HttpMethodReleaseInputStream(response); case HttpStatus.SC_NOT_FOUND: fileid.cache(file, null); // Break through default: throw new DefaultHttpResponseExceptionMappingService().map("Download {0} failed", new HttpResponseException( response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()), file); } } catch(IOException e) { throw new DefaultIOExceptionMappingService().map("Download {0} failed", e, file); } }
@Test public void testReadInterrupt() throws Exception { final byte[] content = RandomUtils.nextBytes(32769); final TransferStatus writeStatus = new TransferStatus(); writeStatus.setLength(content.length); final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path folder = 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(folder, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final StoregateWriteFeature writer = new StoregateWriteFeature(session, nodeid); final HttpResponseOutputStream<File> out = writer.write(test, writeStatus, new DisabledConnectionCallback()); assertNotNull(out); new StreamCopier(writeStatus, writeStatus).transfer(new ByteArrayInputStream(content), out); // Unknown length in status final TransferStatus readStatus = new TransferStatus(); // Read a single byte { final InputStream in = new StoregateReadFeature(session, nodeid).read(test, readStatus, new DisabledConnectionCallback()); assertNotNull(in.read()); in.close(); } { final InputStream in = new StoregateReadFeature(session, nodeid).read(test, readStatus, new DisabledConnectionCallback()); assertNotNull(in); in.close(); } new StoregateDeleteFeature(session, nodeid).delete(Collections.singletonList(folder), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
@VisibleForTesting String buildBody(Stream stream, AlertCondition.CheckResult checkResult, List<Message> backlog) { final String template; if (pluginConfig == null || pluginConfig.getString("body") == null) { template = bodyTemplate; } else { template = pluginConfig.getString("body"); } Map<String, Object> model = getModel(stream, checkResult, backlog); return this.templateEngine.transform(template, model); }
@Test public void buildBodyContainsInfoMessageIfWebInterfaceURLIsIncomplete() throws Exception { final EmailConfiguration configuration = new EmailConfiguration() { @Override public URI getWebInterfaceUri() { return URI.create(""); } }; this.emailAlertSender = new FormattedEmailAlertSender(configuration, mockNotificationService, nodeId, templateEngine, emailFactory); Stream stream = mock(Stream.class); when(stream.getId()).thenReturn("123456"); when(stream.getTitle()).thenReturn("Stream Title"); AlertCondition alertCondition = mock(AlertCondition.class); AlertCondition.CheckResult checkResult = mock(AbstractAlertCondition.CheckResult.class); when(checkResult.getTriggeredAt()).thenReturn(new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC)); when(checkResult.getTriggeredCondition()).thenReturn(alertCondition); String body = emailAlertSender.buildBody(stream, checkResult, Collections.<Message>emptyList()); assertThat(body).contains("Stream URL: Please configure 'transport_email_web_interface_url' in your Graylog configuration file."); }
@Override @Nullable public BlobHttpContent getContent() { return null; }
@Test public void testGetContent() { Assert.assertNull(testBlobPuller.getContent()); }
@Override public Optional<FieldTypes> get(final String fieldName) { return Optional.ofNullable(get(ImmutableSet.of(fieldName)).get(fieldName)); }
@Test public void getMultipleFieldsWithIndexScope() { dbService.save(createDto("graylog_0", "abc", Collections.emptySet())); dbService.save(createDto("graylog_1", "xyz", Collections.emptySet())); dbService.save(createDto("graylog_2", "xyz", of( FieldTypeDTO.create("yolo1", "boolean") ))); dbService.save(createDto("graylog_3", "xyz", of( FieldTypeDTO.create("yolo1", "text") ))); final Map<String, FieldTypes> result = lookup.get(of("yolo1", "timestamp"), of("graylog_1", "graylog_2")); assertThat(result).containsOnlyKeys("yolo1", "timestamp"); assertThat(result.get("yolo1").fieldName()).isEqualTo("yolo1"); assertThat(result.get("yolo1").types()).hasSize(1); assertThat(result.get("yolo1").types()).containsOnly( FieldTypes.Type.builder() .type("boolean") .properties(of("enumerable")) .indexNames(of("graylog_2")) .build() ); assertThat(result.get("timestamp").fieldName()).isEqualTo("timestamp"); assertThat(result.get("timestamp").types()).hasSize(1); assertThat(result.get("timestamp").types()).containsOnly(FieldTypes.Type.builder() .type("date") .properties(of("enumerable")) .indexNames(of("graylog_1", "graylog_2")) .build()); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return areNewFieldsEqual((Request<?>) obj); }
@Test(dataProvider = "toRequestFieldsData") public void testRequestMetadataFieldsEqual(List<PathSpec> pathSpecs1, List<PathSpec> pathSpecs2, Map<String,String> param1, Map<String,String> param2, boolean expect) { GetRequestBuilder<Long, TestRecord> builder1 = generateDummyRequestBuilder(); GetRequestBuilder<Long, TestRecord> builder2 = generateDummyRequestBuilder(); for (Map.Entry<String, String> entry : param1.entrySet()) { builder1.setParam(entry.getKey(), entry.getValue()); } for (Map.Entry<String, String> entry : param2.entrySet()) { builder2.setParam(entry.getKey(), entry.getValue()); } builder1.addMetadataFields(pathSpecs1.toArray(new PathSpec[pathSpecs1.size()])); builder2.addMetadataFields(pathSpecs2.toArray(new PathSpec[pathSpecs2.size()])); assertEquals(builder1.build().equals(builder2.build()), expect); }
@Override public Collection<String> getJdbcUrlPrefixes() { return Collections.singletonList(String.format("jdbc:%s:", getType().toLowerCase())); }
@Test void assertGetJdbcUrlPrefixes() { assertThat(TypedSPILoader.getService(DatabaseType.class, "PostgreSQL").getJdbcUrlPrefixes(), is(Collections.singletonList("jdbc:postgresql:"))); }
@Override public void logoutSuccess(HttpRequest request, @Nullable String login) { checkRequest(request); if (!LOGGER.isDebugEnabled()) { return; } LOGGER.debug("logout success [IP|{}|{}][login|{}]", request.getRemoteAddr(), getAllIps(request), preventLogFlood(emptyIfNull(login))); }
@Test public void logout_success_creates_DEBUG_log_with_empty_login_if_login_argument_is_null() { underTest.logoutSuccess(mockRequest(), null); verifyLog("logout success [IP||][login|]", Set.of("login", "logout failure")); }
@PutMapping private CarDto updateCar(@RequestBody CarDto carDto) { Car car = carMapper.toCar(carDto); return carMapper.toCarDto(carService.update(car)); }
@Test @Sql("/insert_car.sql") void updateCar() throws Exception { // given CarDto carDto = CarDto.builder() .id(UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80")) .name("vw") .color("white") .build(); // when mockMvc.perform( put("/cars") .content(objectMapper.writeValueAsString(carDto)) .contentType(MediaType.APPLICATION_JSON) ) // then .andExpect(status().isOk()); }
public Optional<Account> getByAccountIdentifier(final UUID uuid) { return checkRedisThenAccounts( getByUuidTimer, () -> redisGetByAccountIdentifier(uuid), () -> accounts.getByAccountIdentifier(uuid) ); }
@Test void testGetAccountByUuidNotInCache() { UUID uuid = UUID.randomUUID(); UUID pni = UUID.randomUUID(); Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]); when(commands.get(eq("Account3::" + uuid))).thenReturn(null); when(accounts.getByAccountIdentifier(eq(uuid))).thenReturn(Optional.of(account)); Optional<Account> retrieved = accountsManager.getByAccountIdentifier(uuid); assertTrue(retrieved.isPresent()); assertSame(retrieved.get(), account); verify(commands, times(1)).get(eq("Account3::" + uuid)); verify(commands, times(1)).setex(eq("AccountMap::" + pni), anyLong(), eq(uuid.toString())); verify(commands, times(1)).setex(eq("Account3::" + uuid), anyLong(), anyString()); verifyNoMoreInteractions(commands); verify(accounts, times(1)).getByAccountIdentifier(eq(uuid)); verifyNoMoreInteractions(accounts); }
@Override public Iterator<LongStatistic> getLongStatistics() { return new LongIterator(); }
@Test public void testGetLongStatistics() { short iterations = 0; // number of the iter.hasNext() final Iterator<LongStatistic> iter = statistics.getLongStatistics(); while (iter.hasNext()) { final LongStatistic longStat = iter.next(); assertNotNull(longStat); final OpType opType = OpType.fromSymbol(longStat.getName()); assertNotNull(opType); assertTrue(expectedOpsCountMap.containsKey(opType)); assertEquals(expectedOpsCountMap.get(opType).longValue(), longStat.getValue()); iterations++; } // check that all the OpType enum entries are iterated via iter assertEquals(OpType.values().length, iterations); }
@Override public SeriesSpec apply(final Metric metric) { metricValidator.validate(metric); return switch (metric.functionName()) { case Average.NAME -> Average.builder().field(metric.fieldName()).build(); case Cardinality.NAME -> Cardinality.builder().field(metric.fieldName()).build(); case Count.NAME -> Count.builder().field(metric.fieldName()).build(); case Latest.NAME -> Latest.builder().field(metric.fieldName()).build(); case Max.NAME -> Max.builder().field(metric.fieldName()).build(); case Min.NAME -> Min.builder().field(metric.fieldName()).build(); case Percentage.NAME -> Percentage.builder() .field(metric.fieldName()) .strategy(metric.configuration() != null ? ((PercentageConfiguration) metric.configuration()).strategy() : null) .build(); case Percentile.NAME -> Percentile.builder() .field(metric.fieldName()) .percentile(((PercentileConfiguration) metric.configuration()).percentile()) .build(); case StdDev.NAME -> StdDev.builder().field(metric.fieldName()).build(); case Sum.NAME -> Sum.builder().field(metric.fieldName()).build(); case SumOfSquares.NAME -> SumOfSquares.builder().field(metric.fieldName()).build(); case Variance.NAME -> Variance.builder().field(metric.fieldName()).build(); default -> Count.builder().field(metric.fieldName()).build(); //TODO: do we want to have a default at all? }; }
@Test void throwsExceptionWhenValidatorThrowsException() { doThrow(ValidationException.class).when(metricValidator).validate(any()); assertThrows(ValidationException.class, () -> toTest.apply(new Metric("unknown", "http_method"))); }
@Override @PublicAPI(usage = ACCESS) public void check(JavaClasses classes) { getArchRule().check(classes); }
@Test public void should_allow_empty_should_if_configured() { configurationRule.setFailOnEmptyShould(false); ruleWithEmptyShould().check(new ClassFileImporter().importClasses(getClass())); }
@Override public void onMsg(TbContext ctx, TbMsg msg) { EntityType originatorType = msg.getOriginator().getEntityType(); ctx.tellNext(msg, config.getOriginatorTypes().contains(originatorType) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE); }
@Test void givenAsset_whenOnMsg_then_False() { // GIVEN AssetId assetId = new AssetId(UUID.randomUUID()); TbMsg msg = getTbMsg(assetId); // WHEN node.onMsg(ctx, msg); // THEN ArgumentCaptor<TbMsg> newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class); verify(ctx, times(1)).tellNext(newMsgCaptor.capture(), eq(TbNodeConnectionType.FALSE)); verify(ctx, never()).tellFailure(any(), any()); TbMsg newMsg = newMsgCaptor.getValue(); assertThat(newMsg).isNotNull(); assertThat(newMsg).isSameAs(msg); }
public void logAndProcessFailure( String computationId, ExecutableWork executableWork, Throwable t, Consumer<Work> onInvalidWork) { if (shouldRetryLocally(computationId, executableWork.work(), t)) { // Try again after some delay and at the end of the queue to avoid a tight loop. executeWithDelay(retryLocallyDelayMs, executableWork); } else { // Consider the item invalid. It will eventually be retried by Windmill if it still needs to // be processed. onInvalidWork.accept(executableWork.work()); } }
@Test public void logAndProcessFailure_doesNotRetryWhenWorkItemCancelled() { Set<Work> executedWork = new HashSet<>(); ExecutableWork work = createWork(executedWork::add); WorkFailureProcessor workFailureProcessor = createWorkFailureProcessor(streamingEngineFailureReporter()); Set<Work> invalidWork = new HashSet<>(); workFailureProcessor.logAndProcessFailure( DEFAULT_COMPUTATION_ID, work, new WorkItemCancelledException(work.getWorkItem().getShardingKey()), invalidWork::add); assertThat(executedWork).isEmpty(); assertThat(invalidWork).containsExactly(work.work()); }
public static KafkaUserModel fromCrd(KafkaUser kafkaUser, String secretPrefix, boolean aclsAdminApiSupported) { KafkaUserModel result = new KafkaUserModel(kafkaUser.getMetadata().getNamespace(), kafkaUser.getMetadata().getName(), Labels.fromResource(kafkaUser).withStrimziKind(kafkaUser.getKind()), secretPrefix); validateTlsUsername(kafkaUser); validateDesiredPassword(kafkaUser); result.setOwnerReference(kafkaUser); result.setAuthentication(kafkaUser.getSpec().getAuthentication()); if (kafkaUser.getSpec().getAuthorization() != null && kafkaUser.getSpec().getAuthorization().getType().equals(KafkaUserAuthorizationSimple.TYPE_SIMPLE)) { if (aclsAdminApiSupported) { KafkaUserAuthorizationSimple simple = (KafkaUserAuthorizationSimple) kafkaUser.getSpec().getAuthorization(); result.setSimpleAclRules(simple.getAcls()); } else { throw new InvalidResourceException("Simple authorization ACL rules are configured but not supported in the Kafka cluster configuration."); } } result.setQuotas(kafkaUser.getSpec().getQuotas()); if (kafkaUser.getSpec().getTemplate() != null && kafkaUser.getSpec().getTemplate().getSecret() != null && kafkaUser.getSpec().getTemplate().getSecret().getMetadata() != null) { result.templateSecretLabels = kafkaUser.getSpec().getTemplate().getSecret().getMetadata().getLabels(); result.templateSecretAnnotations = kafkaUser.getSpec().getTemplate().getSecret().getMetadata().getAnnotations(); } return result; }
@Test public void testFromCrdScramShaUserWithMissingPasswordKeyThrows() { KafkaUser missingKey = new KafkaUserBuilder(scramShaUser) .editSpec() .withNewKafkaUserScramSha512ClientAuthentication() .withNewPassword() .withNewValueFrom() .withNewSecretKeyRef(null, "my-secret", false) .endValueFrom() .endPassword() .endKafkaUserScramSha512ClientAuthentication() .endSpec() .build(); InvalidResourceException e = assertThrows(InvalidResourceException.class, () -> { KafkaUserModel.fromCrd(missingKey, UserOperatorConfig.SECRET_PREFIX.defaultValue(), Boolean.parseBoolean(UserOperatorConfig.ACLS_ADMIN_API_SUPPORTED.defaultValue())); }); assertThat(e.getMessage(), is("Resource requests custom SCRAM-SHA-512 password but doesn't specify the secret name and/or key")); }
boolean isWriteEnclosureForValueMetaInterface( ValueMetaInterface v ) { return ( isWriteEnclosed( v ) ) || isEnclosureFixDisabledAndContainsSeparatorOrEnclosure( v.getName().getBytes() ); }
@Test public void testWriteEnclosedForValueMetaInterface() { TextFileOutputData data = new TextFileOutputData(); data.binarySeparator = new byte[1]; data.binaryEnclosure = new byte[1]; data.writer = new ByteArrayOutputStream(); TextFileOutputMeta meta = getTextFileOutputMeta(); meta.setEnclosureFixDisabled(false); TextFileOutput textFileOutput = getTextFileOutput(data, meta); ValueMetaBase valueMetaInterface =getValueMetaInterface(); assertFalse(textFileOutput.isWriteEnclosureForValueMetaInterface(valueMetaInterface)); }
public Object getParameter(String key) { return param.get(key); }
@Test void testGetParameterWithNullDefaultValue() { assertThrows(IllegalArgumentException.class, () -> { identityContext.getParameter(TEST, null); }); }
public static boolean isShuttingDown() { return shuttingDown; }
@Test public void isShuttingDown() throws Exception { Assert.assertEquals(RpcRunningState.isShuttingDown(), RpcRunningState.shuttingDown); }
@Override public boolean storesUpperCaseIdentifiers() { return false; }
@Test void assertStoresUpperCaseIdentifiers() { assertFalse(metaData.storesUpperCaseIdentifiers()); }
@Override @PublicAPI(usage = ACCESS) public JavaClass toErasure() { return erasure; }
@Test public void erased_wildcard_bound_by_single_class_is_this_class() { @SuppressWarnings("unused") class ClassWithBoundTypeParameterWithSingleClassBound<T extends List<? extends Serializable>> { } JavaWildcardType type = importWildcardTypeOf(ClassWithBoundTypeParameterWithSingleClassBound.class); assertThatType(type.toErasure()).matches(Serializable.class); }
@Override public List<String> getChildrenKeys(final String key) { try ( Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(repositorySQL.getSelectByParentKeySQL())) { preparedStatement.setString(1, key); try (ResultSet resultSet = preparedStatement.executeQuery()) { List<String> resultChildren = new LinkedList<>(); while (resultSet.next()) { String childrenKey = resultSet.getString("key"); if (Strings.isNullOrEmpty(childrenKey)) { continue; } int lastIndexOf = childrenKey.lastIndexOf(SEPARATOR); resultChildren.add(childrenKey.substring(lastIndexOf + 1)); } resultChildren.sort(Comparator.reverseOrder()); return new ArrayList<>(resultChildren); } } catch (final SQLException ex) { log.error("Get children {} data by key: {} failed", getType(), key, ex); return Collections.emptyList(); } }
@Test void assertPersistAndGetChildrenKeysFailure() throws SQLException { when(mockJdbcConnection.prepareStatement(repositorySQL.getSelectByParentKeySQL())).thenReturn(mockPreparedStatement); when(mockPreparedStatement.executeQuery()).thenReturn(mockResultSet); when(mockResultSet.next()).thenReturn(false); List<String> actual = repository.getChildrenKeys("key"); assertTrue(actual.isEmpty()); }
@Override public byte[] readArray(int size) { int remaining = buf.remaining(); if (size > remaining) { throw new RuntimeException("Error reading byte array of " + size + " byte(s): only " + remaining + " byte(s) available"); } byte[] arr = new byte[size]; buf.get(arr); return arr; }
@Test public void testReadArray() { ByteBuffer buf = ByteBuffer.allocate(1024); ByteBufferAccessor accessor = new ByteBufferAccessor(buf); final byte[] testArray = new byte[] {0x4b, 0x61, 0x46}; accessor.writeByteArray(testArray); accessor.writeInt(12345); accessor.flip(); final byte[] testArray2 = accessor.readArray(3); assertArrayEquals(testArray, testArray2); assertEquals(12345, accessor.readInt()); assertEquals("Error reading byte array of 3 byte(s): only 0 byte(s) available", assertThrows(RuntimeException.class, () -> accessor.readArray(3)).getMessage()); }
public static List<Path> pluginUrls(Path topPath) throws IOException { boolean containsClassFiles = false; Set<Path> archives = new TreeSet<>(); LinkedList<DirectoryEntry> dfs = new LinkedList<>(); Set<Path> visited = new HashSet<>(); if (isArchive(topPath)) { return Collections.singletonList(topPath); } DirectoryStream<Path> topListing = Files.newDirectoryStream( topPath, PLUGIN_PATH_FILTER ); dfs.push(new DirectoryEntry(topListing)); visited.add(topPath); try { while (!dfs.isEmpty()) { Iterator<Path> neighbors = dfs.peek().iterator; if (!neighbors.hasNext()) { dfs.pop().stream.close(); continue; } Path adjacent = neighbors.next(); if (Files.isSymbolicLink(adjacent)) { try { Path symlink = Files.readSymbolicLink(adjacent); // if symlink is absolute resolve() returns the absolute symlink itself Path parent = adjacent.getParent(); if (parent == null) { continue; } Path absolute = parent.resolve(symlink).toRealPath(); if (Files.exists(absolute)) { adjacent = absolute; } else { continue; } } catch (IOException e) { // See https://issues.apache.org/jira/browse/KAFKA-6288 for a reported // failure. Such a failure at this stage is not easily reproducible and // therefore an exception is caught and ignored after issuing a // warning. This allows class scanning to continue for non-broken plugins. log.warn( "Resolving symbolic link '{}' failed. Ignoring this path.", adjacent, e ); continue; } } if (!visited.contains(adjacent)) { visited.add(adjacent); if (isArchive(adjacent)) { archives.add(adjacent); } else if (isClassFile(adjacent)) { containsClassFiles = true; } else { DirectoryStream<Path> listing = Files.newDirectoryStream( adjacent, PLUGIN_PATH_FILTER ); dfs.push(new DirectoryEntry(listing)); } } } } finally { while (!dfs.isEmpty()) { dfs.pop().stream.close(); } } if (containsClassFiles) { if (archives.isEmpty()) { return Collections.singletonList(topPath); } log.warn("Plugin path contains both java archives and class files. Returning only the" + " archives"); } return Arrays.asList(archives.toArray(new Path[0])); }
@Test public void testPluginUrlsWithClasses() throws Exception { Files.createDirectories(pluginPath.resolve("org/apache/kafka/converters")); Files.createDirectories(pluginPath.resolve("com/mycompany/transforms")); Files.createDirectories(pluginPath.resolve("edu/research/connectors")); Files.createFile(pluginPath.resolve("org/apache/kafka/converters/README.txt")); Files.createFile(pluginPath.resolve("org/apache/kafka/converters/AlienFormat.class")); Files.createDirectories(pluginPath.resolve("com/mycompany/transforms/Blackhole.class")); Files.createDirectories(pluginPath.resolve("edu/research/connectors/HalSink.class")); List<Path> expectedUrls = new ArrayList<>(); expectedUrls.add(pluginPath); assertUrls(expectedUrls, PluginUtils.pluginUrls(pluginPath)); }
public int compare(boolean b1, boolean b2) { throw new UnsupportedOperationException( "compare(boolean, boolean) was called on a non-boolean comparator: " + toString()); }
@Test public void testFloatComparator() { Float[] valuesInAscendingOrder = { null, Float.NEGATIVE_INFINITY, -Float.MAX_VALUE, -1234.5678F, -Float.MIN_VALUE, 0.0F, Float.MIN_VALUE, 1234.5678F, Float.MAX_VALUE, Float.POSITIVE_INFINITY }; for (int i = 0; i < valuesInAscendingOrder.length; ++i) { for (int j = 0; j < valuesInAscendingOrder.length; ++j) { Float vi = valuesInAscendingOrder[i]; Float vj = valuesInAscendingOrder[j]; int exp = i - j; assertSignumEquals(vi, vj, exp, FLOAT_COMPARATOR.compare(vi, vj)); if (vi != null && vj != null) { assertSignumEquals(vi, vj, exp, FLOAT_COMPARATOR.compare(vi.floatValue(), vj.floatValue())); } } } checkThrowingUnsupportedException(FLOAT_COMPARATOR, Float.TYPE); }
Configuration getEffectiveConfiguration(String[] args) throws CliArgsException { final CommandLine commandLine = cli.parseCommandLineOptions(args, true); final Configuration effectiveConfiguration = new Configuration(baseConfiguration); effectiveConfiguration.addAll(cli.toConfiguration(commandLine)); effectiveConfiguration.set(DeploymentOptions.TARGET, KubernetesSessionClusterExecutor.NAME); return effectiveConfiguration; }
@Test void testDynamicProperties() throws Exception { final KubernetesSessionCli cli = new KubernetesSessionCli( new Configuration(), confDirPath.toAbsolutePath().toString()); final String[] args = new String[] { "-e", KubernetesSessionClusterExecutor.NAME, "-Dpekko.ask.timeout=5 min", "-Denv.java.opts=-DappName=foobar" }; final Configuration executorConfig = cli.getEffectiveConfiguration(args); final ClusterClientFactory<String> clientFactory = getClusterClientFactory(executorConfig); assertThat(clientFactory).isNotNull(); final Map<String, String> executorConfigMap = executorConfig.toMap(); assertThat(executorConfigMap).hasSize(4); assertThat(executorConfigMap) .contains( entry("pekko.ask.timeout", "5 min"), entry("env.java.opts", "-DappName=foobar")); assertThat(executorConfig.get(DeploymentOptionsInternal.CONF_DIR)) .isEqualTo(confDirPath.toAbsolutePath().toString()); assertThat(executorConfigMap).containsKey(DeploymentOptions.TARGET.key()); }
public static List<String> parseScope(String spaceDelimitedScope) throws OAuthBearerConfigException { List<String> retval = new ArrayList<>(); for (String individualScopeItem : Objects.requireNonNull(spaceDelimitedScope).split(" ")) { if (!individualScopeItem.isEmpty()) { if (!isValidScopeItem(individualScopeItem)) throw new OAuthBearerConfigException(String.format("Invalid scope value: %s", individualScopeItem)); retval.add(individualScopeItem); } } return Collections.unmodifiableList(retval); }
@Test public void invalidScope() { for (String invalidScope : new String[] {"\"foo", "\\foo"}) { try { OAuthBearerScopeUtils.parseScope(invalidScope); fail("did not detect invalid scope: " + invalidScope); } catch (OAuthBearerConfigException expected) { // empty } } }
public static Calendar getLongFromDateTime(String date, String dateFormat, String time, String timeFormat) { Calendar cal = Calendar.getInstance(); Calendar cDate = Calendar.getInstance(); Calendar cTime = Calendar.getInstance(); SimpleDateFormat sdfDate = new SimpleDateFormat(dateFormat); SimpleDateFormat sdfTime = new SimpleDateFormat(timeFormat); try { cDate.setTime(sdfDate.parse(date)); cTime.setTime(sdfTime.parse(time)); } catch (ParseException e) { LogDelegate.e("Date or time parsing error: " + e.getMessage()); } cal.set(Calendar.YEAR, cDate.get(Calendar.YEAR)); cal.set(Calendar.MONTH, cDate.get(Calendar.MONTH)); cal.set(Calendar.DAY_OF_MONTH, cDate.get(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, cTime.get(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cTime.get(Calendar.MINUTE)); cal.set(Calendar.SECOND, 0); return cal; }
@Test public void getLongFromDateTimeTest() { String date = "2020-03-12"; String dateformat = "yyyy-MM-dd"; String time = "15:15:15"; String timeformat = "HH:mm:ss"; Calendar calendar = DateUtils.getLongFromDateTime(date, dateformat, time, timeformat); assertEquals(calendar.get(Calendar.YEAR), 2020); assertEquals(calendar.get(Calendar.MONTH), 2); assertEquals(calendar.get(Calendar.DATE), 12); assertEquals(calendar.get(Calendar.HOUR_OF_DAY), 15); assertEquals(calendar.get(Calendar.MINUTE), 15); assertEquals(calendar.get(Calendar.SECOND), 0); }
private int hash(String key) { int klen = key.length(); int out = klen; if (select == null) { for (int i = 0; i < klen; i++) { int c = key.charAt(i) - min; if (c < 0) return -1; if (c >= kvals.length) return -2; out += kvals[c]; } } else { for (int i : select) { if (i >= klen) continue; int c = key.charAt(i) - min; if (c < 0) return -1; if (c >= kvals.length) return -2; out += kvals[c]; } } return out; }
@Test public void testHash() { System.out.println("PerfectHash"); PerfectHash hash = new PerfectHash("abc", "great", "hash"); assertEquals(0, hash.get("abc")); assertEquals(1, hash.get("great")); assertEquals(2, hash.get("hash")); assertEquals(-1, hash.get("perfect")); assertEquals(-1, hash.get("hash2")); }
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testUnauthorizedTopic() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); assertEquals(1, sendFetches()); client.prepareResponse(fullFetchResponse(tidp0, records, Errors.TOPIC_AUTHORIZATION_FAILED, 100L, 0)); networkClientDelegate.poll(time.timer(0)); try { collectFetch(); fail("collectFetch should have thrown a TopicAuthorizationException"); } catch (TopicAuthorizationException e) { assertEquals(singleton(topicName), e.unauthorizedTopics()); } }
@Override public DirectPipelineResult run(Pipeline pipeline) { try { options = MAPPER .readValue(MAPPER.writeValueAsBytes(options), PipelineOptions.class) .as(DirectOptions.class); } catch (IOException e) { throw new IllegalArgumentException( "PipelineOptions specified failed to serialize to JSON.", e); } performRewrites(pipeline); MetricsEnvironment.setMetricsSupported(true); try { DirectGraphVisitor graphVisitor = new DirectGraphVisitor(); pipeline.traverseTopologically(graphVisitor); @SuppressWarnings("rawtypes") KeyedPValueTrackingVisitor keyedPValueVisitor = KeyedPValueTrackingVisitor.create(); pipeline.traverseTopologically(keyedPValueVisitor); DisplayDataValidator.validatePipeline(pipeline); DisplayDataValidator.validateOptions(options); ExecutorService metricsPool = Executors.newCachedThreadPool( new ThreadFactoryBuilder() .setThreadFactory(MoreExecutors.platformThreadFactory()) .setDaemon(false) // otherwise you say you want to leak, please don't! .setNameFormat("direct-metrics-counter-committer") .build()); DirectGraph graph = graphVisitor.getGraph(); EvaluationContext context = EvaluationContext.create( clockSupplier.get(), Enforcement.bundleFactoryFor(enabledEnforcements, graph), graph, keyedPValueVisitor.getKeyedPValues(), metricsPool); TransformEvaluatorRegistry registry = TransformEvaluatorRegistry.javaSdkNativeRegistry(context, options); PipelineExecutor executor = ExecutorServiceParallelExecutor.create( options.getTargetParallelism(), registry, Enforcement.defaultModelEnforcements(enabledEnforcements), context, metricsPool); executor.start(graph, RootProviderRegistry.javaNativeRegistry(context, options)); DirectPipelineResult result = new DirectPipelineResult(executor, context); if (options.isBlockOnRun()) { try { result.waitUntilFinish(); } catch (UserCodeException userException) { throw new PipelineExecutionException(userException.getCause()); } catch (Throwable t) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } throw new RuntimeException(t); } } return result; } finally { MetricsEnvironment.setMetricsSupported(false); } }
@Test public void testMutatingOutputCoderDoFnError() throws Exception { Pipeline pipeline = getPipeline(); pipeline .apply(Create.of(42)) .apply( ParDo.of( new DoFn<Integer, byte[]>() { @ProcessElement public void processElement(ProcessContext c) { byte[] outputArray = new byte[] {0x1, 0x2, 0x3}; c.output(outputArray); outputArray[0] = 0xa; c.output(outputArray); } })); thrown.expect(IllegalMutationException.class); thrown.expectMessage("output"); thrown.expectMessage("must not be mutated"); pipeline.run(); }
@Override @SuppressFBWarnings("AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION") public Object invoke(Object proxy, Method method, Object[] args) { if (args == null && "toString".equals(method.getName())) { return toString(); } else if (args != null && args.length == 1 && "equals".equals(method.getName())) { return equals(args[0]); } else if (args == null && "hashCode".equals(method.getName())) { return hashCode(); } else if (args == null && "outputRuntimeOptions".equals(method.getName())) { return outputRuntimeOptions((PipelineOptions) proxy); } else if (args == null && "revision".equals(method.getName())) { return revision.get(); } else if (args != null && "as".equals(method.getName()) && args[0] instanceof Class) { @SuppressWarnings("unchecked") Class<? extends PipelineOptions> clazz = (Class<? extends PipelineOptions>) args[0]; return as(clazz); } else if (args != null && "populateDisplayData".equals(method.getName()) && args[0] instanceof DisplayData.Builder) { @SuppressWarnings("unchecked") DisplayData.Builder builder = (DisplayData.Builder) args[0]; builder.delegate(new PipelineOptionsDisplayData()); return Void.TYPE; } String methodName = method.getName(); ComputedProperties properties = computedProperties; if (properties.gettersToPropertyNames.containsKey(methodName)) { String propertyName = properties.gettersToPropertyNames.get(methodName); // we can't use computeIfAbsent here because evaluating the default may cause more properties // to be evaluated, and computeIfAbsent is not re-entrant. if (!options.containsKey(propertyName)) { // Lazy bind the default to the method. Object value = jsonOptions.containsKey(propertyName) ? getValueFromJson(propertyName, method) : getDefault((PipelineOptions) proxy, method); options.put(propertyName, BoundValue.fromDefault(value)); } return options.get(propertyName).getValue(); } else if (properties.settersToPropertyNames.containsKey(methodName)) { BoundValue prev = options.put( properties.settersToPropertyNames.get(methodName), BoundValue.fromExplicitOption(args[0])); if (prev == null ? args[0] != null : !Objects.equals(args[0], prev.getValue())) { revision.incrementAndGet(); } return Void.TYPE; } throw new RuntimeException( "Unknown method [" + method + "] invoked with args [" + Arrays.toString(args) + "]."); }
@Test public void testInvokeWithUnknownMethod() throws Exception { expectedException.expect(RuntimeException.class); expectedException.expectMessage( "Unknown method [public abstract void " + "org.apache.beam.sdk.options.ProxyInvocationHandlerTest$UnknownMethod.unknownMethod()] " + "invoked with args [null]."); ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap()); handler.invoke(handler, UnknownMethod.class.getMethod("unknownMethod"), null); }
@Override public List<TransferItem> list(final Session<?> session, final Path remote, final Local directory, final ListProgressListener listener) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("List children for %s", directory)); } if(directory.isSymbolicLink()) { final Symlink symlink = session.getFeature(Symlink.class); if(new UploadSymlinkResolver(symlink, roots).resolve(directory)) { if(log.isDebugEnabled()) { log.debug(String.format("Do not list children for symbolic link %s", directory)); } // We can resolve the target of the symbolic link and will create a link on the remote system // using the symlink feature of the session return Collections.emptyList(); } } final List<TransferItem> children = new ArrayList<>(); for(Local local : directory.list().filter(comparator, filter)) { children.add(new TransferItem(new Path(remote, local.getName(), local.isDirectory() ? EnumSet.of(Path.Type.directory) : EnumSet.of(Path.Type.file)), local)); } return children; }
@Test public void testChildrenEmpty() throws Exception { final Path root = new Path("/t", EnumSet.of(Path.Type.directory)) { }; Transfer t = new UploadTransfer(new Host(new TestProtocol()), root, new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString())); assertTrue(t.list(new NullSession(new Host(new TestProtocol())), root, new NullLocal("t") { @Override public AttributedList<Local> list() { return AttributedList.emptyList(); } }, new DisabledListProgressListener()).isEmpty()); }
@Override @Nullable public byte[] readByteArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, BYTE_ARRAY, super::readByteArray); }
@Test public void testReadByteArray() throws Exception { assertNull(reader.readByteArray("NO SUCH FIELD")); }
@Transactional(readOnly = true) public TemplateResponse generateReviewForm(String reviewRequestCode) { ReviewGroup reviewGroup = reviewGroupRepository.findByReviewRequestCode(reviewRequestCode) .orElseThrow(() -> new ReviewGroupNotFoundByReviewRequestCodeException(reviewRequestCode)); Template template = templateRepository.findById(reviewGroup.getTemplateId()) .orElseThrow(() -> new TemplateNotFoundByReviewGroupException( reviewGroup.getId(), reviewGroup.getTemplateId() )); return templateMapper.mapToTemplateResponse(reviewGroup, template); }
@Test void 리뷰이에게_작성될_리뷰_양식_생성_시_저장된_템플릿이_없을_경우_예외가_발생한다() { // given ReviewGroup reviewGroup = new ReviewGroup("리뷰이명", "프로젝트명", "reviewRequestCode", "groupAccessCode"); reviewGroupRepository.save(reviewGroup); // when, then assertThatThrownBy(() -> templateService.generateReviewForm(reviewGroup.getReviewRequestCode())) .isInstanceOf(TemplateNotFoundByReviewGroupException.class); }
public static ProviderInfo parseProviderInfo(String originUrl) { String url = originUrl; String host = null; int port = 80; String path = null; String schema = null; int i = url.indexOf("://"); // seperator between schema and body if (i > 0) { schema = url.substring(0, i); // http url = url.substring(i + 3); // 127.0.0.1:8080/xxx/yyy?a=1&b=2&[c]=[ccc] } Map<String, String> parameters = new HashMap<String, String>(); i = url.indexOf('?'); // seperator between body and parameters if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); //a=1&b=2&[c]=[ccc] for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); // 127.0.0.1:8080/xxx/yyy } i = url.indexOf('/'); if (i >= 0) { path = url.substring(i + 1); // xxx/yyy url = url.substring(0, i); // 127.0.0.1:8080 } i = url.indexOf(':'); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); // 8080 url = url.substring(0, i); // 127.0.0.1 } if (url.length() > 0) { host = url; // 127.0.0.1 } ProviderInfo providerInfo = new ProviderInfo(); providerInfo.setOriginUrl(originUrl); providerInfo.setHost(host); if (port != 80) { providerInfo.setPort(port); } if (path != null) { providerInfo.setPath(path); } if (schema != null) { providerInfo.setProtocolType(schema); } // 解析特殊属性 // p=1 String protocolStr = getValue(parameters, RPC_REMOTING_PROTOCOL); if (schema == null && protocolStr != null) { // 1->bolt 13->tr if ((RemotingConstants.PROTOCOL_BOLT + "").equals(protocolStr)) { protocolStr = PROTOCOL_TYPE_BOLT; } else if ((RemotingConstants.PROTOCOL_TR + "").equals(protocolStr)) { protocolStr = PROTOCOL_TYPE_TR; } try { providerInfo.setProtocolType(protocolStr); } catch (Exception e) { LOGGER.error(LogCodes.getLog(LogCodes.ERROR_INVALID_ATTRIBUTE, "protocol", originUrl)); } } // TODO SOFAVERSION v=4.0 // timeout String timeoutStr = getValue(parameters, ATTR_TIMEOUT, TIMEOUT); if (timeoutStr != null) { removeOldKeys(parameters, ATTR_TIMEOUT, TIMEOUT); try {// 加入动态 providerInfo.setDynamicAttr(ATTR_TIMEOUT, Integer.parseInt(timeoutStr)); } catch (Exception e) { LOGGER.error(LogCodes.getLog(LogCodes.ERROR_INVALID_ATTRIBUTE, "timeout", originUrl)); } } // serializeType 使用字符传递 String serializationStr = getValue(parameters, ATTR_SERIALIZATION, SERIALIZE_TYPE_KEY); if (serializationStr != null) { removeOldKeys(parameters, ATTR_SERIALIZATION, SERIALIZE_TYPE_KEY); // 1 -> hessian 2->java 4->hessian2 11->protobuf if ((RemotingConstants.SERIALIZE_CODE_HESSIAN + "").equals(serializationStr)) { serializationStr = SERIALIZE_HESSIAN; } else if ((RemotingConstants.SERIALIZE_CODE_JAVA + "").equals(serializationStr)) { serializationStr = SERIALIZE_JAVA; } else if ((RemotingConstants.SERIALIZE_CODE_HESSIAN2 + "").equals(serializationStr)) { serializationStr = SERIALIZE_HESSIAN2; } else if ((RemotingConstants.SERIALIZE_CODE_PROTOBUF + "").equals(serializationStr)) { serializationStr = SERIALIZE_PROTOBUF; } providerInfo.setSerializationType(serializationStr); } // appName String appNameStr = getValue(parameters, ATTR_APP_NAME, APP_NAME, SofaRegistryConstants.SELF_APP_NAME); if (appNameStr != null) { removeOldKeys(parameters, APP_NAME, SofaRegistryConstants.SELF_APP_NAME); providerInfo.setStaticAttr(ATTR_APP_NAME, appNameStr); } // connections String connections = getValue(parameters, ATTR_CONNECTIONS, SofaRegistryConstants.CONNECTI_NUM); if (connections != null) { removeOldKeys(parameters, SofaRegistryConstants.CONNECTI_NUM); providerInfo.setStaticAttr(ATTR_CONNECTIONS, connections); } //rpc version String rpcVersion = getValue(parameters, ATTR_RPC_VERSION); providerInfo.setRpcVersion(CommonUtils.parseInt(rpcVersion, providerInfo.getRpcVersion())); // weight String weightStr = getValue(parameters, ATTR_WEIGHT, WEIGHT_KEY); if (weightStr != null) { removeOldKeys(parameters, ATTR_WEIGHT, WEIGHT_KEY); try { int weight = Integer.parseInt(weightStr); providerInfo.setWeight(weight); providerInfo.setStaticAttr(ATTR_WEIGHT, weightStr); } catch (Exception e) { LOGGER.error(LogCodes.getLog(LogCodes.ERROR_INVALID_ATTRIBUTE, "weight", originUrl)); } } // warmupTime String warmupTimeStr = getValue(parameters, ATTR_WARMUP_TIME, SofaRegistryConstants.WARMUP_TIME_KEY); int warmupTime = 0; if (warmupTimeStr != null) { removeOldKeys(parameters, ATTR_WARMUP_TIME, SofaRegistryConstants.WARMUP_TIME_KEY); try { warmupTime = Integer.parseInt(warmupTimeStr); providerInfo.setStaticAttr(ATTR_WARMUP_TIME, warmupTimeStr); } catch (Exception e) { LOGGER.error(LogCodes.getLog(LogCodes.ERROR_INVALID_ATTRIBUTE, "warmupTime", originUrl)); } } // warmupWeight String warmupWeightStr = getValue(parameters, ATTR_WARMUP_WEIGHT, SofaRegistryConstants.WARMUP_WEIGHT_KEY); int warmupWeight = 0; if (warmupWeightStr != null) { removeOldKeys(parameters, ATTR_WARMUP_WEIGHT, SofaRegistryConstants.WARMUP_WEIGHT_KEY); try { warmupWeight = Integer.parseInt(warmupWeightStr); providerInfo.setStaticAttr(ATTR_WARMUP_WEIGHT, warmupWeightStr); } catch (Exception e) { LOGGER.error(LogCodes.getLog(LogCodes.ERROR_INVALID_ATTRIBUTE, "warmupWeight", originUrl)); } } // startTime String startTimeStr = getValue(parameters, ATTR_START_TIME); long startTime = 0L; if (startTimeStr != null) { try { startTime = Long.parseLong(startTimeStr); } catch (Exception e) { LOGGER.error(LogCodes.getLog(LogCodes.ERROR_INVALID_ATTRIBUTE, "startTime", originUrl)); } } if (startTime == 0) { startTime = System.currentTimeMillis(); } // 设置预热状态 if (StringUtils.isNotBlank(warmupTimeStr) && StringUtils.isNotBlank(warmupWeightStr)) { if (warmupTime > 0) { providerInfo.setStatus(ProviderStatus.WARMING_UP); providerInfo.setDynamicAttr(ATTR_WARMUP_WEIGHT, warmupWeight); providerInfo.setDynamicAttr(ATTR_WARM_UP_END_TIME, startTime + warmupTime); } } // 解析hostMachineName String hostMachineName = getValue(parameters, HOST_MACHINE_KEY); if (StringUtils.isNotBlank(hostMachineName)) { providerInfo.setDynamicAttr(ATTR_HOST_MACHINE, hostMachineName); } // 解析方法参数 List<String> methodKeys = new ArrayList<String>(); Map<String, Object> methodParameters = new HashMap<String, Object>(); for (Map.Entry<String, String> entry : parameters.entrySet()) { if (entry.getKey().startsWith("[") && entry.getKey().endsWith("]") && entry.getValue().startsWith("[") && entry.getValue().endsWith("]")) { // 认为是方法配置 String key = entry.getKey(); methodKeys.add(key); String methodName = key.substring(1, key.length() - 1); parseMethodInfo(methodParameters, methodName, entry.getValue()); } } for (String methodKey : methodKeys) { parameters.remove(methodKey); } providerInfo.getStaticAttrs().putAll(parameters); providerInfo.getDynamicAttrs().putAll(methodParameters); providerInfo.setStaticAttr(ProviderInfoAttrs.ATTR_SOURCE, "sofa"); return providerInfo; }
@Test public void parseProviderInfo() throws Exception { String defaultProtocol = RpcConfigs.getStringValue(RpcOptions.DEFAULT_PROTOCOL); // 10.244.22.1:8080?zone=GZ00A&self_app_name=icardcenter&app_name=icardcenter&_TIMEOUT=3000 // 11.166.0.239:12200?_TIMEOUT=3000&p=1&_SERIALIZETYPE=hessian2&app_name=iptcore&zone=GZ00A&_IDLETIMEOUT=27&_MAXREADIDLETIME=30&v=4.0 // 10.209.76.82:12200?_TIMEOUT=3000&p=1&_SERIALIZETYPE=hessian2&app_name=ipayprocess&zone=GZ00A&_IDLETIMEOUT=27&_MAXREADIDLETIME=30&v=4.0 // 10.15.232.229:55555?_CONNECTIONNUM=1&v=4.0&_SERIALIZETYPE=4&app_name=test&p=1&_TIMEOUT=4000 // 10.15.232.229:12222?_TIMEOUT=3333&p=1&_SERIALIZETYPE=4&_CONNECTIONNUM=1&_WARMUPTIME=60000&_WARMUPWEIGHT=5&app_name=test-server&v=4.0&_WEIGHT=2000&[cd]=[clientTimeout#5555]&[echoStr]=[timeout#4444] // [xxxx]=[clientTimeout#2000@retries#2] // [xxxx]=[_AUTORECONNECT#false@_TIMEOUT#2000] String url = "10.244.22.1:8080?zone=GZ00A&self_app_name=icardcenter&app_name=icardcenter&_TIMEOUT=3000"; ProviderInfo provider = SofaRegistryHelper.parseProviderInfo(url); Assert.assertTrue(defaultProtocol.equals(provider.getProtocolType())); Assert.assertTrue("10.244.22.1".equals(provider.getHost())); Assert.assertTrue(provider.getPort() == 8080); Assert.assertTrue("GZ00A".equals(provider.getAttr("zone"))); Assert.assertTrue("icardcenter".equals(provider.getAttr(ProviderInfoAttrs.ATTR_APP_NAME))); Assert.assertTrue((Integer) provider.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT) == 3000); url = "11.166.0.239:12200?_TIMEOUT=3000&p=1&_SERIALIZETYPE=hessian2&app_name=iptcore&zone=GZ00B&_IDLETIMEOUT=27&_MAXREADIDLETIME=30&v=4.0"; provider = SofaRegistryHelper.parseProviderInfo(url); Assert.assertTrue(RpcConstants.PROTOCOL_TYPE_BOLT.equals(provider.getProtocolType())); Assert.assertTrue(RpcConstants.SERIALIZE_HESSIAN2.equals(provider.getSerializationType())); Assert.assertTrue("11.166.0.239".equals(provider.getHost())); Assert.assertTrue(provider.getPort() == 12200); Assert.assertTrue("GZ00B".equals(provider.getAttr("zone"))); Assert.assertTrue("iptcore".equals(provider.getAttr(ProviderInfoAttrs.ATTR_APP_NAME))); Assert.assertTrue("27".equals(provider.getAttr("_IDLETIMEOUT"))); Assert.assertTrue("30".equals(provider.getAttr("_MAXREADIDLETIME"))); Assert.assertTrue("4.0".equals(provider.getAttr("v"))); Assert.assertTrue("1".equals(provider.getAttr("p"))); url = "10.209.80.104:12200?zone=GZ00A&self_app_name=icif&_SERIALIZETYPE=java&app_name=icif&_TIMEOUT=3000"; provider = SofaRegistryHelper.parseProviderInfo(url); Assert.assertTrue(defaultProtocol.equals(provider.getProtocolType())); Assert.assertTrue(RpcConstants.SERIALIZE_JAVA.equals(provider.getSerializationType())); Assert.assertTrue("10.209.80.104".equals(provider.getHost())); Assert.assertTrue(provider.getPort() == 12200); Assert.assertTrue("GZ00A".equals(provider.getAttr("zone"))); Assert.assertTrue("icif".equals(provider.getAttr(ProviderInfoAttrs.ATTR_APP_NAME))); Assert.assertTrue((Integer) provider.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT) == 3000); Assert.assertTrue(provider.getAttr("v") == null); Assert.assertTrue(provider.getAttr("p") == null); url = "10.209.76.82:12200?_TIMEOUT=3000&p=13&_SERIALIZETYPE=11&app_name=ipayprocess&zone=GZ00A&_IDLETIMEOUT=27&_MAXREADIDLETIME=30&v=4.0&[xx]=[_AUTORECONNECT#false@_TIMEOUT#2000]"; provider = SofaRegistryHelper.parseProviderInfo(url); Assert.assertTrue(RpcConstants.PROTOCOL_TYPE_TR.equals(provider.getProtocolType())); Assert.assertTrue(RpcConstants.SERIALIZE_PROTOBUF.equals(provider.getSerializationType())); Assert.assertTrue("10.209.76.82".equals(provider.getHost())); Assert.assertTrue(provider.getPort() == 12200); Assert.assertTrue("GZ00A".equals(provider.getAttr("zone"))); Assert.assertTrue("ipayprocess".equals(provider.getAttr(ProviderInfoAttrs.ATTR_APP_NAME))); Assert.assertTrue((Integer) provider.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT) == 3000); Assert.assertTrue("27".equals(provider.getAttr("_IDLETIMEOUT"))); Assert.assertTrue("30".equals(provider.getAttr("_MAXREADIDLETIME"))); Assert.assertTrue("4.0".equals(provider.getAttr("v"))); Assert.assertTrue("13".equals(provider.getAttr("p"))); Assert.assertTrue((Integer) provider.getDynamicAttr(".xx.timeout") == 2000); Assert.assertTrue("false".equals(provider.getAttr(".xx._AUTORECONNECT"))); url = "tri://10.15.232.229:55555?_CONNECTIONNUM=1&v=4.0&_SERIALIZETYPE=11&app_name=test&p=1&_TIMEOUT=4000"; provider = SofaRegistryHelper.parseProviderInfo(url); Assert.assertTrue(RpcConstants.PROTOCOL_TYPE_TRIPLE.equals(provider.getProtocolType())); Assert.assertTrue(RpcConstants.SERIALIZE_PROTOBUF.equals(provider.getSerializationType())); Assert.assertTrue("10.15.232.229".equals(provider.getHost())); Assert.assertTrue(provider.getPort() == 55555); Assert.assertTrue("test".equals(provider.getAttr(ProviderInfoAttrs.ATTR_APP_NAME))); Assert.assertTrue("1".equals(provider.getAttr(ProviderInfoAttrs.ATTR_CONNECTIONS))); Assert.assertTrue((Integer) provider.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT) == 4000); Assert.assertTrue("4.0".equals(provider.getAttr("v"))); Assert.assertTrue("1".equals(provider.getAttr("p"))); url = "10.15.232.229:12222?_TIMEOUT=3333&p=1&_SERIALIZETYPE=4&_CONNECTIONNUM=1&_WARMUPTIME=6&_WARMUPWEIGHT=5&app_name=test-server&v=4.0&_WEIGHT=2000&[cd]=[]&[echoStr]=[clientTimeout#4444]"; provider = SofaRegistryHelper.parseProviderInfo(url); Assert.assertTrue(RpcConstants.PROTOCOL_TYPE_BOLT.equals(provider.getProtocolType())); Assert.assertTrue(RpcConstants.SERIALIZE_HESSIAN2.equals(provider.getSerializationType())); Assert.assertTrue("10.15.232.229".equals(provider.getHost())); Assert.assertTrue(provider.getPort() == 12222); Assert.assertTrue("test-server".equals(provider.getAttr(ProviderInfoAttrs.ATTR_APP_NAME))); Assert.assertTrue("1".equals(provider.getAttr(ProviderInfoAttrs.ATTR_CONNECTIONS))); Assert.assertTrue((Integer) provider.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT) == 3333); Assert.assertTrue((Integer) provider.getDynamicAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT) == 5); Assert.assertTrue(provider.getDynamicAttr(ProviderInfoAttrs.ATTR_WARM_UP_END_TIME) != null); Assert.assertEquals(provider.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT), "5"); Assert.assertEquals(provider.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_TIME), "6"); Assert.assertTrue(provider.getWeight() == 5); Assert.assertTrue(provider.getStatus() == ProviderStatus.WARMING_UP); try { Thread.sleep(10); } catch (Exception e) { } Assert.assertTrue(provider.getWeight() == 2000); Assert.assertTrue(provider.getStatus() == ProviderStatus.AVAILABLE); Assert.assertTrue(provider.getDynamicAttr(ProviderInfoAttrs.ATTR_WARM_UP_END_TIME) == null); Assert.assertTrue("4.0".equals(provider.getAttr("v"))); Assert.assertTrue("1".equals(provider.getAttr("p"))); Assert.assertTrue(provider.getAttr(".cd.timeout") == null); Assert.assertTrue((Integer) provider.getDynamicAttr(".echoStr.timeout") == 4444); url = "10.15.232.229:12222?_TIMEOUT=3333&p=1&_SERIALIZETYPE=4&_CONNECTIONNUM=1&_WARMUPTIME=6&_WARMUPWEIGHT=5&startTime=123456"; provider = SofaRegistryHelper.parseProviderInfo(url); Assert.assertTrue((Integer) provider.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT) == 3333); Assert.assertTrue((Integer) provider.getDynamicAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT) == 5); Assert.assertTrue(provider.getDynamicAttr(ProviderInfoAttrs.ATTR_WARM_UP_END_TIME) != null); Assert.assertEquals(provider.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT), "5"); Assert.assertEquals(provider.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_TIME), "6"); Assert.assertTrue(provider.getWeight() == 100); Assert.assertTrue(provider.getStatus() == ProviderStatus.AVAILABLE); url = "bolt://10.244.22.1:8080?zone=GZ00A&appName=icardcenter&timeout=3000&serialization=hessian2"; provider = SofaRegistryHelper.parseProviderInfo(url); Assert.assertTrue(RpcConstants.PROTOCOL_TYPE_BOLT.equals(provider.getProtocolType())); Assert.assertTrue(RpcConstants.SERIALIZE_HESSIAN2.equals(provider.getSerializationType())); Assert.assertTrue("10.244.22.1".equals(provider.getHost())); Assert.assertTrue(provider.getPort() == 8080); Assert.assertTrue("GZ00A".equals(provider.getAttr("zone"))); Assert.assertTrue("icardcenter".equals(provider.getAttr(ProviderInfoAttrs.ATTR_APP_NAME))); Assert.assertTrue((Integer) provider.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT) == 3000); }
@Override public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) { AbstractWALEvent result; byte[] bytes = new byte[data.remaining()]; data.get(bytes); String dataText = new String(bytes, StandardCharsets.UTF_8); if (decodeWithTX) { result = decodeDataWithTX(dataText); } else { result = decodeDataIgnoreTX(dataText); } result.setLogSequenceNumber(logSequenceNumber); return result; }
@Test void assertDecodeUnknownRowEventType() { MppTableData tableData = new MppTableData(); tableData.setTableName("public.test"); tableData.setOpType("UNKNOWN"); tableData.setColumnsName(new String[]{"data"}); tableData.setColumnsType(new String[]{"character varying"}); tableData.setColumnsVal(new String[]{"1 2 3"}); ByteBuffer data = ByteBuffer.wrap(JsonUtils.toJsonString(tableData).getBytes()); assertThrows(IngestException.class, () -> new MppdbDecodingPlugin(null, false, false).decode(data, logSequenceNumber)); }
private Mono<ServerResponse> installFromUri(ServerRequest request) { var content = request.bodyToMono(InstallFromUriRequest.class) .map(InstallFromUriRequest::uri) .flatMapMany(urlDataBufferFetcher::fetch); return themeService.install(content) .flatMap(theme -> ServerResponse.ok().bodyValue(theme)); }
@Test void installFromUri() { final URI uri = URI.create("https://example.com/test-theme.zip"); var metadata = new Metadata(); metadata.setName("fake-theme"); var theme = new Theme(); theme.setMetadata(metadata); when(themeService.install(any())).thenReturn(Mono.just(theme)); var body = new ThemeEndpoint.UpgradeFromUriRequest(uri); webTestClient.post() .uri("/themes/-/install-from-uri") .bodyValue(body) .exchange() .expectStatus().isOk() .expectBody(Theme.class).isEqualTo(theme); verify(themeService).install(any()); }
@Udf public String extractParam( @UdfParameter(description = "a valid URL") final String input, @UdfParameter(description = "the parameter key") final String paramToFind) { final String query = UrlParser.extract(input, URI::getQuery); if (query == null) { return null; } for (final String param : PARAM_SPLITTER.split(query)) { final List<String> kvParam = KV_SPLITTER.splitToList(param); if (kvParam.size() == 1 && kvParam.get(0).equals(paramToFind)) { return ""; } else if (kvParam.size() == 2 && kvParam.get(0).equals(paramToFind)) { return kvParam.get(1); } } return null; }
@Test public void shouldReturnNullIfParamNotPresent() { assertThat(extractUdf.extractParam("https://docs.confluent.io?foo%20bar=baz&blank#scalar-functions", "absent"), nullValue()); }
public static UUID fromString(String src) { return UUID.fromString(src.substring(7, 15) + "-" + src.substring(3, 7) + "-1" + src.substring(0, 3) + "-" + src.substring(15, 19) + "-" + src.substring(19)); }
@Test public void basicUuidConversion() { UUID original = UUID.fromString("3dd11790-abf2-11ea-b151-83a091b9d4cc"); Assertions.assertEquals(Uuids.unixTimestamp(original), 1591886749577L); }
@Override public Processor<KO, SubscriptionWrapper<K>, CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>> get() { return new ContextualProcessor<KO, SubscriptionWrapper<K>, CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>>() { private TimestampedKeyValueStore<Bytes, SubscriptionWrapper<K>> store; private Sensor droppedRecordsSensor; @Override public void init(final ProcessorContext<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>> context) { super.init(context); final InternalProcessorContext<?, ?> internalProcessorContext = (InternalProcessorContext<?, ?>) context; droppedRecordsSensor = TaskMetrics.droppedRecordsSensor( Thread.currentThread().getName(), internalProcessorContext.taskId().toString(), internalProcessorContext.metrics() ); store = internalProcessorContext.getStateStore(storeName); keySchema.init(context); } @Override public void process(final Record<KO, SubscriptionWrapper<K>> record) { if (record.key() == null && !SubscriptionWrapper.Instruction.PROPAGATE_NULL_IF_NO_FK_VAL_AVAILABLE.equals(record.value().getInstruction())) { dropRecord(); return; } if (record.value().getVersion() > SubscriptionWrapper.CURRENT_VERSION) { //Guard against modifications to SubscriptionWrapper. Need to ensure that there is compatibility //with previous versions to enable rolling upgrades. Must develop a strategy for upgrading //from older SubscriptionWrapper versions to newer versions. throw new UnsupportedVersionException("SubscriptionWrapper is of an incompatible version."); } context().forward( record.withKey(new CombinedKey<>(record.key(), record.value().getPrimaryKey())) .withValue(inferChange(record)) .withTimestamp(record.timestamp()) ); } private Change<ValueAndTimestamp<SubscriptionWrapper<K>>> inferChange(final Record<KO, SubscriptionWrapper<K>> record) { if (record.key() == null) { return new Change<>(ValueAndTimestamp.make(record.value(), record.timestamp()), null); } else { return inferBasedOnState(record); } } private Change<ValueAndTimestamp<SubscriptionWrapper<K>>> inferBasedOnState(final Record<KO, SubscriptionWrapper<K>> record) { final Bytes subscriptionKey = keySchema.toBytes(record.key(), record.value().getPrimaryKey()); final ValueAndTimestamp<SubscriptionWrapper<K>> newValue = ValueAndTimestamp.make(record.value(), record.timestamp()); final ValueAndTimestamp<SubscriptionWrapper<K>> oldValue = store.get(subscriptionKey); //This store is used by the prefix scanner in ForeignTableJoinProcessorSupplier if (record.value().getInstruction().equals(SubscriptionWrapper.Instruction.DELETE_KEY_AND_PROPAGATE) || record.value().getInstruction().equals(SubscriptionWrapper.Instruction.DELETE_KEY_NO_PROPAGATE)) { store.delete(subscriptionKey); } else { store.put(subscriptionKey, newValue); } return new Change<>(newValue, oldValue); } private void dropRecord() { if (context().recordMetadata().isPresent()) { final RecordMetadata recordMetadata = context().recordMetadata().get(); LOG.warn( "Skipping record due to null foreign key. " + "topic=[{}] partition=[{}] offset=[{}]", recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset() ); } else { LOG.warn( "Skipping record due to null foreign key. Topic, partition, and offset not known." ); } droppedRecordsSensor.record(); } }; }
@Test public void shouldPropagateNullIfNoFKValAvailableV0() { final StoreBuilder<TimestampedKeyValueStore<Bytes, SubscriptionWrapper<String>>> storeBuilder = storeBuilder(); final SubscriptionReceiveProcessorSupplier<String, String> supplier = supplier(storeBuilder); final Processor<String, SubscriptionWrapper<String>, CombinedKey<String, String>, Change<ValueAndTimestamp<SubscriptionWrapper<String>>>> processor = supplier.get(); stateStore = storeBuilder.build(); context.addStateStore(stateStore); stateStore.init((StateStoreContext) context, stateStore); final SubscriptionWrapper<String> oldWrapper = new SubscriptionWrapper<>( new long[]{1L, 2L}, Instruction.PROPAGATE_NULL_IF_NO_FK_VAL_AVAILABLE, PK2, SubscriptionWrapper.VERSION_0, null ); final ValueAndTimestamp<SubscriptionWrapper<String>> oldValue = ValueAndTimestamp.make(oldWrapper, 0); final Bytes key = COMBINED_KEY_SCHEMA.toBytes(FK, PK1); stateStore.put(key, oldValue); processor.init(context); final SubscriptionWrapper<String> newWrapper = new SubscriptionWrapper<>( new long[]{1L, 2L}, Instruction.PROPAGATE_NULL_IF_NO_FK_VAL_AVAILABLE, PK1, SubscriptionWrapper.VERSION_0, null ); final ValueAndTimestamp<SubscriptionWrapper<String>> newValue = ValueAndTimestamp.make( newWrapper, 1L); final Record<String, SubscriptionWrapper<String>> record = new Record<>( FK, newWrapper, 1L ); processor.process(record); final List<CapturedForward<? extends CombinedKey<String, String>, ? extends Change<ValueAndTimestamp<SubscriptionWrapper<String>>>>> forwarded = context.forwarded(); assertEquals(newValue, stateStore.get(key)); assertEquals(1, forwarded.size()); assertEquals( record.withKey(new CombinedKey<>(FK, PK1)) .withValue(new Change<>(newValue, oldValue)), forwarded.get(0).record() ); }
public T getMetaForEntry( Repository rep, IMetaStore metaStore, VariableSpace space ) throws KettleException { try { T theMeta = null; if ( jobEntryBase.getParentJob() != null ) { metaFileCache = jobEntryBase.getParentJobMeta().getMetaFileCache(); //Get the cache from the parent or create it } CurrentDirectoryResolver r = new CurrentDirectoryResolver(); VariableSpace tmpSpace = r.resolveCurrentDirectory( specificationMethod, space, rep, jobEntryBase.getParentJob(), filename ); final String[] idContainer = new String[ 1 ]; //unigue portion of cache key passed though argument switch ( specificationMethod ) { case FILENAME: String realFilename = tmpSpace.environmentSubstitute( filename ); try { theMeta = attemptLoadMeta( realFilename, rep, metaStore, tmpSpace, null, idContainer ); } catch ( KettleException e ) { // try to load from repository, this trans may have been developed locally and later uploaded to the // repository if ( rep == null ) { theMeta = isTransMeta() ? (T) new TransMeta( realFilename, metaStore, null, true, jobEntryBase.getParentVariableSpace(), null ) : (T) new JobMeta( jobEntryBase.getParentVariableSpace(), realFilename, rep, metaStore, null ); } else { theMeta = getMetaFromRepository( rep, r, realFilename, tmpSpace ); } if ( theMeta != null ) { idContainer[ 0 ] = realFilename; } } break; case REPOSITORY_BY_NAME: String realDirectory = tmpSpace.environmentSubstitute( directory != null ? directory : "" ); String realName = tmpSpace.environmentSubstitute( metaName ); String metaPath = StringUtil.trimEnd( realDirectory, '/' ) + RepositoryFile.SEPARATOR + StringUtil .trimStart( realName, '/' ); if ( metaPath.startsWith( "file://" ) || metaPath.startsWith( "zip:file://" ) || metaPath.startsWith( "hdfs://" ) ) { String extension = isTransMeta() ? RepositoryObjectType.TRANSFORMATION.getExtension() : RepositoryObjectType.JOB.getExtension(); if ( !metaPath.endsWith( extension ) ) { metaPath = metaPath + extension; } theMeta = attemptCacheRead( metaPath ); //try to get from the cache first if ( theMeta == null ) { if ( isTransMeta() ) { theMeta = (T) new TransMeta( metaPath, metaStore, null, true, jobEntryBase.getParentVariableSpace(), null ); } else { theMeta = (T) new JobMeta( tmpSpace, metaPath, rep, metaStore, null ); } idContainer[ 0 ] = metaPath; } } else { theMeta = attemptCacheRead( metaPath ); //try to get from the cache first if ( theMeta == null ) { if ( isTransMeta() ) { theMeta = rep == null ? (T) new TransMeta( metaPath, metaStore, null, true, jobEntryBase.getParentVariableSpace(), null ) : getMetaFromRepository( rep, r, metaPath, tmpSpace ); } else { theMeta = getMetaFromRepository( rep, r, metaPath, tmpSpace ); } if ( theMeta != null ) { idContainer[ 0 ] = metaPath; } } } break; case REPOSITORY_BY_REFERENCE: if ( metaObjectId == null ) { if ( isTransMeta() ) { throw new KettleException( BaseMessages.getString( persistentClass, "JobTrans.Exception.ReferencedTransformationIdIsNull" ) ); } else { throw new KettleException( BaseMessages.getString( persistentClass, "JobJob.Exception.ReferencedTransformationIdIsNull" ) ); } } if ( rep != null ) { theMeta = attemptCacheRead( metaObjectId.toString() ); //try to get from the cache first if ( theMeta == null ) { // Load the last revision if ( isTransMeta() ) { theMeta = (T) rep.loadTransformation( metaObjectId, null ); } else { theMeta = (T) rep.loadJob( metaObjectId, null ); } idContainer[ 0 ] = metaObjectId.toString(); } } else { throw new KettleException( "Could not execute " + friendlyMetaType + " specified in a repository since we're not connected to one" ); } break; default: throw new KettleException( "The specified object location specification method '" + specificationMethod + "' is not yet supported in this " + friendlyMetaType + " entry." ); } cacheMeta( idContainer[ 0 ], theMeta ); return theMeta; } catch ( final KettleException ke ) { // if we get a KettleException, simply re-throw it throw ke; } catch ( Exception e ) { throw new KettleException( BaseMessages.getString( persistentClass, "JobTrans.Exception.MetaDataLoad" ), e ); } }
@Test //A job getting the JobMeta from the repo public void getMetaForEntryAsJobFromRepoTest() throws Exception { setupJobEntryJob(); specificationMethod = ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME; MetaFileLoaderImpl metaFileLoader = new MetaFileLoaderImpl<JobMeta>( jobEntryBase, specificationMethod ); JobMeta jobMeta = (JobMeta) metaFileLoader.getMetaForEntry( repository, store, space ); validateFirstJobMetaAccess( jobMeta ); jobMeta = (JobMeta) metaFileLoader.getMetaForEntry( repository, store, space ); validateSecondJobMetaAccess( jobMeta ); }
@Override public CompletableFuture<TxnOffsetCommitResponseData> commitTransactionalOffsets( RequestContext context, TxnOffsetCommitRequestData request, BufferSupplier bufferSupplier ) { if (!isActive.get()) { return CompletableFuture.completedFuture(TxnOffsetCommitRequest.getErrorResponse( request, Errors.COORDINATOR_NOT_AVAILABLE )); } if (!isGroupIdNotEmpty(request.groupId())) { return CompletableFuture.completedFuture(TxnOffsetCommitRequest.getErrorResponse( request, Errors.INVALID_GROUP_ID )); } return runtime.scheduleTransactionalWriteOperation( "txn-commit-offset", topicPartitionFor(request.groupId()), request.transactionalId(), request.producerId(), request.producerEpoch(), Duration.ofMillis(config.offsetCommitTimeoutMs()), coordinator -> coordinator.commitTransactionalOffset(context, request), context.apiVersion() ).exceptionally(exception -> handleOperationException( "txn-commit-offset", request, exception, (error, __) -> TxnOffsetCommitRequest.getErrorResponse(request, error) )); }
@Test public void testCommitTransactionalOffsets() throws ExecutionException, InterruptedException { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), createConfig(), runtime, new GroupCoordinatorMetrics(), createConfigManager() ); service.startup(() -> 1); TxnOffsetCommitRequestData request = new TxnOffsetCommitRequestData() .setGroupId("foo") .setTransactionalId("transactional-id") .setProducerId(10L) .setProducerEpoch((short) 5) .setMemberId("member-id") .setGenerationId(10) .setTopics(Collections.singletonList(new TxnOffsetCommitRequestData.TxnOffsetCommitRequestTopic() .setName("topic") .setPartitions(Collections.singletonList(new TxnOffsetCommitRequestData.TxnOffsetCommitRequestPartition() .setPartitionIndex(0) .setCommittedOffset(100))))); TxnOffsetCommitResponseData response = new TxnOffsetCommitResponseData() .setTopics(Collections.singletonList(new TxnOffsetCommitResponseData.TxnOffsetCommitResponseTopic() .setName("topic") .setPartitions(Collections.singletonList(new TxnOffsetCommitResponseData.TxnOffsetCommitResponsePartition() .setPartitionIndex(0) .setErrorCode(Errors.NONE.code()))))); when(runtime.scheduleTransactionalWriteOperation( ArgumentMatchers.eq("txn-commit-offset"), ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)), ArgumentMatchers.eq("transactional-id"), ArgumentMatchers.eq(10L), ArgumentMatchers.eq((short) 5), ArgumentMatchers.eq(Duration.ofMillis(5000)), ArgumentMatchers.any(), ArgumentMatchers.any() )).thenReturn(CompletableFuture.completedFuture(response)); CompletableFuture<TxnOffsetCommitResponseData> future = service.commitTransactionalOffsets( requestContext(ApiKeys.TXN_OFFSET_COMMIT), request, BufferSupplier.NO_CACHING ); assertEquals(response, future.get()); }
boolean isMapped(String userId) { return idToDirectoryNameMap.containsKey(getIdStrategy().keyFor(userId)); }
@Test public void testDuplicatedUserId() throws IOException { UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE); assertThat(mapper.isMapped("user2"), is(true)); assertThat(mapper.isMapped("user1"), is(true)); }
public static long findMinLegalValue( Function<Long, Boolean> legalChecker, long low, long high) { if (!legalChecker.apply(high)) { return -1; } while (low <= high) { long mid = (low + high) / 2; if (legalChecker.apply(mid)) { high = mid - 1; } else { low = mid + 1; } } return high + 1; }
@Test void testFindMinLegalValue() { assertThat(BisectionSearchUtils.findMinLegalValue(value -> 29 / value <= 3, 1, 17)) .isEqualTo(8); assertThat(BisectionSearchUtils.findMinLegalValue(value -> 29 / value <= 3, 8, 17)) .isEqualTo(8); assertThat(BisectionSearchUtils.findMinLegalValue(value -> 29 / value <= 3, 1, 8)) .isEqualTo(8); assertThat(BisectionSearchUtils.findMinLegalValue(value -> 29 / value <= 3, 9, 17)) .isEqualTo(9); assertThat(BisectionSearchUtils.findMinLegalValue(value -> 29 / value <= 3, 1, 7)) .isEqualTo(-1); }
@Override public Processor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>> get() { return new ContextualProcessor<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>, K, SubscriptionResponseWrapper<VO>>() { private KTableValueGetter<KO, VO> foreignValues; @Override public void init(final ProcessorContext<K, SubscriptionResponseWrapper<VO>> context) { super.init(context); foreignValues = foreignValueGetterSupplier.get(); foreignValues.init(context); } @Override public void process(final Record<CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>> record) { Objects.requireNonNull(record.key(), "This processor should never see a null key."); Objects.requireNonNull(record.value(), "This processor should never see a null value."); final ValueAndTimestamp<SubscriptionWrapper<K>> valueAndTimestamp = record.value().newValue; Objects.requireNonNull(valueAndTimestamp, "This processor should never see a null newValue."); final SubscriptionWrapper<K> value = valueAndTimestamp.value(); if (value.getVersion() > SubscriptionWrapper.CURRENT_VERSION) { //Guard against modifications to SubscriptionWrapper. Need to ensure that there is compatibility //with previous versions to enable rolling upgrades. Must develop a strategy for upgrading //from older SubscriptionWrapper versions to newer versions. throw new UnsupportedVersionException("SubscriptionWrapper is of an incompatible version."); } final ValueAndTimestamp<VO> foreignValueAndTime = record.key().getForeignKey() == null ? null : foreignValues.get(record.key().getForeignKey()); final long resultTimestamp = foreignValueAndTime == null ? valueAndTimestamp.timestamp() : Math.max(valueAndTimestamp.timestamp(), foreignValueAndTime.timestamp()); switch (value.getInstruction()) { case DELETE_KEY_AND_PROPAGATE: context().forward( record.withKey(record.key().getPrimaryKey()) .withValue(new SubscriptionResponseWrapper<VO>( value.getHash(), null, value.getPrimaryPartition() )) .withTimestamp(resultTimestamp) ); break; case PROPAGATE_NULL_IF_NO_FK_VAL_AVAILABLE: //This one needs to go through regardless of LEFT or INNER join, since the extracted FK was //changed and there is no match for it. We must propagate the (key, null) to ensure that the //downstream consumers are alerted to this fact. final VO valueToSend = foreignValueAndTime == null ? null : foreignValueAndTime.value(); context().forward( record.withKey(record.key().getPrimaryKey()) .withValue(new SubscriptionResponseWrapper<>( value.getHash(), valueToSend, value.getPrimaryPartition() )) .withTimestamp(resultTimestamp) ); break; case PROPAGATE_ONLY_IF_FK_VAL_AVAILABLE: if (foreignValueAndTime != null) { context().forward( record.withKey(record.key().getPrimaryKey()) .withValue(new SubscriptionResponseWrapper<>( value.getHash(), foreignValueAndTime.value(), value.getPrimaryPartition() )) .withTimestamp(resultTimestamp) ); } break; case DELETE_KEY_NO_PROPAGATE: break; default: throw new IllegalStateException("Unhandled instruction: " + value.getInstruction()); } } }; }
@Test public void shouldPropagateOnlyIfFKAvailableV0() { final MockProcessorContext<String, SubscriptionResponseWrapper<String>> context = new MockProcessorContext<>(); processor.init(context); final SubscriptionWrapper<String> newValue = new SubscriptionWrapper<>( new long[]{1L}, Instruction.PROPAGATE_ONLY_IF_FK_VAL_AVAILABLE, "pk1", SubscriptionWrapper.VERSION_0, null ); final Record<CombinedKey<String, String>, Change<ValueAndTimestamp<SubscriptionWrapper<String>>>> record = new Record<>( new CombinedKey<>("fk1", "pk1"), new Change<>(ValueAndTimestamp.make(newValue, 1L), null), 1L ); processor.process(record); final List<CapturedForward<? extends String, ? extends SubscriptionResponseWrapper<String>>> forwarded = context.forwarded(); assertEquals(1, forwarded.size()); assertEquals( new Record<>( "pk1", new SubscriptionResponseWrapper<>( newValue.getHash(), "foo", null ), 1L ), forwarded.get(0).record() ); }
public static EthMappingAddress ethMappingAddress(MacAddress mac) { return new EthMappingAddress(mac); }
@Test public void testEthMappingAddressMethod() { MacAddress mac = MacAddress.valueOf("00:00:00:00:00:01"); MappingAddress mappingAddress = MappingAddresses.ethMappingAddress(mac); EthMappingAddress ethMappingAddress = checkAndConvert(mappingAddress, MappingAddress.Type.ETH, EthMappingAddress.class); assertThat(ethMappingAddress.mac(), is(equalTo(mac))); }
public static DataCleaner<Track<NopHit>> simpleSmoothing() { NopEncoder nopEncoder = new NopEncoder(); DataCleaner<Track<NopHit>> cleaner = coreSmoothing(); ToStringFunction<Track<NopHit>> toString = track -> nopEncoder.asRawNop(track); ExceptionHandler exceptionHandler = new SequentialFileWriter("trackCleaningExceptions"); return new ExceptionCatchingCleaner<>(cleaner, toString, exceptionHandler); }
@Test public void testSimultaneousSmoothing() { /* * The file: starsTrackWithCoastedPoints.txt contains... * * 2 Coasted Points * * 1 Dropped Point * * 1 artifically added vertical outlier (the 43rd point had its altitude set to 000) * * 1 possible vertical outlier that wasn't fixed (the very first point) * * This test verifies that (A) the coasted and dropped points are removed, (B) the vertical * outlier is fixed. */ Track<NopHit> unSmoothedTrack = Tracks.createTrackFromResource( Track.class, "starsTrackWithCoastedPoints.txt" ); VerticalOutlierDetector<NopHit> vod = new VerticalOutlierDetector<>(); int sizeBeforeSmoothing = unSmoothedTrack.size(); int numVerticalOutliersBeforeSmoothing = vod.getOutliers(unSmoothedTrack).size(); Track<NopHit> smoothedTrack = (simpleSmoothing()).clean(unSmoothedTrack).get(); int sizeAfterSmoothing = smoothedTrack.size(); int numVerticalOutliersAfterSmoothing = vod.getOutliers(smoothedTrack).size(); //accounts for the DownSampler that removes poitns that occur within 3.5 sec int pointsDroppedDueToBeingToCloseInTime = 16; int numPointsRemoved = sizeBeforeSmoothing - sizeAfterSmoothing; int numVerticalOutliersCorrected = numVerticalOutliersBeforeSmoothing - numVerticalOutliersAfterSmoothing; assertEquals( 3 + pointsDroppedDueToBeingToCloseInTime, numPointsRemoved, "Exactly 3 points should be been removed (2 coasted and 1 dropped)" ); assertEquals( 1, numVerticalOutliersCorrected, "Exactly 1 poitn should have had its altitude corrected (the 1st point)" ); }
public FEELFnResult<String> invoke(@ParameterName("string") String string, @ParameterName("match") String match) { if ( string == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "string", "cannot be null" ) ); } if ( match == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "match", "cannot be null" ) ); } int index = string.indexOf( match ); if ( index > 0 ) { return FEELFnResult.ofResult( string.substring( 0, index ) ); } else { return FEELFnResult.ofResult( "" ); } }
@Test void invokeNull() { FunctionTestUtil.assertResultError(substringBeforeFunction.invoke((String) null, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(substringBeforeFunction.invoke(null, "test"), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(substringBeforeFunction.invoke("test", null), InvalidParametersEvent.class); }
@VisibleForTesting Collection<CompletableFuture<Channel>> getResponseChannelFutures() { return responseChannelFutures; }
@Test void testResponseChannelFuturesResolvedExceptionallyOnClose() throws Exception { try (final RestClient restClient = new RestClient(new Configuration(), Executors.directExecutor())) { CompletableFuture<Channel> responseChannelFuture = new CompletableFuture<>(); // Add the future to the client's internal collection of pending response futures restClient.getResponseChannelFutures().add(responseChannelFuture); // Close the client, which should resolve all pending response futures exceptionally and // clear the collection restClient.close(); // Ensure the client's internal collection of pending response futures was cleared after // close assertThat(restClient.getResponseChannelFutures()).isEmpty(); FlinkAssertions.assertThatFuture(responseChannelFuture) .eventuallyFailsWith(ExecutionException.class) .withCauseInstanceOf(IllegalStateException.class) .extracting(Throwable::getCause, as(THROWABLE)) .hasMessage("RestClient closed before request completed"); } }
@Override public void accept(T t) { updateTimeHighWaterMark(t.time()); shortTermStorage.add(t); drainDueToLatestInput(t); //standard drain policy drainDueToTimeHighWaterMark(); //prevent blow-up when data goes backwards in time sizeHighWaterMark = Math.max(sizeHighWaterMark, shortTermStorage.size()); }
@Test public void testOverflowBug() { /* * It should not be possible to crash an ApproximateTimeSorter by overloading the memory by * continuously providing older and older points. */ Duration maxLag = Duration.ofSeconds(3); //a very small sorting window ConsumingArrayList<TimePojo> downstreamConsumer = newConsumingArrayList(); ApproximateTimeSorter<TimePojo> sorter = new ApproximateTimeSorter<>(maxLag, downstreamConsumer); //add Points to the sorter that keep getting older and older int NUM_POINTS = 50_000; for (int i = 0; i < NUM_POINTS; i++) { Instant time = EPOCH.minusSeconds(i); sorter.accept(new TimePojo(time)); } int numPointsPastSorter = downstreamConsumer.size(); /* * We want most of the points to pass this sorter because this stream of "perfectly out of * order" data should not: (1) lead to an OutOfMemoryException or (2) be a fixable input * type. In other words, this data is so bad it isn't reasonable to get it organized. */ assertTrue(numPointsPastSorter >= NUM_POINTS * .99); }
public static <T> PrefetchableIterable<T> fromArray(T... values) { if (values.length == 0) { return emptyIterable(); } return new Default<T>() { @Override public PrefetchableIterator<T> createIterator() { return PrefetchableIterators.fromArray(values); } }; }
@Test public void testFromArray() { verifyIterable(PrefetchableIterables.fromArray("A", "B", "C"), "A", "B", "C"); verifyIterable(PrefetchableIterables.fromArray()); }
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchingFunctionException(arguments); } // if none were found (candidate isn't present) try again with implicit casting candidate = findMatchingCandidate(arguments, true); if (candidate.isPresent()) { return candidate.get(); } throw createNoMatchingFunctionException(arguments); }
@Test public void shouldFindGenericMethodWithStringParam() { // Given: givenFunctions( function(EXPECTED, -1, GENERIC_LIST) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(Collections.singletonList(SqlArgument.of(SqlArray.of(SqlTypes.STRING)))); // Then: assertThat(fun.name(), equalTo(EXPECTED)); }
@Override public boolean registerAllRequestsProcessedListener(NotificationListener listener) throws IOException { return super.registerAllRequestsProcessedListener(listener); }
@Test void testSubscribeAndClose() throws Exception { final TestNotificationListener listener = new TestNotificationListener(); addRequest(); addRequest(); writer.registerAllRequestsProcessedListener(listener); final CheckedThread asyncCloseThread = new CheckedThread() { @Override public void go() throws Exception { writer.close(); } }; asyncCloseThread.start(); handleRequest(); handleRequest(); asyncCloseThread.sync(); assertThat(listener.getNumberOfNotifications()) .withFailMessage("Listener was not notified.") .isOne(); }
public TwilioEndpoint(String uri, TwilioComponent component, TwilioApiName apiName, String methodName, TwilioConfiguration endpointConfiguration) { super(uri, component, apiName, methodName, TwilioApiCollection.getCollection().getHelper(apiName), endpointConfiguration); this.component = component; this.configuration = endpointConfiguration; }
@Test public void testTwilioEndpoint() { // should not use reflection when creating and configuring endpoint final BeanIntrospection beanIntrospection = PluginHelper.getBeanIntrospection(context); long before = beanIntrospection.getInvokedCounter(); TwilioEndpoint te = context.getEndpoint("twilio:account/fetcher?pathSid=123", TwilioEndpoint.class); AccountEndpointConfiguration aec = (AccountEndpointConfiguration) te.getConfiguration(); Assertions.assertEquals("123", aec.getPathSid()); te = context.getEndpoint( "twilio://call/create?from=RAW(+15005550006)&to=RAW(+14108675310)&url=http://demo.twilio.com/docs/voice.xml", TwilioEndpoint.class); Assertions.assertTrue(te.getConfiguration() instanceof CallEndpointConfiguration); CallEndpointConfiguration cee = (CallEndpointConfiguration) te.getConfiguration(); Assertions.assertEquals("+15005550006", cee.getFrom().getEndpoint()); Assertions.assertEquals("+14108675310", cee.getTo().getEndpoint()); long after = beanIntrospection.getInvokedCounter(); Assertions.assertEquals(before, after); }
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void testMisc31() { Reader reader = new Reader(new SwaggerConfiguration().openAPI(new OpenAPI()).openAPI31(true)); Set<Class<?>> classes = new HashSet<>(Arrays.asList(Misc31Resource.class)); OpenAPI openAPI = reader.read(classes); String yaml = "openapi: 3.1.0\n" + "paths:\n" + " /pet:\n" + " put:\n" + " operationId: updatePet\n" + " responses:\n" + " default:\n" + " description: default response\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/ModelWithOAS31Stuff'\n" + " application/xml:\n" + " schema:\n" + " $ref: '#/components/schemas/ModelWithOAS31Stuff'\n" + "components:\n" + " schemas:\n" + " ModelWithOAS31Stuff:\n" + " type: object\n" + " $comment: Random comment at schema level\n" + " $id: http://yourdomain.com/schemas/myschema.json\n" + " description: this is model for testing OAS 3.1 resolving\n" + " properties:\n" + " randomList:\n" + " type: array\n" + " contains:\n" + " type: string\n" + " items:\n" + " type: string\n" + " maxContains: 10\n" + " minContains: 1\n" + " prefixItems:\n" + " - type: string\n" + " unevaluatedItems:\n" + " type: number\n" + " status:\n" + " type:\n" + " - string\n" + " - number\n" + " intValue:\n" + " type: integer\n" + " format: int32\n" + " $anchor: intValue\n" + " $comment: comment at schema property level\n" + " exclusiveMaximum: 100\n" + " exclusiveMinimum: 1\n" + " text:\n" + " type: string\n" + " contentEncoding: plan/text\n" + " contentMediaType: base64\n" + " encodedString:\n" + " type: string\n" + " contentMediaType: application/jwt\n" + " contentSchema:\n" + " $ref: '#/components/schemas/MultipleBaseBean'\n" + " address:\n" + " $ref: '#/components/schemas/Address'\n" + " client:\n" + " type: string\n" + " dependentSchemas:\n" + " creditCard:\n" + " $ref: '#/components/schemas/CreditCard'\n" + " MultipleBaseBean:\n" + " description: MultipleBaseBean\n" + " properties:\n" + " beanType:\n" + " type: string\n" + " a:\n" + " type: integer\n" + " format: int32\n" + " b:\n" + " type: string\n" + " MultipleSub1Bean:\n" + " allOf:\n" + " - $ref: '#/components/schemas/MultipleBaseBean'\n" + " - type: object\n" + " properties:\n" + " c:\n" + " type: integer\n" + " format: int32\n" + " description: MultipleSub1Bean\n" + " MultipleSub2Bean:\n" + " allOf:\n" + " - $ref: '#/components/schemas/MultipleBaseBean'\n" + " - type: object\n" + " properties:\n" + " d:\n" + " type: integer\n" + " format: int32\n" + " description: MultipleSub2Bean\n" + " Address:\n" + " if:\n" + " $ref: '#/components/schemas/AnnotatedCountry'\n" + " then:\n" + " $ref: '#/components/schemas/PostalCodeNumberPattern'\n" + " else:\n" + " $ref: '#/components/schemas/PostalCodePattern'\n" + " dependentRequired:\n" + " street:\n" + " - country\n" + " properties:\n" + " street:\n" + " type: string\n" + " country:\n" + " type: string\n" + " enum:\n" + " - United States of America\n" + " - Canada\n" + " propertyNames:\n" + " $ref: '#/components/schemas/PropertyNamesPattern'\n" + " AnnotatedCountry:\n" + " properties:\n" + " country:\n" + " const: United States\n" + " CreditCard:\n" + " properties:\n" + " billingAddress:\n" + " type: string\n" + " PostalCodeNumberPattern:\n" + " properties:\n" + " postalCode:\n" + " pattern: \"[0-9]{5}(-[0-9]{4})?\"\n" + " PostalCodePattern:\n" + " properties:\n" + " postalCode:\n" + " pattern: \"[A-Z][0-9][A-Z] [0-9][A-Z][0-9]\"\n" + " PropertyNamesPattern:\n" + " pattern: \"^[A-Za-z_][A-Za-z0-9_]*$\"\n"; SerializationMatchers.assertEqualsToYaml31(openAPI, yaml); }
@Override public String getPrincipal() { Subject subject = org.apache.shiro.SecurityUtils.getSubject(); String principal; if (subject.isAuthenticated()) { principal = extractPrincipal(subject); if (zConf.isUsernameForceLowerCase()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Converting principal name {} to lower case: {}", principal, principal.toLowerCase()); } principal = principal.toLowerCase(); } } else { // TODO(jl): Could be better to occur error? principal = "anonymous"; } return principal; }
@Test void testUsernameForceLowerCase() throws IOException, InterruptedException { String expectedName = "java.security.Principal.getName()"; when(zConf.isUsernameForceLowerCase()).thenReturn(true); setupPrincipalName(expectedName); assertEquals(expectedName.toLowerCase(), shiroSecurityService.getPrincipal()); }
public static void writeBinaryCodedLengthBytes(byte[] data, ByteArrayOutputStream out) throws IOException { // 1. write length byte/bytes if (data.length < 252) { out.write((byte) data.length); } else if (data.length < (1 << 16L)) { out.write((byte) 252); writeUnsignedShortLittleEndian(data.length, out); } else if (data.length < (1 << 24L)) { out.write((byte) 253); writeUnsignedMediumLittleEndian(data.length, out); } else { out.write((byte) 254); writeUnsignedIntLittleEndian(data.length, out); } // 2. write real data followed length byte/bytes out.write(data); }
@Test public void testWriteBinaryCodedLengthBytes2() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteHelper.writeBinaryCodedLengthBytes(new byte[252], out); byte[] expected = new byte[255]; expected[0] = -4; expected[1] = -4; Assert.assertArrayEquals(expected, (out.toByteArray())); }
@Nonnull public static <T> BatchSource<T> list(@Nonnull String listName) { return batchFromProcessor("listSource(" + listName + ')', readListP(listName)); }
@Test public void list_byRef() { // Given List<Integer> input = sequence(itemCount); addToSrcList(input); // When BatchSource<Object> source = Sources.list(srcList); // Then p.readFrom(source).writeTo(sink); execute(); assertEquals(input, sinkList); }
@Override public Object clone() throws CloneNotSupportedException { return new CowSet<>(_map.clone()); }
@Test public void testClone() throws CloneNotSupportedException { final CowSet<String> set1 = new CowSet<>(); set1.add("test"); @SuppressWarnings("unchecked") final CowSet<String> set2 = (CowSet<String>)set1.clone(); @SuppressWarnings("unchecked") final CowSet<String> set3 = (CowSet<String>)set2.clone(); Assert.assertEquals(set1, set2); Assert.assertEquals(set2, set3); set2.add("test2"); Assert.assertFalse(set1.contains("test2")); Assert.assertTrue(set2.contains("test2")); Assert.assertFalse(set3.contains("test2")); Assert.assertFalse(set2.equals(set1)); Assert.assertFalse(set2.equals(set3)); set3.add("test3"); Assert.assertFalse(set1.contains("test3")); Assert.assertFalse(set2.contains("test3")); Assert.assertTrue(set3.contains("test3")); Assert.assertFalse(set3.equals(set1)); Assert.assertFalse(set3.equals(set2)); set1.remove("test"); Assert.assertFalse(set1.contains("test")); Assert.assertTrue(set2.contains("test")); Assert.assertTrue(set3.contains("test")); Assert.assertFalse(set1.equals(set2)); Assert.assertFalse(set1.equals(set3)); }
@Override public KTable<Windowed<K>, V> reduce(final Reducer<V> reducer) { return reduce(reducer, NamedInternal.empty()); }
@Test public void shouldThrowNullPointerOnMaterializedReduceIfReducerIsNull() { assertThrows(NullPointerException.class, () -> windowedStream.reduce(null, Materialized.as("store"))); }
@SuppressFBWarnings("EI_EXPOSE_REP") public Comparable[] getComponents() { return components; }
@Test public void testConstruction() { assertThat(new CompositeValue(new Comparable[]{1, 1.1, "1.1"}).getComponents()).isEqualTo(new Object[]{1, 1.1, "1.1"}); assertThat(new CompositeValue(1, "prefix", null).getComponents()) .isEqualTo(new Object[]{"prefix"}); assertThat(new CompositeValue(2, "prefix", "filler").getComponents()) .isEqualTo(new Object[]{"prefix", "filler"}); assertThat(new CompositeValue(5, "prefix", "filler").getComponents()) .isEqualTo(new Object[]{"prefix", "filler", "filler", "filler", "filler"}); }
public List<KiePMMLDroolsRule> declareRulesFromCharacteristics(final Characteristics characteristics, final String parentPath, Number initialScore) { logger.trace("declareRulesFromCharacteristics {} {} {}", characteristics, parentPath, initialScore); final List<KiePMMLDroolsRule> toReturn = new ArrayList<>(); final List<Characteristic> characteristicList = characteristics.getCharacteristics(); for (int i = 0; i < characteristicList.size(); i++) { final Characteristic characteristic = characteristicList.get(i); if (i == 0) { String statusConstraint = StringUtils.isEmpty(parentPath) ? KiePMMLAbstractModelASTFactory.STATUS_NULL : String.format(KiePMMLAbstractModelASTFactory.STATUS_PATTERN, parentPath); String currentRule = String.format(PATH_PATTERN, parentPath, characteristic.getName()); KiePMMLDroolsRule.Builder builder = KiePMMLDroolsRule.builder(currentRule, currentRule, null) .withStatusConstraint(statusConstraint); if (initialScore != null) { builder = builder.withAccumulation(initialScore); } toReturn.add(builder.build()); } boolean isLastCharacteristic = (i == characteristicList.size() - 1); String statusToSet = isLastCharacteristic ? DONE : String.format(PATH_PATTERN, parentPath, characteristicList.get(i + 1).getName()); declareRuleFromCharacteristic(characteristic, parentPath, toReturn, statusToSet, isLastCharacteristic); } return toReturn; }
@Test void declareRulesFromCharacteristics() { Characteristics characteristics = scorecardModel.getCharacteristics(); String parentPath = "_will"; List<KiePMMLDroolsRule> retrieved = getKiePMMLScorecardModelCharacteristicASTFactory() .declareRulesFromCharacteristics(characteristics, parentPath, null); final List<Characteristic> characteristicList = characteristics.getCharacteristics(); List<Attribute> attributes = new ArrayList<>(); AtomicInteger counter = new AtomicInteger(0); for (int i = 0; i < characteristicList.size(); i++) { Characteristic characteristic = characteristicList.get(i); attributes.addAll(characteristic.getAttributes()); for (int j = 0; j < characteristic.getAttributes().size(); j++) { Attribute attribute = characteristic.getAttributes().get(j); KiePMMLDroolsRule rule = retrieved.get(counter.incrementAndGet()); int expectedOperatorValuesSize = 1; Integer expectedAndConstraints = null; Integer expectedInConstraints = null; BOOLEAN_OPERATOR expectedOperator = BOOLEAN_OPERATOR.AND; if (attribute.getPredicate() instanceof SimplePredicate) { expectedAndConstraints = 1; } if (attribute.getPredicate() instanceof CompoundPredicate) { expectedOperatorValuesSize = ((CompoundPredicate) attribute.getPredicate()).getPredicates().size(); expectedAndConstraints = 1; } if (attribute.getPredicate() instanceof SimpleSetPredicate) { expectedInConstraints = 1; } boolean isLastCharacteristic = (i == characteristicList.size() - 1); String statusToSet = isLastCharacteristic ? DONE : String.format(PATH_PATTERN, parentPath, characteristicList.get(i + 1).getName()); commonValidateRule(rule, attribute, statusToSet, parentPath + "_" + characteristic.getName(), j, isLastCharacteristic, expectedAndConstraints, expectedInConstraints, expectedOperator, null, expectedOperatorValuesSize); } } assertThat(attributes).hasSize(retrieved.size() - 1); }
public static long getCurrentPID() { return Long.parseLong(getRuntimeMXBean().getName().split("@")[0]); }
@Test public void getCurrentPidTest() { final long pid = SystemUtil.getCurrentPID(); assertTrue(pid > 0); }
public GlobalTransactional getTransactionAnnotation() { return transactionAnnotation; }
@Test public void testGetTransactionAnnotation() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { MethodDesc methodDesc = getMethodDesc(); assertThat(methodDesc.getTransactionAnnotation()).isEqualTo(transactional); }
void precheckMaxResultLimitOnLocalPartitions(String mapName) { // check if feature is enabled if (!isPreCheckEnabled) { return; } // limit number of local partitions to check to keep runtime constant PartitionIdSet localPartitions = mapServiceContext.getCachedOwnedPartitions(); int partitionsToCheck = min(localPartitions.size(), maxLocalPartitionsLimitForPreCheck); if (partitionsToCheck == 0) { return; } // calculate size of local partitions int localPartitionSize = getLocalPartitionSize(mapName, localPartitions, partitionsToCheck); if (localPartitionSize == 0) { return; } // check local result size long localResultLimit = getNodeResultLimit(partitionsToCheck); if (localPartitionSize > localResultLimit * MAX_RESULT_LIMIT_FACTOR_FOR_PRECHECK) { var localMapStatsProvider = mapServiceContext.getLocalMapStatsProvider(); if (localMapStatsProvider != null && localMapStatsProvider.hasLocalMapStatsImpl(mapName)) { localMapStatsProvider.getLocalMapStatsImpl(mapName).incrementQueryResultSizeExceededCount(); } throw new QueryResultSizeExceededException(maxResultLimit, " Result size exceeded in local pre-check."); } }
@Test public void testLocalPreCheckEnabledWitDifferentPartitionSizesBelowLimit() { int[] partitionSizes = {566, 1132, Integer.MAX_VALUE}; populatePartitions(partitionSizes); initMocksWithConfiguration(200000, 2); limiter.precheckMaxResultLimitOnLocalPartitions(ANY_MAP_NAME); }
public static <K, V> ProducerRecordCoder<K, V> of(Coder<K> keyCoder, Coder<V> valueCoder) { return new ProducerRecordCoder<>(keyCoder, valueCoder); }
@Test public void testCoderIsSerializableWithWellKnownCoderType() { CoderProperties.coderSerializable( ProducerRecordCoder.of(GlobalWindow.Coder.INSTANCE, GlobalWindow.Coder.INSTANCE)); }
public static List<ConstraintKey> getConstraintKeys( DatabaseMetaData metadata, TablePath tablePath) throws SQLException { // We set approximate to true to avoid querying the statistics table, which is slow. try (ResultSet resultSet = metadata.getIndexInfo( tablePath.getDatabaseName(), tablePath.getSchemaName(), tablePath.getTableName(), false, true)) { // index name -> index Map<String, ConstraintKey> constraintKeyMap = new HashMap<>(); while (resultSet.next()) { String columnName = resultSet.getString("COLUMN_NAME"); if (columnName == null) { continue; } String indexName = cleanKeyName(resultSet.getString("INDEX_NAME")); boolean noUnique = resultSet.getBoolean("NON_UNIQUE"); ConstraintKey constraintKey = constraintKeyMap.computeIfAbsent( indexName, s -> { ConstraintKey.ConstraintType constraintType = ConstraintKey.ConstraintType.INDEX_KEY; if (!noUnique) { constraintType = ConstraintKey.ConstraintType.UNIQUE_KEY; } return ConstraintKey.of( constraintType, indexName, new ArrayList<>()); }); ConstraintKey.ColumnSortType sortType = "A".equals(resultSet.getString("ASC_OR_DESC")) ? ConstraintKey.ColumnSortType.ASC : ConstraintKey.ColumnSortType.DESC; ConstraintKey.ConstraintKeyColumn constraintKeyColumn = new ConstraintKey.ConstraintKeyColumn(columnName, sortType); constraintKey.getColumnNames().add(constraintKeyColumn); } return new ArrayList<>(constraintKeyMap.values()); } }
@Test void testConstraintKeysNameWithOutSpecialChar() throws SQLException { List<ConstraintKey> constraintKeys = CatalogUtils.getConstraintKeys( new TestDatabaseMetaData(), TablePath.of("test.test")); Assertions.assertEquals("testfdawe_", constraintKeys.get(0).getConstraintName()); }
@Override public RecordCursor cursor() { return new PrometheusRecordCursor(columnHandles, byteSource); }
@Test public void testCursorSimple() { RecordSet recordSet = new PrometheusRecordSet( new PrometheusClient(new PrometheusConnectorConfig(), METRIC_CODEC, TYPE_MANAGER), new PrometheusSplit(dataUri), ImmutableList.of( new PrometheusColumnHandle("labels", varcharMapType, 0), new PrometheusColumnHandle("timestamp", TIMESTAMP_WITH_TIME_ZONE, 1), new PrometheusColumnHandle("value", DoubleType.DOUBLE, 2))); RecordCursor cursor = recordSet.cursor(); assertEquals(cursor.getType(0), varcharMapType); assertEquals(cursor.getType(1), TIMESTAMP_WITH_TIME_ZONE); assertEquals(cursor.getType(2), DoubleType.DOUBLE); List<PrometheusStandardizedRow> actual = new ArrayList<>(); while (cursor.advanceNextPosition()) { actual.add(new PrometheusStandardizedRow( (Block) cursor.getObject(0), ((Instant) cursor.getObject(1)), cursor.getDouble(2))); assertFalse(cursor.isNull(0)); assertFalse(cursor.isNull(1)); assertFalse(cursor.isNull(2)); } List<PrometheusStandardizedRow> expected = ImmutableList.<PrometheusStandardizedRow>builder() .add(new PrometheusStandardizedRow(getBlockFromMap(varcharMapType, ImmutableMap.of("instance", "localhost:9090", "__name__", "up", "job", "prometheus")), ofEpochMilli(1565962969044L), 1.0)) .add(new PrometheusStandardizedRow(getBlockFromMap(varcharMapType, ImmutableMap.of("instance", "localhost:9090", "__name__", "up", "job", "prometheus")), ofEpochMilli(1565962984045L), 1.0)) .add(new PrometheusStandardizedRow(getBlockFromMap(varcharMapType, ImmutableMap.of("instance", "localhost:9090", "__name__", "up", "job", "prometheus")), ofEpochMilli(1565962999044L), 1.0)) .add(new PrometheusStandardizedRow(getBlockFromMap(varcharMapType, ImmutableMap.of("instance", "localhost:9090", "__name__", "up", "job", "prometheus")), ofEpochMilli(1565963014044L), 1.0)) .build(); List<PairLike<PrometheusStandardizedRow, PrometheusStandardizedRow>> pairs = Streams.zip(actual.stream(), expected.stream(), PairLike::new) .collect(Collectors.toList()); pairs.forEach(pair -> { assertEquals(getMapFromBlock(varcharMapType, pair.getFirst().getLabels()), getMapFromBlock(varcharMapType, pair.getSecond().getLabels())); assertEquals(pair.getFirst().getTimestamp(), pair.getSecond().getTimestamp()); assertEquals(pair.getFirst().getValue(), pair.getSecond().getValue()); }); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { if(file.isDirectory()) { return this.toAttributes(new FoldersApi(new BoxApiClient(session.getClient())).getFoldersId(fileid.getFileId(file), DEFAULT_FIELDS, null, null)); } return this.toAttributes(new FilesApi(new BoxApiClient(session.getClient())).getFilesId(fileid.getFileId(file), StringUtils.EMPTY, DEFAULT_FIELDS, null, null)); } catch(ApiException e) { throw new BoxExceptionMappingService(fileid).map("Failure to read attributes of {0}", e, file); } }
@Test public void testFindFile() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); final Path folder = new BoxDirectoryFeature(session, fileid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus()); final long folderModification = new BoxAttributesFinderFeature(session, fileid).find(folder).getModificationDate(); final Path test = new BoxTouchFeature(session, fileid) .touch(new Path(folder, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus().withLength(0L)); assertEquals(folderModification, new BoxAttributesFinderFeature(session, fileid).find(folder).getModificationDate(), 0L); final BoxAttributesFinderFeature f = new BoxAttributesFinderFeature(session, fileid); final PathAttributes attributes = f.find(test); assertEquals(0L, attributes.getSize()); assertNotEquals(-1L, attributes.getModificationDate()); assertNotNull(attributes.getFileId()); assertNotNull(attributes.getETag()); assertNotNull(attributes.getChecksum().algorithm); assertTrue(attributes.getPermission().isReadable()); assertTrue(attributes.getPermission().isWritable()); // Test wrong type try { f.find(new Path(test.getAbsolute(), EnumSet.of(Path.Type.directory))); fail(); } catch(NotfoundException e) { // Expected } new BoxDeleteFeature(session, fileid).delete(Collections.singletonList(folder), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
public static PredicateTreeAnalyzerResult analyzePredicateTree(Predicate predicate) { AnalyzerContext context = new AnalyzerContext(); int treeSize = aggregatePredicateStatistics(predicate, false, context); int minFeature = ((int)Math.ceil(findMinFeature(predicate, false, context))) + (context.hasNegationPredicate ? 1 : 0); return new PredicateTreeAnalyzerResult(minFeature, treeSize, context.subTreeSizes); }
@Test void require_that_minfeature_is_1_for_simple_negative_term() { Predicate p = not(feature("foo").inSet("bar")); PredicateTreeAnalyzerResult r = PredicateTreeAnalyzer.analyzePredicateTree(p); assertEquals(1, r.minFeature); }